@hatiolab/things-scene 10.1.77 → 10.1.78

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,s,i){const r=5+i,o=n.x,a=n.y,c=s.x,l=s.y;if(Math.abs(o-c)>r&&Math.abs(a-l)>r){const n=(l-a)/(c-o),s=a-n*o;if(Math.abs(e-(n*t+s))>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,s=2){for(let i=0;i<n.length-1;i++)if(ug(t,e,n[i],n[i+1],s))return!0;return!1}function fg(t,e,n,s){if("arrow"!=t.slice(-5))return n;const i=Math.atan2(s.y-n.y,s.x-n.x),r=1.5*e;return{x:n.x+Math.cos(i)*r,y:n.y+Math.sin(i)*r}}function mg(t,e,n){let{lineWidth:s=dg,strokeStyle:i="#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)&&(s=Number(s)||dg,t.lineCap=r,t.lineWidth=s,t.strokeStyle=i,t.fillStyle=i,t.globalAlpha*=o,"none"!=a&&gg(t,e[0],e[1],s,a,yg(l,s)),"none"!=c)){const n=e.length;gg(t,e[n-1],e[n-2],s,c,yg(h,s))}}function gg(t,e,n,s,i,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),i){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+s,-r.Y),t.lineTo(s,0),t.lineTo(hg*r.X+s,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:s}){this.component=t,this._anchorName=e,this._position=n,this.self=s}get position(){const t=this.anchor;if(t){const{position:e}=t,n=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(n.x,n.y)}return this._position}set position({x:t,y:e}){this._position={x:t,y:e}}get anchor(){return this.component?.findAnchor(this._anchorName)}get direction(){const t=this.component.bounds,e=this.anchor;if(!e)return _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,s=0;switch(this.direction){case vg:s=20;break;case bg:s=-20;break;case xg:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+s};const i=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(i.x,i.y)}}}class Mg extends Cc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const s=t.get(n.component)||n.component;this.set(e,{...n,component:s})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._fromEnd=new wg({component:s,fromto:"from",anchor:e,position:n,self:this})}return this._fromEnd}get from(){return this.getState("from")}set from(t){delete this._fromEnd,this.set("from",t)}get toEnd(){if(this.parent&&!this._toEnd){const{component:t,anchor:e,position:n}=this.getState("to")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._toEnd=new wg({component:s,fromto:"to",anchor:e,position:n,self:this})}return this._toEnd}get to(){return this.getState("to")}set to(t){delete this._toEnd,this.set("to",t)}move({x:t,y:e},n){n&&(this.from={position:this._fromEnd?.position||this.getState("from")?.position||{x:0,y:0}},this.to={position:this._toEnd?.position||this.getState("to")?.position||{x:0,y:0}}),super.move({x:t,y:e})}render(t){const{begin:e="none",end:n="none",lineWidth:s,round:i=0}=this.state;let r=this.drawPath;mg(t,r,this.state),t.beginPath();const o=fg(e,s,r[0],r[1]),a=fg(n,s,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,i),s=Math.sqrt((o.x-e.x)**2+(o.y-e.y)**2),a=0!==s?Math.atan2(o.x-e.x,o.y-e.y):0,l=Math.sin(a)*Math.min(n,s/2)+e.x,h=Math.cos(a)*Math.min(n,s/2)+e.y,d=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 s=r[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!s){t.lineTo(l.x,l.y);break}const o=Zr(l,i);let a=Math.sqrt((n.x-l.x)*(n.x-l.x)+(n.y-l.y)*(n.y-l.y)),c=0!==a?Math.atan2(n.x-l.x,n.y-l.y):0,h=Math.sin(c)*Math.min(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((s.x-l.x)*(s.x-l.x)+(s.y-l.y)*(s.y-l.y)),c=0!==a?Math.atan2(s.x-l.x,s.y-l.y):0,h=Math.sin(c)*Math.min(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(s,i),n=Math.sqrt((l.x-s.x)**2+(l.y-s.y)**2),r=0!==n?Math.atan2(l.x-s.x,l.y-s.y):0,o=Math.sin(r)*Math.min(e,n/2)+s.x,a=Math.cos(r)*Math.min(e,n/2)+s.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:s,x2:i,y2:r}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:s},this.toEnd?.position||e?.position||{x:i,y:r}]}set path(t){const[e,n]=t,{from:s,to:i}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...s,position:e},to:{...i,position:n}})}get textBounds(){const t=this.drawPath;let e,n,s=0;for(let i=1;i<t.length;i++){const r=t[i-1],o=t[i],a=(r.x-o.x)*(r.x-o.x)+(r.y-o.y)*(r.y-o.y);a>s&&(s=Math.ceil(a),e=r,n=o)}let{paddingTop:i,paddingLeft:r,paddingRight:o,paddingBottom:a}=this.state;return a||=0,i||=0,r||=0,o||=0,{left:Math.min(e.x,n.x)+r,top:Math.min(e.y,n.y)+i,width:Math.max(Math.abs(e.x-n.x)-r-o,0),height:Math.max(Math.abs(e.y-n.y)-i-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 Eg extends(lm(Tc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:s,ry:i,startAngle:r,endAngle:o,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(s),Math.abs(i),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:s}=this.state;return[{x:t-n,y:e-s},{x:t+n,y:e-s},{x:t+n,y:e+s},{x:t-n,y:e+s}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2,rx:(n.x-e.x)/2,ry:(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s,rx:i,ry:r}=this.state,o=(t-n)/(2*i-.5),a=(e-s)/(2*r-.5);return o*o+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:s,rx:i,ry:r}=t.model,o=2*Math.PI*e,a=n+i*Math.cos(o),c=s+r*Math.sin(o);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:s,height:i}=t.bounds,r=e+s/2,o=n+i/2;return[{name:"TOP",position:{x:r,y:n}},{name:"RIGHT",position:{x:e+s,y:o}},{name:"BOTTOM",position:{x:r,y:n+i}},{name:"LEFT",position:{x:e,y:o}}]}(this)}get nature(){return Sg}}Cc.memoize(Eg.prototype,"path",!1),Cc.register("ellipse",Eg);const Ag={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,s,i){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=s?`${n.label}: ${s}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,r+l/2,o+h-4),t.restore()),i&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${i}`,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,Ag.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 s=n[e+1];n[e+1]={...s||{},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 s=!1;return n.forEach((i,r)=>{const o=(r+n.length+1)%n.length,a=i.x,c=i.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}get controls(){const t=this.path;return t.map((e,n)=>{const s=t[n+1>=t.length?0:n+1];return{x:(e.x+s.x)/2,y:(e.y+s.y)/2,handler:Dg}})}get nature(){return zg}}Cc.memoize(Rg.prototype,"controls",!1),Cc.register("polygon",Rg);const jg=[];class Lg extends(sh(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:s=!1}="boolean"==typeof e?{ghost:e}:e,i=t.parent;if(i){if(this===i)return;i.removeComponent(t,n||s)}const r=this._components.push(t)-1;s&&(t._silentAdd=!0),t.parent=this,t.added(this),n||s||this.trigger("add",this,t,r),t.delegate_on(this),s?(i&&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 s=t.parent;s&&s.removeComponent(t,n);const i=this._components.splice(0,e);this._components=i.concat(t,this._components),e=this._components.indexOf(t),t.parent=this,t.added(this),n||this.trigger("add",this,t,e),t.delegate_on(this),n||t.trigger("added",this,t,e)}add(t,e=!1){return t instanceof Array?(t.forEach(t=>{-1==this._components.indexOf(t)&&this.addComponent(t,e)}),this):this.add.call(this,[t],e)}remove(t,e=!1){return t instanceof Array?this._components?(t.forEach(t=>this.removeComponent(t,e)),this):this:this.remove.call(this,[t],e)}getAt(t){if(this._components)return this._components[t]}forEach(t,e){this._components&&this._components.forEach(t,e)}traverse(t,e){t.call(e,this),this._components&&this._components.forEach(n=>{n.isContainer()?n.traverse(t,e):t.call(e,n)})}indexOf(t){return(this._components||jg).indexOf(t)}size(){return(this._components||jg).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let s=this._components.splice(0,n);const i=this._components.splice(1);this._components=s.concat(i),t=Math.max(0,t),t=Math.min(t,this._components.length),s=this._components.splice(0,t),this._components=s.concat(e,this._components)}moveChildForward(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this._components[e]=this._components[e+1],this._components[e+1]=t)}moveChildBackward(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this._components[e]=this._components[e-1],this._components[e-1]=t)}moveChildToFront(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=n.concat(s,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=this._components.concat(n,s)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return ec(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let s=this.components.length-1;s>=0;s--){const i=this.components[s].findAll(t,...e);i&&(n=n.concat(i))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return ec(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const s=this.components[n].findFirst(t,...e);if(null!=s)return s}return t(this,...e)?this:void 0}}findById(t){return this.root.findAllById?.(t)?.[0]}findByRefid(t){return this.root.findByRefid?.(t)}capture(t,e,n){if(!this.app.isEditMode&&this.hidden)return!1;const s=this.fromParent(t,e);if(!this.contains(s.x,s.y))return!1;const i=this.bounds;s.x-=i.left,s.y-=i.top;const r=this.layout.capturables(this);for(let i=r.length-1;i>=0;i--){const o=r[i];let a;if(a="static"==o.position?o.capture(s.x,s.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:s,top:i,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<s||a.x>s+r||a.y<i||a.y>i+o)return!1;a.x-=s,a.y-=i,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const s=a[t];if(!s.isContainer())continue;const i=s.capturePath(n,e);if(i)return i}return this.focusible&&this}render(t){"popup"!==this.position&&super.render(t)}postrender(t){if("popup"===this.position)return void super.postrender(t);const e=this.layout.drawables(this);if(e.length>0){let{left:n=0,top:s=0,width:i,height:r}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,s,i,r),t.clip(),t.closePath()),t.translate(n,s),e.forEach(e=>{const n=this.root?.transitionEffect;n?.isReparenting(e)||e.draw(this.position&&"static"!==this.position?t:this.getContext(e))}),t.translate(-n,-s),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>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 s=n[e];n[e]={...s||{},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 s=t[n],i=t[n+1];0==n&&e.push({x:s.x,y:s.y,handler:Fg}),e.push({x:(s.x+i.x)/2,y:(s.y+i.y)/2,handler:Fg}),n==t.length-2&&e.push({x:i.x,y:i.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:s,boundaryPosition:i=t}=this.fromEnd||{},{component:r,direction:o,boundaryPosition:a=e}=this.toEnd||{},c=[i,a],l=[];i&&l.push(i);let h,d=n?.bounds;d&&(h=n.toScene(d.left,d.top),h=this.transcoordT2P(h.x,h.y),d={...d,left:h.x,top:h.y});const u=d?{left:d.left-20,top:d.top-20,width:d.width+40,height:d.height+40}:{left:i.x,top:i.y,width:0,height:0};d=d||u;let p=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,E,A,k,C,T=0,O=0;d.left+d.width<p.left?(w=0,M=1,k=s,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=s,v=(d.left+p.width+p.left)/2,T=d.left-v),d.top+d.height<p.top?(x=0,S=1,E=s,A=o,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,E=o,A=s,_=(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(A){case bg:switch(E){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(E){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(E){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(E){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(s){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 s=n[e-1];return t.x!==s.x||t.y!==s.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const s=n[e-1],i=n[e+1];return!(t.x===s.x&&t.x===i.x||t.y===s.y&&t.y===i.y)})}get nature(){return 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:s,height:i,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,s,i);else try{t.drawImage(this._image,e,n,s,i)}catch(r){t.drawImage(Gg.noimage,e,n,s,i)}else!this.app.isViewMode&&t.drawImage(Gg.noimage,e,n,s,i)}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:s}=this.state;if(n){this._image=new Image;try{s&&(this._image.crossOrigin=s),this._image.src=this.app.url(n)||""}catch(t){return void e(t)}this._image.onload=()=>{if(this.get("isGray")){const t=this._image.width,e=this._image.height;this._offcanvas=Cc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const s=function(t,e,n){let s;try{s=t.getImageData(0,0,e,n)}catch(t){return Qs("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const i=s.data;for(let t=0;t<e*n*4;t+=4){const e=i[t],n=i[t+1],r=i[t+2],o=Math.floor((e+n+r)/3);s.data[t]=o,s.data[t+1]=o,s.data[t+2]=o}return s}(n,t,e);n.putImageData(s,0,0)}t(this)},this._image.onerror=t=>{this._image&&!this._image.currentSrc&&(this._image=null),e(t)}}else t(this)}get src(){return this.get("src")}set src(t){this.set("src",t)}onchange(t,e){(t.hasOwnProperty("src")||t.hasOwnProperty("isGray"))&&(this._offcanvas=null,this._image=null,this.prepareIf(t.src))}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("image/"))return void(this.src=e[n])}}Cc.register("image-view",Gg);class Vg extends(ig(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,s,i=0,r=function(t){for(var n=0,s=0;s<t;s++)e.charCodeAt(i>>3)&1<<(7&i)&&(n|=1<<s),i++;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(s=n,(n=r(l))!==a){if(n===c)break;if(n<h.length)s!==a&&h.push(h[s].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[s].concat(h[s][0]))}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 s=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=s.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(s.splice(0,3)),e.userInput=s.shift(),e.transparencyGiven=s.shift(),e.delayTime=n.stream.readUnsigned(),e.transparencyIndex=n.stream.readByte(),e.terminator=n.stream.readByte(),n.handler.gce&&n.handler.gce(e)}(e);break;case 254:e.extType="com",function(t){t.comment=n.readSubBlocks(),n.handler.com&&n.handler.com(t)}(e);break;case 1:e.extType="pte",function(t){n.stream.readByte(),t.ptHeader=n.stream.readBytes(12),t.ptData=n.readSubBlocks(),n.handler.pte&&n.handler.pte(t)}(e);break;case 255:e.extType="app",function(t){n.stream.readByte(),t.identifier=n.stream.read(8),t.authCode=n.stream.read(3),"NETSCAPE"===t.identifier?function(t){n.stream.readByte(),t.unknown=n.stream.readByte(),t.iterations=n.stream.readUnsigned(),t.terminator=n.stream.readByte(),n.handler.app&&n.handler.app.NETSCAPE&&n.handler.app.NETSCAPE(t)}(t):function(t){t.appData=n.readSubBlocks(),n.handler.app&&n.handler.app[t.identifier]&&n.handler.app[t.identifier](t)}(t)}(e);break;default:e.extType="unknown",function(t){t.data=n.readSubBlocks(),n.handler.unknown&&n.handler.unknown(t)}(e)}},e.prototype.parseImg=function(e){e.leftPos=this.stream.readUnsigned(),e.topPos=this.stream.readUnsigned(),e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.lctFlag&&(e.lct=this.parseCT(1<<e.lctSize+1)),e.lzwMinCodeSize=this.stream.readByte();var s=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,s),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),s=t.length/e,i=function(s,i){var r=t.slice(i*e,(i+1)*e);n.splice.apply(n,[s*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<s;l+=o[c])i(l,a),a++;return n}(e.pixels,e.width)),this.handler.img&&this.handler.img(e)},e.prototype.parseBlock=function(){var t={};switch(t.sentinel=this.stream.readByte(),String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this.handler.eof&&this.handler.eof(t);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&setTimeout(this.parseBlock.bind(this),0)},e.prototype.parse=function(){this.parseHeader(),setTimeout(this.parseBlock.bind(this),0)},e}();return 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 s in this.gifImgElement=t,this.options={autoPlay:!0},this.loading=!1,this.ready=!1,this.transparency=null,this.delay=null,this.disposalMethod=null,this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,this.playing=!0,this.forward=!0,this.ctxScaled=!1,this.frames=[],this.frameOffsets=[],this.initialized=!1,this.currentFrameIndex=-1,this.iterationCount=0,this.stepping=!1,this.handler={hdr:this.withProgress(this.doHdr.bind(this)),gce:this.withProgress(this.doGCE.bind(this)),com:this.withProgress(this.doNothing.bind(this)),app:{NETSCAPE:this.withProgress(this.doNothing.bind(this))},img:this.withProgress(this.doImg.bind(this)),eof:function(){n.pushFrame(),n.canvas.width=n.hdr.width*n.getCanvasScale(),n.canvas.height=n.hdr.height*n.getCanvasScale(),n.playerInit(),n.loading=!1,n.ready=!0,n.loadCallback&&n.loadCallback(n.gifImgElement)}},e)this.options[s]=e[s];this.onEndListener=e.onEnd,this.loopDelay=e.loopDelay||0,this.overrideLoopMode=null!=e.loopMode?e.loopMode:"auto",this.drawWhileLoading=null==e.drawWhileLoading||e.drawWhileLoading}return n.prototype.init=function(){var t=this.gifImgElement.parentNode,e=document.createElement("div");this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"),this.tmpCanvas=document.createElement("canvas"),e.className=this.options.enclosingClass||"super-gif",e.appendChild(this.canvas),t&&(t.insertBefore(e,this.gifImgElement),t.removeChild(this.gifImgElement)),this.initialized=!0},n.prototype.loadSetup=function(t){return!this.loading&&(t&&(this.loadCallback=t),this.loading=!0,this.frames=[],this.clear(),this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,!0)},n.prototype.completeLoop=function(){this.onEndListener&&this.onEndListener(this.gifImgElement),this.iterationCount++,!1!==this.overrideLoopMode||this.iterationCount<0?this.doStep():(this.stepping=!1,this.playing=!1)},n.prototype.doStep=function(){if(this.stepping=this.playing,this.stepping){this.stepFrame(1);var t=10*this.frames[this.currentFrameIndex].delay;t||(t=100),0===this.getNextFrameNo()?(t+=this.loopDelay,setTimeout(this.completeLoop.bind(this),t)):setTimeout(this.doStep.bind(this),t)}},n.prototype.step=function(){this.stepping||setTimeout(this.doStep.bind(this),0)},n.prototype.putFrame=function(){var t;this.currentFrameIndex=parseInt(this.currentFrameIndex.toString(),10),this.currentFrameIndex>this.frames.length-1&&(this.currentFrameIndex=0),this.currentFrameIndex<0&&(this.currentFrameIndex=0),t=this.frameOffsets[this.currentFrameIndex],this.tmpCanvas.getContext("2d").putImageData(this.frames[this.currentFrameIndex].data,t.x,t.y),this.canvasContext.globalCompositeOperation="copy",this.canvasContext.drawImage(this.tmpCanvas,0,0)},n.prototype.playerInit=function(){this.loadErrorCause||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.options.autoPlay?this.step():(this.currentFrameIndex=0,this.putFrame()))},n.prototype.clear=function(){this.transparency=null,this.delay=null,this.lastDisposalMethod=this.disposalMethod,this.disposalMethod=null,this.frame=null},n.prototype.parseStream=function(e){try{new t.SuperGifParser(e,this.handler).parse()}catch(t){this.handleError("parse")}},n.prototype.setSizes=function(t,e){this.canvas.width=t*this.getCanvasScale(),this.canvas.height=e*this.getCanvasScale(),this.tmpCanvas.width=t,this.tmpCanvas.height=e,this.tmpCanvas.style.width=t+"px",this.tmpCanvas.style.height=e+"px",this.tmpCanvas.getContext("2d").setTransform(1,0,0,1,0,0)},n.prototype.drawError=function(){this.canvasContext.fillStyle="black",this.canvasContext.fillRect(0,0,this.hdr.width,this.hdr.height),this.canvasContext.strokeStyle="red",this.canvasContext.lineWidth=3,this.canvasContext.moveTo(0,0),this.canvasContext.lineTo(this.hdr.width,this.hdr.height),this.canvasContext.moveTo(0,this.hdr.height),this.canvasContext.lineTo(this.hdr.width,0),this.canvasContext.stroke()},n.prototype.handleError=function(t){this.loadErrorCause=t,this.hdr={width:this.gifImgElement.width,height:this.gifImgElement.height},this.frames=[],this.drawError()},n.prototype.doHdr=function(t){this.hdr=t,this.setSizes(this.hdr.width,this.hdr.height)},n.prototype.doGCE=function(t){this.pushFrame(),this.clear(),this.transparency=t.transparencyGiven?t.transparencyIndex:null,this.delay=t.delayTime,this.disposalMethod=t.disposalMethod},n.prototype.pushFrame=function(){this.frame&&(this.frames.push({data:this.frame.getImageData(0,0,this.hdr.width,this.hdr.height),delay:this.delay}),this.frameOffsets.push({x:0,y:0}))},n.prototype.doImg=function(t){var e=this;this.frame||(this.frame=this.tmpCanvas.getContext("2d"));var n=this.frames.length,s=t.lctFlag?t.lct:this.hdr.gct;n>0&&(3===this.lastDisposalMethod?null!==this.disposalRestoreFromIdx?this.frame.putImageData(frames[this.disposalRestoreFromIdx].data,0,0):this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height):this.disposalRestoreFromIdx=n-1,2===this.lastDisposalMethod&&this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height));var i=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(i.data[4*n+0]=s[t][0],i.data[4*n+1]=s[t][1],i.data[4*n+2]=s[t][2],i.data[4*n+3]=255)}),this.frame.putImageData(i,t.leftPos,t.topPos),this.ctxScaled||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.ctxScaled=!0),this.drawWhileLoading&&(this.canvasContext.drawImage(this.tmpCanvas,0,0),this.drawWhileLoading=this.options.autoPlay),this.lastImg=t},n.prototype.doNothing=function(){},n.prototype.withProgress=function(t){return function(e){t(e)}},n.prototype.getNextFrameNo=function(){var t=this.forward?1:-1;return(this.currentFrameIndex+t+this.frames.length)%this.frames.length},n.prototype.stepFrame=function(t){this.currentFrameIndex=this.currentFrameIndex+t,this.putFrame()},n.prototype.getCanvasScale=function(){return this.options.maxWidth&&this.hdr&&this.hdr.width>this.options.maxWidth?this.options.maxWidth/this.hdr.width:window.devicePixelRatio||1},n.prototype.play=function(){this.playing=!0,this.step()},n.prototype.pause=function(){this.playing=!1},n.prototype.isPlaying=function(){return this.playing},n.prototype.getCanvas=function(){return this.canvas},n.prototype.isLoading=function(){return this.loading},n.prototype.isReady=function(){return this.ready},n.prototype.isAutoPlay=function(){return this.options.autoPlay},n.prototype.getLength=function(){return this.frames.length},n.prototype.getCurrentFrame=function(){return this.currentFrameIndex},n.prototype.moveTo=function(t){this.currentFrameIndex=t,this.putFrame()},n.prototype.loadURL=function(t,n){var s=this;if(this.loadSetup(n)){var i=new XMLHttpRequest;i.open("GET",t,!0),"overrideMimeType"in i?i.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in i?i.responseType="arraybuffer":i.setRequestHeader("Accept-Charset","x-user-defined"),i.onloadstart=function(){s.initialized||s.init()},i.onload=function(){if(200===i.status){var t=i.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){s.parseStream(n)},0)}else s.handleError("xhr - response")},i.onerror=function(){s.handleError("xhr")},i.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return 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 sy 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",sy);const iy={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:s,height:i}=this.state;t.beginPath(),this.drawImage(t,ry.image,e,n,s,i)}get nature(){return iy}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 Qs(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 s=super.capture(t,e,n);if(s!==this)return s}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,s=t.height/e.height;this.path=this.path.map(i=>({x:t.left+(i.x-e.left)*n,y:t.top+(i.y-e.top)*s})),this.components&&this.components.forEach(t=>{if(t.mutable)t.mutatePath(null,function(t){return t.map(function(t){return{x:t.x*n,y:t.y*s}})});else{const e=t.bounds,i=t.center,r={x:i.x*(1-n),y:i.y*(1-s)},o=e.width*(1-n),a=e.height*(1-s),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*s}}})}get focusible(){return!1}get bounds(){return super.bounds}get hasTextProperty(){return!1}isIdentifiable(){return!1}calculateBounds(){this.clearCache(),this.__MUTATING__=!0,this.mutateBounds(function(t){const e=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,s=n.width/e.width,i=n.height/e.height;return"both"===this.model.fit?{x:s,y:i}:{x:Math.min(s,i),y:Math.min(s,i)}}draw(t){this._drawing||(this._drawing=!0,super.draw(t),this._drawing=!1)}prerender(t){if(super.prerender(t),this.ref){const e=this.ref.center,n=this.center,s=this.refScale;t.translate(n.x,n.y),t.scale(s.x,s.y),t.translate(-e.x,-e.y)}}postrender(t){if(this.ref)return this.ref.postrender(t);super.postrender(t)}render(t){if(this.ref)return this.ref.render(t);const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),t.rect(e,n,s,i)}get nature(){return 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(ig(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 s=(async()=>{this.__ref=await n.get(t,!0),this.__ref.target=this.element,this.__ref.fit(e),this.__ref.data=this.data})();this.root?.app?.loadTracker?.track(`ref:${t}`,"ref-board",t,s);try{await s}catch(t){Qs(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:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,gy.image,e,n,s,i)}onchange(t,e){"value"in t?this.show?this.onchangeShow(!0):this.show=!0:"show"in t&&this.onchangeShow(this.show)}onchangeShow(t){if(this.app.isEditMode)return;(this.getState("board")||this.getState("containerRef")||this.getState("htmlTemplate"))&&(t?this.openPopup(this.value):this.hidePopup())}openPopup(t,e){if(this.app.isEditMode)return;const n=this.getState("anchorRef"),s=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;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:s,anchorPin:this.getState("anchorPin")||"top",anchorOffsetX:this.getState("anchorOffsetX")??0,anchorOffsetY:this.getState("anchorOffsetY")??0,anchorOffsetZ:this.getState("anchorOffsetZ")??0,constantSize:this.getState("constantSize")??!0,tether:this.getState("tether")??!1,offScreen:this.getState("offScreen")||"hide",...e})}hidePopup(){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 s=!1;return n.forEach((i,r)=>{const o=(r+n.length+1)%n.length,a=i.x,c=i.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}}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:s,x2:i,y2:r,x3:o,y3:a}=this.state,c=[n,s,i,r,o,a];let l=!1;for(let n=0;n<c.length;n+=2){const s=(n+2)%c.length,i=c[n],r=c[n+1],o=c[s+1];r>e!=o>e&&t<(c[s]-i)*(e-r)/(o-r)+i&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:s,x3:i,y3:r}=this.state;return[{x:t,y:e},{x:n,y:s},{x:i,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:s,rx:i}=n.model;i=Math.abs(i);let r=(n.fromParent(t.x,t.y).x-s)/i*100;r=r>=100||r<=-100?100:Math.abs(r),n.set({ratio:r})}};class Sy extends Eg{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:s,rx:i,ry:r,startAngle:o,endAngle:a,anticlockwise:c}=this.state;i=Math.abs(i),r=Math.abs(r),t.beginPath(),t.ellipse(n,s,i,r,0,o||0,a||2*Math.PI,c),t.moveTo(n+i/100*e,s),t.ellipse(n,s,i/100*e,r/100*e,0,o||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:s,rx:i,ry:r,ratio:o}=this.state;i=Math.abs(i),r=Math.abs(r);const a=(t-n)/(2*i-.5),c=(e-s)/(2*r-.5),l=(t-n)/(i/100*o*2-.5),h=(e-s)/(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:s}=this.state;return n=Math.abs(n),[{x:t+n/100*s,y:e,handler:My}]}get nature(){return wy}}Cc.memoize(Sy.prototype,"controls",!1),Cc.register("donut",Sy);const Ey={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"},Ay={ondragmove:function(t,e,n){const{cy:s,ry:i}=n.model;let r=(n.fromParent(t.x,t.y).y-s)/i*100+100;r>=100?r=100:r<=0&&(r=0),n.set({ratio:r})}};class ky extends Eg{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:s,cy:i,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(s,i),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:s}=this.state;return[{x:t,y:e-n+n*(s/100),handler:Ay}]}get nature(){return Ey}}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:s}=this.state,i=this.app?.scale||1;t.beginPath(),t.scale(1/i,1/i),t.ellipse(e,n,Math.abs(Ty.RADIUS),Math.abs(Ty.RADIUS),0,0,2*Math.PI,s),t.scale(i,i),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-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:s}=this.state,i=(t-n)/(2*Ty.RADIUS-.5),r=(e-s)/(2*Ty.RADIUS-.5);return i*i+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,s=this.component.state.depth||.5*Math.min(e,n),i=.15*Math.min(e,n,s),r=new R(1,1,1,4,i/Math.min(e,n,s));r.scale(e,s,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 s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,r=s.max.y-s.min.y,o=s.max.z-s.min.z;this.setDimensionScale(t/i,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:s,height:i}=this.bounds,r=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,r,e,n,s,i),t.globalAlpha=1}added(t){super.added(t);const e=this.serviceName;e&&(this._registeredRoot=this.root,this._registeredRoot?.registerService?.(e,this))}removed(t){const e=this.serviceName;e&&this._registeredRoot&&(this._registeredRoot.unregisterService?.(e),this._registeredRoot=void 0),super.removed(t)}get controls(){return[]}}function 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 s;s=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-s,this.animate({step:t=>{this._anim_alpha=s*(t-1),this.invalidate()},duration:1e3,delta:"circ",options:{x:1},ease:"out"}).start()}dispose(){super.dispose(),delete this._value_substitutor}onchange(t,e){t.hasOwnProperty("value")&&delete this._value_substitutor}get animAlpha(){return this._anim_alpha||0}get animValue(){return(this._lastValue||0)+(this._anim_alpha||0)}defaultValueSubstitutor(){return this.getState("value")}get valueSubstitutor(){return this._value_substitutor||(this._value_substitutor=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(xs(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 s=this.parentNode?.querySelector("[name=playTargets]");s&&(s.src=t)}},{type:"gltf-info",label:"",name:"gltfInfo",readonly:!0,property:{action:(t,e)=>{t._ratioLocking=!0;try{t.set(e)}finally{t._ratioLocking=!1}}},editor:{fullwidth:!0}},{type:"gltf-fill-targets",label:"fill-targets",name:"fillStyleTargets",editor:{fullwidth:!0}},{type:"gltf-play-targets",label:"play-targets",name:"playTargets",editor:{fullwidth:!0}}];function 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:s,height:i}=this.bounds;t.beginPath();const r=this._topViewSnapshot;if(r)return void t.drawImage(r,e,n,s,i);this._ensureTopViewSnapshot(),t.rect(e,n,s,i),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const o=this.getState("src"),a=o&&o.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(s,i));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+s/2,n+i/2,.9*s)}onchange(t,e){super.onchange?.(t,e),"src"in t&&(this._topViewSnapshot=void 0)}_ensureTopViewSnapshot(){if(this._snapshotLoading)return;const t=this.getState("src");if(!t)return;const e=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 s=Ou.renderTopView(e.scene);Ou.setTopViewCache(t,s),this._topViewSnapshot=s,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:s=1}=t;this.setState({width:e,height:n,depth:s}),this.realObject?.updateDimension()}_applyRatioLock(t){if(!("width"in t||"height"in t||"depth"in t))return t;const e=this.state.width||1,n=this.state.height||1,s=this.state.depth||1,i=Of([(t.width??e)/e,(t.height??n)/n,(t.depth??s)/s]);return i?{...t,width:Math.round(e*i),height:Math.round(n*i),depth:Math.round(s*i)}:t}set(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.set(t)}finally{this._ratioLocking=!1}}setState(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.setState(t)}finally{this._ratioLocking=!1}}}}function 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()),s=e.onAvailable(()=>t.resumeEmit());return Hy(e).isFull&&t.pauseEmit(),()=>{n?.(),s?.()}}class Gy{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,s){const i=e.maxCount??1/0;if(t<0||t>=i)return null;const r=this.owner?.state?.width??0,o=this.owner?.state?.height??0,a=s?.state?.width??0,c=s?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(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,s,i,r,o){const a=n.w,c=n.h,l=s.w,h=s.h,d=s.d,u=[],p=l+i,f=h+i,m=Math.max(1,Math.floor((a+i)/p)),g=Math.max(1,Math.floor((c+i)/f)),y=m*g,b=r&&r>0?Math.floor(r):4;if("row"===t||"column"===t){const n=o?.advanceAlongX??!1,s=o?.reverse??!1,i=n?m:g,r=n?g:m,l=(t,e,s)=>((t,e,n)=>u.push({x:-a/2+(t+.5)*p,y:n*d+d/2,z:-c/2+(e+.5)*f}))(n?t:e,n?e:t,s);let h=0;for(let n=0;n<i&&h<e;n++){const o=s?i-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),s=Math.max(1,g-n),i=e*s,o=Math.min(t,i);for(let t=0;t<o;t++){const i=t%e,r=Math.floor(t/e),o=-a/2+(i+(m-e)/2+.5)*p,l=-c/2+(r+(g-s)/2+.5)*f;u.push({x:o,y:n*d+d/2,z:l})}if(t-=o,n++,1===e&&1===s){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(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),s=n%y,i=s%m,o=Math.floor(s/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(i+.5)*p+g,_=-c/2+(o+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),r&&e>=r-1&&s===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(r&&e>=r)break;const s=n%y,i=s%m,o=Math.floor(s/m);let l=-a/2+(i+.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,s={}){const i=s.gap??this.defaults.gap??0,r=s.heightLimit??this.defaults.heightLimit,o=s.fill??this.defaults.fill;return Vy(this.pattern,t,e,n,i,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,s={}){const i=Math.max(1,this.cols),r=Math.max(1,this.rows),o=i*r,a=s.gap??this.defaults.gap??0,c=n.w+a,l=n.h+a,h=[];for(let e=0;e<t;e++){const t=Math.floor(e/o),s=e%o,a=s%i,d=Math.floor(s/i);h.push({position:{x:(a-(i-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,s=e.h*this.gapRatio;return{cols:Math.max(1,Math.floor((t.w-n)/(e.w+n))),rows:Math.max(1,Math.floor((t.h-s)/(e.h+s))),pitchX:e.w+n,pitchZ:e.h+s}}capacity(t,e,n){const{cols:s,rows:i}=this.grid(t,e);return s*i*Math.max(1,Math.floor(n))}layout(t,e,n,s={}){const{cols:i,rows:r,pitchX:o,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=s.heightLimit?Math.max(1,Math.floor(s.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=i*r,p=i*(h?l:1),f=i*r*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,s,l;if(d){const n=Math.floor(t/p),r=t%p;e=r%i,l=Math.floor(r/i),s=n}else{l=Math.floor(t/u);const n=t%u;e=n%i,s=Math.floor(n/i)}this.fillFromFar&&(s=r-1-s),g.push({position:{x:(e-(i-1)/2)*o,z:(s-(r-1)/2)*a,y:l*c+n.d/2}})}return g}}function Xy(t,e,n,s=0){for(let i=0;i<e.length;i++){const r=e[i],o=n[i];r&&o&&(r.parent!==t&&t.attach(r),r.position.set(o.position.x,s+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,s=.12){const i=e.left+e.width/2,r=e.top+e.height/2,o=Math.min(n.w,n.h)*s,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let s=a.get(t);s||(s={x:i+e.position.x-n.w/2+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,s)),s.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,s]of n)if(!e.has(t)){try{this.removeItem(s,!0)}catch{}try{s?.dispose?.()}catch{}}for(const[t,s]of e){if(n.has(t))continue;if(null==s.itemId)continue;const e=this._createItemFromRecord(s);if(e){e[tb]=t;try{this.handoverIn(e)}catch{}}}for(const[t,s]of e){const e=n.get(t);if(e&&(s.itemState&&"function"==typeof e.setState))try{e.setState(s.itemState)}catch{}}}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,s=[];for(const t of this._items){const e=t[tb];null!=e?n.set(String(e),t):s.push(t)}for(const s of t){const t=n.get(s)??null;e.push(this._slotRecordOf(s,t))}for(const t of s)e.push(this._slotRecordOf("",t));for(const[s,i]of n)t.includes(s)||e.push(this._slotRecordOf(s,i));return e}_recordKey(t){return t.slotId??t.cellId??""}_slotRecordOf(t,e){if(!e)return{slotId:t,itemId:null};const n=e?.state?.id;return{slotId:t,itemId:null!=n?String(n):null,itemType:e?.state?.type,itemState:this._extractItemState(e)}}_extractItemState(t){const e=t?.state;if(!e||"object"!=typeof e)return;const n=this._businessFields?.();if(Array.isArray(n)){if(0===n.length)return;const t={};for(const s of n)s in e&&void 0!==e[s]&&(t[s]=e[s]);return Object.keys(t).length>0?t:void 0}const s={};for(const t of Object.keys(e))eb.has(t)||t.startsWith("_")||(s[t]=e[t]);return Object.keys(s).length>0?s:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=Cc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}class sb{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const ib=new sb;function rb(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const ob=t=>"number"==typeof t&&Number.isFinite(t),ab=t=>ob(t)&&t>0,cb=t=>Number.isSafeInteger(t)&&t>0;function lb(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])ab(s[t])||n.push(rb("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(rb("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||cb(t.stackLimit)||t.stackLimit===1/0||n.push(rb("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||ob(t.rotation)||n.push(rb("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(rb("ARRAY_REQUIRED",`${e}.accepts`))}function hb(t){const e=[];return t&&Array.isArray(t.tiers)&&0!==t.tiers.length?(["ON","IN","HANG"].includes(t.mount)||e.push(rb("MOUNT_INVALID","mount")),t.tiers.forEach((n,s)=>{const i=`tiers[${s}]`;if(!n||"object"!=typeof n)return void e.push(rb("OBJECT_REQUIRED",i));n.tierNo!==s+1&&e.push(rb("TIER_NUMBER_SEQUENCE",`${i}.tierNo`)),ob(n.elevation)?s>0&&ob(t.tiers[s-1]?.elevation)&&n.elevation<=t.tiers[s-1].elevation&&e.push(rb("ELEVATION_NOT_ASCENDING",`${i}.elevation`)):e.push(rb("FINITE_NUMBER_REQUIRED",`${i}.elevation`));const r=n.layout;switch(r?.pattern){case"SINGLE":lb(r.slot,`${i}.layout.slot`,e);break;case"ROW":cb(r.count)||e.push(rb("POSITIVE_INTEGER_REQUIRED",`${i}.layout.count`)),ab(r.pitch)||e.push(rb("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch`)),"X"!==r.axis&&"Z"!==r.axis&&e.push(rb("AXIS_INVALID",`${i}.layout.axis`)),lb(r.slot,`${i}.layout.slot`,e);break;case"GRID":cb(r.rows)||e.push(rb("POSITIVE_INTEGER_REQUIRED",`${i}.layout.rows`)),cb(r.cols)||e.push(rb("POSITIVE_INTEGER_REQUIRED",`${i}.layout.cols`)),ab(r.pitch?.x)||e.push(rb("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch.x`)),ab(r.pitch?.z)||e.push(rb("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch.z`)),lb(r.slot,`${i}.layout.slot`,e);break;case"CUSTOM":{const t=Array.isArray(r.slots)?r.slots:[],n=t.map(t=>t?.slotNo).sort((t,e)=>t-e);n.length&&!n.some((t,e)=>t!==e+1)||e.push(rb("SLOT_NUMBER_SEQUENCE",`${i}.layout.slots`)),t.forEach((t,n)=>{ob(t?.offset?.x)&&ob(t?.offset?.z)||e.push(rb("FINITE_NUMBER_REQUIRED",`${i}.layout.slots[${n}].offset`)),lb(t,`${i}.layout.slots[${n}]`,e)});break}default:e.push(rb("PATTERN_INVALID",`${i}.layout.pattern`))}}),e):[rb("TIERS_REQUIRED","tiers")]}function db(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(rb("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}function ub(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 pb(t,e,n,s,i="ROW_MAJOR"){switch(i){case"ROW_MAJOR":return(n-1)*e+s;case"COL_MAJOR":return(s-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?s:e-s+1);case"SERPENTINE_COL":return(s-1)*t+(s%2==1?n:t-n+1)}}function fb(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const mb=(t,e)=>e&&0!==t?-t:t;function gb(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!cb(e.slot)||e.slot>ub(s.layout))return null;const i=s.layout;let r,o,a;switch(i.pattern){case"SINGLE":r=i.slot,o={x:0,z:0};break;case"ROW":{const t=mb((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);r=i.slot,o="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{const{r:t,c:n}=fb(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};r=i.slot,o={x:mb((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:mb((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,elevation:s.elevation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function yb(t){return`t${t.tier}_s${t.slot}`}function bb(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*vb(t){for(const e of t?.tiers??[])for(let t=1;t<=ub(e.layout);t++)yield{tier:e.tierNo,slot:t}}const _b=.05,xb=t=>"number"==typeof t&&Number.isFinite(t),wb=t=>xb(t)&&t>0,Mb=t=>!!t&&wb(t.width)&&wb(t.depth)&&wb(t.height);function Sb(t,e){const n=e*Math.PI/180,s=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),r=t=>Math.round(1e9*t)/1e9;return{width:r(t.width*s+t.depth*i),depth:r(t.width*i+t.depth*s)}}function Eb(t,e,n,s=0,i=.05){if(!Mb(t))return null;if(!xb(s)||!xb(i)||i<0||i>=1)return null;const r=Sb(t,e.rotation),o=Math.min(1,Math.min(e.allowed.width/r.width,e.allowed.depth/r.depth)*(1-i)),a=t.height*o,c="HANG"===n?-1:1,l=e.elevation+c*(s+a/2);return{position:{x:e.offset.x,y:l,z:e.offset.z},rotation:e.rotation,scale:o}}function Ab(t,e,n,s=.05){let i=0;return t.map(t=>{const r=t?Eb(t,e,n,i,s):null;return r&&(i+=t.height*r.scale),r})}function kb(t){return{x:t.offset.x,y:t.elevation,z:t.offset.z}}function Cb(t,e,n,s=0,i=.05){const r=Eb(t,e,n,s,i);return r?{position:{x:0,y:r.position.y-e.elevation,z:0},rotation:r.rotation,scale:r.scale}:null}function Tb(t,e,n=[],s={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const i=s.normalizeType??(t=>null==t?"":String(t)),r=[];let o=!1;if(t.accepts){const n=i(e.type);n?t.accepts.map(i).includes(n)||r.push("TYPE_NOT_ACCEPTED"):o=!0}if(n.length+1>t.stackLimit&&r.push("STACK_LIMIT_EXCEEDED"),Mb(e.dims)){const s=Sb(e.dims,t.rotation);if(s.width>t.allowed.width&&r.push("WIDTH_EXCEEDED"),s.depth>t.allowed.depth&&r.push("DEPTH_EXCEEDED"),n.every(t=>Mb(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:[]}}const Ob=[{id:"__default__",maxCount:1/0}];function Pb(t){const e={id:yb({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function Ib(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 Db(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 vb(t)){const s=gb(t,n);s&&e.push(Pb(s))}return e}slotById(t){const e=this.slotLayout;if(e){const n=bb(t),s=n?gb(e,n):null;return s?Pb(s):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,s){const i=this.slotLayout,r=i?bb(t):null,o=r?gb(i,r):null;return o?Eb(e,o,i.mount,n,s):null}get arrangementStrategy(){return ib}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:Ob;for(const n of e){if(!Ib(n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),s=this._countOccupied(n.id);if(!(s>=e))return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:{slotId:n.id,occupied:s,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 s=this._realObject?.object3d;if(!s)return;s.updateWorldMatrix(!0,!1);const i=new t.Quaternion;s.getWorldQuaternion(i);const r=new t.Quaternion(n.x,n.y,n.z,n.w);return i.clone().multiply(r)}deliveryWorldPosition(e){const n=this._realObject,s=n?.object3d;if(!s)return;s.updateWorldMatrix(!0,!1);const i=new t.Vector3;s.getWorldPosition(i);const r=this._receivingSurfaceLocalY();if(null!==r){const e=new t.Vector3(0,r,0);return s.localToWorld(e),{x:i.x,y:e.y,z:i.z}}return{x:i.x,y:i.y,z:i.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,s=n?n.state??{}:t??{},i={width:Number(s.width)||0,height:Number(s.height)||0,depth:Number(s.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:{...i}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+i.width/2-l/2,u=c.y+i.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-i.depth/2:i.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:r.localPosition&&Number.isFinite(r.localPosition.z)?r.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??i,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 s=this._realObject,i=s?.receivingSurfaceY??0,r=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===i&&!r)return null;const o=Number(e)||0,a=s?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-o/2:o/2)+(s?.geometricOffsetY??0)-i}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!Ib(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 zb(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,r=t.height??0;if(i<=0||r<=0)return[];const o="number"==typeof t.rotation?t.rotation:0,a=Math.cos(o),c=Math.sin(o),l=n+i/2,h=s+r/2,d="inbound"===e?-1:1;return[{lx:-i/2,lz:0,odx:-1,odz:0},{lx:i/2,lz:0,odx:1,odz:0},{lx:0,lz:-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:i/2}})}function Rb(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,r=t.height??0;if(i<=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&&i<r,l=n+i/2,h=s+r/2,d=c?r/2:i/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},E=(c?i:r)/2;return a?{inbounds:[{worldPos:_,direction:S,halfSpan:E}],outbounds:[{worldPos:v,direction:S,halfSpan:E}]}:{inbounds:[{worldPos:v,direction:M,halfSpan:E}],outbounds:[{worldPos:_,direction:M,halfSpan:E}]}}function jb(t){const e=t.left??0,n=t.top??0,s=t.width??0,i=t.height??0;if(s<=0||i<=0)return null;const r="number"==typeof t.rotation?t.rotation:0,o="vertical"===t.orientation||"horizontal"!==t.orientation&&s<i,a=e+s/2,c=n+i/2,l=o?i/2:s/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 Lb(t){const e=t.cx??0,n=t.cy??0,s=Math.abs(t.rx??100),i=Math.abs(t.ry??100),r=t.ratio??50,o=(s+s*r/100)/2,a=(i+i*r/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(s<=0||i<=0)return{inbounds:[],outbounds:[]};const d={x:e+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 Fb(t){const e=Rb(t),n=e.outbounds[0];if(!n)return{inbounds:zb(t,"inbound"),outbounds:[]};const s=zb(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,s=t.worldPos.z-n.worldPos.z;return Math.hypot(e,s)>1}),i=n.direction,r=[];for(const t of s){const e=t.direction.x*i.x+t.direction.z*i.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+i.x,s=t.direction.z+i.z,o=Math.hypot(n,s)||1;r.push({worldPos:t.worldPos,direction:{x:n/o,z:s/o},halfSpan:t.halfSpan})}return{inbounds:[...s,...r],outbounds:e.outbounds}}function Nb(t,e,n={}){const s=n.distance??5,i=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<i)return!1;const 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,i=t.direction.z;if(Math.abs(r*n+o*i)>s)return!1;const a=Math.abs(r*-i+o*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(r,o)<=s}function $b(t,e,n,s=0){const i=n.width??0,r=n.height??0;if(i<=0||r<=0)return!1;const o=(n.left??0)+i/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)<=i/2+s&&Math.abs(f)<=r/2+s}function Hb(t,e,n){const s=n.width??0,i=n.height??0;if(s<=0||i<=0)return 1/0;const r=(n.left??0)+s/2,o=(n.top??0)+i/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,s=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=s}const u=s/2,p=i/2;let f=-1/0,m=1/0;if(Math.abs(l)<1e-9){if(a<-u||a>u)return 1/0}else{const t=(-u-a)/l,e=(u-a)/l;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}if(Math.abs(h)<1e-9){if(c<-p||c>p)return 1/0}else{const t=(-p-c)/h,e=(p-c)/h;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}return m<f?1/0:f>=0?f:m>=0?Math.min(-f,m):-m}function Bb(t,e,n,s=6){return!!$b(t.worldPos.x,t.worldPos.z,e,s)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function Yb(t,e,n){return t.outbounds.map(t=>{const s=[];for(const i of e){let e=null;for(const s of i.topology.inbounds){if(!Nb(t,s,n))continue;const i=t.worldPos.x-s.worldPos.x,r=t.worldPos.z-s.worldPos.z,o=Math.hypot(i,r);(null===e||o<e)&&(e=o)}if(null===e&&i.bounds){const s=i.topology.outbounds[0]?.direction,r=!(i.topology.outbounds&&i.topology.outbounds.length)?n?.sinkMargin??30:6;if(Bb(t,i.bounds,s,r)){const n=Hb(t.worldPos,t.direction,i.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(i.bounds.left??0)+(i.bounds.width??0)/2,s=(i.bounds.top??0)+(i.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-s)+1e3}}}null!==e&&s.push({id:i.id,dist:e})}return 0===s.length?null:(s.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),s[0].id)})}function Gb(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const s=new Map,i=new Set;for(const n of t){const r=t.filter(t=>t.id!==n.id),o=Yb(n.topology,r,e);s.set(n.id,o);for(const t of o)null!=t&&i.add(t)}const r=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const r=s.get(t)??[];r.includes(e)||(r.push(e),s.set(t,r),i.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){(s.get(e.id)??[]).some(t=>null!=t)||o.add(e.id),i.has(e.id)||a.add(e.id)}return{nodes:n,out:s,sinks:o,sources:a}}function Vb(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const s=new Set([e]);for(const i of function(t,e,n){const s=n.get(e);if(s)return s;const i=new Set,r=[e],o=new Set([e]);for(;r.length;){const e=r.shift();for(const n of t.out.get(e)??[])null!=n&&(i.add(n),o.has(n)||(o.add(n),r.push(n)))}return n.set(e,i),i}(t,e,n))s.add(i);return s})}function Ub(t,e,n,s){return e===n?0:function(t,e,n){const s=n.get(e);if(s)return s;const i=new Map([[e,0]]),r=[e];for(;r.length;){const e=r.shift(),n=i.get(e);for(const s of t.out.get(e)??[])null==s||i.has(s)||(i.set(s,n+1),r.push(s))}return n.set(e,i),i}(t,e,s).get(n)??1/0}function Wb(t,e,n){const s=t.out.get(e)??[],i=new Map,r=[];for(let e=0;e<s.length;e++){const o=s[e];if(null==o)continue;const a=o===n?0:Ub(t,o,n,i);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 qb(t,e,n){const s=Wb(t,e,n);return s.length?s[0]:-1}function Xb(t,e,n){return e===n||Wb(t,e,n).length>0}function Kb(t,e){const n=new Set;for(const s of Vb(t,e))for(const e of s)t.sinks.has(e)&&n.add(e);return n}function Qb(t,e,n){return Jb(t,e,n).map(t=>t.index)}function Jb(t,e,n){const s=n instanceof Set?n:new Set(n);if(0===s.size)return[];const i=t.out.get(e)??[],r=new Map,o=[...s].sort(),a=[];for(let e=0;e<i.length;e++){const n=i[e];if(null==n)continue;let s=1/0,c="";for(const e of o){const i=1+(n===e?0:Ub(t,n,e,r));i<s&&(s=i,c=e)}s!==1/0&&a.push({index:e,hops:s,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function Zb(t,e={}){const n=[],s=e.loopCapableIds??new Set,i=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const s=t.nodes.get(e);if(!s||!s.topology.outbounds?.length)continue;(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)||(i.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(),s=new Set,i=[],r=new Set,o=n=>{s.add(n),i.push(n),r.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(r.has(a)){const t=i.indexOf(a),n=i.slice(t),s=n.indexOf([...n].sort()[0]),r=[...n.slice(s),...n.slice(0,s)],o=r.join("→");e.some(t=>t.join("→")===o)||e.push(r)}else s.has(a)||o(a);i.pop(),r.delete(n)};for(const t of n)s.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=>s.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[...i].sort())t.nodes.has(e)&&(a.has(e)||n.push({severity:"warning",code:"unreachable-target",nodeId:e,message:`RoutingTarget "${e}" 에 incoming edge 0 — 누구도 이쪽으로 carrier 를 보내지 않음`}));return n.sort((t,e)=>t.code!==e.code?t.code.localeCompare(e.code):(t.nodeId??"").localeCompare(e.nodeId??"")),n}function tv(t,e){if(!t)return[];const n=[],s=new Set,i=t=>{if(!t||s.has(t))return;if(s.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,s=t.refid??t.state?.refid,i="string"==typeof e&&e.length>0?e:null!=s?String(s):void 0;if(i)try{const e=t.getSegmentTopology(),s=t.state??{},r={left:s.left,top:s.top,width:s.width,height:s.height,rotation:s.rotation};e&&n.push({id:i,topology:e,bounds:r})}catch{}}const r=t?.components;if(Array.isArray(r))for(const t of r)i(t)};return i(t),n}function ev(t,e){const n=t.state?.targetRef??t.state?.downstreamRef;if("string"==typeof n&&n.length>0)return n;if("function"!=typeof t.getSegmentTopology)return null;const s=t.getSegmentTopology();if(!s||0===s.outbounds.length)return null;const i=Yb(s,tv(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),e);for(const t of i)if(t)return t;return null}function nv(t){return!!t&&"function"==typeof t.routingConstraints}function sv(t){return!!t&&"function"==typeof t.acceptedCarrierData}function iv(t,e=16){const n=[],s=t.parent??t.rootModel??t.root;if(!s)return n;const i=ev(t);if(!i)return n;const r=av(s,i);if(!r)return n;const o=[{segment:r,accumulated:{},pathIds:[i],visited:new Set([i])}];for(;o.length>0;){const t=o.shift();if(t.pathIds.length>e)continue;const i=nv(t.segment)?t.segment.routingConstraints():null;if(i&&i.length>0)for(const e of i)for(const i of e.candidates){const r=rv(t.accumulated,i);if(!r)continue;const a=ov(t.segment,e.portId,s);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(sv(t.segment)){const e=t.segment.acceptedCarrierData(),s=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:s});else for(const i of e){const e=rv(t.accumulated,i);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:s})}continue}const e=ev(t.segment);if(!e||t.visited.has(e)){n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:t.pathIds[t.pathIds.length-1]});continue}const i=av(s,e);if(!i)continue;o.push({segment:i,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function rv(t,e){const n={...t};for(const[t,s]of Object.entries(e)){if(t in n&&n[t]!==s)return null;n[t]=s}return n}function ov(t,e,n){if("straight"===e&&t.state?.downstreamRef)return av(n,t.state.downstreamRef);const s=av(n,e);if(s)return s;const i=ev(t);return i?av(n,i):null}function av(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,s=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const i=t.components;if(Array.isArray(i))for(const t of i){const e=s(t);if(e)return e}return null};return s(t)}function cv(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function lv(t,e,n=5,s=[],i=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 s){const e=Array.isArray(t),n=e?t:t.positions,s=e?void 0:t.kind;if(!n.length)continue;const i=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:i});s&&u.set(i,s)}const p=(t,e)=>{const s=c(t,e),i=h.get(`${t}:${"end"===e?"start":"end"}`),r=[];for(const t of d)cv(t.pos,s)<=n&&!r.includes(t.pt)&&r.push(t.pt);for(let t=0;t<l.length;t++)cv(l[t].pos,s)<=n&&!r.includes(t)&&r.push(t);let o=r.find(t=>t!==i)??-1;o<0&&(o=l.length,l.push({pos:s,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 s=0;s<l.length;s++){const i=cv(l[s].pos,t);i<n&&(n=i,e=s)}for(const s of d){const i=cv(s.pos,t);i<n&&(n=i,e=s.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:s}=t(n.pos);e>=0&&s<=i&&(f.add(e),("source"===n.kind?m:g).add(e))}}for(const[t,e]of u)f.add(t),("source"===e?m:g).add(t);const y=(t,e)=>"end"===e!==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 s=l[n];if(2!==s.members.length||f.has(n))continue;const i=s.members[0],r=i.seg===t&&i.end===e?s.members[1]:i;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",s=1/0;for(let i=0;i<r;i++)for(const r of["start","end"]){const o=cv(c(i,r),t.pos);o<s&&(s=o,e=i,n=r)}if(e<0||s>i)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,s=0;for(const e of t.members)void 0!==o[e.seg]&&(y(e.seg,e.end)?n++:s++);const i=e[0];let r;0===s&&n>0?r="end"===i.end:0===n&&s>0&&(r="start"===i.end),void 0!==r&&(o[i.seg]=r,b.push(i.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 s of t)e[s]=0,n.push(s);for(;n.length;){const t=n.shift();for(const s of l[t].members){const i=h.get(`${s.seg}:${"start"===s.end?"end":"start"}`);void 0!==i&&e[i]>e[t]+1&&(e[i]=e[t]+1,n.push(i))}}return e},e=t(m),n=t(g);for(let t=0;t<r;t++){if(void 0!==o[t])continue;const s=h.get(`${t}:start`),i=h.get(`${t}:end`);if(void 0===s||void 0===i)continue;if(l[s].members.length<2||l[i].members.length<2)continue;if(e[s]===1/0||e[i]===1/0||n[s]===1/0||n[i]===1/0)continue;let r;e[s]!==e[i]?r=e[s]<e[i]:n[s]!==n[i]&&(r=n[i]<n[s]),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 hv(...t){}function dv(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function uv(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*pv(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*pv(t)}function fv(t,e,n){const s=e.width??0,i=e.height??0;if(s<=0||i<=0)return!1;const r=(e.left??0)+s/2,o=(e.top??0)+i/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)<=s/2+n&&Math.abs(p)<=i/2+n}function mv(t){const e=[],n=[],s=[],i=[];for(const r of pv(t)){const t=uv(r);if(!t)continue;if(r.flowOrientable){const n=jb(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&&i.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&&s.push({positions:t})}}for(const t of i){const i=[];for(const n of e)for(const e of[n.start,n.end])fv(e,t,16)&&i.push(e);let r=!1,o=!1;for(const e of n)fv(e.pos,t,16)&&("sink"===e.kind?r=!0:o=!0);const a=r&&!o?"sink":o&&!r?"source":void 0;(i.length>=2||a&&i.length>=1)&&s.push({positions:i,kind:a})}if(0===e.length||0===n.length)return new Map;return lv(e,n,8,s,60).directions}function gv(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:mv(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const s=uv(t),i=s?n.map.get(s):void 0;return"reverse"===i||"forward"!==i&&void 0}function yv(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function bv(t,e,n,s){if(!t||!e)return null;const i=[],r=t=>{if(!t||t===s)return;if(Wm(t,e)&&yv(t)){const e=function(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}(t);e&&i.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const o=t.components;if(Array.isArray(o))for(const t of o)r(t)};return r(t),0===i.length?null:(i.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),i[0])}function vv(t){return!!t&&"function"==typeof t.routingDestination}function _v(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*xv(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*xv(t)}function wv(t){const e=[],n=new Map,s=new Map,i=new Set,r=[];for(const o of xv(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||vv(o)||c||yv(o)))continue;const l=_v(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}),s.set(l,o),vv(o)){i.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:s,routingTargetIds:i,stationClients:r}}function Mv(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:s,components:i,routingTargetIds:r,stationClients:o}=wv(t),a=Gb(n);!function(t,e){if(!t)return;const n=t=>{if(!t)return;"function"==typeof t.clearStations&&t.clearStations();const e=t.components;if(Array.isArray(e))for(const t of e)n(t)};n(t);const s=[...e].sort((t,e)=>{const n=_v(t)??"",s=_v(e)??"";return n.localeCompare(s)});for(const e of s){const n=e.declaredHostRef?.();let s=null;if(n&&(s=t.findById?.(n)??null),!s){const n=e.hostCapability?.(),i=e.hostFacingPoint?.();n&&i&&(s=bv(t,n,i,e)?.component??null)}s&&"function"==typeof e.registerWithHost&&e.registerWithHost(s)}const i=e=>{if(!e)return;if(yv(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const s=t.findById?.(n);s&&e.registerDivertStation(n,s)}const n=e.components;if(Array.isArray(n))for(const t of n)i(t)};i(t)}(t,o);const c=new Set;for(const[t,e]of i){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of r){const e=i.get(t);if("function"==typeof e?.routingWeight){const n=e.routingWeight();"number"==typeof n&&(!Number.isFinite(n)||n<=0)&&l.set(t,n)}}const h=Zb(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:s,components:i,issues:h},t.__flowGraph=e}return e}function Sv(t){return Mv(t)?.issues??[]}function Ev(t){const e=Mv(t);return e&&e.graph.nodes.size>0?e.graph:null}function Av(t,e){return Mv(t)?.destToSinks.get(e)??[]}function kv(t,e){return Mv(t)?.components.get(e)}function Cv(t){const e=Mv(t);return e?[...e.destToSinks.keys()]:[]}function Tv(t){return _v(t)}function Ov(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 Pv(t,e,n,s,i){if(1===s.length)return s[0];switch(t){case"index":default:return s[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),s[t%s.length]}case"weight":{const t=s.map(t=>function(t){if("function"==typeof t?.routingWeight){const e=t.routingWeight();if("number"==typeof e&&Number.isFinite(e)&&e>0)return e}return 1}(i.get(t.target))),r=t.reduce((t,e)=>t+e,0);if(r<=0)return s[0];const o=n.counters.get(e)??0;n.counters.set(e,o+1);let a=o%r;for(let e=0;e<s.length;e++){if(a<t[e])return s[e];a-=t[e]}return s[s.length-1]}case"utilization":{let t=1/0,e=s[0];for(const n of s){const s=Ov(i.get(n.target));s<t&&(t=s,e=n)}return e}}}function Iv(t,e,n){const s=t?.root;if(!s)return null;const i=e?.state?.meta?.destination;if("string"!=typeof i||0===i.length)return null;const r=Mv(s);if(!r||0===r.graph.nodes.size)return null;const o=_v(t);if(!o)return null;let a=r.destToSinks.get(i)??[];0===a.length&&(a=[i]);const c=Jb(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],s=n?r.components.get(n):null;return!s||"function"!=typeof s.canReceive||s.canReceive(e)});if(0===h.length)return l[c[0].index]??null;const d=n?.policy??function(t,e){const n=t?.state?.balancingPolicy;if(n)return n;const s=e?.state?.routingBalancingPolicy;return s||"round-robin"}(t,s),u=Pv(d,o,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(s),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,Ev(t)}catch{return null}}}catch{}function Dv(t,e,n){const s=Iv(t,e,n);if(null==s)return null;const i=t?.root,r=kv(i,s)??i?.findById?.(s)??null;return r?{targetId:s,component:r,origin:"explicit"}:null}function zv(t){const e=t?.root,n=Ev(e),s=Tv(t);if(!n||!s)return null;const i=(n.out.get(s)??[]).find(Boolean);if(!i)return null;const r=kv(e,i)??e?.findById?.(i)??null;return r?{id:i,component:r}:null}function Rv(t){const e=Tv(t);return e?jv(t?.root,e):[]}function jv(t,e){if(!t||!e)return[];const n=Ev(t);if(!n)return[];const s=new Set;for(const i of Kb(n,e)){const e=kv(t,i);if(vv(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&s.add(t)}}return[...s]}function Lv(t,e){if(!t||!e)return[];const n=Ev(t);if(!n)return[];const s=new Map;for(const t of n.out.values())for(const e of t)null!=e&&s.set(e,(s.get(e)??0)+1);const i=new Map;for(const r of Kb(n,e)){const e=kv(t,r);if(!vv(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=s.get(r)??0,0===o&&(o=1)),i.set(n,(i.get(n)??0)+o)}return[...i].map(([t,e])=>({value:t,weight:e}))}function Fv(t){return Ev(t)}function Nv(t){const e=Ev(t);if(!e)return[];const n=new Set,s=new Set,i=t=>{if(!t)return;const r=Tv(t);if(r&&e.nodes.has(r)){vv(t)&&n.add(r);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&s.add(r)}const o=t.components;if(Array.isArray(o))for(const t of o)i(t)};return i(t),Zb(e,{routingTargetIds:n,loopCapableIds:s})}function $v(t){if(0===t.length)return;const e=t.reduce((t,e)=>t+e.weight,0);if(e<=0)return t[Math.floor(Math.random()*t.length)].value;const n=Math.random()*e;let s=0;for(const e of t)if(s+=e.weight,n<s)return e.value;return t[t.length-1].value}const Hv={next:Dv,downstream:zv,reachableDestinations:Rv,reachableDestinationsFrom:jv,reachableDestinationsWeightedFrom:Lv,pickWeightedDestination:$v,graphFor:Fv,validate:Nv};function Bv(t){var e;return e=class extends t{constructor(){super(...arguments),this._items=[]}get items(){return this._items}containsItem(t){return-1!==this._items.indexOf(t)}attachPointFor(e,n){const s=t.prototype?.attachPointFor;return"function"==typeof s?s.call(this,e,n):null}addItem(t,e){if(!t||this.containsItem(t))return;const n=t.parent;if(n&&"function"==typeof n.removeItem&&n!==this&&n.removeItem(t,!0),this._items.push(t),t.parent=this,!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 s=-1===this._items.indexOf(t);if(s&&this._items.push(t),t.parent=this,s&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}const i=t._realObject,r=i?.object3d;if(r){let n,s,o=e?.toParent3D,a="world-preserve";if(!o){const i=this.attachPointFor?.(t,{slotId:e?.slotId});i?.attach&&(o=i.attach,n=i.localPosition,s=i.localRotation,a=i.carryPolicy??"world-preserve")}o&&r.parent!==o&&(o.updateWorldMatrix?.(!0,!1),r.updateWorldMatrix?.(!0,!1),o.attach(r),i.suppressTransform=!0),o&&(n&&r.position.set(n.x,n.y,n.z),"world-preserve"!==a?s?r.rotation.set(s.x,s.y,s.z):r.quaternion.identity():s&&r.rotation.set(s.x,s.y,s.z),i?.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,s,i){for(let r=this._items.length-1;r>=0;r--){const o=this._items[r],a="static"===o.position?o.capture?.(t,e,i):o.capture?.(n,s,i);if(a)return a}return null}postrender(t){super.postrender?.(t);const e=this;if("popup"===e.position)return;const n=this._items;if(!n||0===n.length)return;t.save();const s=e.bounds;!e.showOverflow&&s&&(t.beginPath(),t.rect(s.left,s.top,s.width,s.height),t.clip(),t.closePath());const{left:i=0,top:r=0}=e.state??{};t.translate(i,r),this._drawItems(t),t.translate(-i,-r),t.restore()}capture(t,e,n){const s=this,i=this._items;if(i&&i.length>0&&(!s.app||s.app.isEditMode||!s.hidden)){const i=s.fromParent?.(t,e);if(i&&s.contains?.(i.x,i.y)){const r=s.bounds,o=this._captureItems(i.x-r.left,i.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 Yv(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,s={}){const i=e.slot,r=this._countOccupied(i.id),o=this.arrangementStrategy.positionAt(r,i,r,n);Gu.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:r,slotId:i.id,occupantCount:r,carrier:Qy(n)},result:o}),n[tb]=i.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}=s;"function"==typeof this.handoverIn?this.handoverIn(n,{slotId:i.id}):this.reparent?.(n,{animated:h,duration:d,ease:u}),!h&&n._realObject&&(n._realObject.suppressTransform=!1);{const t={},e=this.placementFor?.(n,{slot:i,index:r,occupantCount:r})??null;if(Gu.log({role:"target",contract:"placementFor",component:this,args:{carrier:Qy(n),slotId:i.id,index:r},result:e}),e){const s=n.state??{},r=this.state??{};t.left=e.position.x-(Number(s.width)||0)/2+(Number(r.width)||0)/2,t.top=e.position.z-(Number(s.height)||0)/2+(Number(r.height)||0)/2;const o=this._zPosFromSeatY(e.position.y,s.depth,i);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(i.localPosition&&Number.isFinite(i.localPosition.z)){const e=this._realObject?.geometricOffsetY??0;t.zPos=i.localPosition.z+e}const e=this.acceptanceRotation?.(n,i);Gu.log({role:"target",contract:"acceptanceRotation",component:this,args:{carrier:Qy(n),slotId:i.id},result:e}),e&&Zy(t,e)}const s=this.normalizePose?.(n,i);"function"==typeof this.normalizePose&&Gu.log({role:"target",contract:"normalizePose",component:this,args:{carrier:Qy(n),slotId:i.id},result:s}),s&&Object.assign(t,s),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:i.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),Gu.log({role:"target",contract:"receive:done",component:this,args:{carrier:Qy(n),slotId:i.id}})}async dispatch(t,e,n={}){const s=new qu({source:this,target:e,carrier:t,options:n,physical:async()=>{delete t[tb]}}),i=await s.execute();"rolled-back"!==i.phase?this.trigger("transfer-dispatched",{type:"transfer-dispatched",component:t,container:this,target:e}):this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:i.rejectReason??"rejected"})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e="rejected"){this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:e})}canAccept(t){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 Gv(t){var e;const n=!!t.__hasCapacity,s=!!t.__hasTransferable,i=n?t:Db(t),r=s?i:Yv(i),o=[...t.capabilities??[]];n||o.push("Capacity","PlacementSurface"),s||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(Bv(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 Vv(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 Uv={x:0,y:0,z:0,w:1};function Wv(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function qv(t,e){const n=t.rotation,s=e.rotation,i=e.position,r=n.w*i.x+n.y*i.z-n.z*i.y,o=n.w*i.y+n.z*i.x-n.x*i.z,a=n.w*i.z+n.x*i.y-n.y*i.x,c=-n.x*i.x-n.y*i.y-n.z*i.z,l=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*s.x+n.x*s.w+n.y*s.z-n.z*s.y,y:n.w*s.y-n.x*s.z+n.y*s.w+n.z*s.x,z:n.w*s.z+n.x*s.y-n.y*s.x+n.z*s.w,w:n.w*s.w-n.x*s.x-n.y*s.y-n.z*s.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const Xv={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 Kv(t){const{carrierWorld:e,width:n,depth:s,entryHeight:i,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:{...Uv}}:void 0,u=n/2,p=s/2;return a.map(t=>{const n=Xv[t],s="string"==typeof c?c:c[t]??"unknown",r={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:i,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:Wv(n.yaw)},a={position:{x:r.position.x+n.axis.x*o,y:i,z:r.position.z+n.axis.z*o},rotation:Wv(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:s,approach:qv(e,a),engage:qv(e,r),...d?{mount:d}:{},tolerance:l,priority:h}})}function Qv(t){const{carrierWorld:e,topY:n,approachDistance:s,toolType:i,mountLocalY:r,tolerance:o,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...Uv}};return{id:c??"top",toolType:i,approach:qv(e,{position:{x:0,y:n+s,z:0},rotation:{...Uv}}),engage:qv(e,l),..."number"==typeof r?{mount:{position:{x:0,y:r,z:0},rotation:{...Uv}}}:{},tolerance:o,priority:a}}function Jv(t,e){return t.filter(t=>t.toolType===e.toolType)}function Zv(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,s=t.approach.position.y-e.y,i=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+s*s+i*i)}});return n.sort((t,e)=>{const n=t.f.priority??0,s=e.f.priority??0;return n!==s?n-s:t.dist-e.dist}),n[0].f}class t_{constructor(t){this.owner=t}positionAt(t,e,n,s){if(0!==t)return null;const i=this.owner?.state?.width??0,r=this.owner?.state?.height??0,o=s?.state?.width??0,a=s?.state?.height??0;return{x:Math.max(0,(i-o)/2),y:Math.max(0,(r-a)/2),z:0}}capacity(t){return t.maxCount??1}}let e_=1;function n_(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const s_={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class i_{constructor(t=s_){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-"+e_++},n=(this._byResource.get(e.resource)??[]).filter(t=>n_(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const s=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}});if(s.every(t=>"b-yields"===t.decision)){const s=n.slice();for(const t of s)this._remove(t),this._emit({kind:"evicted",reservation:t,by:e});return this._insert(e),this._emit({kind:"added",reservation:e}),this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:s,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:s}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:s}}conflictLog(){return[...this._conflictLog]}setMaxConflictLog(t){this._maxConflictLog=Math.max(1,t)}_appendConflictLog(t){this._conflictLog.push(t),this._conflictLog.length>this._maxConflictLog&&this._conflictLog.shift()}conflicts(t,e){return(this._byResource.get(t)??[]).filter(t=>n_(t.timeWindow,e))}release(t){this._remove(t)&&this._emit({kind:"released",reservation:t})}releaseAllOf(t){const e=(this._byReserver.get(t)??[]).slice();for(const t of e)this._remove(t),this._emit({kind:"released",reservation:t});return e}forResource(t){return[...this._byResource.get(t)??[]]}forReserver(t){return[...this._byReserver.get(t)??[]]}all(){const t=[];for(const e of this._byResource.values())t.push(...e);return t}clear(){this._byResource.clear(),this._byReserver.clear(),this._conflictLog.length=0}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}_insert(t){let e=this._byResource.get(t.resource);e||(e=[],this._byResource.set(t.resource,e));const n=e.findIndex(e=>e.timeWindow.startSimMs>t.timeWindow.startSimMs);n<0?e.push(t):e.splice(n,0,t);let s=this._byReserver.get(t.reserverId);s||(s=[],this._byReserver.set(t.reserverId,s)),s.push(t)}_remove(t){const e=this._byResource.get(t.resource);if(!e)return!1;const n=e.findIndex(e=>e.id===t.id);if(n<0)return!1;e.splice(n,1),0===e.length&&this._byResource.delete(t.resource);const s=this._byReserver.get(t.reserverId);if(s){const e=s.findIndex(e=>e.id===t.id);e>=0&&s.splice(e,1),0===s.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const r_=new i_;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=r_);class o_{constructor(){this.nodes=new Map,this.edges=new Map,this.laneEndpoints=new Map}addNode(t){this.nodes.has(t.id)||(this.nodes.set(t.id,t),this.edges.set(t.id,[]))}addEdge(t){const e=this.edges.get(t.fromNode);if(!e)throw new Error(`NavGraph.addEdge: source node not found: ${t.fromNode}`);if(!this.nodes.has(t.toNode))throw new Error(`NavGraph.addEdge: target node not found: ${t.toNode}`);e.push(t)}edgesFrom(t){return this.edges.get(t)??[]}findNearestNode(t){let e=null,n=1/0;for(const s of this.nodes.values()){const i=a_(s.position,t);i<n&&(n=i,e=s)}return e}}function a_(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}function c_(t,e){return Math.sqrt(a_(t,e))}function l_(t,e,n={}){const s=new o_,i=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`;s.addNode({id:n,position:t[0],type:"lane-start"}),s.addNode({id:r,position:t[t.length-1],type:"lane-end"}),s.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:r});let o=0;for(let e=1;e<t.length;e++)o+=c_(t[e-1],t[e]);const a=o/(e.speedLimit??i)*1e3;s.addEdge({fromNode:n,toNode:r,resource:e.id,distance:o,durationMs:a,forward:!0}),"twoway"===e.direction&&s.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 i=s.laneEndpoints.get(n);if(!i)continue;const r=s.nodes.get(i.startNodeId).position,o=s.nodes.get(i.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=s.laneEndpoints.get(e);if(!t)continue;const i=s.nodes.get(t.startNodeId).position,h=s.nodes.get(t.endNodeId).position;a+=Math.min(a_(r,i),a_(r,h)),c+=Math.min(a_(o,i),a_(o,h)),l++}if(0===l)continue;const h=a<c?i.startNodeId:i.endNodeId;e.push({laneId:n,nodeId:h,pos:s.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let i=0;i<e.length;i++){if(n===i)continue;const r=e[n],o=e[i],a=c_(r.pos,o.pos);s.addEdge({fromNode:r.nodeId,toNode:o.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return s}function h_(t,e,n,s={}){const i=t.nodes.get(e),r=t.nodes.get(n);if(!i||!r)return null;const o=s.speed?.max??100,a=e=>{const n=t.nodes.get(e);var s,i;return(s=n.position,i=r.position,Math.sqrt(function(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}(s,i)))/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=s.startSimMs??0,p=s.deadlineSimMs;for(;l.size>0;){let e=null,s=null;for(const t of l){const n=c.get(t);(!s||n.fScore<s.fScore||n.fScore===s.fScore&&t<e)&&(s=n,e=t)}if(!s||!e)return null;if(e===n){const t=[];let e=s,n=0;for(;e&&e.cameFromEdge;){const s=e.cameFromEdge,i=u+(e.gScore-s.durationMs);t.unshift({resource:s.resource,timeWindow:{startSimMs:i,endSimMs:i+s.durationMs},fromPos:s.fromPos,toPos:s.toPos}),n+=s.distance,e=c.get(s.fromNodeId)}const i=s.gScore;return void 0!==p&&u+i>p?null:{segments:t,totalDurationMs:i,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=s.gScore+n.durationMs,i=c.get(n.toNode);if(!i||e<i.gScore){const s=t.nodes.get(n.fromNode),i=t.nodes.get(n.toNode),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:s.position,toPos:i.position}};c.set(n.toNode,r),l.add(n.toNode)}}}return null}function d_(t,e,n=0,s){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:s}))}const u_={closed:!0,round:0,divisions:24};class p_{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const s=t[e].x-t[e-1].x,i=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(s*s+i*i))}this.cumulative=n,this.length=n[n.length-1]??0}sample(t){const e=this.length;if(0===this.points.length)return{x:0,y:0,theta:0};if(0===e)return{x:this.points[0].x,y:this.points[0].y,theta:0};let n=t;this.closed?n=(t%e+e)%e:n<0?n=0:n>e&&(n=e);const s=this.cumulative;let i=0,r=s.length-2;for(;i<r;){const t=i+r>>1;s[t+1]<=n?i=t+1:r=t}const o=s[i+1]-s[i],a=o>0?(n-s[i])/o:0,c=this.points[i],l=this.points[i+1],h=l.x-c.x,d=l.y-c.y;return{x:c.x+h*a,y:c.y+d*a,theta:0===h&&0===d?0:Math.atan2(d,h)}}}function f_(t,e={}){const n={...u_,...e},s=t.length;if(0===s)return new p_([],n.closed);if(1===s)return new p_([{x:t[0].x,y:t[0].y}],n.closed);const i=[],r=(t,e)=>{if(i.length>0){const n=i[i.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}i.push({x:t,y:e})},o=(n.closed,s);for(let e=0;e<o;e++){const i=0===e?n.closed?s-1:-1:e-1,o=e===s-1?n.closed?0:-1:e+1,a=i>=0?t[i]: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,s=1-e;r(s*s*d+2*s*e*c.x+e*e*p,s*s*u+2*s*e*c.y+e*e*f)}else d===p&&u===f||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),s=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,i=Math.min(t,e/2),o=Kr({x:p,y:f},{x:Math.sin(s)*i+l.x,y:Math.cos(s)*i+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 s=e/n.divisions,i=o.startAngle+t*s;r(o.cx+o.radius*Math.cos(i),o.cy+o.radius*Math.sin(i))}}}}if(n.closed&&i.length>0){const t=i[0],e=i[i.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&i.push({x:t.x,y:t.y})}return new p_(i,n.closed)}function m_(t,e){return f_(t,e).length}function g_(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 y_(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 b_(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",s={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:g_(n),parentId:t.parent?.state?.id,parentPath:y_(t)},i=t._realObject?.object3d;if(i){i.updateWorldMatrix?.(!0,!1);const t=i.matrixWorld?.elements;t&&(s.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(s.isItem=!0),!0===t.isMover&&(s.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(s.isHolder=!0),"function"==typeof t.pickupFrames)try{s.isPickable=t.pickupFrames().length>0}catch{s.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?s.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(s.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,s]of Object.entries(t.state))"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s&&null!==s||(e[n]=s);s.state=e}if(e){const e=t.components??[];s.childIds=e.map(t=>t.state?.id).filter(Boolean)}return s}function v_(t){function e(t,n){if(!t)return;n.push(b_(t));const s=t.components??[];for(const t of s)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const s=e.components??[];for(const e of s){const s=n(t,e);if(s)return s}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const s=n(e,t?.rootModel??t);if(!s)return null;const i={...b_(s)};if("function"==typeof s.pickupFrames)try{i.pickupFrames=s.pickupFrames()}catch{}if("object"==typeof s.slots)try{i.slots=Array.isArray(s.slots)?s.slots:"function"==typeof s.slots?s.slots():[]}catch{}if("function"==typeof s.acceptanceRotation)try{i.acceptanceWorldQuat=s.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof s.deliveryWorldPosition)try{i.deliveryWorldPosition=s.deliveryWorldPosition(null)}catch{}return i},simStatus(){let e=0;const n=[t?.rootModel??t];for(;n.length>0;){const t=n.pop();if(!t)continue;!0===t.isItem&&e++;const s=t.components??[];for(const t of s)n.push(t)}return{simTime: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=[...r_.all()],e={},n={};for(const s of t)(e[s.resource]??=[]).push(s),(n[s.reserverId]??=[]).push(s);for(const t of Object.values(e))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);for(const t of Object.values(n))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);return{simTime:Dr.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=r_.conflictLog(),e={},n={};let s=0,i=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?s++:i++;return{simTime:Dr.now,log:[...t],total:t.length,rejected:s,preempted:i,byResource:e,byReserver:n}}}}function __(t){const e=v_(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let x_=0;const w_=new FinalizationRegistry(()=>{x_--});class M_{static get residents(){return x_}static get residentsCount(){return x_}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,x_++,w_.register(this,x_)}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,Zs("RELEASED",t)},e(n)},n):n(Error("Reference id("+t+") could not be created. Reference creator should be defined."))})}add(t,e){const n=new Promise((n,s)=>{const i=this.references[t];if(i)i===e?s(Error("Reference ID and target duplicate")):e?s(Error("Reference ID duplicate")):n(i);else{const i=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)i(e);else{if(!this.creator)return void s(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,i,s)}}});return this.references[t]||(this.references[t]=n),n}async get(t,e=!1){let n=this.references[t];if(n){if(!(n instanceof Promise)){if(!(t in this.counters))throw new Error("No Reference Count");return this.counters[t]++,n}if(e)return n=await n,this.counters[t]++,n}if(e)return await this.add(t);throw new Error("No References for "+t)}_id(t){for(const e in this.references){if(this.references[e]===t)return e}}release(t){const e=this._id(t);if(!e)return void Qs("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,Zs("RELEASED",e)))}}const S_={},E_={};let A_=[];function k_(t){const e=t.target,n="SCRIPT"===e.tagName?S_:E_,s=e.src||e.href;n[s]=!0,A_.forEach((t,e)=>{if(!t)return;const{resolve:i,scripts:r,styles:o}=t;if(n===S_){const t=r.indexOf(s);t>-1&&t<r.length-1&&T_(r[t+1])}r.some(t=>!S_[t])||o?.some(t=>!E_[t])||(i(),A_[e]=null)}),A_=A_.filter(Boolean)}function C_(t){if("string"==typeof t)return;const e=t.target,n=e.src,s="SCRIPT"===e.tagName?S_:E_;A_.forEach((e,i)=>{if(!e)return;const{reject:r,scripts:o,styles:a}=e;(s===S_&&o.includes(n)||s===E_&&!!a?.includes(n))&&(r(t),A_[i]=null)}),A_=A_.filter(Boolean),delete s[n],document.head.removeChild(e)}function T_(t){S_[t]=!1;const e=document.createElement("script");e.onload=k_,e.onerror=C_,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class O_{static load(t,e){const n="string"==typeof t?[t]:t,s="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||s&&!Array.isArray(s))return void e(new Error("invalid sources for load"));let i,r=!0;if(s?.forEach(t=>{t in E_||function(t){E_[t]=!1;const e=document.createElement("link");e.onload=k_,e.onerror=C_,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),E_[t]||(r=!1)}),n&&n.length>0)for(const t of n)t in S_?S_[t]||(r=!1):i??=t;if(i)T_(i);else if(r)return void t();A_.push({resolve:t,reject:e,scripts:n,styles:s})})}}const P_="0.0.0";function I_(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 D_(e){const{lineWidth:n=0}=e.state;let{width:s,height:i}=e.bounds;s+=n,i+=n;const r=I_(2*s),o=I_(2*i),a=Bp(r,o),c=new t.CanvasTexture(a);return z_(a,e,2),c.needsUpdate=!0,c.wrapS=t.RepeatWrapping,c.wrapT=t.RepeatWrapping,c.offset.set(0,1-2*i/o),c.repeat.set(2*s/r,2*i/o),c.magFilter=t.NearestFilter,c.minFilter=t.LinearFilter,c.colorSpace=t.SRGBColorSpace,c}function z_(t,e,n){const{lineWidth:s=0}=e.state;let{left:i,top:r}=e.bounds;i-=s/2,r-=s/2;const o=t.getContext("2d");o.scale(n,n),o.translate(-i,-r),e.render(o),e.postrender(o)}function R_(t,e,n=2){const s=t.getContext("2d");s&&(s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,t.width,t.height),z_(t,e,n))}const j_=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class L_ 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 s=Id(this.component.state.material3d),i=new t.PlaneGeometry(1,1);i.rotateX(-Math.PI/2),this.object3d.geometry=i;const r=D_(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,s),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=s.castShadow,this.object3d.receiveShadow=s.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&&(R_(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(!j_.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 F_=new Map;function N_(t){return Math.round(1e3*t)/1e3}function $_(e){return new t.Color(e).getHexString()}const H_={material(e,n,s){const i=e+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+$_(t.color)),null!=t.metalness&&e.push("m"+N_(t.metalness)),null!=t.roughness&&e.push("r"+N_(t.roughness)),null!=t.opacity&&e.push("o"+N_(t.opacity)),null!=t.emissive&&e.push("E"+$_(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+N_(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+N_(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=F_.get(i);return r||F_.set(i,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==s?r:Qd(r,{color:s})},get size(){return F_.size},has(t){const e=t+"::";for(const t of F_.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of F_.values())Zd(t),t.dispose();F_.clear()}};class B_ 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 s=Mu.buildFillStyleTexture(this.component);s?(n.map&&n.map.dispose(),s.needsUpdate=!0,n.map=s,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(su(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 s=this.object3d.geometry;if(!s?.getAttribute("position"))return;const i=new t.EdgesGeometry(s),r=new t.LineBasicMaterial({color:n}),o=new t.LineSegments(i,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 s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,r=s.max.y-s.min.y,o=s.max.z-s.min.z;this.setDimensionScale(t/i,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,s={shared:e,required:n,violated:n&&!e};return void 0!==t&&(s.reason=t),e&&(s.bankKey=this.materialBankKey),s}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=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?su(t):void 0;Jd(this.object3d),this.object3d.material=H_.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 Y_(t,e,n,s){return[["bold",t],["italic",e],[n+"px",!0],[s,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function G_(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 V_(t,e,n){const{bold:s=!1,italic:i=!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=Y_(s,i,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 U_(e,n,s,i){const r=G_(2*n),o=G_(2*s),a=Bp(r,o),c=a.getContext("2d"),{fillStyle:l}=i||{};if(l&&"object"==typeof l&&l.colorStops?.length){const t=du(l,2*n,2*s);t&&c.drawImage(t,0,0)}c.scale(2,2),"string"==typeof l&&""!==l&&"transparent"!==l&&(c.fillStyle=l,c.fillRect(0,0,n,s)),V_(a,e,i);const h=new t.CanvasTexture(a);return h.needsUpdate=!0,h.wrapS=t.RepeatWrapping,h.wrapT=t.RepeatWrapping,h.offset.set(0,1-2*s/o),h.repeat.set(2*n/r,2*s/o),h.minFilter=t.LinearFilter,h.colorSpace=t.SRGBColorSpace,h}function W_(e,n,s,i,r,o,a){const c=new Image;c.crossOrigin="anonymous",c.onload=()=>{const e=2*s,l=2*i,h=G_(e),d=G_(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),s=2*(o.offsetX||0),i=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=s+r,d=i+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 s=h>0?h-Math.ceil(h/t)*t:h;for(let i=d>0?d-Math.ceil(d/n)*n:d;i<l;i+=n)for(let r=s;r<e;r+=t)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,r,i,t,n);p.restore()}}n&&(p.scale(2,2),V_(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=U_(n,s,i,r);a(t)},c.src=e}function q_(t,e){let{bold:n=!1,italic:s=!1,fontFamily:i="Serif",fontSize:r=10,lineHeight:o="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=Y_(n,s,r,i),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 X_ extends B_{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,s=Math.abs(e)||1,i=Math.abs(n)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const r=new t.PlaneGeometry(s,i);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:s=!1,italic:i=!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:s,italic:i,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 W_(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=U_(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(su(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}Jp("text",t=>new X_(t));const K_={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function Q_(t){const e=t.model?.type??"";return"texture"===(K_[e]??"css3d")?new L_(t):new Xp(t)}Jp("html-overlay-element",Q_),Jp("html-overlay-container",Q_);class J_{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,s,i,r){const o=n[3*s],a=n[3*s+1],c=n[3*i],l=n[3*i+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,s,i,r,o){const a=n[3*s],c=n[3*s+1],l=n[3*s+2],h=n[3*i],d=n[3*i+1],u=n[3*i+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 Z_(t,e){const n=t/2,s=e/2;return{points:[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}]}}function tx(t,e,n){const s=Math.max(3,Math.floor(n)),i=[];for(let n=0;n<s;n++){const r=n/s*Math.PI*2;i.push({x:t*Math.cos(r),y:e*Math.sin(r)})}return{points:i,segments:s}}function ex(t){if(0===t.length)return[];let e=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of t)r.x<e&&(e=r.x),r.x>s&&(s=r.x),r.y<n&&(n=r.y),r.y>i&&(i=r.y);const r=(e+s)/2,o=(n+i)/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 nx 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 s=ex(n);return s.length<3?null:{points:s}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new J_),this._boundUVGenerator}build(){super.build();const e=this.effectiveDepth,n=this.shape;if(!n)return;const s=this.boundUVGenerator;s&&s.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const i=this.createGeometry(n),r=this.createMaterials();this._mesh=new t.Mesh(i,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:s=0}=this.component.state,i={steps:1,depth:n,bevelEnabled:s>0,bevelThickness:0,bevelSize:s,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,i);return r.center(),r}createMaterials(){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial;Rd(n,e);const s=new t.MeshStandardMaterial;return Rd(s,e),[n,s]}createTexture(){const{width:e,height:n}=this.component.bounds,s=G_(e),i=G_(n),r=Bp(s,i);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/i),o.repeat.set(e/s,n/i),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,s=this.getMaterials();s&&(nu(s[0],0,e),nu(s[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(su(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,s=this.component.hasTextProperty?this.component.text:"";if(!s){const t=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(su(n))),void(e.needsUpdate=!0)}const{bold:i=!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:i,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 W_(this.component.app.url(n.image),s,y,b,v,n,t=>{e.map&&e.map.dispose(),e.map=t,e.color.set(16777215),e.needsUpdate=!0})}e.map&&e.map.dispose();const _=U_(s,y,b,v);e.map=_,e.color.set(16777215),e.needsUpdate=!0}updateDimension(){super.updateDimension()}onchange(t,e){if("path"in t&&this._mesh){const t=this._mesh.geometry,e=this.shape;if(e){const n=this.createGeometry(e);this._mesh.geometry=n,t.dispose()}}super.onchange(t,e)}}class sx extends nx{get shape(){const{cx:e=0,cy:n=0,rx:s=1,ry:i=1,startAngle:r=0,endAngle:o=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=new t.EllipseCurve(e,n,Math.abs(s),Math.abs(i),r,o,a,0);return new t.Shape(c.getPoints(50))}}Jp("ellipse",t=>new sx(t));class ix extends nx{get shape(){const{width:e,height:n,round:s=0}=this.component.state,i=Oc(s,e,n);if(i>0){const s=i,r=new t.Path;return r.moveTo(s,0),r.lineTo(e-s,0),r.quadraticCurveTo(e,0,e,s),r.lineTo(e,n-s),r.quadraticCurveTo(e,n,e-s,n),r.lineTo(s,n),r.quadraticCurveTo(0,n,0,n-s),r.lineTo(0,s),r.quadraticCurveTo(0,0,s,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 rx(e,n={}){const s=n.round??0,i=n.divisions??24;if(!e||0===e.length)return new t.Shape;const r=e.some(t=>Xr(t)),o=s>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 i=e[(t-1+e.length)%e.length],r=e[t],o=e[(t+1)%e.length];if(i.x===r.x&&i.y===r.y)continue;const a=Zr(r,s);let c=Math.sqrt((i.x-r.x)**2+(i.y-r.y)**2),l=0!==c?Math.atan2(i.x-r.x,i.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,s),e=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),i=0!==e?Math.atan2(r.x-o.x,r.y-o.y):0,a=Kr({x:u,y:p},{x:Math.sin(i)*Math.min(t,e/2)+o.x,y:Math.cos(i)*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(i))}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 ix(t));class ox extends nx{get shape(){const{path:t=[],round:e=0}=this.component.state;return rx(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(nx.prototype).build.call(this);const e=this.effectiveDepth,n=this.shape;if(!n)return;const s=this.boundUVGenerator,i=this.minMax;if(s&&void 0!==i.minX&&void 0!==i.maxX&&void 0!==i.minY&&void 0!==i.maxY){const n=new t.Shape;n.moveTo(i.minX,i.minY),n.lineTo(i.maxX,i.minY),n.lineTo(i.maxX,i.maxY),n.lineTo(i.minX,i.maxY),n.closePath(),s.setShape({extrudedShape:n,extrudedOptions:{depth:e}})}else s&&s.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:s=0}=this.component.state,i={steps:1,depth:n,bevelEnabled:s>0,bevelThickness:0,bevelSize:s,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,i),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,s,i;t.forEach((t,r)=>{if(0==r)return e=s=t.x,void(n=i=t.y);e=Math.min(e,t.x),s=Math.max(s,t.x),n=Math.min(n,t.y),i=Math.max(i,t.y)}),this._minMax={minX:e,minY:n,maxX:s,maxY:i}}return this._minMax}}Jp("polygon",t=>new ox(t));class ax extends nx{get shape(){const{cx:e=0,cy:n=0,rx:s=1,ry:i=1,ratio:r=50,startAngle:o=0,endAngle:a=2*Math.PI,anticlockwise:c=!1}=this.component.state,l=Math.abs(s),h=Math.abs(i),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 s=new t.EllipseCurve(e,n,p,f,o,a,c,0),i=new t.Path(s.getPoints(50));u.holes.push(i)}return u}}Jp("donut",t=>new ax(t));class cx extends nx{get shape(){const{x1:e=0,y1:n=0,x2:s=0,y2:i=0,x3:r=0,y3:o=0,round:a=0}=this.component.state,c=[{x:e,y:n},{x:s,y:i},{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],s=c[t],i=c[(t+1)%c.length];let r=Math.sqrt((n.x-s.x)**2+(n.y-s.y)**2),o=0!==r?Math.atan2(n.x-s.x,n.y-s.y):0;const l=Math.sin(o)*Math.min(a,r/2)+s.x,h=Math.cos(o)*Math.min(a,r/2)+s.y;r=Math.sqrt((i.x-s.x)**2+(i.y-s.y)**2),o=0!==r?Math.atan2(i.x-s.x,i.y-s.y):0;const d=Math.sin(o)*Math.min(a,r/2)+s.x,u=Math.cos(o)*Math.min(a,r/2)+s.y;0===t?e.moveTo(l,h):e.lineTo(l,h),e.quadraticCurveTo(s.x,s.y,d,u)}return new t.Shape(e.getPoints(12))}const l=new t.Shape;return l.moveTo(e,n),l.lineTo(s,i),l.lineTo(r,o),l.closePath(),l}}Jp("triangle",t=>new cx(t));class lx extends nx{get shape(){const{ratio:e=30,wing:n=5,cx:s=0,cy:i=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(s+r*Math.cos(-a),i+o*Math.sin(-a)),d.lineTo(s+(r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,i+(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let t=1;t<n;t++)d.lineTo(s+r*Math.cos(c*t-a),i+o*Math.sin(c*t-a)),d.lineTo(s+(r-l)*(Math.cos(c*(t+1)-a)+Math.cos(c*t-a))/2,i+(o-h)*(Math.sin(c*(t+1)-a)+Math.sin(c*t-a))/2);return d.closePath(),d}}Jp("star",t=>new lx(t));const hx=new Map;function dx(t){return t.userData.__bankOwned=!0,t}const ux={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 s=hx.get(n);return s||hx.set(n,s=dx(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))),s},shaped(t,e){const n="shaped::"+t;let s=hx.get(n);return s||hx.set(n,s=dx(e())),s},owns:t=>!0===t.userData?.__bankOwned,get size(){return hx.size},has:t=>hx.has("primitive::"+t)||hx.has("shaped::"+t),dispose(){for(const t of hx.values())t.dispose();hx.clear()}},px=[8,12,16],fx={cylinder:25,sphere:32},mx=3,gx=128;function yx(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(gx,Math.max(3,Math.floor(t))):e}function bx(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(gx,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function vx(t){return px.includes(t)}const _x={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 xx extends B_{buildGeometry(){const t=this.component.state,e=yx(t.segments,fx.sphere),n=bx(t.heightSegments,e);this.object3d.geometry=ux.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,s=n??t;this.setDimensionScale(2*t,2*s,2*e)}get effectiveDepth(){const{rx:t=0,rz:e}=this.component.state,n=e??t;return Math.max(2*n,1)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return tx(t,e,yx(this.component.state.segments,fx.sphere))}}let wx=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new xx(this)}get nature(){return _x}};wx=tg([Ny("sphere")],wx);class Mx 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(),s=this.component.parent?._realObject;return t+n+e/2-(s?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;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(su(t)):e.opacity=0)}}class Sx extends Mx{buildMaterial(){const e=this.object3d.material;e&&e.dispose(),this.object3d.material=new t.SpriteMaterial({map:D_(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:s=1,height:i=1}=n?.bounds??{},{scale:r=1}=this.component.state;return{x:r*t/s,y:r*e/i,z:r}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const Ex={mutable:!1,resizable:!0,rotatable:!0,properties:[]};let Ax=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Sx(this)}get nature(){return Ex}};Ax=tg([Ny("sprite")],Ax);const kx={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class Cx extends B_{buildGeometry(){this.object3d.geometry=ux.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?Z_(t,e):null}}let Tx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Cx(this)}get nature(){return kx}};Tx=tg([Ny("cube")],Tx);const Ox={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class Px extends B_{buildGeometry(){const t=yx(this.component.state.segments,fx.cylinder);this.object3d.geometry=ux.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 tx(t,e,yx(this.component.state.segments,fx.cylinder))}}let Ix=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Px(this)}get nature(){return Ox}};Ix=tg([Ny("cylinder")],Ix);const Dx={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class zx 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 s=this.createTextureBoard(t,n);s.position.set(0,0,.5*e+1),this.object3d.add(s)}createCube(e,n,s){const{boxColor:i="#ccaa76"}=this.component.state,r=Id(this.component.state.material3d),o=new t.BoxGeometry(e,s,n),a=new t.MeshStandardMaterial({color:i,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 s=Id(this.component.state.material3d),{fillStyle:i="#ccaa76"}=this.component.state,r=Mu.buildFillStyleTexture(this.component),o=new t.MeshStandardMaterial(r?{map:r}:{color:i||"#ccaa76",side:t.FrontSide});Rd(o,s);const a=new t.PlaneGeometry(e,n,1,1),c=new t.Mesh(a,o);return c.castShadow=s.castShadow,c.receiveShadow=s.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 Rx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return Dx}buildRealObject(){return new zx(this)}};var jx;Rx=tg([Ny("banner")],Rx);const Lx={far:1e5,fov:80,near:1,zoom:1},Fx={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 Nx extends Mu{getObject3dInstance(){return new t.Mesh}updateCamera(){const{near:e=Lx.near,far:n=Lx.far,fov:s=Lx.fov,zoom:i=Lx.zoom,showHelper:r}=this.component.state;this.camera.far=n,this.camera.fov=s,this.camera.near=e,this.camera.zoom=i,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:s=0,fillStyle:i="lightgray"}=this.component.state;this.object3d.geometry=new t.BoxGeometry(e,s,n);const r=Id(this.component.state.material3d),o=new t.MeshStandardMaterial({color:i});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 $x=jx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return jx._image||(jx._image=new Image,jx._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=="),jx._image}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,jx.image,e,n,s,i)}buildRealObject(){return new Nx(this)}get nature(){return Fx}};$x=jx=tg([Ny("camera")],$x);const Hx={mutable:!1,resizable:!0,rotatable:!0,properties:[...Ly],"value-property":"source",help:"scene/component/gltf-object"};let Bx=class extends(Fy(Pc(Tc))){get nature(){return Hx}};Bx=tg([Ny("gltf-object")],Bx);const Yx={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 Gx extends Mu{updatePointLight(){const{lightType:e="point",distance:n=0,intensity:s=10,decay:i=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=i),this.object3d.intensity=s,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 Vx=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Gx(this)}get anchors(){return[]}get nature(){return Yx}};Vx=tg([Ny("light")],Vx);const Ux={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class Wx extends B_{buildGeometry(){this.object3d.geometry=ux.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?Z_(t,e):null}}let qx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Wx(this)}get nature(){return Ux}};qx=tg([Ny("wall")],qx);const Xx={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 Kx 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:s}=t,i=n>=.9&&"none"!==s;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??i}}updateHidden(){const t=this.component.state,e=!!this.component.app?.isViewMode;this.object3d.visible=!(t.hidden||e&&t.hideIn3DView)}clear(){return this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0),this._mesh=void 0,super.clear()}build(){super.build();const{width:e,height:n,depth:s=1}=this.component.state;if(!e||!n)return;const i=Math.abs(e),r=Math.abs(n),o=Math.max(s,.5),a=new t.BoxGeometry(i,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,s=Id(this.component.state.material3d),i=Mu.buildFillStyleTexture(this.component);if(i){this._topTexture=i;const e=new t.MeshStandardMaterial({map:i,side:t.DoubleSide});return nu(e,0,n),e.depthWrite=e.opacity>=.9,Rd(e,s),e}const r="string"==typeof n&&"none"!==n?su(n):"#e0e0e0",o=new t.MeshStandardMaterial({color:r,side:t.DoubleSide});return nu(o,0,n),o.depthWrite=o.opacity>=.9,Rd(o,s),o}_buildSideMaterial(){const{strokeStyle:e,alpha:n=1}=this.component.state,s="string"==typeof e&&e?su(e):"#999999",i=Id(this.component.state.material3d),r=new t.MeshStandardMaterial({color:s});return Rd(r,i),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,s=this._mesh.material;for(let t=0;t<s.length;t++){const i=s[t];nu(i,0,2===t?e:n),i.depthWrite=i.opacity>=.9}}updateFillStyle(){if(!this._mesh)return;this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0);const t=this._mesh.material;t[2].dispose(),t[2]=this._buildTopMaterial()}updateStrokeStyle(){if(!this._mesh)return;const t=this._mesh.material,e=this._buildSideMaterial();for(let n=0;n<t.length;n++)2!==n&&(t[n].dispose(),t[n]=e)}}let Qx=class extends rh{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Kx(this)}get nature(){return Xx}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}};Qx.requires3d=!0,Qx=tg([Ny("floor-plate")],Qx);function Jx(e,n={}){const s=n.size??5,i=n.color??4500172,r=n.emissive??2245734,o=new t.SphereGeometry(s,16,12),a=new t.MeshStandardMaterial({color:i,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 Zx extends B_{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:e,height:n}=this.component.state,s=Math.abs(e)||1,i=Math.abs(n)||1,r=new t.PlaneGeometry(s,i);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,s=Math.abs(e)||1,i=Math.max(2,.04*Math.min(n,s));this.object3d.add(Jx(this.component,{size:i,position:[n/2-i,i,-s/2+i]}))}}const tw={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let ew=class extends(Ry(Pc(Tc))){buildRealObject(){return new Zx(this)}get nature(){return tw}};ew=tg([Ny("decal")],ew);class nw extends Mu{getObject3dInstance(){return new t.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const sw="#dde2e8",iw="#9c9c9c",rw="#e8e8ec",ow=.35;function aw(e,n,s,i,r){if(!n.visible)return new t.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=n.alpha*s,a="wall"===i?sw:"floor"===i?iw:rw,c=new t.MeshStandardMaterial({metalness:0,roughness:"wall"===i?.6:.85,transparent:o<1,opacity:o,side:r?t.BackSide:t.DoubleSide});return function(t,e,n,s,i,r){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const s=!r,o=Mu.buildFillStyleTexture(e,n,{mirror:s,rotation:i});if(o)return t.map&&t.map.dispose(),t.map=o,void t.color.set("#ffffff")}t.color.set(s)}}(c,e,n.fillStyle,a,n.rotation,n.mirror),c}class cw extends nw{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,s=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,s=e.height)}const i=this.effectiveDepth||Math.min(n,s)||200,r=e.alpha??1,o=!1!==e.seeThrough,a={east:this._resolveFace("east",sw,!0,ow),west:this._resolveFace("west",sw,!0,ow),north:this._resolveFace("north",sw,!0,ow),south:this._resolveFace("south",sw,!0,ow),floor:this._resolveFace("floor",iw,!0,1),ceiling:this._resolveFace("ceiling",rw,!0,1)},c=[aw(this.component,a.east,r,"wall",o),aw(this.component,a.west,r,"wall",o),aw(this.component,a.ceiling,r,"ceiling",o),aw(this.component,a.floor,r,"floor",o),aw(this.component,a.south,r,"wall",o),aw(this.component,a.north,r,"wall",o)],l=new t.BoxGeometry(n,i,s),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,s,i));this.object3d.add(Jx(this.component,{size:d,position:[n/2,i/2+d,-s/2]}))}_resolveFace(t,e,n,s){const i=this.component.state,r=i.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:s,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 lw={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 hw=class extends(Ry(Pc(Tc))){buildRealObject(){return new cw(this)}get nature(){return lw}added(t){super.added?.(t),this.state.fitToBoard&&(this._syncFromRoot(!0),this._attachRootListener())}async ready(){await super.ready(),this.state.fitToBoard&&this._syncFromRoot(!1)}removed(t){this._detachRootListener(),super.removed?.(t)}dispose(){this._detachRootListener(),super.dispose?.()}onchange(t,e){"fitToBoard"in t&&(t.fitToBoard?(this._syncFromRoot(!0),this._attachRootListener()):this._detachRootListener()),super.onchange?.(t,e)}_syncFromRoot(t=!1){const e=this.rootModel;if(!e||e===this)return;const n=e.state;if(!n)return;const s={},i=Number.isFinite(n.width)?n.width:this.state.width,r=Number.isFinite(n.height)?n.height:this.state.height;i!==this.state.width&&(s.width=i),r!==this.state.height&&(s.height=r);const o=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(o!==this.state.left&&(s.left=o),a!==this.state.top&&(s.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(i,r);e!==t&&(s.depth=e)}}Object.keys(s).length>0&&this.set(s)}_attachRootListener(){if(this._onRootChange)return;const t=this.rootModel;t&&t!==this&&(this._onRootChange=t=>{("width"in t||"height"in t||"left"in t||"top"in t)&&this._syncFromRoot()},t.on?.("change",this._onRootChange))}_detachRootListener(){if(!this._onRootChange)return;const t=this.rootModel;t?.off?.("change",this._onRootChange),this._onRootChange=void 0}};function dw(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function uw(e,n,s,i){const r=[];for(let o=1;o<=i;o++){const a=o/i,c=1-a;r.push(new t.Vector3(c*c*e.x+2*c*a*n.x+a*a*s.x,c*c*e.y+2*c*a*n.y+a*a*s.y,c*c*e.z+2*c*a*n.z+a*a*s.z))}return r}hw=tg([Ny("backdrop")],hw);class pw 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 s=[];s.push(e[0]);for(let i=1;i<e.length;i++){const r=e[i-1],o=e[i],a=e[i+1];if(!a){s.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();s.push(b),s.push(...uw(b,o,v,8))}return s}_buildLine(){const e=this.smoothedPath;if(e.length<2)return;const{strokeStyle:n,lineWidth:s=2,alpha:i=1,lineDash:r,begin:o="none",beginSize:a="size5",end:c="none",endSize:l="size5"}=this.component.state,h=Math.max(s,1),d="string"==typeof n&&"transparent"!==n?su(n):"#000000",u=new t.Color(d),p=this._getResolution(),f=o,m=c,g=dw(f,h),y=dw(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(),E=[...e];g>0&&(E[0]=b.clone().add(_.clone().multiplyScalar(g))),y>0&&(E[E.length-1]=v.clone().add(x.clone().multiplyScalar(y)));const A=new S;A.setPositions(E.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:i<1,opacity:i,resolution:p,dashed:!!k,dashSize:k?.dashSize??1,gapSize:k?.gapSize??1,dashScale:1});if(this._line2=new w(A,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,i,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,i,p)}}}_placeTip(t,e,n,s,i,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(s),e.transparent=i<1,e.opacity=i}else if(t.line2){const e=t.line2.material;e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution.copy(r)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution&&e.resolution.copy(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 s=this.object3d,{width:i=0,height:r=0}=e.parent?.bounds??{},{x:o,y:a}=e.center,c=s.position,l=s.rotation,h=s.scale,d=this.position;if(Math.abs(c.x-d.x)<.001&&Math.abs(c.y-d.y)<.001&&Math.abs(c.z-d.z)<.001&&Math.abs(l.x)<.001&&Math.abs(l.y)<.001&&Math.abs(l.z)<.001&&Math.abs(h.x-1)<.001&&Math.abs(h.y-1)<.001&&Math.abs(h.z-1)<.001)return;const u=pw.computeBakedPath(n,{x:o,y:a},{width:i,height:r},s);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(e,n,s,i){const r=s.width,o=s.height,a=n.x,c=n.y;return i.updateMatrixWorld(!0),e.map(e=>{const n=new t.Vector3(e.x-a,e.z||0,e.y-c).applyMatrix4(i.matrixWorld),s={x:n.x+r/2,y:n.z+o/2};return Math.abs(n.y)>.001&&(s.z=n.y),s})}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 fw extends pw{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center,i=this.component,r=i.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=i.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((i,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(i.x-n,i.z||r+(o-r)*c,i.y-s)})}}Jp("line",t=>new fw(t));class mw extends pw{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center;return e.map(e=>new t.Vector3(e.x-n,e.z||0,e.y-s))}}Jp("polyline",t=>new mw(t));class gw extends pw{get worldPath(){const e=this.component.drawPath;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center,i=this.component,r=i.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=i.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((i,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(i.x-n,i.z||r+(o-r)*c,i.y-s)})}}function yw(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}Jp("ortholine",t=>new gw(t)),Jp("group",t=>new nw(t));class bw{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=yw(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=yw(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=bw;n._p.set(e.position.x,e.position.y,e.position.z);const s=e.rotation;n._e.set(s?.x??0,s?.y??0,s?.z??0),n._q.setFromEuler(n._e);const i=e.scale;"number"==typeof i?n._s.set(i,i,i):n._s.set(i?.x??1,i?.y??1,i?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){bw._c.set(e),this._mesh.setColorAt(t,bw._c)}}function vw(t,e,n){const s=Math.max(1,Math.floor(t.x??1)),i=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<i;t++)for(let e=0;e<r;e++)for(let n=0;n<s;n++)u.push({position:{x:l+n*o,y:h+t*a,z:d+e*c}});return u}bw._m=new t.Matrix4,bw._p=new t.Vector3,bw._q=new t.Quaternion,bw._e=new t.Euler,bw._s=new t.Vector3,bw._c=new t.Color;class _w extends Mu{build(){super.build()}update(){}}const xw={far:1e5,fov:80,near:1,zoom:1};class ww extends Mu{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new t.PerspectiveCamera}updateCamera(){const{near:t=xw.near,far:e=xw.far,fov:n=xw.fov,zoom:s=xw.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=s}}class Mw extends B_{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 Sw 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 Ew=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class Aw 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 s=Id(this.component.state.material3d),i=new t.PlaneGeometry(1,1);i.rotateX(-Math.PI/2),this.object3d.geometry=i;const r=D_(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,s),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=s.castShadow,this.object3d.receiveShadow=s.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&&(R_(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(!Ew.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 kw={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 Cw=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:s,threed:i}=this.state;let{width:r,height:o}=this.bounds;if(r=Math.floor(r),o=Math.floor(o),i){if(this._capability.isInitialized||this.init_scene3d(),this._capability.noSupportWebgl)return void this._capability.showWebglNoSupportText(t,this.state.width,this.state.height);if(!this._capability.renderer3d)return;this._capability.renderThreeD();const i=this._capability.domElement;if(!i||!i.width||!i.height)return;t.drawImage(i,0,0,i.width,i.height,e,n,r,o),s&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return Lc.get("three")}get nature(){return kw}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()}};Cw=tg([Ny("3d-container")],Cw),Zp(t=>new L_(t));const Tw=["x","y","z"],Ow=["Capacity","Holdable","Transferable","FlowNode"],Pw=Object.freeze({Transferable:["Capacity","FlowNode"]}),Iw=["S","M","L","XL"],Dw=[8,12,16,24,32,48],zw=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function Rw(t,e){const n="shape"in t?t.shape:void 0,s=n?.extrusion?.section,i="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===s?.kind||"rectangle"===s?.kind&&Object.values(s.corner??{}).some(t=>t>0));if(!i||"full"===e)return t.segments;const r=t.segments??12,o=Math.ceil(r/("medium"===e?2:4));return Math.min(r,Dw.find(t=>t>=o)??r)}function jw(t,e){if("full"===e)return t;let n=!1;const s=t.geometry.map(t=>{const s=Rw(t,e);return s===t.segments?t:(n=!0,{...t,segments:s})});return n?{...t,geometry:s}:t}class Lw extends Error{code;path;details;constructor(t,e,n,s){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==s&&(this.details=s)}}const Fw=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),Nw=1e-6,$w=256,Hw=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function Bw(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const Yw=t=>Fw[t],Gw=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function Vw(t,e){const[n,s]=Yw(e);if("rectangle"===t.kind){const e=[];for(const i of[n,s]){const n=t.size[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`size.${i}`})}if(!t.corner)return e;for(const i of[n,s]){const n=t.corner[i];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:i}):Number.isFinite(t.size[i])&&n>t.size[i]/2+Nw&&e.push({code:"CORNER_TOO_LARGE",axis:i,max:t.size[i]/2}):e.push({code:"NON_FINITE",at:`corner.${i}`})}return e.length||t.corner[n]>0==t.corner[s]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:s}),e}if("ellipse"===t.kind){const e=[];for(const i of[n,s]){const n=t.radius[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`radius.${i}`})}return e}return function(t,e){const[n,s]=Yw(e),i=[],r=new Set;for(const e of t){"string"==typeof e.id&&Hw.test(e.id)?r.has(e.id)?i.push({code:"DUPLICATE_POINT_ID",point:e.id}):r.add(e.id):i.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,s])"number"==typeof e[t]&&Number.isFinite(e[t])||i.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&i.push({code:"TOO_FEW_POINTS",count:t.length});t.length>$w&&i.push({code:"TOO_MANY_POINTS",count:t.length,limit:$w});if(i.length)return i;const o=t.length,a=function(t,e){const[n,s]=Yw(e);return t.map(t=>[t[n],t[s]])}(t,e),c=e=>Bw(t[e].id,t[(e+1)%o].id),l=Nw,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&&i.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),i.length)return i;for(let t=0;t<o;t++){const e=a[t],n=a[(t+1)%o],s=a[(t+2)%o],r=(n[0]-e[0])*(s[1]-n[1])-(n[1]-e[1])*(s[0]-n[0]),d=(n[0]-e[0])*(s[0]-n[0])+(n[1]-e[1])*(s[1]-n[1]);Math.abs(r)<=l*h[t]&&d<0&&i.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=qw(a[t],a[(t+1)%o],a[e],a[(e+1)%o],l);n&&i.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(i.length)return i;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[s,i]=t[n],[r,o]=t[(n+1)%t.length];e+=s*o-r*i}return e}(a))/2<=l&&i.push({code:"ZERO_AREA"});return i}(t.points,e)}const Uw=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function Ww(t,e,n){const s=n[0]-e[0],i=n[1]-e[1],r=s*s+i*i,o=r?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*i)/r)):0;return Math.hypot(t[0]-e[0]-o*s,t[1]-e[1]-o*i)}function qw(t,e,n,s,i){const r=Uw(n,s,t),o=Uw(n,s,e),a=Uw(t,e,n),c=Uw(t,e,s),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>i*n&&e<-i*n||t<-i*n&&e>i*n;if(h(r,o,Math.hypot(s[0]-n[0],s[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(Ww(t,n,s),Ww(e,n,s),Ww(n,t,e),Ww(s,t,e))<=i?"touch":null}function Xw(t,e){const[n,s]=Yw(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,i]=[n,s].sort(),r=[e,i].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!Gw(t))return r;const o=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${i}${n}`,shape:"curved"})));return[...r,...o]}const i=t.points;return i.map((t,e)=>{const n=i[(e+1)%i.length];return{id:Bw(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function Kw(t,e,n){const[s,i]=Yw(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const r=[s,i].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={[s]:(o(`${s}-`)-o(`${s}+`))/2,[i]:(o(`${i}-`)-o(`${i}+`))/2};if("rectangle"===t.kind){const e={[s]:a(s,t.size[s]),[i]:a(i,t.size[i])};if(!(e[s]>0&&e[i]>0))return{refused:"NO_ROOM_INSIDE"};if(!Gw(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={[s]:n(s),[i]:n(i)};return{section:{kind:"rectangle",size:e,...r[s]>0&&r[i]>0?{corner:r}:{}},centre:c}}const l={[s]:a(s,2*t.radius[s])/2,[i]:a(i,2*t.radius[i])/2};return l[s]>0&&l[i]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const Qw=(t,e)=>Object.fromEntries(Tw.map(n=>[n,n===t?e:0]));function Jw(t,e,n){const[s,i]=Fw[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return Qw(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[s]-r[s],c=o[i]-r[i],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[s]=c/l||0,h[i]=-a/l||0,h}const Zw=(t,e,n)=>{throw new Lw(t,e,n)},tM=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],eM=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),nM=["rectangle","ellipse","polygon","portal"],sM=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function iM(t,e){const n=t??{},s=n.axis;Tw.includes(s)||Zw("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const i=n.section;nM.includes(i)||Zw("PARAM",e,`section is ${nM.join(", ")}, not ${String(n.section)}`);const r=[...Fw[s]].sort(),[o,a]=r,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===i||Zw("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===i?String(n.points??"").split("."):[];"polygon"===i?((l.length<3||l.some(t=>!sM.test(t)))&&Zw("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&Zw("PARAM",e,"a point is named twice")):void 0!==n.points&&Zw("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==i&&"ellipse"!==i&&"portal"!==i||(u.across={[o]:d(),[a]:d()}),c&&(u.corner={[o]:d(),[a]:d()}),"portal"===i&&(u.jamb=d(),u.head=d()),"polygon"===i&&(u.point=Object.fromEntries(l.map(t=>[t,{[o]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==i&&"ellipse"!==i&&Zw("SECTION_KIND",e,`a ${i} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const s=n[t];return"open"!==s&&"closed"!==s&&Zw("PARAM",e,`${t} is open or closed`),s};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"]||Zw("PARAM",e,"the ends of an inside need the inside");return{axis:s,plane:r,section:i,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const rM=(t,e=1)=>[{arg:t,k:e}];function oM(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const s=t.args?.[0],i=t.args?.[1],r=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(s));return"mul@1"!==r?.op||2!==r.args.length||r.args[0]!==i||-.5!==e.constants.find(t=>t.id===r.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function aM(t,e){const n=iM(t.params,t.id),[s,i]=n.plane,r={},o={},a={},[c,l]=eM[n.axis],h=oM(t,e);if(r[n.axis]=rM(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[s,i])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[s,i])r[t]=rM(d[t],u),o[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[s]]&&t.args[d[s]]===t.args[d[i]]&&(o[i]={arg:d[i],k:u,sameAs:s}),"portal"===n.section){const[t,e]=eM[s],[c,l]=eM[i];return a[t]={axis:s,normal:-1,plane:[{arg:d[s],k:-.5}]},a[e]={axis:s,normal:1,plane:[{arg:d[s],k:.5}]},a[c]={axis:i,normal:-1,plane:[]},a[l]={axis:i,normal:1,plane:[{arg:d[i],k:1}]},a[`opening-${t}`]={axis:s,normal:1,plane:[{arg:d[s],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:s,normal:-1,plane:[{arg:d[s],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:i,normal:-1,plane:[{arg:d[i],k:1},{arg:n.arg.head,k:-1}]},{measure:r,edit:o,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[s,i]){const[e,n]=eM[t];a[e]={axis:t,normal:-1,plane:[{arg:d[t],k:-p}],...f},a[n]={axis:t,normal:1,plane:[{arg:d[t],k:p}],...f}}if(n.cavity){const t=n.arg.wall;for(const e of[s,i]){const[n,s]=eM[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${s}`]={axis:e,normal:-1,plane:[{arg:d[e],k:p},{arg:t[`${e}+`],k:-1}],...f}}void 0!==n.arg.startClosed&&(a[`inside-${c}`]={axis:n.axis,normal:1,plane:[...h.lo,{arg:n.arg.startClosed,k:1}]}),void 0!==n.arg.endClosed&&(a[`inside-${l}`]={axis:n.axis,normal:-1,plane:[...h.hi,{arg:n.arg.endClosed,k:-1}]})}return{measure:r,edit:o,faces:a,kind:n.section}}function cM(t,e){const n=t??{},s=n.axis;return Tw.includes(s)||Zw("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&Zw("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:s,profile:n.profile,count:"taper"===n.profile?4:2}}function lM(t,e){const n=cM(t.params,t.id),[s,i]=[...Fw[n.axis]].sort(),r={},o={};if("half-ellipse"===n.profile)return r[n.axis]=rM(1,2),o[n.axis]={arg:1,k:2},r[s]=r[i]=rM(0,2),o[s]={arg:0,k:2},o[i]={arg:0,k:2,sameAs:s},{measure:r,edit:o,faces:{},kind:"sphere"};const[a,c]=eM[n.axis];r[n.axis]=rM(1),o[n.axis]={arg:1,k:1};r[s]=r[i]=[{arg:2,k:2},{arg:3,k:2}],o[s]={arg:3,k:2,with:[2]},o[i]={arg:3,k:2,with:[2],sameAs:s};const l=oM(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 hM(t,e){const n=t??{};"polygon"!==n.section&&Zw("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||Zw("PARAM",e,"a loft has no corners and no inside");const s=iM(n,e),[i,r]=s.plane;return{...s,apex:{[i]:s.count,[r]:s.count+1},count:s.count+2}}function dM(t,e){const n=hM(t.params,t.id),s={},i={},[r]=eM[n.axis];s[n.axis]=rM(1),i[n.axis]={arg:1,k:1};for(const t of n.plane)s[t]="profile",i[t]={refused:"SECTION_CORNERS"};return{measure:s,edit:i,faces:{[r]:{axis:n.axis,normal:-1,plane:oM(t,e).lo}},kind:"pyramid"}}function uM(t,e){return"extrude@1"===t?.op?aM(t,e):"revolve@1"===t?.op?lM(t,e):"loft@1"===t?.op?dM(t,e):void 0}const pM=(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 fM(t,e,n){const s=Tw.find(t=>t!==e&&t!==n),[i,r]=Fw[s];let o=0;for(let e=0;e<t.length;e++){const n=t[e],s=t[(e+1)%t.length];o+=n[i]*s[r]-s[i]*n[r]}return o>0?t:[t[0],...t.slice(1).reverse()]}function mM(t,e){const[n,s]=Fw[e];let i=0;const r=t.points;for(let t=0;t<r.length;t++){const e=r[t],o=r[(t+1)%r.length];i+=e[n]*o[s]-o[n]*e[s]}return i}function gM(t,e,n){const s=iM(n.params,e),[i,r]=s.plane,o=t[0],a=t[1];a>0||Zw("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:o,length:a};let l;if("polygon"===s.section){const e=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[r]:t[s.arg.point[e][r]]}));e.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${r}`]=t[r]}),l={kind:"polygon",points:e}}else if("portal"===s.section){const n=t[s.arg.across[i]],o=t[s.arg.across[r]],a=t[s.arg.jamb],h=t[s.arg.head];n>0&&o>0&&a>0&&h>0&&2*a<n&&h<o||Zw("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${i}`]:n,[`size.${r}`]:o,jamb:a,head:h}),l=function(t,e,n,s,i,r){const o=-n/2,a=n/2,c=o+i,l=a-i,h=s-r,d=(n,s,i)=>({id:n,[t]:s,[e]:i});return{kind:"polygon",points:fM([d("p1",o,0),d("p2",o,s),d("p3",a,s),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(i,r,n,o,a,h)}else{const e={[i]:t[s.arg.across[i]],[r]:t[s.arg.across[r]]},n="ellipse"===s.section?"radius":"size";if(c[`${n}.${i}`]=e[i],c[`${n}.${r}`]=e[r],"ellipse"===s.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},s.rounded){const n={[i]:t[s.arg.corner[i]],[r]:t[s.arg.corner[r]]};c[`corner.${i}`]=n[i],c[`corner.${r}`]=n[r],(n[i]>0||n[r]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=Vw(l,s.axis);h.length&&Zw("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`),"polygon"!==l.kind||"polygon"!==s.section||mM(l,s.axis)>0||Zw("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:s.axis,section:l,start:o,end:o+a};let u;if(s.cavity){const n=Object.fromEntries(Object.entries(s.arg.wall).map(([e,n])=>[e,t[n]]));u={id:s.cavity.id,wall:n,start:"open"===s.cavity.start?"open":{closed:t[s.arg.startClosed]},end:"open"===s.cavity.end?"open":{closed:t[s.arg.endClosed]}};for(const[t,e]of Object.entries(n))c[`wall.${t}`]=e;"open"!==u.start&&(c["closed.start"]=u.start.closed),"open"!==u.end&&(c["closed.end"]=u.end.closed);const i=function(t,e=[]){const{axis:n,section:s,start:i,end:r}=t;if(!(r-i>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=Kw(s,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-i-e(o.start)-e(o.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:o.id}}}const c=Xw(s,n),l=[{id:"start-face",kind:"plane",normal:Qw(n,-1),..."open"===o?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:Qw(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:Jw(s,n,t)}:{id:`side-face:${t.id}`,kind:"curved"}),l.push({id:`edge:start:${t.id}`,kind:"edge"},{id:`edge:end:${t.id}`,kind:"edge"});if("polygon"===s.kind)for(const t of s.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===s.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...Fw[n]].sort();for(const n of["-","+"])for(const s of["-","+"])l.push({id:`edge:${t}${n}${e}${s}`,kind:"edge"})}if(o&&a){for(const t of Xw(a,n)){const e=`cavity-wall:${o.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const s=Jw(a,n,t);l.push({id:e,kind:"plane",normal:{x:-s.x||0,y:-s.y||0,z:-s.z||0}})}}"open"!==o.start&&l.push({id:`cavity-start:${o.id}`,kind:"plane",normal:Qw(n,1)}),"open"!==o.end&&l.push({id:`cavity-end:${o.id}`,kind:"plane",normal:Qw(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in i&&Zw("GEOMETRY_DOMAIN",e,`the inside is not valid: ${i.refused.code}${"refused"in i.refused?` ${i.refused.refused}`:""}`)}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:pM(aM(n).faces,t)}}function yM(t,e,n){const s=cM(n.params,e),i=pM(lM(n).faces,t);if("half-ellipse"===s.profile){const[n,r]=t;return n>0&&r>0||Zw("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:r},revolution:{axis:s.axis,profile:{kind:"half-ellipse",radial:n,axial:r}},faces:i}}const[r,o,a,c]=t;return o>0&&a>=0&&c>=0&&a+c>0||Zw("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:s.axis,profile:{kind:"taper",start:r,end:r+o,startRadius:a,endRadius:c}},faces:i}}function bM(t,e,n){const s=hM(n.params,e),[i,r]=s.plane,o=t[0],a=t[1];a>0||Zw("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:o,length:a},l=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[r]:t[s.arg.point[e][r]]}));l.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${r}`]=t[r]});const h={kind:"polygon",points:l},d=Vw(h,s.axis);d.length&&Zw("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`),mM(h,s.axis)>0||Zw("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[i]:t[s.apex[i]],[r]:t[s.apex[r]]};return Number.isFinite(u[i])&&Number.isFinite(u[r])||Zw("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${i}`]=u[i],c[`apex.${r}`]=u[r],{provider:"loft",dimensions:c,loft:{axis:s.axis,section:h,start:o,end:o+a,apex:u},faces:pM(dM(n).faces,t)}}function vM(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 _M={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const s=iM(n.params,e);return t.length===s.count&&t.every(tM)||Zw("TYPE",e,`a ${s.section} push takes ${s.count} lengths, not ${t.length}`),[vM("extrude",n,aM(n).faces)]},run:(t,e,n)=>[gM(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const s=cM(n.params,e);return t.length===s.count&&t.every(tM)||Zw("TYPE",e,`a ${s.profile} turn takes ${s.count} lengths, not ${t.length}`),[vM("revolve",n,lM(n).faces)]},run:(t,e,n)=>[yM(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const s=hM(n.params,e);return t.length===s.count&&t.every(tM)||Zw("TYPE",e,`a loft of ${s.points.length} points takes ${s.count} lengths, not ${t.length}`),[vM("loft",n,dM(n).faces)]},run:(t,e,n)=>[bM(t,e,n)]}};function xM(t){const e={};if(t.extrusion){const n=t.extrusion,[s,i]=Fw[n.axis];e[n.axis]={min:n.start,max:n.end};const r=n.section;for(const t of[s,i])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 Fw[n.axis]){const s=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...s),max:Math.max(...s)}}return e}const n=t.revolution,[s,i]=Fw[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[s,i])e[t]={min:-n.profile.radial,max:n.profile.radial}}else{const t=Math.max(n.profile.startRadius,n.profile.endRadius);e[n.axis]={min:n.profile.start,max:n.profile.end};for(const n of[s,i])e[n]={min:-t,max:t}}return e}function wM(t,e){"string"!=typeof t&&MM("PARAM",e,"layout required"),t.startsWith("L")||MM("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)))&&MM("PARAM",e,"layout is six groups of term counts, each with one candidate or more"),n}const MM=(t,e,n)=>{throw new Lw(t,e,n)},SM={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]},EM=[1,0,0],AM=[0,0,0],kM=[0,1,0],CM={kind:"count"},TM={kind:"flag"};SM.count=[CM,1];const OM=(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 PM(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||MM("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||MM("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||MM("SCHEMA",s,`unknown ${i}`)}function IM(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||MM("ID",e,"invalid id"),t}function DM(t,e){return"number"==typeof t&&Number.isFinite(t)||MM("NON_FINITE",e,String(t)),t}function zM(t,e){return Object.hasOwn(SM,t)||MM("UNIT",e,String(t)),SM[t]}function RM(t,e,n){(t.length!==e.length||t.some((t,n)=>!OM(t,e[n])))&&MM("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}const jM={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&OM(t[0],t[1])||MM("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)||MM("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)||MM("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&MM("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>(RM(t,[kM],e),[AM]),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=>OM(e,t[0])))&&MM("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&MM("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))&&MM("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)OM(t[n],t[0])||MM("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),OM(t[n+1],t[2])||MM("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],s=(t.length-1)/2,i=e=>t[1+2*e],r=e=>t[2+2*e];for(let t=1;t<s;t++)i(t)>i(t-1)||MM("DOMAIN",e,`keys out of order: at[${t}] = ${i(t)} is not after at[${t-1}] = ${i(t-1)}`);if(n<=i(0))return[r(0)];if(n>=i(s-1))return[r(s-1)];let o=0;for(;o<s-2&&i(o+1)<=n;)o++;const a=(n-i(o))/(i(o+1)-i(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)&&OM(t[0],t[1])||MM("TYPE",e,"at-least compares two scalars of the same dimension"),[TM]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>OM(e,t[0])))&&MM("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=>OM(e,t[0])))&&MM("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 s=wM(n.params.layout,e);let i=0;for(const n of s)for(const s of n){OM(t[i++],EM)||MM("TYPE",e,`candidate constant ${i-1} is a length`);for(let n=0;n<s;n++)OM(t[i++],EM)||MM("TYPE",e,`term value ${i-1} is a length`),OM(t[i++],AM)||MM("TYPE",e,`term ratio ${i-1} is a ratio`)}return i!==t.length&&MM("TYPE",e,`the layout takes ${i} arguments; ${t.length} were given`),Array(6).fill(EM)},run:(t,e,n)=>{const s=wM(n.params.layout,e);let i=0;return s.map((e,n)=>{const s=e.map(e=>{let n=t[i++];for(let s=0;s<e;s++)n+=t[i++]*t[i++];return n});return n%2==0?Math.min(...s):Math.max(...s)})}},"between@1":{ports:["length","center"],types:(t,e)=>(RM(t,[EM,EM,EM,EM],e),[EM,EM]),run:([t,e,n,s],i)=>{(n<0||s<0)&&MM("DOMAIN",i,"negative margin");const r=e-t-n-s;return r>0||MM("NO_SPACE",i,`available=${e-t}; margins=${n+s}; deficit=${Math.max(0,-r)}; positive length required`),[r,(t+e+n-s)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>(RM(t,[EM,EM,EM],e),Array(6).fill(EM)),run:([t,e,n],s)=>([t,e,n].some(t=>!(t>0))&&MM("GEOMETRY_DOMAIN",s,"positive width,height,depth required"),[-t/2,t/2,-e/2,e/2,-n/2,n/2]),geometry:([t,e,n])=>({provider:"box@1",dimensions:{width:t,height:e,depth:n}})},"cylinder@1":{ports:["start","end","radialMin","radialMax"],types:(t,e)=>(RM(t,[EM,EM],e),Array(4).fill(EM)),run:([t,e],n)=>(t>0&&e>0||MM("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}})}},LM=(t,e)=>({kind:"transform",from:t,to:e}),FM=()=>[[1,0,0],[0,1,0],[0,0,1]],NM=t=>t[0].map((e,n)=>t.map(t=>t[n])),$M=(t,e)=>t.reduce((t,n,s)=>t+n*e[s],0),HM=(t,e,n,s)=>0+t[0]*e+t[1]*n+t[2]*s,BM=(t,e)=>3===t.length&&3===e.length?[HM(t[0],e[0],e[1],e[2]),HM(t[1],e[0],e[1],e[2]),HM(t[2],e[0],e[1],e[2])]:t.map(t=>$M(t,e)),YM=(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=>NM(e).map(e=>$M(t,e)));const[n,s,i]=e;return t.map(t=>[HM(t,n[0],s[0],i[0]),HM(t,n[1],s[1],i[1]),HM(t,n[2],s[2],i[2])])},GM=(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]),VM=(t,e)=>({r:YM(t.r,e.r),t:GM(BM(t.r,e.t),t.t)}),UM=t=>{const e=NM(t.r);return{r:e,t:BM(e,t.t.map(t=>-t))}};function WM(t,e,n=[]){PM(t.params,e,n,t.id);for(const s of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])IM(t.params[s],t.id)}function qM(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&MM("TYPE",e,"rigid transforms required")}Object.assign(jM,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>(RM(t,[EM,EM,EM,EM,EM,AM,CM],e),[{kind:"layout"}]),run:([t,e,n,s,i,r,o],a)=>{t>=0&&e>=0&&n>=0&&s>0&&i>0&&r>=0&&r<=1&&Number.isSafeInteger(o)&&o>=0&&o<=1e4||MM("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<s?0:1+Math.floor((c-s)/i);l>o&&MM("RESOURCE_LIMIT",a,`count=${l}, limit=${o}`);const h=l?c-s-(l-1)*i:0;return[{centers:Array.from({length:l},(t,n)=>e+s/2+r*h+n*i),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>(RM(t,[CM,EM,EM,EM,EM,AM,CM],e),[{kind:"layout"}]),run:([t,e,n,s,i,r,o],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(o)&&o>=0&&o<=1e4&&e>=0&&n>=0&&s>=0&&i>0&&r>=0&&r<=1||MM("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>o&&MM("RESOURCE_LIMIT",a,"fixed count exceeds limit"),!t)return[{centers:[],count:0}];const c=e-n-s-i;return(c<0||t>1&&c/(t-1)<i)&&MM("NO_SPACE",a,"fixed count non-overlapping items do not fit"),[{centers:1===t?[n+i/2+r*c]:Array.from({length:t},(e,s)=>n+i/2+s*c/(t-1)),count:t}]}},"assembly@1":{ports:["assembly"],types:(t,e)=>(t.length&&!t.some(e=>"placed"!==e.kind&&"collection"!==e.kind||e.frame!==t[0].frame)||MM("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)||MM("AXIS",e,n.params.axis);const s=4===t.length;return!s||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&OM(t[3],EM)||MM("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!s||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&MM("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,s],i,r)=>{t.count*e.members.length>1e4&&MM("RESOURCE_LIMIT",i,"expanded geometry count > 10000");const o=["x","y","z"].indexOf(r.params.axis),a=["x","y","z"].indexOf(r.params.riseAxis),c=[];for(let i=0;i<t.count;i++)for(const l of e.members){const e=[0,0,0];e[o]=t.centers[i],void 0!==s&&(e[a]=i*s);const h=[r.id,i,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:i,shape:l.shape,pose:VM(VM(n,{r:FM(),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&&OM(t[1],CM)||MM("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,s)=>{const i=t.items.find(t=>t.index===e&&t.key===s.params.member);return i||MM("TARGET_ABSENT",n,`${s.params.member}[${e}]`),[{shape:i.shape,pose:i.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>(RM(t,[EM,EM,EM,kM,kM,kM],e),[LM(n.params.from,n.params.to)]),run:([t,e,n,s,i,r])=>{const o=Math.cos(s),a=Math.sin(s),c=Math.cos(i),l=Math.sin(i),h=Math.cos(r),d=Math.sin(r);return[{r:YM(YM([[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)=>(RM(t,[AM,AM,AM,kM],e),[LM(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const r=Math.hypot(t,e,n);Math.abs(r-1)>1e-6&&MM("AXIS",i,"unit axis required");const o=t/r,a=e/r,c=n/r,l=Math.cos(s),h=Math.sin(s),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)=>(RM(t,[AM,AM,AM,EM],e),[LM(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const r=Math.hypot(t,e,n);return Math.abs(r-1)>1e-6&&MM("AXIS",i,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/r*s,e/r*s,n/r*s]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(qM(t,e,2),t[1].to!==t[0].from&&MM("FRAME_TYPE",e,"composition intermediate frame mismatch"),[LM(t[1].from,t[0].to)]),run:([t,e])=>[VM(t,e)]},"attach@1":{ports:["pose"],types(t,e){qM(t,e,3);const[n,s,i]=t;return n.from===s.to&&s.from===i.from||MM("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[LM(i.to,n.to)]},run:([t,e,n])=>[VM(VM(t,e),UM(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>(RM(t,[EM,EM,EM],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||MM("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[GM(BM(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&OM(t[0],t[1])||MM("FRAME_TYPE",e,"distance requires points in same frame"),[EM]),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||MM("TYPE",e,"shape required");const s=Object.keys(t[0].faces);return[...s,"centre",..."revolve"!==t[0].provider||s.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||MM("UNKNOWN_FEATURE",e,n.params.name),[LM(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const s=function(t,e){const n=xM(t),s=Tw.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return s;const i=t.faces[e],r={x:0,y:1,z:2};if(i){const n=[...s];if(n[r[i.axis]]=i.at,t.loft)for(const e of Fw[t.loft.axis]){const s=t.loft.section.points.map(t=>t[e]);n[r[e]]=(Math.min(...s)+Math.max(...s))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,o=t.cavity,a=o.wall;for(const t of Fw[e.axis])t!==i.axis&&(n[r[t]]=s[r[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(i.axis!==e.axis){const t=e.start+("open"===o.start?0:o.start.closed),s=e.end-("open"===o.end?0:o.end.closed);n[r[e.axis]]=(t+s)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(eM).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]).find(([t])=>t===e);if(!t)return;const i=[...s];return i[r[t[1]]]=t[2]<0?n[t[1]].min:n[t[1]].max,i}}(t,n.params.name);return s||MM("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:s}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||MM("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})}}),jM["member@1"]={...jM["place@1"],geometry:void 0},Object.assign(jM,_M);for(const[t,e]of Object.entries(jM))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const XM=[];for(const[t,e]of Object.entries(jM))e.pure=!XM.includes(t);const KM=["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(jM))e.pure&&KM.includes(t)&&(e.poseForm="run");function QM(t,e,n){return Array.isArray(e)?DM(t,n):"flag"===e.kind?("boolean"!=typeof t&&MM("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&MM("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&nS(t)?iS(t,n):"placed"===e.kind&&eS(t,"shape","pose")&&oS.has(t.shape)&&nS(t.pose)?iS(t.pose,n):(rS(t,n),"shape"===e.kind&&t&&"object"==typeof t&&oS.add(t)),t)}function JM(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++)JM(t[e]);else for(const e in t)JM(t[e]);return t}function ZM(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(nS(t)){const e=new Array(t.r.length);for(let n=0;n<e.length;n++)e[n]=Object.freeze(t.r[n].slice());n={r:Object.freeze(e),t:Object.freeze(t.t.slice())}}else if(Array.isArray(t)){n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=ZM(t[s],e)}else{n={};for(const s in t)n[s]=ZM(t[s],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(jM).filter(t=>!jM[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(jM).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(jM).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(jM));const tS=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],eS=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let s=0;for(const i in t)if(Object.hasOwn(t,i)){if(s>1||i!==(0===s?e:n))return!1;s++}return 2===s},nS=t=>eS(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function sS(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const s=t[n];"number"==typeof s?Number.isFinite(s)||MM("NON_FINITE",e,String(s)):rS(s,e)}}function iS(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const s=t.r[n];Array.isArray(s)?sS(s,e):rS(s,e)}sS(t.t,e)}function rS(t,e){if("number"==typeof t)Number.isFinite(t)||MM("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&rS(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]])))&&oS.has(t))return;for(let s=0;s<n.length;s++)rS(t[n[s]],e)}}const oS=new WeakSet,aS=["transform","placed","assembly","collection","point"],cS=t=>Array.isArray(t)||aS.includes(t?.kind)?void 0:String(t?.kind??"value");function lS(t){return function(t){PM(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||MM("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||MM("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,s=new Map,i=new Map,r=new Map,o=[],a=[],c=(t,e)=>{IM(t,e),n.has(t)&&MM("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)PM(t,["id","unit","min","max"],["role"],"input"),c(t.id,"input"),s.set(t.id,zM(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&MM("SCHEMA",t.id,"unknown input role"),"state"===t.role&&i.set(t.id,new Set([t.id])),DM(t.min,t.id)>DM(t.max,t.id)&&MM("RANGE",t.id,"min > max"),"count"===t.unit&&(QM(t.min,CM,t.id),QM(t.max,CM,t.id));for(const t of e.constants)PM(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),s.set(t.id,zM(t.unit,t.id)[0]),QM(t.value,s.get(t.id),t.id);for(const t of e.nodes){PM(t,["id","op","args","outputs"],["params"],"node"),IM(t.id,"node"),r.has(t.id)&&MM("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(jM,t.op)||MM("OPERATOR",t.id,t.op),jM[t.op].params?WM(t,jM[t.op].params,jM[t.op].optionalParams):Object.hasOwn(t,"params")&&MM("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||MM("SCHEMA",t.id,"args array required"),t.args.forEach(e=>IM(e,t.id)),PM(t.outputs,jM[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)&&MM("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 i=e.args[t.at];if(n.has(i)||MM("UNKNOWN_REFERENCE",e.id,i),!s.has(i)){u(n.get(i));continue}t.inputTypes.push(s.get(i)),t.at++;continue}const r=jM[e.op],c=r.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of i.get(t)??[])p.add(e);p.size&&(void 0===r.state&&MM("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===r.state&&MM("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),r.ports.forEach((t,n)=>s.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>i.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),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)||MM("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||MM("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||MM("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=DM(e,t.id);return(n<t.min||n>t.max)&&MM("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`),QM(n*zM(t.unit,t.id)[1],s.get(t.id),t.id)}function b(t,n){g(t);const i=new Map,r=[],a=new Map,c=new Set;for(const n of e.inputs)i.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)i.set(t.id,DM(t.value*zM(t.unit,t.id)[1],t.id));for(const t of o){const e=jM[t.op],n=t.args.map(t=>i.get(t)),o=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{i.set(t.outputs[e],QM(o[n],s.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const s=tS(e.geometry(n,o,t),t.id);a.set(t.id,s),r.push(...s)}}return{result:{values:Object.fromEntries(i),geometry:r},kept:{input:{...t},values:i,bodies:a}}}return{outputTypes:Object.fromEntries([...s].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...i].map(([t,e])=>[t,[...e].sort()])),order:o.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,s=0,i=[],r=0;const o=(t,e)=>{const n=e||t.length!==i.length||t.some((t,e)=>t!==i[e]);return n&&s++,i=t,n},a=(t,e)=>(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 s=E(t,n,!0);return e=n,a(s,!1)},l=(t,n)=>{const i=++r,a=e;e=void 0;const c=a?.fast;let l;a?(l=E(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 A=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[A]=g[t]+n,S[A]=e.shape??null;const s=12*A;if(e.pose){const t=e.pose.r,n=e.pose.t;M[s]=t[0][0],M[s+1]=t[0][1],M[s+2]=t[0][2],M[s+3]=t[1][0],M[s+4]=t[1][1],M[s+5]=t[1][2],M[s+6]=t[2][0],M[s+7]=t[2][1],M[s+8]=t[2][2],M[s+9]=n[0],M[s+10]=n[1],M[s+11]=n[2]}else M.fill(NaN,s,s+12);A++});const k=d.epoch,C=()=>{r!==i&&MM("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:s,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{C();const e=h().slot.get(t);return void 0===e&&MM("TARGET_ABSENT",t,"no such value"),ZM(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(i,o){if(e&&!o){const o=++r,a=e;e=void 0;const h=S(i,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{r!==o&&MM("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:s,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(i,h.why);return{kind:"evaluation",result:c(i),generation:s,why:h.why}}const a={code:!!e?o:"NOT_BOUND"};if(t.changes)return l(i,a);return{kind:"evaluation",result:c(i),generation:s,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||MM("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&MM("TARGET_ABSENT",t,"no such value");const s=e.fast;if(!s)return ZM(e.slots[n],new Map);const i=h().nodes.find(t=>t.outs.includes(n));if(i&&s.wrote.has(i.index)&&!s.moved.has(n)){return ZM(i.op.run(i.args.map(t=>s.slots[t]),i.n.id,i.n)[i.outs.indexOf(n)],new Map)}return ZM(s.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],i=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>i(t.id)),e.constants.forEach(t=>i(t.id));const r=o.map((e,n)=>{const r=jM[e.op];return r.ports.forEach(t=>i(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=>s.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 s of a[t])e[s]||(e[s]=1,n.push(...r[s].outs))}const s=[];return e.forEach((t,e)=>t&&s.push(e)),s},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"===s.get(t)?.kind)},p}function _(t,n=!0){const s=v(),i=s.keys.map(e=>t.values.get(e));i.forEach((t,e)=>s.shapeSlot[e]&&JM(t));const r=s.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of s.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:r,shown:r.map(()=>{}),values:n,geometry:[],mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set(s.shapes.filter(t=>r[t])),slots:new Set(s.keys.keys())}}}const o=new Map,a=r.map(t=>t?.map(t=>ZM(t,o))),c={};s.keys.forEach((t,e)=>c[t]=ZM(i[e],o));const l=[];for(const t of s.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:r,shown:a,values:c,geometry:l,mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),i=f.get(n);if(i)return i;const r=v(),o=t.forbidden??{},a=new Set(t.external??[]),c={inputs:e.inputs.map((t,e)=>{const n=cS(s.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,s]of e.outs.entries()){const i=cS(e.types[n]);if(i)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:i};const a=r.keys[s];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 s=t.join();let i=e.visits.get(s);if(!i){const r=new Set;for(const e of t)for(const t of n.reach[e])r.add(t);i=[...r].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(s,i)}return i}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let s=0;for(const i of e.shapes)n[i]=s,s+=t.bodies[i]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:s,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,s){const i=v();g(t);const r=n.fast?.raw??n.raw,o=[],a=[];for(let n=0;n<e.inputs.length;n++){const s=e.inputs[n],i=t[s.id];i!==r[n]&&(a.push(y(s,i)),o.push(n))}for(const t of o)if(!s.inputs[t].fast)return{why:s.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;o.forEach((n,s)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[s],c.mark[n]=l});const h=w(o,s),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,s=e.t,i=12*p;d[p++]=t,u[i]=n[0][0],u[i+1]=n[0][1],u[i+2]=n[0][2],u[i+3]=n[1][0],u[i+4]=n[1][1],u[i+5]=n[1][2],u[i+6]=n[2][0],u[i+7]=n[2][1],u[i+8]=n[2][2],u[i+9]=s[0],u[i+10]=s[1],u[i+11]=s[2]};for(const t of h){const e=i.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const r=new Array(e.args.length);for(let t=0;t<e.args.length;t++)r[t]=c.slots[e.args[t]];if(s.terminal[t]){const[n,s,i,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(VM(i,{r:FM(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of s.members){const s=VM(d[t],n.pose);rS(s,e.n.id),f(u++,s)}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]=QM(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),s=Array.isArray(n)?n:[n];let i=c.start[t];for(const t of s)f(i++,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=i.slot.get(t);return void 0===e&&MM("TARGET_ABSENT",t,"no such value"),ZM(c.slots[e],new Map)},changed:t=>{const e=i.slot.get(t);return void 0!==e&&c.mark[e]===l}}}}function E(t,n,s){const i=v();g(t),n.fast=void 0;const r=++n.epoch,o=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,s)=>{const i=t[e.id];i!==n.raw[s]&&(n.slots[s]=y(e,i),n.raw[s]=i,n.mark[s]=r,o.push(s),c>=0&&(l=!0),c=s)}),l||i.always.length){const t=[];for(const e of[...o.map(t=>i.reach[t]),i.always])for(const s of e)n.ran[s]!==r&&(n.ran[s]=r,t.push(s));a=t.sort((t,e)=>t-e)}else a=c>=0?i.reach[c]:[];const h=[];for(const t of a){const e=i.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===r))continue;const s=e.args.map(t=>n.slots[t]),a=e.op.run(s,e.n.id,e.n);e.outs.forEach((t,s)=>{n.slots[t]=QM(a[s],e.types[s],e.n.id),i.shapeSlot[t]&&JM(n.slots[t]),n.mark[t]=r,o.push(t)}),e.op.geometry&&(n.bodies[t]=tS(e.op.geometry(s,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(!s){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of o)n.values[i.keys[t]]=void 0;return h}return A(n),{values:{...n.values},geometry:n.geometry.slice()}}function A(t){const e=v(),{nodes:n,slots:s}=t.pending;if(!n.size&&!s.size)return;const i=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>ZM(t,i));for(const n of s)t.values[e.keys[n]]=ZM(t.slots[n],i);if(n.size){const n=[];for(const s of e.shapes){const e=t.shown[s];e&&n.push(...e)}t.geometry=n}n.clear(),s.clear()}}(t)}function hS(t,e,n){const s=function(t,e){const n=t.find(t=>t.id===e);if(!n)return{code:"TARGET_ABSENT",message:`${String(e)} is not an input of the figure`};if("state"===n.role)return{code:"PUBLIC_INPUT",message:`${e} is a state input; a board sets it as a parameter`};if(/^(sizing\.)?size\.[xyz]$/.test(e))return{code:"PUBLIC_INPUT",message:`${e} is the figure's size; a board sets it from the instance's bounds`};const s=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return s(n.min)&&s(n.max)?null:{code:"PUBLIC_INPUT",message:`${e} has no range to hold a board's value to; give it one first`}}(t,e);if(s)throw new Lw(s.code,n,s.message)}const dS=(t,e,n)=>{throw new Lw(t,e,n)},uS={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 pS(t,e,n){const{types:s,writers:i,model:r,assetFrame:o}=t;e&&"object"==typeof e&&!Array.isArray(e)||dS("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||dS("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||dS("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||dS("SCHEMA",n,"nonempty string required"),Object.hasOwn(s,t)||dS("TARGET_ABSENT",n,t),s[t]),c=a(e.placement),l=a(e.feature),h=i.get(e.placement),d=i.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=i.get(h.args[0]),e="repeat@1"===t?.op?i.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||dS("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=i.get(h.params.member),"member@1"!==p?.op&&dS("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),r.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&dS("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&&dS("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required");"feature@1"!==d?.op&&dS("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===o&&"transform"===l.kind||dS("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&dS("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=s[d.args[0]].provider,m=d.params.name,g=s[d.args[0]].faces,y=g?.[m];y||dS("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&dS("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 fS(t,e,n,s,i={}){const[r,o]=Fw[e],a=(t,s)=>{const a={x:0,y:0,z:0};return a[e]=n,a[r]=t+(i[r]??0),a[o]=s+(i[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:s},(e,n)=>{const i=2*Math.PI*n/s;return a(t.radius[r]*Math.cos(i),t.radius[o]*Math.sin(i))});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 s=0;s<=8;s++){const i=n+s/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(i),e*(l-d)+d*Math.sin(i)))}return u}function mS(t,e){return function(t,e){const n=t.extrusion;if(n){const s=[...fS(n.section,n.axis,n.start,e),...fS(n.section,n.axis,n.end,e)],i=t.cavity;if(i){const t=Kw(n.section,n.axis,i.wall);if("section"in t){const r=n.start+("open"===i.start?0:i.start.closed),o=n.end-("open"===i.end?0:i.end.closed);s.push(...fS(t.section,n.axis,r,e,t.centre),...fS(t.section,n.axis,o,e,t.centre))}}return s}const s=t.loft;if(s){const t={x:0,y:0,z:0,...s.apex,[s.axis]:s.end};return[...fS(s.section,s.axis,s.start,e),[t.x,t.y,t.z]]}const i=t.revolution,[r,o]=Fw[i.axis],a=(t,n)=>fS({kind:"ellipse",radius:{[r]:n,[o]:n}},i.axis,t,e);if("taper"===i.profile.kind)return[...a(i.profile.start,Math.max(i.profile.startRadius,1e-9)),...a(i.profile.end,Math.max(i.profile.endRadius,1e-9))];const{radial:c,axial:l}=i.profile,h=[];for(let t=1;t<6;t++){const e=t/6*Math.PI;h.push(...a(l*Math.cos(e),c*Math.sin(e)))}return h.push(...a(l,1e-9).slice(0,1),...a(-l,1e-9).slice(0,1)),h}(t,e??12)}function gS(t,e,n){return t.map(([t,s,i])=>[e[0][0]*t+e[0][1]*s+e[0][2]*i+n[0],e[1][0]*t+e[1][1]*s+e[1][2]*i+n[1],e[2][0]*t+e[2][1]*s+e[2][2]*i+n[2]])}function yS(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 bS=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function vS(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const _S=t=>"number"==typeof t&&Number.isFinite(t),xS=t=>_S(t)&&t>0,wS=t=>Number.isSafeInteger(t)&&t>0;function MS(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])xS(s[t])||n.push(vS("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(vS("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||wS(t.stackLimit)||t.stackLimit===1/0||n.push(vS("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||_S(t.rotation)||n.push(vS("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(vS("ARRAY_REQUIRED",`${e}.accepts`))}function SS(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}}const ES=(t,e)=>e&&0!==t?-t:t;function AS(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!wS(e.slot)||e.slot>SS(s.layout))return null;const i=s.layout;let r,o,a;switch(i.pattern){case"SINGLE":r=i.slot,o={x:0,z:0};break;case"ROW":{const t=ES((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);r=i.slot,o="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{const{r:t,c:n}=function(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};r=i.slot,o={x:ES((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:ES((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,elevation:s.elevation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function kS(t){return`t${t.tier}_s${t.slot}`}function CS(t){if(!t?.layout)return[];const e=[];for(const n of function*(t){for(const e of t?.tiers??[])for(let t=1;t<=SS(e.layout);t++)yield{tier:e.tierNo,slot:t}}(t.layout)){const s=AS(t.layout,n);if(!s)continue;const i=kS(n);e.push({id:i,label:`${t.label} ${i}`,role:t.role,frame:t.frame,pose:{...t.pose},accepts:[...s.accepts??[]],capacity:s.stackLimit,tier:s.tier,slot:s.slotNo,...s.name?{name:s.name}:{},offset:{...s.offset},elevation:s.elevation,rotation:s.rotation,mount:t.layout.mount,allowed:{...s.allowed}})}return e}const TS=["floor","ceiling","center","wall"],OS=(t,e,n)=>{throw new Lw(t,e,n)},PS={left:"x",right:"x",bottom:"y",top:"y",back:"z",front:"z"},IS=["fixed","revolute","prismatic"],DS={left:-1,right:1,bottom:-1,top:1,back:-1,front:1};function zS(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 RS(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 jS={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 LS=(t,e)=>t.nodes.find(t=>t.id===e),FS=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function NS(t,e,n){const s=LS(t,e),i="member@1"===s?.op&&(!!LS(t,`${e}.repeat`)||void 0!==function(t,e){const n=LS(t,e);if("member@1"!==n?.op||LS(t,`${e}.repeat`))return;const s=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return s?String(s.id).replace(/\.assembly$/,""):void 0}(t,e));s&&("place@1"===s.op||i)||OS("TARGET_ABSENT",n,`${e} is not a placed part`);const r=FS(t,s.args[0]);r||OS("TARGET_ABSENT",n,`${e} has no shape`);const o=LS(t,`${e}.pose`);return o&&"rigid@1"===o.op||OS("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:s,shape:r,pose:o}}function $S(t,e,n,s){return NS(t,n,s).pose.args.slice(3,6).map(n=>function(t,e,n){const s=t.constants.find(t=>t.id===n);if(s)return s.value;const i=t.inputs.find(t=>t.id===n);return i&&"state"!==i.role?e.designInputs[n]??null:null}(t,e,n))}const HS=t=>Tw.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", ");function BS(t,e,n,s,i){const r=$S(t,e,n,s);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)&&OS("EDIT_TARGET",s,`${n} is turned (${HS(r)}); only quarter turns keep its faces level with the axes`);const o=YS(r);{const i=NS(t,n,s).pose,o=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...r.map(e=>tE(t,"deg",e,"a"))];for(const s of o)cE(e,s,aE(t,n,s)?s:void 0)}return o}function YS(t){const[e,n,s]=t.map(t=>t*Math.PI/180),i=t=>Math.round(Math.cos(t)),r=t=>Math.round(Math.sin(t)),o=[[1,0,0],[0,i(e),-r(e)],[0,r(e),i(e)]],a=[[i(n),0,r(n)],[0,1,0],[-r(n),0,i(n)]],c=[[i(s),-r(s),0],[r(s),i(s),0],[0,0,1]];return GS(GS(o,a),c)}const GS=(t,e)=>t.map(t=>e[0].map((n,s)=>t.reduce((t,n,i)=>t+n*e[i][s],0))),VS=t=>t.map(t=>({ref:t.ref,k:-t.k})),US=t=>t.map(t=>({ref:t.ref,k:t.k/2})),WS={x:["left","right"],y:["bottom","top"],z:["back","front"]};function qS(t,e,n){const{shape:s}=NS(t,e,n),i=function(t,e){const n=uM(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}(s,t);return i||OS("EDIT_TARGET",n,`${e} is a ${s.op}; it has no flat face to fasten by`),{shape:s,faces:i}}function XS(t,e){if("centre"!==e.body1.face)return e.body1.face;const n=`joints.${e.id}.body1.face`;"part"in e.body0||OS("JOINT_SCHEMA",n,"a part stands on the mounting plane by a face of its own, not by its centre");const s=e.body0.face;if(Object.hasOwn(PS,s))return Object.keys(PS).find(t=>PS[t]===PS[s]&&DS[t]===-DS[s]);const i=qS(t,e.body0.part,n).faces[e.body0.face];return i||OS("JOINT_SCHEMA",n,`${e.body0.part} has no face ${e.body0.face}`),Object.keys(PS).find(t=>PS[t]===i.axis&&DS[t]===-i.normal)}const KS=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function QS(t,e,n){const{shape:s,faces:i}=qS(t,e,n),r={},o=uM(s,t).measure;for(const t of Tw){const[e,n]=WS[t].map(t=>i[t]),a=o[t],c=a&&"profile"!==a?KS(s,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?KS(s,e):[...KS(s,n),...VS(c)],h=n?KS(s,n):[...KS(s,e),...c];r[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(VS(h))}}return r}function JS(t,e,n,s){const i=QS(t,n,s),r=BS(t,e,n,s),o={};return Tw.forEach((t,e)=>{const n=r[e].findIndex(t=>0!==t),s=i[Tw[n]];s&&(o[t]=r[e][n]>0?s:{lo:VS(s.hi),hi:VS(s.lo),centred:s.centred})}),o}function ZS(t,e){const n=new Set([...t.nodes.map(t=>t.id),...t.nodes.flatMap(t=>Object.values(t.outputs)),...t.constants.map(t=>t.id),...t.inputs.map(t=>t.id)]);return t=>{let s=`${e}.${t}`;for(let i=2;n.has(s)||n.has(`${s}.value`);i++)s=`${e}.${t}.${i}`;return n.add(s),n.add(`${s}.value`),s}}function tE(t,e,n,s){const i=t.constants.find(t=>t.unit===e&&t.value===n);if(i)return i.id;const r=`${s}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:r,unit:e,value:n}),r}function eE(t,e,n,s,i,r){let o=n;if(1!==s){const n=e(`${r}.times`);t.nodes.push({id:n,op:"mul@1",args:[o,tE(t,"ratio",s,"k")],outputs:{value:`${n}.value`}}),o=`${n}.value`}if(0!==i){const n=e(`${r}.plus`);t.nodes.push({id:n,op:"add@1",args:[o,tE(t,"mm",i,"d")],outputs:{value:`${n}.value`}}),o=`${n}.value`}return o}function nE(t,e,n,s,i,r){if(void 0===s)return tE(t,"mm",0,"d");if("number"==typeof s)return Number.isFinite(s)||OS("SCHEMA",r,"a finite length is required"),tE(t,"mm",s,"d");s&&"object"==typeof s&&(Object.hasOwn(s,"sum")||s.from)||OS("SCHEMA",r,"a length is a number of millimetres, or something to follow");const{terms:o,plus:a,sum:c}=RS(s),l=sE(t,e,o,a,r);return c?eE(t,n,iE(t,n,l,`${i}.sum`),1,a,i):eE(t,n,l[0].ref,l[0].k,a,i)}function sE(t,e,n,s,i){return Array.isArray(n)&&n.length||OS("SCHEMA",i,"a sum has one term or more"),Number.isFinite(s)||OS("SCHEMA",i,"finite times and plus required"),n.map((s,r)=>{const o=n.length>1?`${i}.sum.${r}`:i;return s&&"object"==typeof s&&s.from||OS("SCHEMA",o,"a length is a number of millimetres, or something to follow"),Number.isFinite(s.times??1)||OS("SCHEMA",o,"finite times and plus required"),{ref:rE(t,e,s.from,o),k:s.times??1}})}function iE(t,e,n,s){const i=n.filter(t=>0!==t.k);if(!i.length)return tE(t,"mm",0,"d");let r="";for(const[n,o]of i.entries()){const i=eE(t,e,o.ref,o.k,0,`${s}.${n}`);if(r){const o=e(`${s}.${n}.sum`);t.nodes.push({id:o,op:"add@1",args:[r,i],outputs:{value:`${o}.value`}}),r=`${o}.value`}else r=i}return r}function rE(t,e,n,s){if(n&&"object"==typeof n||OS("SCHEMA",s,"a dimension source is required"),"instance"===n.of){const i=`size.${n.axis}`;return t.inputs.some(t=>t.id===i)||OS("TARGET_ABSENT",s,`the instance has no ${i}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const s=LS(t,`sizing.size.${e}`);return s||OS("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),s.outputs.value}(t,n.axis,s):i}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||OS("TARGET_ABSENT",s,`${n.input} is not an input of this asset`),"state"===e.role&&OS("EDIT_TARGET",s,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?oE(t,n.part,n.axis,s):OS("SCHEMA",s,`${String(n.of)} is not a dimension source`)}function oE(t,e,n,s){const i=NS(t,e,s).shape,r=uM(i);if(r){const o=r.edit[n];if("refused"in o)return OS("EDIT_TARGET",s,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(o.sameAs)return oE(t,e,o.sameAs,s);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(LS(t,a))return c;const l=i.args[o.arg],h=tE(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),i.args=i.args.map(t=>t===l?c:t);const d=LS(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return OS("EDIT_TARGET",s,`${e} is a ${i.op}; it is not a shape with measures`)}const aE=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role);function cE(t,e,n){const s=t.document.model,i=new Set([...FE(t.occupancy),...FE(t.document.capabilities),...FE(t.joints)]),r=t=>s.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||i.has(t);if(r(e))return;const o=s.inputs.findIndex(t=>t.id===e);if(o>=0){if(e!==n)return;return s.inputs.splice(o,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const a=FS(s,e);if(a&&"place@1"!==a.op&&!Object.values(a.outputs).some(t=>t!==e&&r(t))){s.nodes=s.nodes.filter(t=>t!==a);for(const e of a.args)cE(t,e)}}function lE(t,e){if(!LS(t,`${e}.chain`)&&!LS(t,`${e}.repeat`))return null;const n=LS(t,`${e}.seat.rigid`)??LS(t,`${e}.motion`),s=/^(.*)\.local$/.exec(String(n?.params?.to));return s&&s[1]!==e?s[1]:null}function hE(t,e,n){const s=t.document.model,i=e.to,r=`${e.part} to ${i?.plane??i?.part}`;if(i&&"object"==typeof i||OS("SCHEMA",r,"a target face, or the plane the figure is mounted on, is required"),void 0!==i.plane)return function(t,e,n){const s=t.document.model,i=e.to;"mounting-plane"!==i.plane&&OS("SCHEMA",n,`${String(i.plane)} is not a plane a part can stand on`);void 0!==e.facing&&"meet"!==e.facing&&OS("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)||OS("ATTACH_FACE",n,"wall"===r?`${String(e.face)} faces along ${PS[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 ${PS[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`);lE(s,e.part)&&!e.replace&&OS("ATTACH_REPLACED",n,`${e.part} is already fastened to ${lE(s,e.part)}; pass replace to stand it on the plane instead`);const c=JS(s,t,e.part,n);c[a]&&Object.hasOwn(qS(s,e.part,n).faces,e.face)||OS("EDIT_TARGET",n,`${e.part} has no flat ${e.face} face`);const l=ZS(s,`${e.part}.on.plane`),h="top"===e.face?-1:1,d=nE(s,t,l,e.gap,`gap.${a}`,n),u={x:"",y:"",z:""};u[a]=iE(s,l,[...VS(h>0?c[a].lo:c[a].hi),{ref:d,k:h}],`stand.${a}`);const p=tE(s,"mm",0,"d"),f={x:p,y:p,z:p};f[a]=u[a];for(const i of Tw.filter(t=>t!==a)){const r=e.align?.[i]??"centre",o=c[i];if("centre"===r)u[i]=tE(s,"mm",0,"d");else if("object"==typeof r&&r&&Object.hasOwn(r,"mm"))u[i]=nE(s,t,l,r.mm,`align.${i}`,n);else{if(("min"===r||"max"===r)&&pE(s,i)){o||OS("ATTACH_FACE",n,`${e.part} has no edges along ${i} to line up with the figure's side`);const a="min"===r?-1:1;u[i]=iE(s,l,[{ref:rE(s,t,{of:"instance",axis:i},n),k:.5*a}],`figure-edge.${i}`),f[i]=iE(s,l,VS("min"===r?o.lo:o.hi),`own-edge.${i}`);continue}OS("SCHEMA",n,`the plane has no edges to line ${e.part} up with on ${i}; declare the figure's size, or give the centre or a measured offset`)}o&&!o.centred&&(f[i]=iE(s,l,VS([...US(o.lo),...US(o.hi)]),`own-centre.${i}`))}const m=Tw.map(t=>t===a?p:u[t]);return uE(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===i.part&&OS("ATTACH_CYCLE",r,"a part cannot be fastened to itself");const o="centre"===e.face;o||Object.hasOwn(PS,String(e.face))||OS("SCHEMA",r,`${String(e.face)} is not a face`);const a=qS(s,i.part,r),c=Object.hasOwn(a.faces,String(i.face))?a.faces[i.face]:void 0;c||OS("SCHEMA",r,`${i.part} has no face ${String(i.face)}; it has ${Object.keys(a.faces).join(", ")}`);const l=e.facing??"meet";"meet"!==l&&"flush"!==l&&OS("SCHEMA",r,`${String(l)} is neither meet nor flush`);const h=c.axis,d=c.normal;o&&"meet"!==l&&OS("ATTACH_FACE",r,`${e.part} fastened by its centre sits on ${i.face}; flush has no meaning for a centre`),o&&(e={...e,face:Object.keys(PS).find(t=>PS[t]===h&&DS[t]===-d)}),PS[e.face]!==h&&OS("ATTACH_FACE",r,`${e.face} faces along ${PS[e.face]} and ${i.face} along ${h}; fastening them would need a turn, which this command does not do`);const u=Object.keys(PS).find(t=>PS[t]===h&&DS[t]===("meet"===l?-d:d));"meet"===l&&e.face!==u&&OS("ATTACH_FACE",r,`to meet ${i.face}, ${e.part} offers its ${u}; pass flush to lay ${e.face} in the same plane instead`),"flush"===l&&e.face!==u&&OS("ATTACH_FACE",r,`to lie flush with ${i.face}, ${e.part} offers its ${u}`),lE(s,e.part)&&!e.replace&&OS("ATTACH_REPLACED",r,`${e.part} is already fastened to ${lE(s,e.part)}; pass replace to move it, or detach it first`);for(let t=i.part;t;t=lE(s,t))t===e.part&&OS("ATTACH_CYCLE",r,`${i.part} already hangs from ${e.part}`);const p=QS(s,i.part,r),f=JS(s,t,e.part,r),m=f[h];m&&Object.hasOwn(qS(s,e.part,r).faces,e.face)||o||OS("EDIT_TARGET",r,`${e.part} has no flat ${e.face} face`);const g=ZS(s,`${e.part}.on.${i.part}`),y="meet"===l?d:-d,b=nE(s,t,g,e.gap,`gap.${h}`,r),v=tE(s,"mm",0,"d"),_={x:"",y:"",z:""},x={x:v,y:v,z:v};_[h]=iE(s,g,[...KS(a.shape,c),...o?[{ref:b,k:y}]:[]],`seat.${h}`);const w=o?m&&!m.centred?[...US(m.lo),...US(m.hi)]:[]:DS[e.face]>0?m.hi:m.lo;x[h]=o?w.length?iE(s,g,VS(w),`along.${h}`):v:iE(s,g,[...VS(w),{ref:b,k:y}],`along.${h}`);for(const n of Tw.filter(t=>t!==h)){const o=e.align?.[n]??"centre",a=p[n],c=f[n],l=t=>t&&!t.centred?[...US(t.lo),...US(t.hi)]:[],h=(t,e)=>l(t).length?iE(s,g,l(t),e):tE(s,"mm",0,"d"),d=()=>l(c).length?iE(s,g,VS(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=nE(s,t,g,o.mm,`align.${n}`,r);_[n]=l(a).length?iE(s,g,[...l(a),{ref:e,k:1}],`align.${n}.from-centre`):e,x[n]=d()}else"min"===o||"max"===o?(a||OS("ATTACH_FACE",r,`${i.part} has no edges along ${n} to line ${e.part} up with; give the centre or a measured offset`),c||OS("ATTACH_FACE",r,`${e.part} has no edges along ${n} to line up; give the centre or a measured offset`),_[n]=iE(s,g,"min"===o?a.lo:a.hi,`edge.${n}`),x[n]=iE(s,g,VS("min"===o?c.lo:c.hi),`own-edge.${n}`)):OS("SCHEMA",r,`${String(o)} is not an alignment`)}if(n&&n.deg){const[o,a]=AE[h];for(const t of[o,a]){const s=e.align?.[t]??"centre";"min"!==s&&"max"!==s||OS("ATTACH_FACE",r,`${e.part} is twisted ${dE(n.deg)}° about ${h}; its sides are not level with ${i.part}'s edges -- place it by the centre or a distance`)}const c=n=>{const i=e.align?.[n]??"centre",o=f[n],a=o&&!o.centred?VS([...US(o.lo),...US(o.hi)]):[];return"object"==typeof i&&i&&Object.hasOwn(i,"mm")?[{ref:nE(s,t,g,i.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(dE(n.deg)).replace("-","m").replace(".","_"),y=t=>{const e=`twist.${t}.${m}`,i=n.deg*Math.PI/180;return s.constants.some(t=>t.id===e)||s.constants.push({id:e,unit:"ratio",value:u("cos"===t?Math.cos(i):"sin"===t?Math.sin(i):-Math.sin(i))}),e},b=(t,e,n)=>{const i=g(n);return s.nodes.push({id:i,op:"mul@1",args:[t,e],outputs:{value:`${i}.value`}}),`${i}.value`},v=(t,e,n)=>{const i=g(n);return s.nodes.push({id:i,op:"add@1",args:[t,e],outputs:{value:`${i}.value`}}),`${i}.value`};for(const t of[o,a]){const e=p[t];_[t]=e&&!e.centred?iE(s,g,[...US(e.lo),...US(e.hi)],`twist-centre.${t}`):tE(s,"mm",0,"d")}const w=iE(s,g,l,`twist-own.${o}`),M=iE(s,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 uE(t,e.part,`${i.part}.local`,{seat:[_.x,_.y,_.z],pose:[x.x,x.y,x.z]}),t}const dE=t=>Math.round(1e6*t)/1e6;function uE(t,e,n,s){const i=t.document.model,{place:r,pose:o}=NS(i,e,e),a=s?o.args.slice(0,3):[];s&&(o.args=[...s.pose,...o.args.slice(3)]),o.params={...o.params,to:`${e}.seat`};const c=LS(i,`${e}.motion`),l=tE(i,"mm",0,"d"),h=tE(i,"deg",0,"a");let d=LS(i,`${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:{}},i.nodes.push(d));const u=s?d.args.slice(0,3):[];s&&(d.args=[...s.seat,...d.args.slice(3)]),d.params={from:c?`${e}.joint`:`${e}.seat`,to:n};let p=LS(i,`${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`}},i.nodes.push(p))):p&&(i.nodes=i.nodes.filter(t=>t!==p));let f=LS(i,`${e}.chain`);f||(f={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},i.nodes.push(f)),f.args=[d.outputs.pose,c?p.outputs.pose:o.outputs.pose];const m=/^(.*)\.local$/.exec(n);let g=LS(i,`${e}.world`);if(m&&m[1]!==e){const t=LS(i,`${m[1]}.world`)?.outputs?.pose??LS(i,`${m[1]}.chain`)?.outputs?.pose??LS(i,`${m[1]}.turned`)?.outputs?.pose??LS(i,`${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`}},i.nodes.push(g)),r.args=[r.args[0],g.outputs.pose]}else g&&(i.nodes=i.nodes.filter(t=>t!==g)),r.args=[r.args[0],f.outputs.pose];for(const n of[...a,...u])cE(t,n,aE(i,e,n)?n:void 0)}const pE=(t,e)=>t.inputs.find(t=>t.id===bS[e]),fE=t=>t.state?.id??t.id;function mE(t,e){const n=t.document.model,s=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||OS("JOINT_SCHEMA","joints","a joint has an id"),function(t,e){const n=(t,e,n)=>{if(t&&"object"==typeof t&&!Array.isArray(t))for(const[s,i]of Object.entries(t))void 0===i||e.includes(s)||OS("JOINT_SCHEMA",n,`${s} is a field this kernel does not know`)},s=(t,e)=>n(t,jS.source,e),i=(t,e)=>{if(t&&"object"==typeof t&&(n(t,jS.measure,e),s(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[i,r]of t.sum.entries())n(r,jS.term,`${e}.sum.${i}`),s(r?.from,`${e}.sum.${i}.from`)};n(t,jS.joint,e),n(t.body0,jS.body0,`${e}.body0`),n(t.body1,jS.body1,`${e}.body1`);const r=t.origin;if(n(r,jS.origin,`${e}.origin`),r&&"object"==typeof r){i(r.gap,`${e}.origin.gap`),n(r.turn,jS.axes,`${e}.origin.turn`),n(r.align,jS.axes,`${e}.origin.align`);for(const[t,s]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(s,jS.alignment,`${e}.origin.align.${t}`),i(s?.mm,`${e}.origin.align.${t}.mm`)}if(t.travel&&"object"==typeof t.travel&&(n(t.travel,jS.travel,`${e}.travel`),s(t.travel.source,`${e}.travel.source`),Array.isArray(t.travel.sum)&&i({sum:t.travel.sum},`${e}.travel`)),n(t.state,jS.state,`${e}.state`),n(t.mimic,jS.mimic,`${e}.mimic`),Array.isArray(t.mimic?.sum))for(const[s,i]of t.mimic.sum.entries())n(i,jS.leader,`${e}.mimic.sum.${s}`);n(t.repeat,jS.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(i(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,jS.rise,`${e}.repeat.rise`))}(e,s),IS.includes(e.type)||OS("JOINT_SCHEMA",s,`${String(e.type)} is not a joint type; ${IS.join(", ")}`),e.body1&&"string"==typeof e.body1.part||OS("JOINT_SCHEMA",s,"a joint carries a part (body1)"),NS(n,e.body1.part,s),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||OS("JOINT_SCHEMA",s,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&NS(n,e.body0.part,s);const i=(t.joints??[]).filter(t=>t.id!==e.id),r=i.find(t=>t.body1.part===e.body1.part);if(r&&OS("JOINT_TREE",s,`${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=>i.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&OS("ATTACH_CYCLE",s,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const i=t(n);n=i&&"part"in i?i.part:void 0}}const o="fixed"!==e.type,a=void 0!==e.lowerLimit||void 0!==e.upperLimit;if(o&&!["X","Y","Z"].includes(e.axis)&&OS("JOINT_SCHEMA",s,`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||OS("JOINT_SCHEMA",s,"a fixed joint has no axis, limits, mimic or travel"),void 0!==e.travel&&"prismatic"!==e.type&&OS("JOINT_SCHEMA",s,"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||OS("JOINT_SCHEMA",s,`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||OS("JOINT_SCHEMA",s,"a mimic sum follows one joint or more");const t=new Set;for(const n of zS(e)){const r=i.find(t=>t.id===n?.joint);r&&"fixed"!==r.type||OS("JOINT_SCHEMA",s,`${String(n?.joint)} is not a moving joint to follow`),t.has(r.id)&&OS("JOINT_SCHEMA",s,`${r.id} is followed twice; a sum names each joint once`),t.add(r.id),r.mimic&&OS("JOINT_SCHEMA",s,`${r.id} follows another joint; follow the one it follows`),"prismatic"===r.type!=("prismatic"===e.type)&&OS("JOINT_SCHEMA",s,`${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)||OS("JOINT_SCHEMA",s,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||OS("JOINT_SCHEMA",s,"a mimic's offset is a number in the joint's unit")}void 0===e.origin?.twist||Number.isFinite(e.origin.twist)||OS("JOINT_SCHEMA",`${s}.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)&&OS("JOINT_SCHEMA",`${s}.origin.turn`,"a turn is in quarter turns; an angle about the face's normal is its twist");const c=[...i,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 i=t(e.body1.part).map(t=>c.find(e=>e.body1.part===t)).filter(t=>t.repeat),r=[...n,...i].find(t=>t.repeat.axis===e.repeat.axis);r&&OS("JOINT_SCHEMA",`${s}.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,i=`${s}.repeat`;"part"in e.body0||OS("JOINT_SCHEMA",i,"a row fills the part it is fastened to; the mounting plane has no length to fill"),["X","Y","Z"].includes(n.axis)||OS("JOINT_SCHEMA",i,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===PS[XS(t.document.model,e)]&&OS("JOINT_SCHEMA",i,`a row runs across the face it is fastened to; ${n.axis} is out of that face`),("number"==typeof n.pitch?Number.isFinite(n.pitch)&&n.pitch>0:(t=>{const e=RS(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)})(n.pitch))||OS("GEOMETRY_DOMAIN",i,"a row has a positive pitch, or one that follows a length"),void 0===n.count||Number.isSafeInteger(n.count)&&n.count>=1&&n.count<=100||OS("GEOMETRY_DOMAIN",i,"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||OS("JOINT_SCHEMA",`${i}.rise`,`a row rises along X, Y or Z other than the one it runs along (${n.axis})`),Number.isFinite(n.rise.mm)&&0!==n.rise.mm||OS("GEOMETRY_DOMAIN",`${i}.rise`,"a rise is a length in mm, not zero"))}}function gE(t,e){const n=t.document.model,s=e.body1.part,{pose:i}=NS(n,s,s),r="part"in e.body0?e.body0.part:void 0,o=`joints.${e.id}`,a=r?vE(ME(t,r,o)):yE,c=!bE(a),l=Tw.map(t=>e.origin?.turn?.[t]??0),h=XS(n,e),d=PS[h],u=e.origin?.twist?GS(kE(d,e.origin.twist),YS(l)):YS(l),p=GS(a,u),f=CE(_E(a,xE[h]),`${e.body1.part}'s ${h}`,r??"",a,o),m=_E(a,Tw.map(t=>t===d?1:0)),g=(e.origin?.twist??0)*Math.sign(m[Tw.indexOf(f.axis)]),{quarter:y,deg:b}=function(t,e,n,s){const i=Tw.indexOf(e),[r,o]=AE[e].map(t=>Tw.indexOf(t));let a;for(const e of TE){const s=GS(t,vE(e));if(Math.abs(s[i][i]-1)>1e-9)continue;const c=180*Math.atan2(s[o][r],s[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||OS("ATTACH_FACE",s,`the part would stand turned about more than the face's normal (${HS(OE(t))})`);return{quarter:a.quarter,deg:a.off<1e-6?n:dE(a.deg)}}(p,f.axis,g,o),v=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...(c||e.origin?.twist?EE(y):l).map(t=>tE(n,"deg",t,"a"))];for(const e of v)cE(t,e,aE(n,s,e)?e:void 0);const _=t=>c&&Object.hasOwn(xE,t)?wE(CE(_E(a,xE[t]),t,r??"",a,o).vector):t;if(hE(t,{kind:"attach",part:s,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?PE(r?vE(SE(t,r,o)):a,e.origin.align,o):e.origin.align}:{},replace:!0},b?{deg:b}:void 0),b){const e=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...OE(p).map(t=>tE(n,"deg",t,"a"))];for(const n of e)cE(t,n)}if(e.repeat&&c&&OS("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&&IE(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=zS(e).map(e=>({leader:(t.joints??[]).find(t=>t.id===e.joint),k:e.multiplier})),E=_E(a,Tw.map(t=>t===e.axis.toLowerCase()?1:0)),A=E.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);A<0&&OS("JOINT_SCHEMA",o,`${r} stands twisted; the axis ${e.axis} is not level with an axis in it`),function(t,e,n,s=1){const i=t.document.model,r=e.part;NS(i,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&OS("SCHEMA",r,"a slide or a turn is required");Tw.includes(e.motion.axis)||OS("SCHEMA",r,`${String(e.motion.axis)} is not an axis`);LS(i,`${e.part}.motion`),0;LS(i,`${e.part}.motion`)&&LE(t,{part:e.part});const o=e.motion.frame??"attachment",a=jE(t,e.part);"asset"===o&&a!==t.document.capabilities.assetFrame?OS("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&&OS("SCHEMA",r,`${String(o)} is not a frame for the axis`);const c=e.state,l=ZS(i,`${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(i.nodes.push({id:n,op:"mul@1",args:[e.of,tE(i,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=l(`mimic.${t}.sum`);i.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");i.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,tE(i,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),h=`${t}.value`}if(n.c){const t=l("mimic.offset"),s="slide"===e.motion.kind?"mm":"deg";i.nodes.push({id:t,op:"add@1",args:[h,tE(i,s,n.c,"d")],outputs:{value:`${t}.value`}}),h=`${t}.value`}}else{c&&"string"==typeof c.id&&c.id.trim()||OS("SCHEMA",r,"a state input id is required");const n=i.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(i.inputs.some(t=>t.id===c.id)){if((i.nodes.some(t=>t.args.includes(c.id))||(t.drivers??[]).some(t=>t.state===c.id)||t.appearance.some(t=>t.visibility===c.id))&&OS("DUPLICATE_WRITER",r,`${c.id} already exists`),i.inputs=i.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 s="turn"===e.motion.kind?["deg"]:["mm","ratio"];s.includes(c.unit)||OS("SCHEMA",r,`a ${e.motion.kind} takes a ${s.join(" or ")} control, not ${String(c.unit)}`),Number.isFinite(c.min)&&Number.isFinite(c.max)&&c.max>c.min||OS("SCHEMA",r,"a range with max above min is required");const o=c.start??c.min;o>=c.min&&o<=c.max||OS("SCHEMA",r,"the starting value is outside the range"),n||(i.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||OS("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let s;if(Object.hasOwn(n,"sum")){const e=n.plus??0;s=eE(i,l,iE(i,l,sE(i,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?rE(i,t,n.source,r):tE(i,"mm",n.plus??0,"d");s=n.source?eE(i,l,e,n.times??1,n.plus??0,"travel"):e}const o=l("distance");i.nodes.push({id:o,op:"mul@1",args:[h,s],outputs:{value:`${o}.value`}}),h=`${o}.value`}else"slide"===e.motion.kind&&e.travel&&OS("SCHEMA",r,"a mm control is the distance; travel would say it twice");const d=Tw.map(t=>tE(i,"ratio",t===e.motion.axis?s:0,"axis"));if(i.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}}),uE(t,e.part,a),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||OS("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||OS("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:s,motion:{kind:x,axis:Tw[A]},state:{id:fE(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:LS(n,`${t.body1.part}.motion`)?.args[3]??fE(t),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,E[A]>0?1:-1),e.repeat&&IE(t,e)}const yE=[[1,0,0],[0,1,0],[0,0,1]],bE=t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)),vE=t=>t[0].map((e,n)=>t.map(t=>t[n])),_E=(t,e)=>t.map(t=>t.reduce((t,n,s)=>t+n*e[s],0)),xE={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]},wE=t=>Object.keys(xE).find(e=>xE[e].every((e,n)=>e===t[n]));function ME(t,e,n){const s=(t.joints??[]).find(t=>t.body1.part===e),i=s?Tw.map(t=>s.origin?.turn?.[t]??0):$S(t.document.model,t,e,n);i.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&OS("EDIT_TARGET",n,`${e} is turned (${HS(i)}); fastening to a turned part by its faces is covered only for quarter turns`);const r=i.every(t=>0===t)?yE:YS(i);return s?.origin?.twist?GS(kE(PS[XS(t.document.model,s)],s.origin.twist),r):r}function SE(t,e,n){const s=(t.joints??[]).find(t=>t.body1.part===e);if(!s?.origin?.twist)return ME(t,e,n);const i=Tw.map(t=>s.origin?.turn?.[t]??0);return i.every(t=>0===t)?yE:YS(i)}function EE(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(!YS(n).every((e,n)=>e.every((e,s)=>e===t[n][s])))throw new Error(`no turn gives ${JSON.stringify(t)}`);return n}const AE={x:["y","z"],y:["z","x"],z:["x","y"]};function kE(t,e){const n=Math.cos(e*Math.PI/180),s=Math.sin(e*Math.PI/180),[i,r]=AE[t].map(t=>Tw.indexOf(t)),o=[[1,0,0],[0,1,0],[0,0,1]];return o[i][i]=n,o[i][r]=-s,o[r][i]=s,o[r][r]=n,o}function CE(t,e,n,s,i){const r=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);return r<0&&OS("ATTACH_FACE",i,`${n} stands twisted (${HS(OE(vE(s)))}); ${e} is not level with an axis in it`),{axis:Tw[r],vector:t.map(t=>Math.abs(t)<1e-9?0:Math.sign(t))}}const TE=(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const s of[0,90,180,270]){const i=YS([e,n,s]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===i[e][n])))||t.push(i)}return t})();function OE(t){const e=t=>{const e=dE(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 PE(t,e,n){const s={};for(const[i,r]of Object.entries(e)){const e=_E(t,Tw.map(t=>t===i?1:0)),o=e.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);o<0&&OS("ATTACH_FACE",n,`the parent stands twisted; placing along ${i} is not level with an axis in it -- place it by the centre`);const a=Math.sign(e[o]),c=Tw[o];"centre"===r||a>0?s[c]=r:"min"===r||"max"===r?s[c]="min"===r?"max":"min":"number"==typeof r.mm?s[c]={mm:-r.mm}:OS("SCHEMA",n,`an offset that follows another value cannot be turned over onto ${c}; give it as a number`)}return s}function IE(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,r=`joints.${e.id}.repeat`,o=e.repeat.axis.toLowerCase(),a=Tw.indexOf(o),c=QS(n,i,r)[o];c||OS("EDIT_TARGET",r,`${i} has no two faces along ${o}; there is no length to fill`);const l=JS(n,t,s,r)[o],h=l?void 0:function(t,e,n,s,i){const{shape:r}=NS(t,n,i),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=BS(t,e,n,i),c=Tw[a[Tw.indexOf(s)].findIndex(t=>0!==t)];if(c===o.along)return;const l=`${n}.width.${c}`;if(!LS(t,l)){const e=tE(t,"mm",0,"d"),n=tE(t,"ratio",2,"k"),[s,i]=o.radii;t.nodes.push({id:l,op:"affine-bounds@1",args:[e,e,s,n,e,i,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,s,o,r);l||h||OS("EDIT_TARGET",r,`${s} has no two faces along ${o}; its copies cannot be spaced`);const{place:d,pose:u}=NS(n,s,r),p=LS(n,`${s}.seat.rigid`),f=ZS(n,`${s}.row`),m=tE(n,"mm",0,"d");p.args=p.args.map((t,e)=>e===a?iE(n,f,c.lo,"start"):t);const g=h||l.centred?m:iE(n,f,VS([...US(l.lo),...US(l.hi)]),"own-centre");u.args=u.args.map((t,e)=>e===a?g:t);const y=iE(n,f,[...c.hi,...VS(c.lo)],"length"),b=h??iE(n,f,[...l.hi,...VS(l.lo)],"extent"),v=tE(n,"ratio",.5,"k"),_=tE(n,"count",100,"limit"),x=e.repeat.count;n.nodes.push(void 0===x?{id:`${s}.layout`,op:"fit-pitch@1",args:[y,m,m,b,nE(n,t,f,e.repeat.pitch,"pitch",r),v,_],outputs:{layout:`${s}.layout.value`}}:{id:`${s}.layout`,op:"fixed-count@1",args:[tE(n,"count",x,"count"),y,m,m,b,v,_],outputs:{layout:`${s}.layout.value`}}),d.op="member@1",d.args=[d.args[0],LS(n,`${s}.turned`)?.outputs?.pose??u.outputs.pose],n.nodes.push({id:`${s}.assembly`,op:"assembly@1",args:[d.outputs.placed],outputs:{assembly:`${s}.assembly.value`}});const w=LS(n,`${i}.world`)?.outputs?.pose??LS(n,`${i}.chain`)?.outputs?.pose??LS(n,`${i}.turned`)?.outputs?.pose??LS(n,`${i}.pose`)?.outputs?.pose;let M=p.outputs.pose;w&&(n.nodes.push({id:`${s}.row`,op:"compose@1",args:[w,p.outputs.pose],outputs:{pose:`${s}.row.value`}}),M=`${s}.row.value`),n.nodes=n.nodes.filter(t=>t.id!==`${s}.chain`&&t.id!==`${s}.world`);const S=e.repeat.rise;n.nodes.push({id:`${s}.repeat`,op:"repeat@1",args:[`${s}.layout.value`,`${s}.assembly.value`,M,...S?[tE(n,"mm",S.mm,"rise")]:[]],outputs:{collection:`${s}.repeat.value`},params:{axis:o,...S?{riseAxis:S.axis.toLowerCase()}:{}}})}function DE(t,e){const n=t.document.model,s=e.body1.part;!function(t,e){const n=t.document.model,s=LS(n,e);if("member@1"!==s?.op||!LS(n,`${e}.repeat`))return;const i=LS(n,`${e}.layout`),r=LS(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)),s.op="place@1";for(const e of[...i?.args??[],...r?[r]:[]])cE(t,e)}(t,s),LS(n,`${s}.motion`)&&LE(t,{part:s});const{pose:i,place:r}=NS(n,s,s),o=new Set([`${s}.seat.rigid`,`${s}.chain`,`${s}.world`,`${s}.turned`]);n.nodes=n.nodes.filter(t=>!o.has(t.id)&&!t.id.startsWith(`${s}.on.`));const a=tE(n,"mm",0,"d"),c=i.args.slice(0,3);i.args=[a,a,a,...i.args.slice(3)],i.params={...i.params,to:t.document.capabilities.assetFrame};for(const e of c)cE(t,e,aE(n,s,e)?e:void 0);r.args=[r.args[0],i.outputs.pose]}function zE(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=RS(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 s=t.origin.align[n];s&&"object"==typeof s&&Object.hasOwn(s,"mm")&&e.push({at:`align.${n}`,get:()=>s.mm,set:t=>s.mm=t})}return e}function RE(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:s}of zE(n))for(const i of RS(s())?.terms??[])"part"===i?.from?.of&&oE(t.document.model,i.from.part,i.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],s=new Map(t.map(t=>[t.body1.part,t]));for(;n.length<t.length;){const i=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?s.get(t.body0.part):void 0;return(!n||e.has(n.id))&&zS(t).every(t=>e.has(t.joint))});i.length||OS("JOINT_TREE","joints","the joints do not make a tree");for(const t of i)e.add(t.id),n.push(t)}return n}(e),s={...t.stateDefaults};for(const e of t.document.model.nodes)"member@1"!==e.op||LS(t.document.model,`${e.id}.repeat`)||(e.op="place@1");for(const e of[...n].reverse())DE(t,e);for(const e of n)gE(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const s=LS(n,`${t.body1.part}.assembly`),i=r=>{for(const o of e.filter(t=>"part"in t.body0&&t.body0.part===r)){if(o.repeat){const e=LS(n,`${o.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},s.args.push(e.outputs.collection);continue}const e=LS(n,o.body1.part);e.op="member@1",s.args.push(e.outputs.placed),i(o.body1.part)}};i(t.body1.part)}}(t,e);for(const e of n)"fixed"===e.type||e.mimic||void 0===s[fE(e)]||(t.stateDefaults[fE(e)]=s[fE(e)])}const jE=(t,e)=>{const n=lE(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame};function LE(t,e){const n=t.document.model,s=LS(n,`${e.part}.motion`);s||OS("EDIT_TARGET",e.part,`${e.part} does not move`);const i=s.args[3],r=LS(n,`${e.part}.seat.rigid`)?.params?.to??s.params.to,o=n.inputs.find(t=>t.id===i&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(FS(n,i)?.args??[]).includes(t.id));return n.nodes=n.nodes.filter(t=>t!==s),uE(t,e.part,r),cE(t,i,i),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 FE=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 NE(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,s=t.document.capabilities.bindings.map(t=>{const s="string"==typeof t.pose?null:t.pose,i=s?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===s.placement):null,r=s?FS(e,s.feature):null,o=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:i?.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}}),i=CS(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),s=FS(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:s?.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,offset:{...t.offset},elevation:t.elevation,rotation:t.rotation}}});return[...s,...i]}const $E=(t,e,n)=>{throw new Lw(t,e,n)};function HE(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||$E("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||$E("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||$E("SCHEMA",s,`unknown ${i}`)}const BE=(t,e)=>{"string"==typeof t&&t.trim()||$E("SCHEMA",e,"nonempty string required")};function YE(t,e){return function(t,e){const n=lS(t),s=structuredClone(e),i=n.outputTypes,r=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),o=new Map;HE(s,["version","assetFrame","bindings"],["names","slotLayout"],"capabilities"),"r3-capability-3"!==s.version&&$E("VERSION","capabilities",s.version);if(BE(s.assetFrame,"assetFrame"),void 0!==s.names){Array.isArray(s.names)||$E("SCHEMA","names","array required");for(const t of s.names)Ow.includes(t)||$E("CAPABILITY_NAME","names",`${String(t)} is not one of ${Ow.join(", ")}`);new Set(s.names).size!==s.names.length&&$E("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(Pw))s.names.includes(t)&&!e.some(t=>s.names.includes(t))&&$E("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}Array.isArray(s.bindings)||$E("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(BE(t,e),Object.hasOwn(i,t)||$E("TARGET_ABSENT",e,t),i[t]),l=(t,e,n)=>{const i=c(t,e);("transform"!==i.kind||i.to!==s.assetFrame||void 0!==n&&i.from!==n)&&$E("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>pS({types:i,writers:r,model:t,assetFrame:s.assetFrame},e,n),d=new Map;for(const t of s.bindings){HE(t,["id","label","role","frame","pose","accepts","capacity"],["region","contacts"],"binding");for(const e of["id","label","frame"])BE(t[e],e);if(a.has(t.id)&&$E("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||$E("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&&$E("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||$E("SCHEMA",t.id,"nonempty accepts required"),t.accepts.forEach(e=>BE(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&$E("SCHEMA",t.id,"duplicate accepted type"),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&$E("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){HE(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&$E("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||$E("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&$E("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||$E("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const s of t.contacts){const i=h(s,t.id),r=JSON.stringify([s.placement,s.feature]);e.has(r)&&$E("DUPLICATE_CONTACT",t.id,r),e.add(r),n.push(i)}o.set(t.id,n)}}const u=[];if(void 0!==s.slotLayout){const t=s.slotLayout;HE(t,["label","role","frame","pose","layout"],[],"slotLayout");for(const e of["label","frame"])BE(t[e],"slotLayout."+e);["seat","grip"].includes(t.role)||$E("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),"string"==typeof t.pose&&$E("SLOT_LAYOUT_FACE","slotLayout.pose","a slot layout sits on a face of a part");const e=h(t.pose,"slotLayout");e.frame!==t.frame&&$E("FRAME_TYPE","slotLayout","slot layout frame must be the selected feature frame");const n=e.normal[1];n||$E("SLOT_LAYOUT_FACE","slotLayout.pose","a slot layout sits on a horizontal face (its normal along Y)");const i=function(t){const e=[];return t&&Array.isArray(t.tiers)&&0!==t.tiers.length?(["ON","IN","HANG"].includes(t.mount)||e.push(vS("MOUNT_INVALID","mount")),t.tiers.forEach((n,s)=>{const i=`tiers[${s}]`;if(!n||"object"!=typeof n)return void e.push(vS("OBJECT_REQUIRED",i));n.tierNo!==s+1&&e.push(vS("TIER_NUMBER_SEQUENCE",`${i}.tierNo`)),_S(n.elevation)?s>0&&_S(t.tiers[s-1]?.elevation)&&n.elevation<=t.tiers[s-1].elevation&&e.push(vS("ELEVATION_NOT_ASCENDING",`${i}.elevation`)):e.push(vS("FINITE_NUMBER_REQUIRED",`${i}.elevation`));const r=n.layout;switch(r?.pattern){case"SINGLE":MS(r.slot,`${i}.layout.slot`,e);break;case"ROW":wS(r.count)||e.push(vS("POSITIVE_INTEGER_REQUIRED",`${i}.layout.count`)),xS(r.pitch)||e.push(vS("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch`)),"X"!==r.axis&&"Z"!==r.axis&&e.push(vS("AXIS_INVALID",`${i}.layout.axis`)),MS(r.slot,`${i}.layout.slot`,e);break;case"GRID":wS(r.rows)||e.push(vS("POSITIVE_INTEGER_REQUIRED",`${i}.layout.rows`)),wS(r.cols)||e.push(vS("POSITIVE_INTEGER_REQUIRED",`${i}.layout.cols`)),xS(r.pitch?.x)||e.push(vS("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch.x`)),xS(r.pitch?.z)||e.push(vS("POSITIVE_NUMBER_REQUIRED",`${i}.layout.pitch.z`)),MS(r.slot,`${i}.layout.slot`,e);break;case"CUSTOM":{const t=Array.isArray(r.slots)?r.slots:[],n=t.map(t=>t?.slotNo).sort((t,e)=>t-e);n.length&&!n.some((t,e)=>t!==e+1)||e.push(vS("SLOT_NUMBER_SEQUENCE",`${i}.layout.slots`)),t.forEach((t,n)=>{_S(t?.offset?.x)&&_S(t?.offset?.z)||e.push(vS("FINITE_NUMBER_REQUIRED",`${i}.layout.slots[${n}].offset`)),MS(t,`${i}.layout.slots[${n}]`,e)});break}default:e.push(vS("PATTERN_INVALID",`${i}.layout.pattern`))}}),e):[vS("TIERS_REQUIRED","tiers")]}(t.layout),r=i.length?i:function(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(vS("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}(t.layout);r.length&&$E("SLOT_LAYOUT",`slotLayout.layout.${r[0].path}`,r.map(t=>`${t.code} at ${t.path}`).join("; "));for(const s of CS(t))s.accepts.length||$E("SCHEMA",s.id,"nonempty accepts required"),s.accepts.forEach(t=>BE(t,s.id)),new Set(s.accepts).size!==s.accepts.length&&$E("SCHEMA",s.id,"duplicate accepted type"),(!Number.isSafeInteger(s.capacity)||s.capacity<1)&&$E("CAPACITY",s.id,"positive integer capacity required"),a.has(s.id)&&$E("DUPLICATE_BINDING",s.id,"duplicate id"),a.add(s.id),d.set(s.id,e),u.push({...s,up:n})}const p=[...s.bindings,...u];function f(t,e){const n=t.pose.r,s=[e.offset.x,e.elevation*e.up,e.offset.z],i=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*s[n],0)),r=e.rotation*Math.PI/180,o=Math.cos(r),a=Math.sin(r),c=[[o,0,a],[0,1,0],[-a,0,o]],l=n.map(t=>c[0].map((e,n)=>t.reduce((t,e,s)=>t+e*c[s][n],0)));return{...t,pose:{r:l,t:i}}}function m(t,e,n){const s=t=>function(t,e){const n=t[e.placement],s=t[e.feature],i=n.pose.r,r=i.map(t=>t.reduce((t,n,s)=>t+n*e.normal[s],0)),o=i.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*s.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,s=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);s||dS("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=s.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:i.map(t=>[...t]),t:o},normal:r,provenance:"verified-planar-surface"}}(e,t);let i=null;if(t.allowed)i={kind:"centered-box",dimensions:[t.allowed.width,t.allowed.height,t.allowed.depth]};else if(t.region){const n=t.region.dimensions.map(t=>e[t]);n.some(t=>!Number.isFinite(t)||t<=0)&&$E("REGION_DOMAIN",t.id,"positive region dimensions required"),i={kind:t.region.kind,dimensions:n}}let r={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];HE(e,["type","occupied"],[],t.id+".request"),BE(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&$E("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const s=[];t.accepts.includes(e.type)||s.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&s.push("CAPACITY_FULL"),r={status:s.length?"failed":"satisfied",reasons:s}}const a=(o.get(t.id)??[]).map(s),c=d.has(t.id)?s(d.get(t.id)):null,l=c&&t.allowed?f(c,t):c;return{id:t.id,label:t.label,role:t.role,frame:t.frame,pose:l?l.pose:e[t.pose],...l?{targetGeometryId:l.geometryId}:{},region:i,contacts:a,checks:{declaration:{status:"satisfied"},eligibility: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 HE(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(i),dependence:structuredClone(n.dependence),evaluate:(t,e={})=>g(n,t,e),evaluator(t={}){const e=n.evaluator({reads:_,changes:!!t.changes});return{evaluate:(t,n={})=>g(e,t,n),advance:(t,n={})=>{HE(n,[],[...a],"requests");const s=Object.keys(n).length>0,i=e.advance(t,s?"REQUESTS":void 0);if("evaluation"===i.kind)return{...i,result:y(i.result,n)};if("changes"===i.kind){const t=p.filter(t=>s||i.structure||v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{...i,places:t}}const r=p.filter(t=>v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{kind:"poses",generation:i.generation,bodies:i.bodies,poses:i.poses,places:r}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const s=p.find(e=>e.id===t);return s||$E("TARGET_ABSENT",t,"no such place"),HE(n,[],[...a],"requests"),m(s,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const GE=1048576;function VE(t,e){throw new Lw(t,"document",e)}function UE(t){return(new TextEncoder).encode(t).byteLength}function WE(t){const e=new Set;!function t(n,s){if(s>64&&VE("DOCUMENT_LIMIT","nesting exceeds 64"),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||VE("JSON_VALUE","nonfinite number"));"object"!=typeof n&&VE("JSON_VALUE","only JSON values are allowed"),e.has(n)&&VE("JSON_VALUE","cycle");const i=Array.isArray(n);i||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||VE("JSON_VALUE","plain objects required"),e.add(n);const r=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(r)){if(i&&"length"===e)continue;"string"!=typeof e&&VE("JSON_VALUE","symbols unsupported");const o=r[e];o.enumerable&&Object.hasOwn(o,"value")||VE("JSON_VALUE","hidden properties and accessors unsupported"),!i||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||VE("JSON_VALUE","extra array property"),t(o.value,s+1)}i&&Object.keys(n).length!==n.length&&VE("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function qE(t){if(WE(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new Lw("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new Lw("VERSION","document","unsupported document version");if(UE(JSON.stringify(t))>GE)throw new Lw("DOCUMENT_LIMIT","document","over 1 MiB");const e=t;if(!Array.isArray(e.model?.nodes)||e.model.nodes.length>8192)throw new Lw("DOCUMENT_LIMIT","document","maximum 8192 nodes");return YE(e.model,e.capabilities)}const XE=(t,e,n)=>{throw new Lw(t,e,n)};function KE(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function QE(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const s=n[n.length-1];if(e>=s.at)return s.value;let i=0;for(;i<n.length-2&&n[i+1].at<=e;)i++;const r=n[i],o=n[i+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 JE(t,e,n="other"){Number.isFinite(e)||XE("DRIVER_TIME",t.id,"finite time required");const s=Math.max(0,e),i=t.time.duration,r=t.keys[0].value,o=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=QE(t,Math.min(s/i,1));else{const e=Math.floor(s/i);a=QE(t,(s-e*i)/i),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,s=n/2,i=((t+s)%n+n)%n-s;return i===s?-s:i}(a,n):XE("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}const ZE=(t,e,n)=>{throw new Lw(t,e,n)};function tA(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||ZE("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||ZE("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||ZE("ASSET_SCHEMA",s,`unknown ${i}`)}function eA(t){return function(t){WE(t);const e=nA(t);UE(JSON.stringify(e))>GE&&ZE("DOCUMENT_LIMIT","asset","over 1 MiB");tA(e,["version","name","document","designInputs","stateDefaults","palette","appearance"],["occupancy","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs"],"asset"),void 0===e.placement||TS.includes(e.placement)||ZE("ASSET_SCHEMA","placement",`one of ${TS.join(", ")} required`);"figure-asset-1"!==e.version&&ZE("VERSION","asset",e.version);"string"==typeof e.name&&e.name.trim()||ZE("ASSET_SCHEMA","name","nonempty name required");const n=structuredClone(e),s=qE(n.document),i=n.document.model,r=i.inputs.filter(t=>"state"!==t.role).map(t=>t.id),o=i.inputs.filter(t=>"state"===t.role).map(t=>t.id);tA(n.designInputs,r,[],"designInputs"),void 0===n.detailLevel||(t=>Iw.includes(t))(n.detailLevel)||ZE("ASSET_SCHEMA","detailLevel",`${String(n.detailLevel)} is not a detail level; ${Iw.join(", ")}`);if(void 0!==n.sizing){"uniform"!==n.sizing&&ZE("ASSET_SCHEMA","sizing",`${String(n.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])i.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||ZE("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(tA(n.stateDefaults,o,[],"stateDefaults"),void 0!==n.publicInputs){Array.isArray(n.publicInputs)||ZE("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,s]of n.publicInputs.entries()){const n=`publicInputs[${e}]`;tA(s,["input","label"],["hint"],n),hS(i.inputs,s.input,`${n}.input`),"string"==typeof s.label&&s.label.trim()||ZE("ASSET_SCHEMA",`${n}.label`,"a name shown on the board"),void 0!==s.hint&&"string"!=typeof s.hint&&ZE("ASSET_SCHEMA",`${n}.hint`,"one line"),t.has(s.input)&&ZE("PUBLIC_INPUT",`${n}.input`,`${s.input} is listed twice`),t.add(s.input)}}n.palette&&"object"==typeof n.palette&&!Array.isArray(n.palette)||ZE("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)||ZE("PALETTE","palette","six digit hex color required");const a=t=>{"string"==typeof t&&Object.hasOwn(n.palette,t)||ZE("PALETTE",String(t),"unresolved color token")},c=new Map(i.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),l=new Map(i.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),h=new Map;Array.isArray(n.appearance)||ZE("ASSET_SCHEMA","appearance","array required");for(const t of n.appearance){if(tA(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=s.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||ZE("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(l.has(t.target)&&!h.has(t.target)||ZE("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),tA(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)||ZE("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&ZE("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;tA(e,["token","intensity","on"],[],"emissive"),a(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&ZE("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)||ZE("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&ZE("QUALITY","segments","segments unsupported on this provider"),h.set(t.target,t)}h.size!==l.size&&ZE("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==n.occupancy){if(tA(n.occupancy,["bounds"],["contact"],"occupancy"),void 0!==n.occupancy.contact){const t=n.occupancy.contact;tA(t,["plane","surface"],[],"occupancy.contact"),"mounting-plane"!==t.plane&&ZE("OCCUPANCY","occupancy.contact",`${String(t.plane)} is not a plane the figure can be mounted on`),pS({types:s.outputTypes,writers:c,model:i,assetFrame:n.document.capabilities.assetFrame},t.surface,"occupancy.contact.surface")}tA(n.occupancy.bounds,["x","y","z"],[],"occupancy.bounds");const t=JSON.stringify([1,0,0]);for(const e of["x","y","z"]){tA(n.occupancy.bounds[e],["min","max"],[],`occupancy.bounds.${e}`);for(const i of["min","max"]){const r=`occupancy.bounds.${e}.${i}`,o=n.occupancy.bounds[e][i];"string"==typeof o&&JSON.stringify(s.outputTypes[o])===t||ZE("OCCUPANCY",r,`${String(o)} is not a length value in the graph`),s.dependence[o]?.length&&ZE("OCCUPANCY_STATE",r,`${o} depends on state input ${s.dependence[o].join(", ")}; the occupancy is state-independent`)}}}(function(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||XE("DRIVER","drivers","array required");const n=KE(t),s=new Set,i=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"])&&XE("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||XE("DRIVER",e,"id required"),s.has(t.id)&&XE("DRIVER",e,"duplicate driver id"),s.add(t.id),"string"==typeof t.clip&&t.clip.trim()||XE("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||XE("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`),i.has(t.state)&&XE("DRIVER_STATE",e,`two drivers write ${t.state}; one writer per state`),i.add(t.state),JSON.stringify(o(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||XE("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||XE("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&&XE("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)&&XE("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"])&&XE("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||XE("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>c||XE("DRIVER_KEYS",e,"key at values must strictly increase"),c=n.at,Number.isFinite(n.value)||XE("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&XE("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||XE("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||XE("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&XE("DRIVER",e,"accumulates must be a boolean");const l=n.get(t.state);t.accumulates&&"deg"!==l&&"rad"!==l&&XE("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)||XE("STATE_INPUT","stateInputs","object required");const n=KE(t);for(const[t,s]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||XE("STATE_INPUT",e,`${t} is not a state input of this asset`),s&&"object"==typeof s&&!Array.isArray(s)||XE("STATE_INPUT",e,"object required");for(const t of Object.keys(s))"label"!==t&&"sweep"!==t&&XE("STATE_INPUT",e,`unknown ${t}`);void 0===s.label||"string"==typeof s.label&&s.label.trim()||XE("STATE_INPUT",e,"label must be a nonempty string"),void 0===s.sweep||Number.isFinite(s.sweep)&&s.sweep>=0||XE("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(n),void 0===n.joints||Array.isArray(n.joints)||ZE("ASSET_SCHEMA","joints","joints is a list");function d(t={}){tA(t,[],o,"state overrides");const e={...n.designInputs,...n.stateDefaults,...t},i=s.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=i.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||ZE("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(n.material),visible:void 0===n.visibility||i.values[n.visibility],...void 0!==n.segments?{segments:n.segments}:{}}});return{...i,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)mE({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);RE(n);const s=t=>JSON.stringify({nodes:[...t.nodes].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0),inputs:[...t.inputs].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0)});s(n.document.model)!==s(t.document.model)&&OS("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 nA(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&&ZE("PLACEMENT_CONFLICT","placement",`the asset says ${String(e.placement)} and its room says ${String(n)}; keep one`);const{placement:s,...i}=e.occupancy;return{...e,placement:n,occupancy:i}}const sA="0.4.2";function iA(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 rA=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,iA(t),!1!==t.visible]);function oA(t,e){const n=function(t,e){const n=e??qE(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=yS(t),r=t=>{const e=void 0===t?void 0:s.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!r("string"==typeof n?.[0]?n[0]:t.id)||!!e&&r(i.get(e))}}(t,e),s=yS(t),i=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?s.get(r.key):r.id;void 0!==t&&i.has(t)||e.add(r.id)}return e}}const aA=t=>`${iA(t)}|${!1!==t.visible?"shown":"hidden"}`;function cA(t,e={}){const n=[],s=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 i=s.get(t)??[];i.push(e),s.set(t,i)}const i=[],r=[];for(const[t,e]of s){const s=new Map;for(const t of e){const e=rA(t),n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}for(const[o,a]of s)a.length>1?i.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 s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of n){const n=s.get(t);if(!n||!e.still.has(t)||n.material.transparent)continue;const r=aA(n),o=i.get(r);o?o.push(t):i.set(r,[t])}const r=new Set;for(const[t,e]of i)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 s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of n){const n=s.get(t),r=e.carried.get(t);if(!n||void 0===r||e.still?.has(t)||n.material.transparent)continue;const o=`${r}|${aA(n)}`,a=i.get(o);a?a.ids.push(t):i.set(o,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of i)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:i,merged:o,carried:a,alone:n,unbatched:r}}const lA=Dw[0];function hA(t,e,n,s={}){const[i,r]=Fw[e],o=s[i]??0,a=s[r]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[i],t[r]]);else if("ellipse"===t.kind){const e=t.radius[i],s=t.radius[r];c=Array.from({length:n},(t,i)=>{const r=2*Math.PI*i/n;return[e*Math.cos(r),s*Math.sin(r)]})}else{const e=t.size[i]/2,n=t.size[r]/2,s=t.corner?.[i]??0,o=t.corner?.[r]??0;if(s>0&&o>0){c=[];for(const[t,i,r]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=lA;a++){const l=r+a/lA*(Math.PI/2);c.push([t*(e-s)+s*Math.cos(l),i*(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]),dA(c)<0?c.reverse():c}const dA=t=>t.reduce((e,n,s)=>e+n[0]*t[(s+1)%t.length][1]-t[(s+1)%t.length][0]*n[1],0)/2;function uA(t){const e=[...t].sort((t,e)=>t[0]-e[0]||t[1]-e[1]).map(([t,e])=>[t,e]);if(e.length<3)return e;const n=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]),s=[];for(const t of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],t)<=1e-9;)s.pop();s.push(t)}const i=[];for(let t=e.length-1;t>=0;t--){const s=e[t];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],s)<=1e-9;)i.pop();i.push(s)}return s.slice(0,-1).concat(i.slice(0,-1))}const pA=t=>"shape"in t&&"pose"in t&&!!t.shape;function fA(t,e,n,s={}){const[i,r]=Fw.y;return hA(t,"y",n,s).map(([t,n])=>{const s={x:0,y:e,z:0};return s[i]=t,s[r]=n,[s.x,s.y,s.z]})}let mA=null;function gA(t){mA=t}function yA(t,e=[],n){mA?.registerType?.(t,e,n)}function bA(t){if(Array.isArray(t))return`[${t.map(bA).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${bA(e[t])}`).join(",")}}`}return JSON.stringify(t)}const vA=new Map;function _A(t){const e=function(t){const e=bA(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}|${sA}`,s=vA.get(n);if(s)return vA.delete(n),vA.set(n,s),s;const i=nA(structuredClone(t)),r=new Map;for(const t of i.document.model.nodes)for(const e of Object.values(t.outputs))r.set(e,t.id);const o={key:n,fingerprint:e,kernel:sA,compiled:eA(i),document:qE(i.document),looks:new Map(i.appearance.map(t=>[t.target,t])),writers:r,asset:i};return vA.set(n,o),vA.size>256&&vA.delete(vA.keys().next().value),o}const xA=new Map;function wA(t,e){eA(e);const n={type:t,compiled:_A(e)};return xA.set(t,n),yA(t,e.document.capabilities.names??[],nA(e).placement),n}function MA(t){return xA.get(t)??null}function SA(t){return xA.has(t)}function EA(t){return xA.delete(t)}function AA(){xA.clear()}const kA=["x","y","z"],CA=new WeakMap;function TA(t){let e=CA.get(t);return e||CA.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,s=kA.every(t=>"number"==typeof n[zw[t]]&&e.some(e=>e.id===zw[t])),i={};if(s)for(const t of kA){const n=e.find(e=>e.id===zw[t]);i[t]={min:n.min??0,max:n.max??1/0}}const r=lS(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 kA)n[zw[t]]=e[t];const s=r.evaluate(n).values,i=t=>Math.max((s[o[t].max]??0)-(s[o[t].min]??0),1e-6);return{x:i("x"),y:i("y"),z:i("z")}},c=s?{x:n[zw.x],y:n[zw.y],z:n[zw.z]}:null,l=!s||"uniform"===t.sizing,h=a(c),d={};if(c&&l){const t=Math.min(2,...kA.map(t=>i[t].max/c[t])),e=Math.max(.5,...kA.map(t=>i[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 kA)d[e]=(t[e]-h[e])/(c[e]*(n-1))}}else if(c)for(const t of kA){const{min:e,max:n}=i[t],s=c[t],r=n>s?Math.min(n,2*s):e<s?Math.max(e,s/2):s;if(r===s)continue;const o=a({...c,[t]:r});d[t]=(o[t]-h[t])/(r-s)}return{evaluated:s,proportional:l,limits:i,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 OA(t){return TA(t).proportional}function PA(t,e,n=[]){const s=TA(t),i=n.find(t=>void 0!==e[t])??"x",r=(t,e)=>{const n=s.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!s.evaluated){const t=Math.max(e[i]/s.authored[i],1e-6);return{inputs:null,scale:t,occupancy:{x:s.authored.x*t,y:s.authored.y*t,z:s.authored.z*t}}}const o=s.authoredInputs;let a;if(s.proportional){let t=Math.max(s.inputFor(i,e[i])/o[i],1e-6);for(const e of kA){const n=s.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",s.inputFor("x",e.x)),y:r("y",void 0!==e.y?s.inputFor("y",e.y):o.y),z:r("z",s.inputFor("z",e.z))};return{inputs:a,scale:1,occupancy:s.occupancyAt(a)}}const IA=Math.cos(40*Math.PI/180);function DA(e){const[n,s]=Fw[e];return([i,r],o)=>{const a={x:0,y:0,z:0};return a[n]=i,a[s]=r,a[e]=o,new t.Vector3(a.x,a.y,a.z)}}class zA{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,s,i,r){for(const[o,a]of[[t,s],[e,i],[n,r]])this.positions.push(o.x,o.y,o.z),this.normals.push(a.x,a.y,a.z)}facing(e,n,s,i){(new t.Vector3).subVectors(n,e).cross((new t.Vector3).subVectors(s,e)).dot(i)<0?this.tri(e,s,n,i,i,i):this.tri(e,n,s,i,i,i)}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 RA(e,n,s,i,r,o){const a=DA(s),c=n.length,l=n.map((t,e)=>{const s=n[(e+1)%c],i=s[0]-t[0],r=s[1]-t[1],a=Math.hypot(i,r)||1;return[o*r/a,-o*i/a]}),h=t=>a(t,0),d=(t,e)=>{const n=l[t],s=l[e];return n[0]*s[0]+n[1]*s[1]<IA?h(n):h([n[0]+s[0],n[1]+s[1]]).normalize()};for(let s=0;s<c;s++){const o=n[s],u=n[(s+1)%c],p=d(s,(s-1+c)%c),f=d(s,(s+1)%c),m=a(o,i),g=a(u,i),y=a(u,r),b=a(o,r),v=h(l[s]);(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 jA(e,n,s,i,r,o){const a=DA(s),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,s]of d)e.facing(a(u[t],i),a(u[n],i),a(u[s],i),c)}const LA=new Map;let FA=0,NA=67108864;function $A(){return{entries:LA.size,bytes:FA,limit:NA}}function HA(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),s=t.extrusion,i=t.cavity,r=t.revolution,o=t.loft,a=s?`${s.axis}:${s.section.kind}:${i?`${"open"===i.start?"o":"c"}${"open"===i.end?"o":"c"}`:"-"}`:r?`${r.axis}:${r.profile.kind}`:o?`${o.axis}:point`:"";return`${t.provider}|${a}|${n}|s${e}|p1`}function BA(t,e=12,n=1/0){const s=HA(t,e),i=LA.get(s);if(i)return i.users++,i.geometry;const r=GA(t,e),o=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(r);if(FA+o>NA||o>n)throw r.dispose(),new Error("figure: geometry bank budget exceeded");return r.userData.figureKey=s,LA.set(s,{geometry:r,users:1,bytes:o}),FA+=o,r}function YA(t){const e=t.userData.figureKey;if(!e)return;const n=LA.get(e);n&&--n.users<=0&&(LA.delete(e),FA-=n.bytes,n.geometry.dispose())}function GA(e,n=12){if("extrude"===e.provider&&e.extrusion)return function(t,e){const n=t.extrusion,s=hA(n.section,n.axis,e),i=new zA;RA(i,s,n.axis,n.start,n.end,1);const r=t.cavity,o=r&&Kw(n.section,n.axis,r.wall);if(!r||!o||!("section"in o))return jA(i,s,n.axis,n.start,-1),jA(i,s,n.axis,n.end,1),i.geometry();const a=hA(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 RA(i,a,n.axis,c,l,-1),"open"===r.start?jA(i,s,n.axis,n.start,-1,a):(jA(i,s,n.axis,n.start,-1),jA(i,a,n.axis,c,1)),"open"===r.end?jA(i,s,n.axis,n.end,1,a):(jA(i,s,n.axis,n.end,1),jA(i,a,n.axis,l,-1)),i.geometry()}(e,n);if("revolve"===e.provider&&e.revolution)return function(e,n){const s=e.profile;let i;return"half-ellipse"===s.kind?i=new t.SphereGeometry(1,n,Math.max(2,Math.round(n/2))).scale(s.radial,s.axial,s.radial):(i=new t.CylinderGeometry(s.endRadius,s.startRadius,s.end-s.start,n),i.translate(0,(s.start+s.end)/2,0)),"x"===e.axis&&i.rotateZ(-Math.PI/2),"z"===e.axis&&i.rotateX(Math.PI/2),i}(e.revolution,n);const s=e.loft;return"loft"===e.provider&&s?function(e){const[n,s]=Fw[e.axis],i=DA(e.axis),r=hA(e.section,e.axis,0),o=i([e.apex[n],e.apex[s]],e.end),a=new zA;jA(a,r,e.axis,e.start,e.end>e.start?-1:1);const c=r.length;for(let n=0;n<c;n++){const s=i(r[n],e.start),l=i(r[(n+1)%c],e.start),h=(new t.Vector3).subVectors(l,s).cross((new t.Vector3).subVectors(o,s)).normalize();a.tri(s,l,o,h,h,h)}return a.geometry()}(s):new t.BufferGeometry}const VA=new Map;let UA=0,WA=0,qA=67108864;function XA(e,n=1/0){const s=(t=>t.map(t=>HA(t.shape,t.segments)).join(";"))(e),i=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const s=t.pose.r,i=t.pose.t;e.set([s[0][0],s[0][1],s[0][2],s[1][0],s[1][1],s[1][2],s[2][0],s[2][1],s[2][2],i[0],i[1],i[2]],12*n)}),e}(e),r=VA.get(s),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,i));if(o)return o.users++,o;const a=e.map(t=>BA(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(WA+l>qA)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:s}=t.pose;p.set(n[0][0],n[0][1],n[0][2],s[0],n[1][0],n[1][1],n[1][2],s[1],n[2][0],n[2][1],n[2][2],s[2],0,0,0,1),f.getNormalMatrix(p);const i=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),s=c.getZ(t);if(h[3*m]=i[0]*e+i[4]*n+i[8]*s+i[12],h[3*m+1]=i[1]*e+i[5]*n+i[9]*s+i[13],h[3*m+2]=i[2]*e+i[6]*n+i[10]*s+i[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:i};return g.userData.figureMergedKey=s,g.userData.figureMergedEntry=y,r?r.push(y):VA.set(s,[y]),UA++,WA+=l,y}finally{for(const t of a)YA(t)}}function KA(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,s=void 0===e?void 0:VA.get(e);!n||!s?.includes(n)||--n.users>0||(s.splice(s.indexOf(n),1),s.length||VA.delete(e),UA--,WA-=n.bytes,n.geometry.dispose())}function QA(){let t=0;for(const e of VA.values())for(const n of e)t+=n.users;return{entries:UA,users:t,bytes:WA,limit:qA}}const JA=t=>1e-9*Math.round(t/1e-9)+0;class ZA{static carrierJudgeOf(t){let e=ZA.carrierJudges.get(t);return e||ZA.carrierJudges.set(t,e=function(t,e){const n=e??qE(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))i.set(t,e);const 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=i.get(t),s="compose@1"!==n?.op||"string"!=typeof n.args[0]||o(n.args[1])?t:c(n.args[0]);return a.set(t,s),s};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||r.has(n.id))continue;const t=s.get(n.id),i="place@1"===t?.op?t.args[1]:void 0;"string"==typeof i&&o(i)&&!o(t.args[0])&&e.set(n.id,c(i))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=ZA.stillJudges.get(t);return e||ZA.stillJudges.set(t,e=oA(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=_A(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 s=this.slots[t];if(s&&"mesh"in s)return n.copy(s.mesh.matrix);if(s&&"entry"in s)return s.entry.set.mesh.getMatrixAt(s.index,n),n;if(s&&"rides"in s){const t=s.rides,i=12*t.ids.indexOf(e.id),r=t.relative;return n.set(r[i],r[i+1],r[i+2],r[i+9],r[i+3],r[i+4],r[i+5],r[i+10],r[i+6],r[i+7],r[i+8],r[i+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(ZA.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((s,i)=>{if(!("shape"in s)||!("pose"in s)||!1===s.visible)return;let r=ZA.shapeBounds.get(s.shape);if(!r){const e=xM(s.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)),ZA.shapeBounds.set(s.shape,r)}this.semanticBounds.union(n.copy(r).applyMatrix4(this.bodyMatrix(i,s,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,s=this.lastDrawn;if(this.lastLodError=void 0,!s||s.geometry.every(t=>Rw(t,n)===Rw(t,e)))return this._renderLevel=e,!0;const i=new t.Matrix4,r=s.geometry.map((t,e)=>{if(!("pose"in t))return t;const n=this.bodyMatrix(e,t,i).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={...s,geometry:r},a=jw(o,e),c=[],l=[],h=$A().bytes+QA().bytes,d=()=>ZA.LOD_TRANSITION_LIMIT_BYTES-($A().bytes+QA().bytes-h);try{const e=new Set;for(const t of a.geometry){if(!("shape"in t))continue;const n=HA(t.shape,t.segments);e.has(n)||(e.add(n),c.push(BA(t.shape,t.segments,d())))}const n=cA(a.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf}:{}),s=new Map(a.geometry.map(t=>[t.id,t]));for(const e of[...n.merged,...n.carried]){let n=e.ids.map(t=>s.get(t));if("carrier"in e){const e=(new t.Matrix4).copy(ZA.matrixOf(n[0].pose)).invert(),s=new t.Matrix4;n=n.map(t=>{const n=s.multiplyMatrices(e,ZA.matrixOf(t.pose)).elements,i=t=>JA(n[t]);return{...t,pose:{r:[[i(0),i(4),i(8)],[i(1),i(5),i(9)],[i(2),i(6),i(10)]],t:[i(12),i(13),i(14)]}}})}const i=XA(n,d());i&&l.push(i.geometry)}if($A().bytes+QA().bytes-h>ZA.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)KA(t);for(const t of c)YA(t);return!1}try{return this._renderLevel=e,this.draw(o,this.generation),!0}finally{for(const t of l)KA(t);for(const t of c)YA(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(zw.x)&&e(zw.y)&&e(zw.z)?{x:t[zw.x],y:t[zw.y],z:t[zw.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const s of["x","y","z"]){const i=e.find(t=>t.id===zw[s]);if(!i)continue;const r=t[s],o=Math.min(Math.max(r,i.min??-1/0),i.max??1/0);o!==r&&this.clamped.push({axis:s,asked:r,used:o,bound:o>r?"min":"max"}),n[s]=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)),s=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),i={};for(const[r,o]of Object.entries(t??{})){const t=s.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&&(i[r]=this.design[r])):i[r]=o}try{this.compiled.document.evaluate({...this.evaluationInputs(),...i}),this.design=i}catch(t){for(const[n,s]of Object.entries(i))e.push({input:n,value:s,reason:t instanceof Error?t.message:String(t)})}this.designRefused=e}get designValues(){return{...this.design}}setState(t){this.external={...t}}static clipOf(t){return t.clip}get clips(){return[...new Set((this.asset.drivers??[]).map(t=>ZA.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 s=t.get(e.state);n[e.state]=JE(e,this.clipTime(ZA.clipOf(e)),"deg"===s||"rad"===s?s:"other")}for(const[t,s]of Object.entries(this.external))e.has(t)&&(n[t]=s);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 s="changes"===e.kind?this.fromChanges(e,t):null;this.draw(s??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const s=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||s.has(n)||!t.structure&&!t.changed(n))continue;const i=!0===t.read(n);this.flags.get(n)!==i&&s.add(n),this.flags.set(n,i)}const i=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),r=new Int32Array(i.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<i.length;e++){const n=r[e],o=i[e];if(n<0&&!(o&&s.size&&void 0!==this.flagOf(o)&&s.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,s=12*n;l.shape=t.shapes[n],l.pose={r:[[e[s],e[s+1],e[s+2]],[e[s+3],e[s+4],e[s+5]],[e[s+6],e[s+7],e[s+8]]],t:[e[s+9],e[s+10],e[s+11]]}}else l.shape=o.shape,l.pose=o.pose;i[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:i,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,s=this.compiled.looks.get(n);if(!s)throw new Error(`figure: no appearance for ${n}`);const i=void 0===s.visibility||e(s.visibility);let r=this.materials.get(n);r||this.materials.set(n,r=structuredClone(s.material));const o={...t,material:r,visible:i};return void 0!==s.segments&&(o.segments=s.segments),{dressed:o,visible:i,ref:s.visibility}}evaluation(){return this.evaluate()}movesMerged(t){if(!this.merged.size)return!1;for(let e=0;e<t.length;e++){const n=this.slots[t[e]];if(n&&"merged"in n)return!0}return!1}movePoses(t){t.bodies.length&&this._lodRevision++;const e=ZA.matrix,n=new Set;for(let s=0;s<t.bodies.length;s++){const i=this.slots[t.bodies[s]];if(!i)continue;const r=t.poses,o=12*s;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 i)&&!("rides"in i))if("mesh"in i){i.mesh.matrix.copy(e),i.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(i.id);t&&(t.pose=void 0)}else i.entry.set.setMatrix(i.index,e),n.add(i.entry)}for(const t of this.batches.values())n.has(t)?(t.settled=!1,t.set.commitMatrices(),t.set.mesh.boundingSphere=null,t.set.mesh.frustumCulled=!1):t.settled||(t.set.commit(),t.set.mesh.frustumCulled=!0,t.settled=!0);for(const e of t.places){const t=this.places.get(e.id);t&&ZA.pose(t,e.pose)}}draw(e,n){this.lastDrawn=e,this._lodRevision++,this._lodGeometryRevision++,e=jw(e,this._renderLevel);const s=this.planOf(e.geometry),i=new Map(e.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),r=this.drawCarried(s,i,this.drawMerged(s,i)),o=new Set;for(const e of r){const n=i.get(e);if(!("pose"in n))continue;o.add(e);let s=this.meshes.get(e);const r=!1!==n.visible,a=this.drawnWith.get(e);if(!s||!a||a.shape!==n.shape||a.segments!==n.segments){const i=BA(n.shape,n.segments);s?s.geometry!==i?(YA(s.geometry),s.geometry=i):YA(i):(s=new t.Mesh(i,this.materialFor(n)),s.name=e,s.matrixAutoUpdate=!1,this.meshes.set(e,s),r&&this.group.add(s))}a&&a.pose===n.pose||ZA.pose(s,n.pose),this.drawnWith.set(e,{shape:n.shape,segments:n.segments,pose:n.pose}),s.castShadow=r,r&&s.parent!==this.group?this.group.add(s):r||s.parent!==this.group||this.group.remove(s)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),YA(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const a=new Set;for(const t of s.batches){a.add(t.key);const e=i.get(t.ids[0]);if(!("pose"in e))continue;let n=this.batches.get(t.key);if(!n){const s=BA(e.shape,e.segments);n={set:new bw({geometry:s,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:s},this.batches.set(t.key,n)}const{set:s}=n,r=s.count!==t.ids.length;s.setCount(t.ids.length);const o=s.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=i.get(t);if(!("pose"in n))return;ZA.matrixOf(n.pose);const r=ZA.matrix.elements;for(let t=0;t<16&&!c;t++)o[16*e+t]!==Math.fround(r[t])&&(c=!0);s.setMatrix(e,ZA.matrix)}),n.ids=t.ids,r||!c&&!n.settled?(s.commit(),s.mesh.frustumCulled=!0,n.settled=!0):c&&(n.settled=!1,s.commitMatrices(),s.mesh.boundingSphere=null,s.mesh.frustumCulled=!1);const l=!1!==e.visible;l&&s.object3d.parent!==this.group?this.group.add(s.object3d):l||s.object3d.parent!==this.group||this.group.remove(s.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(),YA(e.geometry),this.batches.delete(t));for(const t of e.bindings){const e=this.places.get(t.id);e&&ZA.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 s=[...e.alone],i=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=XA(e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!n){s.push(...r.ids);continue}if(o)KA(o.mesh.geometry),o.mesh.geometry=n.geometry,o.ids=r.ids,o.starts=n.starts;else{const s=new t.Mesh(n.geometry,this.materialFor(e[0]));s.name=`figure-merged:${this.merged.size}`,s.matrixAutoUpdate=!1,s.castShadow=!0,o={mesh:s,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}))}i.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)i.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),KA(e.mesh.geometry),this.merged.delete(t));return s}drawCarried(e,n,s){const i=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(ZA.matrixOf(e[0].pose)).invert();const c=e.map(t=>{const e=o.multiplyMatrices(r,ZA.matrixOf(t.pose)).elements,n=t=>JA(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=XA(e.map((t,e)=>({shape:t.shape,segments:t.segments,pose:c[e]})));if(!n){s.push(...a.ids);continue}if(h)KA(h.mesh.geometry),h.mesh.geometry=n.geometry,h.ids=a.ids,h.starts=n.starts;else{const s=new t.Mesh(n.geometry,this.materialFor(e[0]));s.name=`figure-carried:${this.carried.size}`,s.matrixAutoUpdate=!1,s.castShadow=!0,h={mesh:s,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}ZA.pose(h.mesh,e[0].pose),i.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)i.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),KA(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),s}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(!NE(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 s=this.evaluator&&this.lastDrawn?this.placeNow(e):this.evaluation().bindings.find(t=>t.id===e);return s&&ZA.pose(n,s.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(ZA.matrixOf(e)),t.matrixWorldNeedsUpdate=!0}planOf(t){const e=this.planned,n=t.filter(t=>"pose"in t);if(e&&e.ids.length===n.length&&n.every((t,n)=>t.id===e.ids[n]&&t.shape===e.shapes[n]&&t.segments===e.segments[n]&&!1!==t.visible===e.shown[n]))return e.plan;const s=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===s.length&&s.every((t,n)=>t===e.ids[n])||(this.stillOf=ZA.stillJudgeOf(this.compiled)(t),this.carriedOf=ZA.carrierJudgeOf(this.compiled)(t));const i=this.merge?this.stillOf:void 0,r=cA(t,i?{still:i,carried:this.carriedOf}:{});return this.planned={ids:s,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:r,still:i},r}static matrixOf(t){const e=t.r,n=t.t;return ZA.matrix.set(e[0][0],e[0][1],e[0][2],n[0],e[1][0],e[1][1],e[1][2],n[1],e[2][0],e[2][1],e[2][2],n[2],0,0,0,1)}bodyAt(t,e,n){if(t.isMesh&&this.meshes.get(t.name)===t)return t.name;for(const n of this.batches.values())if(n.set.mesh===t&&void 0!==e){const t=n.set.indexOf(e);return t>=0?n.ids[t]:void 0}for(const e of[...this.merged.values(),...this.carried.values()]){if(e.mesh!==t||void 0===n)continue;const{starts:s}=e;if(n<0||n>=s[s.length-1])return;let i=0,r=e.ids.length-1;for(;i<r;){const t=i+r+1>>1;s[t]<=n?i=t:r=t-1}return e.ids[i]}}drawOf(t){const e=this.meshes.get(t);if(e)return e.parent===this.group?{kind:"alone",object:e}:void 0;for(const e of this.batches.values()){const n=e.ids.indexOf(t);if(n>=0)return e.set.object3d.parent===this.group?{kind:"copy",object:e.set.mesh,index:n}:void 0}for(const e of this.merged.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"merged",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}for(const e of this.carried.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"carried",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}}get draws(){let t=0;for(const e of this.batches.values())e.set.object3d.parent===this.group&&(t+=e.set.count);return{batches:[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).length,merged:[...this.merged.values()].filter(t=>t.mesh.parent===this.group).length,carried:[...this.carried.values()].filter(t=>t.mesh.parent===this.group).length,alone:[...this.meshes.values()].filter(t=>t.parent===this.group).length,instances:t}}evaluationInputs(){const t={...this.asset.designInputs,...this.design,...this.asset.stateDefaults,...this.stateOverrides()};return this.size&&(t[zw.x]=this.size.x,t[zw.y]=this.size.y,t[zw.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,s=new Map,i=t.geometry.map(e=>{const i=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),i&&i.body===e&&i.visible===r.visible?(s.set(e.id,i),i.dressed):(s.set(e.id,{body:e,visible:r.visible,dressed:r.dressed}),r.dressed)});return this.dressed=s,{geometry:i,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,s=!!e.emissive?.on,i=s&&e.emissive?this.colourOf(e.emissive.token):this.colourOf(e.token),r=s&&e.emissive?e.emissive.intensity:0,o=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${s?"on":"off"}|${i}|${r}`;return H_.material(o,{color:i,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:e.transparent??!1,opacity:e.transparent?n.opacity??.3:1,emissive:i,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),YA(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(),YA(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),KA(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),KA(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}ZA.shapeBounds=new WeakMap,ZA.LOD_TRANSITION_LIMIT_BYTES=16777216,ZA.matrix=new t.Matrix4,ZA.carrierJudges=new WeakMap,ZA.stillJudges=new WeakMap;class tk 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 MA(this.component.state.type)}getObject3dInstance(){return new t.Group}build(){super.build();const t=this.figure;t&&(this.rig=new ZA(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,s=this.component.state.depth;return PA(t,{x:e,z:n,y:"number"==typeof s&&Number.isFinite(s)&&s>0?s: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,s="ceiling"===t?n:"center"===t?n/2:0;this.rig.group.position.y=-this.effectiveDepth/2+s}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 s=!1;for(const i of e.clips){const r=n[i]??0;Number.isFinite(r)&&0!==r&&(e.setClipTime(i,e.clipTime(i)+t/1e3*r),s=!0)}s&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,s=n?.placeNode(t);if(!n||!s)return;const i=NE(n.asset).find(e=>e.id===t)?.face,r=i&&uS[i]||[0,0,0],o=t=>{const n=Number(e?.state?.[t]);return Number.isFinite(n)&&n>0?n/2:0};return{attach:s,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 ek(t,e,n=1){const s=new ZA(t.compiled.asset);s.setSize(e);const i=s.evaluateOnce(),r=function(t,e){const n=[];for(const s of t){if(!1===s.visible||!pA(s))continue;let t;try{t=gS(mS(s.shape,s.segments),s.pose.r,s.pose.t)}catch{continue}if(t.length<3)continue;const i=t=>t.map(t=>[t[0],t[2]]),r=Math.abs(s.pose.r[1][1]-1)<1e-6,o=s.shape.extrusion;let a;const c=[];if(r&&"y"===o?.axis){const t=(t,e)=>i(gS(fA(t,o.end,s.segments??12,e),s.pose.r,s.pose.t));a=t(o.section);const e=s.shape.cavity;if(e&&"open"===e.end){const n=Kw(o.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=uA(i(t));const l=s.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:s.id,color:e[h]??"#9a9a9a",outline:a,holes:c,top:Math.max(...t.map(t=>t[1])),transparent:!!l.transparent})}return n.sort((t,e)=>t.top-e.top)}(i.geometry,i.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:s.drawnSize}}const nk=Ow,sk=Object.freeze({Capacity:t=>Db(t),Holdable:t=>Bv(t),Transferable:t=>Yv(t),FlowNode:t=>Gv(t)}),ik=Object.freeze({Capacity:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",Holdable:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",Transferable:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",FlowNode:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다"});function rk(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:[...t.accepts]}))}const ok=new Map;function ak(t,e=[],n){const s=new Set(e),i=[...s].filter(t=>!nk.includes(t));if(i.length>0)throw new Error(`모르는 능력이다: ${i.join(" · ")} — 쓸 수 있는 것은 ${nk.join(" · ")}`);for(const[t,e]of Object.entries(Pw))if(s.has(t)&&!e.some(t=>s.has(t)))throw new Error(`${t} 은 혼자 설 수 없다 — ${e.join(" 이나 ")} 가 함께 있어야 한다`);const r=`${[...s].sort().join("+")}|${n??""}`,o=ok.get(r);if(o)return o;const a=0===s.size?t:(c=function(t,e){const n=t.capabilities??[],s=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(s),configurable:!0}),t}(function(t,e){if(e.has("FlowNode"))return sk.FlowNode(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=sk[t](n));return n}(t,s),s),class extends c{get _places(){const t=MA(this.state?.type)?.compiled.asset;return t?NE(t):null}get slots(){const t=this._places;return t?.length?rk(t):super.slots??[]}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,s=e?.slotId??t?.[tb],i=this._places;return i&&s&&i.some(t=>t.id===s)?this._realObject?.placeAttachment?.(s,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 ok.set(r,l),l}function ck(){ok.clear()}const lk={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 hk extends(Pc(Tc)){static registerType(t,e=[],n){const s=Cc.register(t);if(s&&!(s===hk||s.prototype instanceof hk))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const i=ak(hk,e,n);Cc.register(t,i)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=MA(this.state.type);if(!t)return lk;const e=t.compiled.asset,n=e.document.model.inputs,s=(e.publicInputs??[]).flatMap(t=>{const s=n.find(e=>e.id===t.input);return s?[{key:t.input,label:t.label,unit:s.unit,min:s.min,max:s.max,default:e.designInputs[t.input]}]:[]}),i=n.filter(t=>"state"===t.role).map(t=>({key:t.id,label:e.stateInputs?.[t.id]?.label??t.id,unit:t.unit,min:t.min,max:t.max,default:e.stateDefaults[t.id]})),r=[...new Set((e.drivers??[]).map(t=>t.clip))].map(t=>({key:t,label:t,min:0,max:3})),o=[...lk.properties];return s.length&&o.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:s}}),i.length&&o.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:i}}),r.length&&o.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),o.length===lk.properties.length?lk:{...lk,properties:o}}buildRealObject(){return SA(this.state.type)?new tk(this):void 0}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state,r=MA(this.state.type);if(!r)return void this.renderPlace(t,e,n,s,i);const o=this.topView(r,s,i),a=e+s/2,c="wall"===r.compiled.asset.placement?n:n+i/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 s=PA(t.compiled.asset,{x:e,z:n,y:this.askedDepth}),i=s.inputs,r=`${t.compiled.fingerprint}|${i?`${i.x}|${i.y}|${i.z}`:`x${s.scale}`}`;return this._top?.key!==r&&(this._top={key:r,view:ek(t,i,s.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 s=MA(this.state.type);if(!s)return super.adjustResize(t,e,n);const i=s.compiled.asset,r=OA(i),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}=PA(i,{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=MA(this.state.type);if(!e)return;const n=e.compiled.asset,s=OA(n),{width:i=0,height:r=0}=this.state,{occupancy:o}=PA(n,{x:i,z:r,y:this.askedDepth},t),a={};Math.abs(o.x-i)>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||s&&void 0===c&&t.includes("y"))&&(a.depth=o.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,s,i){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,s,i),t.stroke(),t.restore()}postrender(t){Cc.prototype.postrender.call(this,t)}}gA(hk);const dk={"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"},uk=new Map([["default",dk]]);let pk="default",fk=0;function mk(){return fk}function gk(t,e){uk.set(t,e),t===pk&&fk++}function yk(t){if(!uk.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...uk.keys()].join(", ")}`);t!==pk&&(pk=t,fk++)}function bk(){return pk}function vk(){return uk.get(pk)}function _k(t){const e=vk()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${pk}'). 쓸 수 있는 것 — ${Object.keys(vk()).join(", ")}`);return e}const xk=dk["palette.neutral"];function wk(){uk.clear(),uk.set("default",dk),pk="default",fk++}const Mk={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},Sk=["shape","segments"],Ek=["color","preset","transparent","glow"];function Ak(e,n){let s;try{s=GA(e,n)}catch{return null}if(!s?.getAttribute("position"))return null;const i=s.clone();s.dispose(),i.computeBoundingBox();const r=i.boundingBox,o=r.getCenter(new t.Vector3),a=r.getSize(new t.Vector3);return i.translate(-o.x,-o.y,-o.z),i.scale(1/(a.x||1),1/(a.y||1),1/(a.z||1)),i.computeBoundingBox(),i.getAttribute("normal")||i.computeVertexNormals(),{geometry:i,extent:a,centre:o}}class kk extends Mu{build(){super.build();const e=this.component.state,n=e.shape?Ak(e.shape,e.segments):null;if(!n)return;const s=new t.Mesh(n.geometry,this.material());s.castShadow=!0,s.receiveShadow=!0,this.object3d.add(s),this.mesh=s,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(Sk)?this.update():(super.onchange(t,e),n(Ek)&&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",s=t.transparent??!1,i=t.glow,r=i?i.color:n,o=i?i.intensity:0;return H_.material(`figure-part|${n}|${t.preset??"default"}|${s}|${i?`${i.color}:${o}`:"-"}`,{color:r,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:s,opacity:s?e.opacity??.3:1,emissive:r,emissiveIntensity:o})}}class Ck extends(Pc(Tc)){static registerType(){Cc.register("figure-part",Ck)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return Mk}buildRealObject(){return new kk(this)}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state;t.beginPath(),t.rect(e,n,s,i),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var Tk;Ck.registerType(),function(t){t.compile=Bl,t.duplicate=Yl,t.select=ec,t.match=Ja}(Tk||(Tk={})),js.registerResidents(()=>({componentResidentsCount:Cc.residentsCount,sceneResidentsCount:Ju.residentsCount,referenceMapResidentsCount:M_.residentsCount,sceneResidents:Cc.residents}));var Ok=Object.freeze({__proto__:null,AbsoluteLayout:Nc,Animation:Ea,AudioPlayer:ry,BULGE_EPSILON:qr,get Banner(){return Rx},Banner3D:zx,BoxSelectionManager:Lf,CAPABILITY_MIXINS:sk,COMMON_PLACEHOLDER_PROPERTIES:kg,CORE_PLACEHOLDER_TYPES:Pg,get Camera(){return $x},Camera3D:Nx,CameraBookmarkManager:jf,CameraManager:xf,Capacity:Db,CapacityEventTracker:By,CardLayout:Hc,CenteringQueueStrategy:Gy,CenteringSlotStrategy:t_,Component:Cc,Connectable:lm,Container:lg,ContainerAbstract:rh,ControlsManager:Ef,get Cube(){return Tx},Cube3D:Cx,get Cylinder(){return Ix},Cylinder3D:Px,DEFAULT:Ki,DEFAULT_CEILING:_u,DEFAULT_PALETTE:dk,DEFAULT_PLACEMENT:fu,DEFAULT_SEAT_MARGIN:_b,DPPX:Wi,DataLagTracker:hh,DataSource:zy,DefaultLoadingOverlayRenderer:Vd,Donut:Sy,DonutExtrude:ax,Ellipse:Eg,EllipseExtrude:sx,EventManager3D:Af,EventMap:fl,FIGURE_CAPABILITIES:nk,FIGURE_CAPABILITY_NOTES:ik,FPS:$p,FigureInstance:hk,FigurePart:Ck,FigurePartRealObject:kk,FixedSlotStrategy:sb,get FloorPlate(){return Qx},FlowEngine:Hv,FlowNode:Gv,GESTURES:qi,get GLTFObject(){return Bx},GLTF_BASE_URL_ALIAS:jy,GenericObject:Og,GeometryBank:ux,GifView:sy,GizmoManager:Cf,GizmoOperationManager:Pf,GlobalRef:py,GltfComponent:Fy,GridStacking:Wy,Group:cy,HTMLAbsoluteLayout:Fc,HTMLOverlayContainer:dy,HTMLOverlayElement:Vg,Holdable:Bv,ImageView:Gg,InfoWindow:Rc,InstancedSet:bw,InteractionManager:If,ItemsDataBinding:nb,KEYEVENTS:Xi,Layer:bp,Layout:Lc,LightManager:Mf,LightObject:Gx,Line:Mg,Line3D:fw,LinearHorizontalLayout:Yc,LinearVerticalLayout:Vc,LoadTracker:ph,LoadingOverlay:Ld,LocalRef:hy,MATERIAL_PRESETS:Pd,MAX_SEGMENTS:gx,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:H_,get Model(){return Tk},MoveHandle:sh,NOTHING:Fi,NavGraph:o_,Node:Ty,OrthoLine:Bg,OrthoLine3D:gw,PIXEL_RATIO:Hp,PLACEHOLDER_THEMES:Ag,Path:vy,PatternStacking:Uy,PlacementManager:Df,get PointLight(){return Vx},Polygon:Rg,PolygonContainer:Lg,PolygonExtrude:ox,PolygonPathPolyline:p_,Polyline:$g,Polyline3D:mw,Popup:gy,PopupContainer:by,Pose6DOF:_l,RealObject:Mu,RealObjectCamera:ww,RealObjectDomElement:Xp,RealObjectDomTexture:L_,RealObjectDummy:_w,RealObjectExternalModel:Au,RealObjectExtrude:nx,RealObjectGLTF:Ou,RealObjectGroup:nw,RealObjectLine:pw,RealObjectMesh:B_,RealObjectPlane:Mw,RealObjectPlane2D:Aw,RealObjectScene:Sw,RealObjectService:Oy,RealObjectSprite:Mx,RealObjectSprite2D:Sx,RealObjectText:X_,Rect:um,RectExtrude:ix,RectPath:Pc,ReferenceMap:M_,RendererManager:wf,ReservationTable:i_,RootContainer:lh,Ruler:fm,SCALE_MIN:tu,SCENE_MODE:Vi,SEGMENT_DEFAULTS:fx,SEGMENT_PRESETS:px,SHORTCUT_SECTIONS:em,Scene:Ju,SceneManager:_f,ScenePopup:yp,SceneSearchEngine:Ru,ScriptLoader:O_,SearchOverlay:Lu,ServiceComponent:Iy,Shape:Tc,get Sphere(){return wx},Sphere3D:xx,get Sprite(){return Ax},Star:ky,StarExtrude:lx,TRANSFER_SLOT_KEY:tb,TableLayout:Uc,Text:oy,ThreeCapability:qf,get ThreeContainer(){return Cw},ThreeDOnly:Ry,Tracker:Nu,Transfer:qu,TransitionEffect:nh,Triangle:xy,TriangleExtrude:cx,UNIT_DIMENSION:iu,UNIT_ROTATE:au,UNIT_SCALE:ru,UNIT_TRANSLATE:ou,UNTOKENED_COLOR:xk,ValueHolder:Dy,VertexGizmoManager:Bf,VolumeStacking:qy,get Wall(){return qx},Wall3D:Wx,Z_PRIORITY:gu,acquireFigureGeometry:BA,activePalette:vk,activePaletteName:bk,addressOfSlotId:bb,allDestinations:Cv,anchorsConnect:Nb,animate:Sa,applyAlpha:nu,applyMaterial3dProps:Rd,applyPolicy:Pv,applySeatingRotation:Zy,applyStackLayout:Xy,applyZPriorityToMaterials:bu,arcSegmentTopology:Lb,autoWireBackPressure:Yy,buildArrow3D:Wp,buildContractInspector:v_,buildCoordinateGround:of,buildFigureGeometry:GA,buildFlowGraph:Gb,buildNavGraph:l_,buildShapeFromPolygonPath:rx,buildTether:cp,bulgeFromDrag:Jr,bulgeHandlePosition:Qr,canReach:Xb,capability:qm,centerOnBBox:ex,chooseNearestPickupFrame:Zv,clearTether:hp,collectAdjacentSegments:tv,compile:ka,componentForNode:kv,computeArcParams:Kr,computeFlowMap:mv,computeStackPositions:Vy,cornerHandlePosition:to,cornerRadiusFromDrag:eo,create:tp,createCanvas:Bp,createCanvasTexture:D_,createFloor:yf,createRealObjectFor:tf,createSelectionHandle3D:Jx,dataLagTracker:dh,debug:Zs,deliversInto:Bb,delta:wa,disposeCoordinateGround:hf,disposeObject3D:hu,disposeTether:dp,downstream:zv,drawTextTexture:V_,effectiveCornerRadius:Zr,ellipseOutline:tx,enumerateDataScenarios:iv,error:Qs,figureClassFor:ak,figureSectionOutline:hA,fillStyleOpacity:eu,filterByToolType:Jv,filterShortcuts:nm,findNearestWithCapability:bv,flattenPolygonPath:f_,flowGraphFor:Ev,flowGraphIssues:Sv,flowReverseFor:gv,fontStyle:Y_,footprint2D:Ky,frameClock:Rr,ftId:dv,ftrace:hv,getAllCapabilityMeta:Jm,getCapabilityMeta:Qm,getFigure:MA,getPose:El,getWorldPose:Al,globalSimClock:Dr,gltfNatureProperties:Ly,graphFor:Fv,gridCellOf:fb,gridPlacements:vw,gridSlotNo:pb,hasArc:Xr,hasCapability:Wm,hasCapacity:$y,hasFigure:SA,inferCapacity:Hy,inferDownstreamId:ev,inferFlowDirections:lv,initFontFamilyWatcher:Ji,inspector:jd,installContractInspector:__,isFlowNode:Vv,isGenericPlaceholder:Ig,isGeometricHost:yv,isParted:Su,isRoutingTarget:vv,isSegmentPreset:vx,isStateDriven:mu,isThreedEnabled:Iu,judgeItemFit:Tb,layoutIssue:rb,matchOutbounds:Yb,metrics:js,next:Dv,nextHop:qb,nextHops:Wb,nextHopsToAny:Qb,nextHopsToAnyDetailed:Jb,niceGridStep:sf,nodeIdOf:Tv,opaqueColor:su,paletteVersion:mk,partAtByIndex:Eu,persistenceIssues:db,pickWeightedDestination:$v,planPathAStar:h_,planToReservations:d_,pointInRotatedRect:$b,polygonOffsetForPriority:yu,polygonPathLength:m_,projectToScreen:ip,quatFromYaw:Wv,rayAbsDistanceToRect:Hb,reachableByOutbound:Vb,reachableDestinations:Rv,reachableDestinationsFrom:jv,reachableDestinationsWeightedFrom:Lv,reachableSinks:Kb,receiptToJSON:Uu,recommendsLogarithmicDepthForSky:vf,rectFaceAnchors:zb,rectOutline:Z_,rectangularFootprintFrames:Kv,registerCapabilityMeta:Km,registerDefaultRealObjectFactory:Zp,registerFigure:wA,registerFigureType:yA,registerPalette:gk,registerRealObjectFactory:Jp,registerTypeResolver:Rl,releaseFigureGeometry:YA,renderCanvasTexture:z_,renderPlaceholder:Cg,reservationTable:r_,resetFigureClasses:ck,resetFigures:AA,resetPalettes:wk,resolveAnchorWorldPosition:ap,resolveHeightSegments:bx,resolveMaterial3d:Id,resolveNextHop:Iv,resolveSegments:yx,resolveSlot:gb,resolveToken:_k,resolveUnknownTypes:Ll,resolveVariant:Qd,rotatedFootprint:Sb,sceneComponent:Ny,seatInAnchor:Cb,seatTransform:Eb,setActivePalette:yk,setPose:kl,setThreedEnabled:Du,setWorldPose:Cl,sinksForDestination:Av,slotAddresses:vb,slotAnchorPosition:kb,slotCount:ub,slotIdOf:yb,slotsFromBindings:rk,stackSeatTransforms:Ab,standardYieldPolicy:s_,stopFPSMeasure:Np,straightSegmentEndpoints:jb,straightSegmentMultiInbound:Fb,straightSegmentTopology:Rb,textBounds:q_,textTexture:U_,toThreeSide:zd,topApproachFrame:Qv,transferLog:Xu,transferTracer:Gu,uniformZ:no,unitFigurePartGeometry:Ak,unknownTypesOf:jl,unregisterFigure:EA,unresolvedReasonOf:Dl,updateDefaultFontFamily:Qi,updateTether:lp,useFigureComponent:gA,validate:Nv,validateFlowGraph:Zb,validateSlotLayout:hb,version:P_,warn:Js});const Pk=globalThis;"undefined"==typeof globalThis||Pk.scene||(Pk.scene=Ok);export{Nc as AbsoluteLayout,Ea as Animation,ry as AudioPlayer,qr as BULGE_EPSILON,Rx as Banner,zx as Banner3D,Lf as BoxSelectionManager,sk as CAPABILITY_MIXINS,kg as COMMON_PLACEHOLDER_PROPERTIES,Pg as CORE_PLACEHOLDER_TYPES,$x as Camera,Nx as Camera3D,jf as CameraBookmarkManager,xf as CameraManager,Db as Capacity,By as CapacityEventTracker,Hc as CardLayout,Gy as CenteringQueueStrategy,t_ as CenteringSlotStrategy,Cc as Component,lm as Connectable,lg as Container,rh as ContainerAbstract,Ef as ControlsManager,Tx as Cube,Cx as Cube3D,Ix as Cylinder,Px as Cylinder3D,Ki as DEFAULT,_u as DEFAULT_CEILING,dk as DEFAULT_PALETTE,fu as DEFAULT_PLACEMENT,_b as DEFAULT_SEAT_MARGIN,Wi as DPPX,hh as DataLagTracker,zy as DataSource,Vd as DefaultLoadingOverlayRenderer,Sy as Donut,ax as DonutExtrude,Eg as Ellipse,sx as EllipseExtrude,Af as EventManager3D,fl as EventMap,nk as FIGURE_CAPABILITIES,ik as FIGURE_CAPABILITY_NOTES,$p as FPS,hk as FigureInstance,Ck as FigurePart,kk as FigurePartRealObject,sb as FixedSlotStrategy,Qx as FloorPlate,Hv as FlowEngine,Gv as FlowNode,qi as GESTURES,Bx as GLTFObject,jy as GLTF_BASE_URL_ALIAS,Og as GenericObject,ux as GeometryBank,sy as GifView,Cf as GizmoManager,Pf as GizmoOperationManager,py as GlobalRef,Fy as GltfComponent,Wy as GridStacking,cy as Group,Fc as HTMLAbsoluteLayout,dy as HTMLOverlayContainer,Vg as HTMLOverlayElement,Bv as Holdable,Gg as ImageView,Rc as InfoWindow,bw as InstancedSet,If as InteractionManager,nb as ItemsDataBinding,Xi as KEYEVENTS,bp as Layer,Lc as Layout,Mf as LightManager,Gx as LightObject,Mg as Line,fw as Line3D,Yc as LinearHorizontalLayout,Vc as LinearVerticalLayout,ph as LoadTracker,Ld as LoadingOverlay,hy as LocalRef,Pd as MATERIAL_PRESETS,gx as MAX_SEGMENTS,Ui as MAX_UNDO_SIZE,mx as MIN_SEGMENTS,Bi as MODE_ADD,$i as MODE_EDIT,Gi as MODE_PASTE_DATABIND,Yi as MODE_PASTE_STYLE,Hi as MODE_SHIFT,Ni as MODE_VIEW,H_ as MaterialBank,Tk as Model,sh as MoveHandle,Fi as NOTHING,o_ as NavGraph,Ty as Node,Bg as OrthoLine,gw as OrthoLine3D,Hp as PIXEL_RATIO,Ag as PLACEHOLDER_THEMES,vy as Path,Uy as PatternStacking,Df as PlacementManager,Vx as PointLight,Rg as Polygon,Lg as PolygonContainer,ox as PolygonExtrude,p_ as PolygonPathPolyline,$g as Polyline,mw as Polyline3D,gy as Popup,by as PopupContainer,_l as Pose6DOF,Mu as RealObject,ww as RealObjectCamera,Xp as RealObjectDomElement,L_ as RealObjectDomTexture,_w as RealObjectDummy,Au as RealObjectExternalModel,nx as RealObjectExtrude,Ou as RealObjectGLTF,nw as RealObjectGroup,pw as RealObjectLine,B_ as RealObjectMesh,Mw as RealObjectPlane,Aw as RealObjectPlane2D,Sw as RealObjectScene,Oy as RealObjectService,Mx as RealObjectSprite,Sx as RealObjectSprite2D,X_ as RealObjectText,um as Rect,ix as RectExtrude,Pc as RectPath,M_ as ReferenceMap,wf as RendererManager,i_ as ReservationTable,lh as RootContainer,fm as Ruler,tu as SCALE_MIN,Vi as SCENE_MODE,fx as SEGMENT_DEFAULTS,px as SEGMENT_PRESETS,em as SHORTCUT_SECTIONS,Ju as Scene,_f as SceneManager,yp as ScenePopup,Ru as SceneSearchEngine,O_ as ScriptLoader,Lu as SearchOverlay,Iy as ServiceComponent,Tc as Shape,wx as Sphere,xx as Sphere3D,Ax as Sprite,ky as Star,lx as StarExtrude,tb as TRANSFER_SLOT_KEY,Uc as TableLayout,oy as Text,qf as ThreeCapability,Cw as ThreeContainer,Ry as ThreeDOnly,Nu as Tracker,qu as Transfer,nh as TransitionEffect,xy as Triangle,cx as TriangleExtrude,iu as UNIT_DIMENSION,au as UNIT_ROTATE,ru as UNIT_SCALE,ou as UNIT_TRANSLATE,xk as UNTOKENED_COLOR,Dy as ValueHolder,Bf as VertexGizmoManager,qy as VolumeStacking,qx as Wall,Wx as Wall3D,gu as Z_PRIORITY,BA as acquireFigureGeometry,vk as activePalette,bk as activePaletteName,bb as addressOfSlotId,Cv as allDestinations,Nb as anchorsConnect,Sa as animate,nu as applyAlpha,Rd as applyMaterial3dProps,Pv as applyPolicy,Zy as applySeatingRotation,Xy as applyStackLayout,bu as applyZPriorityToMaterials,Lb as arcSegmentTopology,Yy as autoWireBackPressure,Wp as buildArrow3D,v_ as buildContractInspector,of as buildCoordinateGround,GA as buildFigureGeometry,Gb as buildFlowGraph,l_ as buildNavGraph,rx as buildShapeFromPolygonPath,cp as buildTether,Jr as bulgeFromDrag,Qr as bulgeHandlePosition,Xb as canReach,qm as capability,ex as centerOnBBox,Zv as chooseNearestPickupFrame,hp as clearTether,tv as collectAdjacentSegments,ka as compile,kv as componentForNode,Kr as computeArcParams,mv as computeFlowMap,Vy as computeStackPositions,to as cornerHandlePosition,eo as cornerRadiusFromDrag,tp as create,Bp as createCanvas,D_ as createCanvasTexture,yf as createFloor,tf as createRealObjectFor,Jx as createSelectionHandle3D,dh as dataLagTracker,Zs as debug,Bb as deliversInto,wa as delta,hf as disposeCoordinateGround,hu as disposeObject3D,dp as disposeTether,zv as downstream,V_ as drawTextTexture,Zr as effectiveCornerRadius,tx as ellipseOutline,iv as enumerateDataScenarios,Qs as error,ak as figureClassFor,hA as figureSectionOutline,eu as fillStyleOpacity,Jv as filterByToolType,nm as filterShortcuts,bv as findNearestWithCapability,f_ as flattenPolygonPath,Ev as flowGraphFor,Sv as flowGraphIssues,gv as flowReverseFor,Y_ as fontStyle,Ky as footprint2D,Rr as frameClock,dv as ftId,hv as ftrace,Jm as getAllCapabilityMeta,Qm as getCapabilityMeta,MA as getFigure,El as getPose,Al as getWorldPose,Dr as globalSimClock,Ly as gltfNatureProperties,Fv as graphFor,fb as gridCellOf,vw as gridPlacements,pb as gridSlotNo,Xr as hasArc,Wm as hasCapability,$y as hasCapacity,SA as hasFigure,Hy as inferCapacity,ev as inferDownstreamId,lv as inferFlowDirections,Ji as initFontFamilyWatcher,jd as inspector,__ as installContractInspector,Vv as isFlowNode,Ig as isGenericPlaceholder,yv as isGeometricHost,Su as isParted,vv as isRoutingTarget,vx as isSegmentPreset,mu as isStateDriven,Iu as isThreedEnabled,Tb as judgeItemFit,rb as layoutIssue,Yb as matchOutbounds,js as metrics,Dv as next,qb as nextHop,Wb as nextHops,Qb as nextHopsToAny,Jb as nextHopsToAnyDetailed,sf as niceGridStep,Tv as nodeIdOf,su as opaqueColor,mk as paletteVersion,Eu as partAtByIndex,db as persistenceIssues,$v as pickWeightedDestination,h_ as planPathAStar,d_ as planToReservations,$b as pointInRotatedRect,yu as polygonOffsetForPriority,m_ as polygonPathLength,ip as projectToScreen,Wv as quatFromYaw,Hb as rayAbsDistanceToRect,Vb as reachableByOutbound,Rv as reachableDestinations,jv as reachableDestinationsFrom,Lv as reachableDestinationsWeightedFrom,Kb as reachableSinks,Uu as receiptToJSON,vf as recommendsLogarithmicDepthForSky,zb as rectFaceAnchors,Z_ as rectOutline,Kv as rectangularFootprintFrames,Km as registerCapabilityMeta,Zp as registerDefaultRealObjectFactory,wA as registerFigure,yA as registerFigureType,gk as registerPalette,Jp as registerRealObjectFactory,Rl as registerTypeResolver,YA as releaseFigureGeometry,z_ as renderCanvasTexture,Cg as renderPlaceholder,r_ as reservationTable,ck as resetFigureClasses,AA as resetFigures,wk as resetPalettes,ap as resolveAnchorWorldPosition,bx as resolveHeightSegments,Id as resolveMaterial3d,Iv as resolveNextHop,yx as resolveSegments,gb as resolveSlot,_k as resolveToken,Ll as resolveUnknownTypes,Qd as resolveVariant,Sb as rotatedFootprint,Ny as sceneComponent,Cb as seatInAnchor,Eb as seatTransform,yk as setActivePalette,kl as setPose,Du as setThreedEnabled,Cl as setWorldPose,Av as sinksForDestination,vb as slotAddresses,kb as slotAnchorPosition,ub as slotCount,yb as slotIdOf,rk as slotsFromBindings,Ab as stackSeatTransforms,s_ as standardYieldPolicy,Np as stopFPSMeasure,jb as straightSegmentEndpoints,Fb as straightSegmentMultiInbound,Rb as straightSegmentTopology,q_ as textBounds,U_ as textTexture,zd as toThreeSide,Qv as topApproachFrame,Xu as transferLog,Gu as transferTracer,no as uniformZ,Ak as unitFigurePartGeometry,jl as unknownTypesOf,EA as unregisterFigure,Dl as unresolvedReasonOf,Qi as updateDefaultFontFamily,lp as updateTether,gA as useFigureComponent,Nv as validate,Zb as validateFlowGraph,hb as validateSlotLayout,P_ as version,Js 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,s,i){const r=5+i,o=n.x,a=n.y,c=s.x,l=s.y;if(Math.abs(o-c)>r&&Math.abs(a-l)>r){const n=(l-a)/(c-o),s=a-n*o;if(Math.abs(e-(n*t+s))>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,s=2){for(let i=0;i<n.length-1;i++)if(ug(t,e,n[i],n[i+1],s))return!0;return!1}function fg(t,e,n,s){if("arrow"!=t.slice(-5))return n;const i=Math.atan2(s.y-n.y,s.x-n.x),r=1.5*e;return{x:n.x+Math.cos(i)*r,y:n.y+Math.sin(i)*r}}function mg(t,e,n){let{lineWidth:s=dg,strokeStyle:i="#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)&&(s=Number(s)||dg,t.lineCap=r,t.lineWidth=s,t.strokeStyle=i,t.fillStyle=i,t.globalAlpha*=o,"none"!=a&&gg(t,e[0],e[1],s,a,yg(l,s)),"none"!=c)){const n=e.length;gg(t,e[n-1],e[n-2],s,c,yg(h,s))}}function gg(t,e,n,s,i,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),i){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+s,-r.Y),t.lineTo(s,0),t.lineTo(hg*r.X+s,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:s}){this.component=t,this._anchorName=e,this._position=n,this.self=s}get position(){const t=this.anchor;if(t){const{position:e}=t,n=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(n.x,n.y)}return this._position}set position({x:t,y:e}){this._position={x:t,y:e}}get anchor(){return this.component?.findAnchor(this._anchorName)}get direction(){const t=this.component.bounds,e=this.anchor;if(!e)return _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,s=0;switch(this.direction){case vg:s=20;break;case bg:s=-20;break;case xg:n=-20;break;default:n=20}e={x:e.x+n,y:e.y+s};const i=this.component.toScene(e.x,e.y);return this.self.transcoordT2P(i.x,i.y)}}}class Mg extends Cc{isLine(){return!0}is3dish(){return!0}replaceRefids(t){["from","to"].forEach(e=>{const n=this.get(e);if(n?.component){const s=t.get(n.component)||n.component;this.set(e,{...n,component:s})}})}get fromEnd(){if(this.parent&&!this._fromEnd){const{component:t,anchor:e,position:n}=this.getState("from")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._fromEnd=new wg({component:s,fromto:"from",anchor:e,position:n,self:this})}return this._fromEnd}get from(){return this.getState("from")}set from(t){delete this._fromEnd,this.set("from",t)}get toEnd(){if(this.parent&&!this._toEnd){const{component:t,anchor:e,position:n}=this.getState("to")||{};if(!t)return;const s=this.root?.findByRefid?.(t);if(!s)return;this._toEnd=new wg({component:s,fromto:"to",anchor:e,position:n,self:this})}return this._toEnd}get to(){return this.getState("to")}set to(t){delete this._toEnd,this.set("to",t)}move({x:t,y:e},n){n&&(this.from={position:this._fromEnd?.position||this.getState("from")?.position||{x:0,y:0}},this.to={position:this._toEnd?.position||this.getState("to")?.position||{x:0,y:0}}),super.move({x:t,y:e})}render(t){const{begin:e="none",end:n="none",lineWidth:s,round:i=0}=this.state;let r=this.drawPath;mg(t,r,this.state),t.beginPath();const o=fg(e,s,r[0],r[1]),a=fg(n,s,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,i),s=Math.sqrt((o.x-e.x)**2+(o.y-e.y)**2),a=0!==s?Math.atan2(o.x-e.x,o.y-e.y):0,l=Math.sin(a)*Math.min(n,s/2)+e.x,h=Math.cos(a)*Math.min(n,s/2)+e.y,d=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 s=r[e+1];if(n.x===l.x&&n.y===l.y)continue;if(!s){t.lineTo(l.x,l.y);break}const o=Zr(l,i);let a=Math.sqrt((n.x-l.x)*(n.x-l.x)+(n.y-l.y)*(n.y-l.y)),c=0!==a?Math.atan2(n.x-l.x,n.y-l.y):0,h=Math.sin(c)*Math.min(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((s.x-l.x)*(s.x-l.x)+(s.y-l.y)*(s.y-l.y)),c=0!==a?Math.atan2(s.x-l.x,s.y-l.y):0,h=Math.sin(c)*Math.min(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(s,i),n=Math.sqrt((l.x-s.x)**2+(l.y-s.y)**2),r=0!==n?Math.atan2(l.x-s.x,l.y-s.y):0,o=Math.sin(r)*Math.min(e,n/2)+s.x,a=Math.cos(r)*Math.min(e,n/2)+s.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:s,x2:i,y2:r}=this.state;return[this.fromEnd?.position||t?.position||{x:n,y:s},this.toEnd?.position||e?.position||{x:i,y:r}]}set path(t){const[e,n]=t,{from:s,to:i}=this.state;delete this._fromEnd,delete this._toEnd,this.set({from:{...s,position:e},to:{...i,position:n}})}get textBounds(){const t=this.drawPath;let e,n,s=0;for(let i=1;i<t.length;i++){const r=t[i-1],o=t[i],a=(r.x-o.x)*(r.x-o.x)+(r.y-o.y)*(r.y-o.y);a>s&&(s=Math.ceil(a),e=r,n=o)}let{paddingTop:i,paddingLeft:r,paddingRight:o,paddingBottom:a}=this.state;return a||=0,i||=0,r||=0,o||=0,{left:Math.min(e.x,n.x)+r,top:Math.min(e.y,n.y)+i,width:Math.max(Math.abs(e.x-n.x)-r-o,0),height:Math.max(Math.abs(e.y-n.y)-i-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 Eg extends(lm(Tc)){is3dish(){return!0}render(t){const{cx:e,cy:n,rx:s,ry:i,startAngle:r,endAngle:o,anticlockwise:a}=this.state;t.beginPath(),t.ellipse(e,n,Math.abs(s),Math.abs(i),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:s}=this.state;return[{x:t-n,y:e-s},{x:t+n,y:e-s},{x:t+n,y:e+s},{x:t-n,y:e+s}]}set path(t){const e=t[0],n=t[2];this.set({cx:e.x+(n.x-e.x)/2,cy:e.y+(n.y-e.y)/2,rx:(n.x-e.x)/2,ry:(n.y-e.y)/2})}contains(t,e){const{cx:n,cy:s,rx:i,ry:r}=this.state,o=(t-n)/(2*i-.5),a=(e-s)/(2*r-.5);return o*o+a*a<.25}outline(t){return function(t,e){const{cx:n,cy:s,rx:i,ry:r}=t.model,o=2*Math.PI*e,a=n+i*Math.cos(o),c=s+r*Math.sin(o);return t.toScene(a,c)}(this,t)}get anchors(){return function(t){const{left:e,top:n,width:s,height:i}=t.bounds,r=e+s/2,o=n+i/2;return[{name:"TOP",position:{x:r,y:n}},{name:"RIGHT",position:{x:e+s,y:o}},{name:"BOTTOM",position:{x:r,y:n+i}},{name:"LEFT",position:{x:e,y:o}}]}(this)}get nature(){return Sg}}Cc.memoize(Eg.prototype,"path",!1),Cc.register("ellipse",Eg);const Ag={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,s,i){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=s?`${n.label}: ${s}`:n.label;h>=32&&(t.save(),t.fillStyle=n.stroke,t.font="10px Arial",t.textAlign="center",t.textBaseline="bottom",t.fillText(d,r+l/2,o+h-4),t.restore()),i&&h>=40&&(t.save(),t.fillStyle=n.stroke,t.font="9px Arial",t.textAlign="right",t.textBaseline="top",t.fillText(`hint: ${i}`,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,Ag.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 s=n[e+1];n[e+1]={...s||{},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 s=!1;return n.forEach((i,r)=>{const o=(r+n.length+1)%n.length,a=i.x,c=i.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}get controls(){const t=this.path;return t.map((e,n)=>{const s=t[n+1>=t.length?0:n+1];return{x:(e.x+s.x)/2,y:(e.y+s.y)/2,handler:Dg}})}get nature(){return zg}}Cc.memoize(Rg.prototype,"controls",!1),Cc.register("polygon",Rg);const jg=[];class Lg extends(sh(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:s=!1}="boolean"==typeof e?{ghost:e}:e,i=t.parent;if(i){if(this===i)return;i.removeComponent(t,n||s)}const r=this._components.push(t)-1;s&&(t._silentAdd=!0),t.parent=this,t.added(this),n||s||this.trigger("add",this,t,r),t.delegate_on(this),s?(i&&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 s=t.parent;s&&s.removeComponent(t,n);const i=this._components.splice(0,e);this._components=i.concat(t,this._components),e=this._components.indexOf(t),t.parent=this,t.added(this),n||this.trigger("add",this,t,e),t.delegate_on(this),n||t.trigger("added",this,t,e)}add(t,e=!1){return t instanceof Array?(t.forEach(t=>{-1==this._components.indexOf(t)&&this.addComponent(t,e)}),this):this.add.call(this,[t],e)}remove(t,e=!1){return t instanceof Array?this._components?(t.forEach(t=>this.removeComponent(t,e)),this):this:this.remove.call(this,[t],e)}getAt(t){if(this._components)return this._components[t]}forEach(t,e){this._components&&this._components.forEach(t,e)}traverse(t,e){t.call(e,this),this._components&&this._components.forEach(n=>{n.isContainer()?n.traverse(t,e):t.call(e,n)})}indexOf(t){return(this._components||jg).indexOf(t)}size(){return(this._components||jg).length}moveChildAt(t,e){const n=this.indexOf(e);if(-1==n)return;let s=this._components.splice(0,n);const i=this._components.splice(1);this._components=s.concat(i),t=Math.max(0,t),t=Math.min(t,this._components.length),s=this._components.splice(0,t),this._components=s.concat(e,this._components)}moveChildForward(t){const e=this.indexOf(t);-1!=e&&e!=this.size()-1&&(this._components[e]=this._components[e+1],this._components[e+1]=t)}moveChildBackward(t){const e=this.indexOf(t);-1!=e&&0!=e&&(this._components[e]=this._components[e-1],this._components[e-1]=t)}moveChildToFront(t){const e=this.indexOf(t);if(-1==e||e==this.size()-1)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=n.concat(s,this._components)}moveChildToBack(t){const e=this.indexOf(t);if(-1==e||0==e)return;const n=this._components.splice(0,e),s=this._components.splice(1);this._components=this._components.concat(n,s)}symmetryX(t){super.symmetryX(t),this.components.map(t=>{t.symmetryX(0)})}findAll(t,...e){if("string"==typeof t)return ec(t,this,e[0]||this);if("function"!=typeof t)return[];let n=[];for(let s=this.components.length-1;s>=0;s--){const i=this.components[s].findAll(t,...e);i&&(n=n.concat(i))}return t(this,...e)&&n.push(this),n}findFirst(t,...e){if("string"==typeof t)return ec(t,this,e[0])[0];if("function"==typeof t){for(let n=this.components.length-1;n>=0;n--){const s=this.components[n].findFirst(t,...e);if(null!=s)return s}return t(this,...e)?this:void 0}}findById(t){return this.root.findAllById?.(t)?.[0]}findByRefid(t){return this.root.findByRefid?.(t)}capture(t,e,n){if(!this.app.isEditMode&&this.hidden)return!1;const s=this.fromParent(t,e);if(!this.contains(s.x,s.y))return!1;const i=this.bounds;s.x-=i.left,s.y-=i.top;const r=this.layout.capturables(this);for(let i=r.length-1;i>=0;i--){const o=r[i];let a;if(a="static"==o.position?o.capture(s.x,s.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:s,top:i,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<s||a.x>s+r||a.y<i||a.y>i+o)return!1;a.x-=s,a.y-=i,n.push(a)}const a=this.layout.capturables(this);for(let t=a.length-1;t>=0;t--){const s=a[t];if(!s.isContainer())continue;const i=s.capturePath(n,e);if(i)return i}return this.focusible&&this}render(t){"popup"!==this.position&&super.render(t)}postrender(t){if("popup"===this.position)return void super.postrender(t);const e=this.layout.drawables(this);if(e.length>0){let{left:n=0,top:s=0,width:i,height:r}=this.bounds;t.save(),this.showOverflow||(t.beginPath(),t.rect(n,s,i,r),t.clip(),t.closePath()),t.translate(n,s),e.forEach(e=>{const n=this.root?.transitionEffect;n?.isReparenting(e)||e.draw(this.position&&"static"!==this.position?t:this.getContext(e))}),t.translate(-n,-s),t.restore()}super.postrender(t)}trim(){this.components.forEach(t=>{t.trim()}),super.trim()}}["layout"].forEach(t=>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 s=n[e];n[e]={...s||{},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 s=t[n],i=t[n+1];0==n&&e.push({x:s.x,y:s.y,handler:Fg}),e.push({x:(s.x+i.x)/2,y:(s.y+i.y)/2,handler:Fg}),n==t.length-2&&e.push({x:i.x,y:i.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:s,boundaryPosition:i=t}=this.fromEnd||{},{component:r,direction:o,boundaryPosition:a=e}=this.toEnd||{},c=[i,a],l=[];i&&l.push(i);let h,d=n?.bounds;d&&(h=n.toScene(d.left,d.top),h=this.transcoordT2P(h.x,h.y),d={...d,left:h.x,top:h.y});const u=d?{left:d.left-20,top:d.top-20,width:d.width+40,height:d.height+40}:{left:i.x,top:i.y,width:0,height:0};d=d||u;let p=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,E,A,k,C,T=0,O=0;d.left+d.width<p.left?(w=0,M=1,k=s,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=s,v=(d.left+p.width+p.left)/2,T=d.left-v),d.top+d.height<p.top?(x=0,S=1,E=s,A=o,_=(d.top+d.height+p.top)/2,O=p.top-_):p.top+p.height<d.top&&(x=1,S=0,E=o,A=s,_=(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(A){case bg:switch(E){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(E){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(E){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(E){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(s){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 s=n[e-1];return t.x!==s.x||t.y!==s.y}).filter((t,e,n)=>{if(0===e||e>=n.length-1)return!0;const s=n[e-1],i=n[e+1];return!(t.x===s.x&&t.x===i.x||t.y===s.y&&t.y===i.y)})}get nature(){return 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:s,height:i,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,s,i);else try{t.drawImage(this._image,e,n,s,i)}catch(r){t.drawImage(Gg.noimage,e,n,s,i)}else!this.app.isViewMode&&t.drawImage(Gg.noimage,e,n,s,i)}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:s}=this.state;if(n){this._image=new Image;try{s&&(this._image.crossOrigin=s),this._image.src=this.app.url(n)||""}catch(t){return void e(t)}this._image.onload=()=>{if(this.get("isGray")){const t=this._image.width,e=this._image.height;this._offcanvas=Cc.createCanvas(t,e);const n=this._offcanvas.getContext("2d");n.drawImage(this._image,0,0);const s=function(t,e,n){let s;try{s=t.getImageData(0,0,e,n)}catch(t){return Qs("Get Image Data Error: "+(t instanceof Error?t.message:String(t))),null}const i=s.data;for(let t=0;t<e*n*4;t+=4){const e=i[t],n=i[t+1],r=i[t+2],o=Math.floor((e+n+r)/3);s.data[t]=o,s.data[t+1]=o,s.data[t+2]=o}return s}(n,t,e);n.putImageData(s,0,0)}t(this)},this._image.onerror=t=>{this._image&&!this._image.currentSrc&&(this._image=null),e(t)}}else t(this)}get src(){return this.get("src")}set src(t){this.set("src",t)}onchange(t,e){(t.hasOwnProperty("src")||t.hasOwnProperty("isGray"))&&(this._offcanvas=null,this._image=null,this.prepareIf(t.src))}ondropfile(t,e){for(let n=0;n<t.length;n++)if(t[n].type.startsWith("image/"))return void(this.src=e[n])}}Cc.register("image-view",Gg);class Vg extends(ig(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,s,i=0,r=function(t){for(var n=0,s=0;s<t;s++)e.charCodeAt(i>>3)&1<<(7&i)&&(n|=1<<s),i++;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(s=n,(n=r(l))!==a){if(n===c)break;if(n<h.length)s!==a&&h.push(h[s].concat(h[n][0]));else{if(n!==h.length)throw new Error("Invalid LZW code.");h.push(h[s].concat(h[s][0]))}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 s=t.SuperGifUtils.byteToBitArr(n.stream.readByte());e.reserved=s.splice(0,3),e.disposalMethod=t.SuperGifUtils.bitsToNum(s.splice(0,3)),e.userInput=s.shift(),e.transparencyGiven=s.shift(),e.delayTime=n.stream.readUnsigned(),e.transparencyIndex=n.stream.readByte(),e.terminator=n.stream.readByte(),n.handler.gce&&n.handler.gce(e)}(e);break;case 254:e.extType="com",function(t){t.comment=n.readSubBlocks(),n.handler.com&&n.handler.com(t)}(e);break;case 1:e.extType="pte",function(t){n.stream.readByte(),t.ptHeader=n.stream.readBytes(12),t.ptData=n.readSubBlocks(),n.handler.pte&&n.handler.pte(t)}(e);break;case 255:e.extType="app",function(t){n.stream.readByte(),t.identifier=n.stream.read(8),t.authCode=n.stream.read(3),"NETSCAPE"===t.identifier?function(t){n.stream.readByte(),t.unknown=n.stream.readByte(),t.iterations=n.stream.readUnsigned(),t.terminator=n.stream.readByte(),n.handler.app&&n.handler.app.NETSCAPE&&n.handler.app.NETSCAPE(t)}(t):function(t){t.appData=n.readSubBlocks(),n.handler.app&&n.handler.app[t.identifier]&&n.handler.app[t.identifier](t)}(t)}(e);break;default:e.extType="unknown",function(t){t.data=n.readSubBlocks(),n.handler.unknown&&n.handler.unknown(t)}(e)}},e.prototype.parseImg=function(e){e.leftPos=this.stream.readUnsigned(),e.topPos=this.stream.readUnsigned(),e.width=this.stream.readUnsigned(),e.height=this.stream.readUnsigned();var n=t.SuperGifUtils.byteToBitArr(this.stream.readByte());e.lctFlag=n.shift(),e.interlaced=n.shift(),e.sorted=n.shift(),e.reserved=n.splice(0,2),e.lctSize=t.SuperGifUtils.bitsToNum(n.splice(0,3)),e.lctFlag&&(e.lct=this.parseCT(1<<e.lctSize+1)),e.lzwMinCodeSize=this.stream.readByte();var s=this.readSubBlocks();e.pixels=t.SuperGifUtils.lzwDecode(e.lzwMinCodeSize,s),e.interlaced&&(e.pixels=function(t,e){for(var n=new Array(t.length),s=t.length/e,i=function(s,i){var r=t.slice(i*e,(i+1)*e);n.splice.apply(n,[s*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<s;l+=o[c])i(l,a),a++;return n}(e.pixels,e.width)),this.handler.img&&this.handler.img(e)},e.prototype.parseBlock=function(){var t={};switch(t.sentinel=this.stream.readByte(),String.fromCharCode(t.sentinel)){case"!":t.type="ext",this.parseExt(t);break;case",":t.type="img",this.parseImg(t);break;case";":t.type="eof",this.handler.eof&&this.handler.eof(t);break;default:throw new Error("Unknown block: 0x"+t.sentinel.toString(16))}"eof"!==t.type&&setTimeout(this.parseBlock.bind(this),0)},e.prototype.parse=function(){this.parseHeader(),setTimeout(this.parseBlock.bind(this),0)},e}();return 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 s in this.gifImgElement=t,this.options={autoPlay:!0},this.loading=!1,this.ready=!1,this.transparency=null,this.delay=null,this.disposalMethod=null,this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,this.playing=!0,this.forward=!0,this.ctxScaled=!1,this.frames=[],this.frameOffsets=[],this.initialized=!1,this.currentFrameIndex=-1,this.iterationCount=0,this.stepping=!1,this.handler={hdr:this.withProgress(this.doHdr.bind(this)),gce:this.withProgress(this.doGCE.bind(this)),com:this.withProgress(this.doNothing.bind(this)),app:{NETSCAPE:this.withProgress(this.doNothing.bind(this))},img:this.withProgress(this.doImg.bind(this)),eof:function(){n.pushFrame(),n.canvas.width=n.hdr.width*n.getCanvasScale(),n.canvas.height=n.hdr.height*n.getCanvasScale(),n.playerInit(),n.loading=!1,n.ready=!0,n.loadCallback&&n.loadCallback(n.gifImgElement)}},e)this.options[s]=e[s];this.onEndListener=e.onEnd,this.loopDelay=e.loopDelay||0,this.overrideLoopMode=null!=e.loopMode?e.loopMode:"auto",this.drawWhileLoading=null==e.drawWhileLoading||e.drawWhileLoading}return n.prototype.init=function(){var t=this.gifImgElement.parentNode,e=document.createElement("div");this.canvas=document.createElement("canvas"),this.canvasContext=this.canvas.getContext("2d"),this.tmpCanvas=document.createElement("canvas"),e.className=this.options.enclosingClass||"super-gif",e.appendChild(this.canvas),t&&(t.insertBefore(e,this.gifImgElement),t.removeChild(this.gifImgElement)),this.initialized=!0},n.prototype.loadSetup=function(t){return!this.loading&&(t&&(this.loadCallback=t),this.loading=!0,this.frames=[],this.clear(),this.disposalRestoreFromIdx=null,this.lastDisposalMethod=null,this.frame=null,this.lastImg=null,!0)},n.prototype.completeLoop=function(){this.onEndListener&&this.onEndListener(this.gifImgElement),this.iterationCount++,!1!==this.overrideLoopMode||this.iterationCount<0?this.doStep():(this.stepping=!1,this.playing=!1)},n.prototype.doStep=function(){if(this.stepping=this.playing,this.stepping){this.stepFrame(1);var t=10*this.frames[this.currentFrameIndex].delay;t||(t=100),0===this.getNextFrameNo()?(t+=this.loopDelay,setTimeout(this.completeLoop.bind(this),t)):setTimeout(this.doStep.bind(this),t)}},n.prototype.step=function(){this.stepping||setTimeout(this.doStep.bind(this),0)},n.prototype.putFrame=function(){var t;this.currentFrameIndex=parseInt(this.currentFrameIndex.toString(),10),this.currentFrameIndex>this.frames.length-1&&(this.currentFrameIndex=0),this.currentFrameIndex<0&&(this.currentFrameIndex=0),t=this.frameOffsets[this.currentFrameIndex],this.tmpCanvas.getContext("2d").putImageData(this.frames[this.currentFrameIndex].data,t.x,t.y),this.canvasContext.globalCompositeOperation="copy",this.canvasContext.drawImage(this.tmpCanvas,0,0)},n.prototype.playerInit=function(){this.loadErrorCause||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.options.autoPlay?this.step():(this.currentFrameIndex=0,this.putFrame()))},n.prototype.clear=function(){this.transparency=null,this.delay=null,this.lastDisposalMethod=this.disposalMethod,this.disposalMethod=null,this.frame=null},n.prototype.parseStream=function(e){try{new t.SuperGifParser(e,this.handler).parse()}catch(t){this.handleError("parse")}},n.prototype.setSizes=function(t,e){this.canvas.width=t*this.getCanvasScale(),this.canvas.height=e*this.getCanvasScale(),this.tmpCanvas.width=t,this.tmpCanvas.height=e,this.tmpCanvas.style.width=t+"px",this.tmpCanvas.style.height=e+"px",this.tmpCanvas.getContext("2d").setTransform(1,0,0,1,0,0)},n.prototype.drawError=function(){this.canvasContext.fillStyle="black",this.canvasContext.fillRect(0,0,this.hdr.width,this.hdr.height),this.canvasContext.strokeStyle="red",this.canvasContext.lineWidth=3,this.canvasContext.moveTo(0,0),this.canvasContext.lineTo(this.hdr.width,this.hdr.height),this.canvasContext.moveTo(0,this.hdr.height),this.canvasContext.lineTo(this.hdr.width,0),this.canvasContext.stroke()},n.prototype.handleError=function(t){this.loadErrorCause=t,this.hdr={width:this.gifImgElement.width,height:this.gifImgElement.height},this.frames=[],this.drawError()},n.prototype.doHdr=function(t){this.hdr=t,this.setSizes(this.hdr.width,this.hdr.height)},n.prototype.doGCE=function(t){this.pushFrame(),this.clear(),this.transparency=t.transparencyGiven?t.transparencyIndex:null,this.delay=t.delayTime,this.disposalMethod=t.disposalMethod},n.prototype.pushFrame=function(){this.frame&&(this.frames.push({data:this.frame.getImageData(0,0,this.hdr.width,this.hdr.height),delay:this.delay}),this.frameOffsets.push({x:0,y:0}))},n.prototype.doImg=function(t){var e=this;this.frame||(this.frame=this.tmpCanvas.getContext("2d"));var n=this.frames.length,s=t.lctFlag?t.lct:this.hdr.gct;n>0&&(3===this.lastDisposalMethod?null!==this.disposalRestoreFromIdx?this.frame.putImageData(frames[this.disposalRestoreFromIdx].data,0,0):this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height):this.disposalRestoreFromIdx=n-1,2===this.lastDisposalMethod&&this.frame.clearRect(this.lastImg.leftPos,this.lastImg.topPos,this.lastImg.width,this.lastImg.height));var i=this.frame.getImageData(t.leftPos,t.topPos,t.width,t.height);t.pixels.forEach(function(t,n){t!==e.transparency&&(i.data[4*n+0]=s[t][0],i.data[4*n+1]=s[t][1],i.data[4*n+2]=s[t][2],i.data[4*n+3]=255)}),this.frame.putImageData(i,t.leftPos,t.topPos),this.ctxScaled||(this.canvasContext.scale(this.getCanvasScale(),this.getCanvasScale()),this.ctxScaled=!0),this.drawWhileLoading&&(this.canvasContext.drawImage(this.tmpCanvas,0,0),this.drawWhileLoading=this.options.autoPlay),this.lastImg=t},n.prototype.doNothing=function(){},n.prototype.withProgress=function(t){return function(e){t(e)}},n.prototype.getNextFrameNo=function(){var t=this.forward?1:-1;return(this.currentFrameIndex+t+this.frames.length)%this.frames.length},n.prototype.stepFrame=function(t){this.currentFrameIndex=this.currentFrameIndex+t,this.putFrame()},n.prototype.getCanvasScale=function(){return this.options.maxWidth&&this.hdr&&this.hdr.width>this.options.maxWidth?this.options.maxWidth/this.hdr.width:window.devicePixelRatio||1},n.prototype.play=function(){this.playing=!0,this.step()},n.prototype.pause=function(){this.playing=!1},n.prototype.isPlaying=function(){return this.playing},n.prototype.getCanvas=function(){return this.canvas},n.prototype.isLoading=function(){return this.loading},n.prototype.isReady=function(){return this.ready},n.prototype.isAutoPlay=function(){return this.options.autoPlay},n.prototype.getLength=function(){return this.frames.length},n.prototype.getCurrentFrame=function(){return this.currentFrameIndex},n.prototype.moveTo=function(t){this.currentFrameIndex=t,this.putFrame()},n.prototype.loadURL=function(t,n){var s=this;if(this.loadSetup(n)){var i=new XMLHttpRequest;i.open("GET",t,!0),"overrideMimeType"in i?i.overrideMimeType("text/plain; charset=x-user-defined"):"responseType"in i?i.responseType="arraybuffer":i.setRequestHeader("Accept-Charset","x-user-defined"),i.onloadstart=function(){s.initialized||s.init()},i.onload=function(){if(200===i.status){var t=i.response;t.toString().indexOf("ArrayBuffer")>0&&(t=new Uint8Array(t));var n=new e.SuperGifStream(t);setTimeout(function(){s.parseStream(n)},0)}else s.handleError("xhr - response")},i.onerror=function(){s.handleError("xhr")},i.send()}},n.prototype.load=function(t){this.loadURL(this.gifImgElement.src,t)},n}();return 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 sy 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",sy);const iy={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:s,height:i}=this.state;t.beginPath(),this.drawImage(t,ry.image,e,n,s,i)}get nature(){return iy}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 Qs(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 s=super.capture(t,e,n);if(s!==this)return s}set bounds(t){if(this.__MUTATING__)return void(super.bounds=t);const e=this.bounds,n=t.width/e.width,s=t.height/e.height;this.path=this.path.map(i=>({x:t.left+(i.x-e.left)*n,y:t.top+(i.y-e.top)*s})),this.components&&this.components.forEach(t=>{if(t.mutable)t.mutatePath(null,function(t){return t.map(function(t){return{x:t.x*n,y:t.y*s}})});else{const e=t.bounds,i=t.center,r={x:i.x*(1-n),y:i.y*(1-s)},o=e.width*(1-n),a=e.height*(1-s),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*s}}})}get focusible(){return!1}get bounds(){return super.bounds}get hasTextProperty(){return!1}isIdentifiable(){return!1}calculateBounds(){this.clearCache(),this.__MUTATING__=!0,this.mutateBounds(function(t){const e=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,s=n.width/e.width,i=n.height/e.height;return"both"===this.model.fit?{x:s,y:i}:{x:Math.min(s,i),y:Math.min(s,i)}}draw(t){this._drawing||(this._drawing=!0,super.draw(t),this._drawing=!1)}prerender(t){if(super.prerender(t),this.ref){const e=this.ref.center,n=this.center,s=this.refScale;t.translate(n.x,n.y),t.scale(s.x,s.y),t.translate(-e.x,-e.y)}}postrender(t){if(this.ref)return this.ref.postrender(t);super.postrender(t)}render(t){if(this.ref)return this.ref.render(t);const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),t.rect(e,n,s,i)}get nature(){return 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(ig(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 s=(async()=>{this.__ref=await n.get(t,!0),this.__ref.target=this.element,this.__ref.fit(e),this.__ref.data=this.data})();this.root?.app?.loadTracker?.track(`ref:${t}`,"ref-board",t,s);try{await s}catch(t){Qs(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:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,gy.image,e,n,s,i)}onchange(t,e){"value"in t?this.show?this.onchangeShow(!0):this.show=!0:"show"in t&&this.onchangeShow(this.show)}onchangeShow(t){if(this.app.isEditMode)return;(this.getState("board")||this.getState("containerRef")||this.getState("htmlTemplate"))&&(t?this.openPopup(this.value):this.hidePopup())}openPopup(t,e){if(this.app.isEditMode)return;const n=this.getState("anchorRef"),s=n&&this.rootModel?.findById?this.rootModel.findById(n):void 0;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:s,anchorPin:this.getState("anchorPin")||"top",anchorOffsetX:this.getState("anchorOffsetX")??0,anchorOffsetY:this.getState("anchorOffsetY")??0,anchorOffsetZ:this.getState("anchorOffsetZ")??0,constantSize:this.getState("constantSize")??!0,tether:this.getState("tether")??!1,offScreen:this.getState("offScreen")||"hide",...e})}hidePopup(){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 s=!1;return n.forEach((i,r)=>{const o=(r+n.length+1)%n.length,a=i.x,c=i.y,l=n[o].x,h=n[o].y;c>e!=h>e&&t<(l-a)*(e-c)/(h-c)+a&&(s=!s)}),s}}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:s,x2:i,y2:r,x3:o,y3:a}=this.state,c=[n,s,i,r,o,a];let l=!1;for(let n=0;n<c.length;n+=2){const s=(n+2)%c.length,i=c[n],r=c[n+1],o=c[s+1];r>e!=o>e&&t<(c[s]-i)*(e-r)/(o-r)+i&&(l=!l)}return l}get mutable(){return!0}get path(){const{x1:t,y1:e,x2:n,y2:s,x3:i,y3:r}=this.state;return[{x:t,y:e},{x:n,y:s},{x:i,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:s,rx:i}=n.model;i=Math.abs(i);let r=(n.fromParent(t.x,t.y).x-s)/i*100;r=r>=100||r<=-100?100:Math.abs(r),n.set({ratio:r})}};class Sy extends Eg{is3dish(){return!0}render(t){let{ratio:e=50,cx:n,cy:s,rx:i,ry:r,startAngle:o,endAngle:a,anticlockwise:c}=this.state;i=Math.abs(i),r=Math.abs(r),t.beginPath(),t.ellipse(n,s,i,r,0,o||0,a||2*Math.PI,c),t.moveTo(n+i/100*e,s),t.ellipse(n,s,i/100*e,r/100*e,0,o||0,a||2*Math.PI,!0)}contains(t,e){let{cx:n,cy:s,rx:i,ry:r,ratio:o}=this.state;i=Math.abs(i),r=Math.abs(r);const a=(t-n)/(2*i-.5),c=(e-s)/(2*r-.5),l=(t-n)/(i/100*o*2-.5),h=(e-s)/(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:s}=this.state;return n=Math.abs(n),[{x:t+n/100*s,y:e,handler:My}]}get nature(){return wy}}Cc.memoize(Sy.prototype,"controls",!1),Cc.register("donut",Sy);const Ey={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"},Ay={ondragmove:function(t,e,n){const{cy:s,ry:i}=n.model;let r=(n.fromParent(t.x,t.y).y-s)/i*100+100;r>=100?r=100:r<=0&&(r=0),n.set({ratio:r})}};class ky extends Eg{is3dish(){return!0}render(t){const{ratio:e=30,wing:n=5,cx:s,cy:i,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(s,i),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:s}=this.state;return[{x:t,y:e-n+n*(s/100),handler:Ay}]}get nature(){return Ey}}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:s}=this.state,i=this.app?.scale||1;t.beginPath(),t.scale(1/i,1/i),t.ellipse(e,n,Math.abs(Ty.RADIUS),Math.abs(Ty.RADIUS),0,0,2*Math.PI,s),t.scale(i,i),t.closePath()}get path(){const{cx:t,cy:e}=this.state;return[{x:t-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:s}=this.state,i=(t-n)/(2*Ty.RADIUS-.5),r=(e-s)/(2*Ty.RADIUS-.5);return i*i+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,s=this.component.state.depth||.5*Math.min(e,n),i=.15*Math.min(e,n,s),r=new R(1,1,1,4,i/Math.min(e,n,s));r.scale(e,s,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 s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,r=s.max.y-s.min.y,o=s.max.z-s.min.z;this.setDimensionScale(t/i,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:s,height:i}=this.bounds,r=this.constructor.icon;t.beginPath(),t.globalAlpha=.6,this.drawImage(t,r,e,n,s,i),t.globalAlpha=1}added(t){super.added(t);const e=this.serviceName;e&&(this._registeredRoot=this.root,this._registeredRoot?.registerService?.(e,this))}removed(t){const e=this.serviceName;e&&this._registeredRoot&&(this._registeredRoot.unregisterService?.(e),this._registeredRoot=void 0),super.removed(t)}get controls(){return[]}}function 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 s;s=e?t-(Number(n)||0):t-(this._lastValue||0),this._lastValue=t,this._anim_alpha=-s,this.animate({step:t=>{this._anim_alpha=s*(t-1),this.invalidate()},duration:1e3,delta:"circ",options:{x:1},ease:"out"}).start()}dispose(){super.dispose(),delete this._value_substitutor}onchange(t,e){t.hasOwnProperty("value")&&delete this._value_substitutor}get animAlpha(){return this._anim_alpha||0}get animValue(){return(this._lastValue||0)+(this._anim_alpha||0)}defaultValueSubstitutor(){return this.getState("value")}get valueSubstitutor(){return this._value_substitutor||(this._value_substitutor=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(xs(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 s=this.parentNode?.querySelector("[name=playTargets]");s&&(s.src=t)}},{type:"gltf-info",label:"",name:"gltfInfo",readonly:!0,property:{action:(t,e)=>{t._ratioLocking=!0;try{t.set(e)}finally{t._ratioLocking=!1}}},editor:{fullwidth:!0}},{type:"gltf-fill-targets",label:"fill-targets",name:"fillStyleTargets",editor:{fullwidth:!0}},{type:"gltf-play-targets",label:"play-targets",name:"playTargets",editor:{fullwidth:!0}}];function 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:s,height:i}=this.bounds;t.beginPath();const r=this._topViewSnapshot;if(r)return void t.drawImage(r,e,n,s,i);this._ensureTopViewSnapshot(),t.rect(e,n,s,i),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#999",t.lineWidth=1,t.stroke();const o=this.getState("src"),a=o&&o.split("/").pop()?.replace(/\.[^.]+$/,"")||"GLTF",c=Math.max(10,.12*Math.min(s,i));t.fillStyle="#666",t.font=`${c}px sans-serif`,t.textAlign="center",t.textBaseline="middle",t.fillText(a,e+s/2,n+i/2,.9*s)}onchange(t,e){super.onchange?.(t,e),"src"in t&&(this._topViewSnapshot=void 0)}_ensureTopViewSnapshot(){if(this._snapshotLoading)return;const t=this.getState("src");if(!t)return;const e=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 s=Ou.renderTopView(e.scene);Ou.setTopViewCache(t,s),this._topViewSnapshot=s,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:s=1}=t;this.setState({width:e,height:n,depth:s}),this.realObject?.updateDimension()}_applyRatioLock(t){if(!("width"in t||"height"in t||"depth"in t))return t;const e=this.state.width||1,n=this.state.height||1,s=this.state.depth||1,i=Of([(t.width??e)/e,(t.height??n)/n,(t.depth??s)/s]);return i?{...t,width:Math.round(e*i),height:Math.round(n*i),depth:Math.round(s*i)}:t}set(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.set(t)}finally{this._ratioLocking=!1}}setState(t,e){if("string"==typeof t&&(t={[t]:e}),this.state?.ratioLock&&!this._ratioLocking){this._ratioLocking=!0;try{t=this._applyRatioLock(t)}finally{}}try{return super.setState(t)}finally{this._ratioLocking=!1}}}}function 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()),s=e.onAvailable(()=>t.resumeEmit());return Hy(e).isFull&&t.pauseEmit(),()=>{n?.(),s?.()}}class Gy{constructor(t,e=1,n="horizontal"){this.owner=t,this.itemSpacing=e,this.axis=n}positionAt(t,e,n,s){const i=e.maxCount??1/0;if(t<0||t>=i)return null;const r=this.owner?.state?.width??0,o=this.owner?.state?.height??0,a=s?.state?.width??0,c=s?.state?.height??0;return"horizontal"===this.axis?{x:t*this.itemSpacing,y:Math.max(0,(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,s,i,r,o){const a=n.w,c=n.h,l=s.w,h=s.h,d=s.d,u=[],p=l+i,f=h+i,m=Math.max(1,Math.floor((a+i)/p)),g=Math.max(1,Math.floor((c+i)/f)),y=m*g,b=r&&r>0?Math.floor(r):4;if("row"===t||"column"===t){const n=o?.advanceAlongX??!1,s=o?.reverse??!1,i=n?m:g,r=n?g:m,l=(t,e,s)=>((t,e,n)=>u.push({x:-a/2+(t+.5)*p,y:n*d+d/2,z:-c/2+(e+.5)*f}))(n?t:e,n?e:t,s);let h=0;for(let n=0;n<i&&h<e;n++){const o=s?i-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),s=Math.max(1,g-n),i=e*s,o=Math.min(t,i);for(let t=0;t<o;t++){const i=t%e,r=Math.floor(t/e),o=-a/2+(i+(m-e)/2+.5)*p,l=-c/2+(r+(g-s)/2+.5)*f;u.push({x:o,y:n*d+d/2,z:l})}if(t-=o,n++,1===e&&1===s){for(let e=0;e<t;e++)u.push({x:0,y:(n+e)*d+d/2,z:0});break}if(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),s=n%y,i=s%m,o=Math.floor(s/m),g=(t(2*n)-.5)*l*.2,b=(t(2*n+1)-.5)*h*.2,v=-a/2+(i+.5)*p+g,_=-c/2+(o+.5)*f+b;if(u.push({x:v,y:e*d+d/2,z:_}),r&&e>=r-1&&s===y-1)break}return u}for(let n=0;n<e;n++){const e=Math.floor(n/y);if(r&&e>=r)break;const s=n%y,i=s%m,o=Math.floor(s/m);let l=-a/2+(i+.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,s={}){const i=s.gap??this.defaults.gap??0,r=s.heightLimit??this.defaults.heightLimit,o=s.fill??this.defaults.fill;return Vy(this.pattern,t,e,n,i,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,s={}){const i=Math.max(1,this.cols),r=Math.max(1,this.rows),o=i*r,a=s.gap??this.defaults.gap??0,c=n.w+a,l=n.h+a,h=[];for(let e=0;e<t;e++){const t=Math.floor(e/o),s=e%o,a=s%i,d=Math.floor(s/i);h.push({position:{x:(a-(i-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,s=e.h*this.gapRatio;return{cols:Math.max(1,Math.floor((t.w-n)/(e.w+n))),rows:Math.max(1,Math.floor((t.h-s)/(e.h+s))),pitchX:e.w+n,pitchZ:e.h+s}}capacity(t,e,n){const{cols:s,rows:i}=this.grid(t,e);return s*i*Math.max(1,Math.floor(n))}layout(t,e,n,s={}){const{cols:i,rows:r,pitchX:o,pitchZ:a}=this.grid(e,n),c=n.d+n.d*this.gapRatio,l=null!=s.heightLimit?Math.max(1,Math.floor(s.heightLimit)):1/0,h=Number.isFinite(l),d=this.sliceFirst&&h,u=i*r,p=i*(h?l:1),f=i*r*(h?l:t),m=Math.min(t,f),g=[];for(let t=0;t<m;t++){let e,s,l;if(d){const n=Math.floor(t/p),r=t%p;e=r%i,l=Math.floor(r/i),s=n}else{l=Math.floor(t/u);const n=t%u;e=n%i,s=Math.floor(n/i)}this.fillFromFar&&(s=r-1-s),g.push({position:{x:(e-(i-1)/2)*o,z:(s-(r-1)/2)*a,y:l*c+n.d/2}})}return g}}function Xy(t,e,n,s=0){for(let i=0;i<e.length;i++){const r=e[i],o=n[i];r&&o&&(r.parent!==t&&t.attach(r),r.position.set(o.position.x,s+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,s=.12){const i=e.left+e.width/2,r=e.top+e.height/2,o=Math.min(n.w,n.h)*s,a=new Map;for(const e of t){const t=`${Math.round(e.position.x)},${Math.round(e.position.z)}`;let s=a.get(t);s||(s={x:i+e.position.x-n.w/2+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,s)),s.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,s]of n)if(!e.has(t)){try{this.removeItem(s,!0)}catch{}try{s?.dispose?.()}catch{}}for(const[t,s]of e){if(n.has(t))continue;if(null==s.itemId)continue;const e=this._createItemFromRecord(s);if(e){e[tb]=t;try{this.handoverIn(e)}catch{}}}for(const[t,s]of e){const e=n.get(t);if(e&&(s.itemState&&"function"==typeof e.setState))try{e.setState(s.itemState)}catch{}}}_exportSlotRecords(){const t=this.slotIds?.()??[],e=[],n=new Map,s=[];for(const t of this._items){const e=t[tb];null!=e?n.set(String(e),t):s.push(t)}for(const s of t){const t=n.get(s)??null;e.push(this._slotRecordOf(s,t))}for(const t of s)e.push(this._slotRecordOf("",t));for(const[s,i]of n)t.includes(s)||e.push(this._slotRecordOf(s,i));return e}_recordKey(t){return t.slotId??t.cellId??""}_slotRecordOf(t,e){if(!e)return{slotId:t,itemId:null};const n=e?.state?.id;return{slotId:t,itemId:null!=n?String(n):null,itemType:e?.state?.type,itemState:this._extractItemState(e)}}_extractItemState(t){const e=t?.state;if(!e||"object"!=typeof e)return;const n=this._businessFields?.();if(Array.isArray(n)){if(0===n.length)return;const t={};for(const s of n)s in e&&void 0!==e[s]&&(t[s]=e[s]);return Object.keys(t).length>0?t:void 0}const s={};for(const t of Object.keys(e))eb.has(t)||t.startsWith("_")||(s[t]=e[t]);return Object.keys(s).length>0?s:void 0}_businessFields(){return null}_createItemFromRecord(t){const e=t.itemType??t.type;if(!e)return null;try{const n=Cc.register?.(e);if(n&&"function"==typeof n){return new n({type:e,...t.itemState??{}})}}catch{}return null}}}class sb{positionAt(t,e,n){return 0!==t?null:e.localPosition??{x:0,y:0,z:0}}capacity(t){return 1}}const ib=new sb;function rb(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const ob="holder",ab=t=>"number"==typeof t&&Number.isFinite(t),cb=t=>ab(t)&&t>0,lb=t=>Number.isSafeInteger(t)&&t>0;function hb(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])cb(s[t])||n.push(rb("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(rb("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||lb(t.stackLimit)||t.stackLimit===1/0||n.push(rb("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||ab(t.rotation)||n.push(rb("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(rb("ARRAY_REQUIRED",`${e}.accepts`))}function db(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[rb("TIERS_REQUIRED","tiers")];const s=e.anchors?new Set(e.anchors):null,i=new Set;return t.tiers.forEach((t,e)=>{const r=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(rb("OBJECT_REQUIRED",r));if(lb(t.tierNo)?i.has(t.tierNo)?n.push(rb("TIER_NUMBER_DUPLICATE",`${r}.tierNo`,{tierNo:t.tierNo})):i.add(t.tierNo):n.push(rb("POSITIVE_INTEGER_REQUIRED",`${r}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?s&&!s.has(t.anchorId)&&n.push(rb("ANCHOR_UNKNOWN",`${r}.anchorId`,{anchorId:t.anchorId})):n.push(rb("ANCHOR_REQUIRED",`${r}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(rb("MOUNT_INVALID",`${r}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])ab(t.position[e])||n.push(rb("FINITE_NUMBER_REQUIRED",`${r}.position.${e}`));else n.push(rb("OBJECT_REQUIRED",`${r}.position`));ab(t.rotation)||n.push(rb("FINITE_NUMBER_REQUIRED",`${r}.rotation`));const o=t.layout;switch(o?.pattern){case"SINGLE":hb(o.slot,`${r}.layout.slot`,n);break;case"ROW":lb(o.count)||n.push(rb("POSITIVE_INTEGER_REQUIRED",`${r}.layout.count`)),cb(o.pitch)||n.push(rb("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch`)),"X"!==o.axis&&"Z"!==o.axis&&n.push(rb("AXIS_INVALID",`${r}.layout.axis`)),hb(o.slot,`${r}.layout.slot`,n);break;case"GRID":lb(o.rows)||n.push(rb("POSITIVE_INTEGER_REQUIRED",`${r}.layout.rows`)),lb(o.cols)||n.push(rb("POSITIVE_INTEGER_REQUIRED",`${r}.layout.cols`)),cb(o.pitch?.x)||n.push(rb("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.x`)),cb(o.pitch?.z)||n.push(rb("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.z`)),hb(o.slot,`${r}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(o.slots)){n.push(rb("ARRAY_REQUIRED",`${r}.layout.slots`));break}o.slots.length||n.push(rb("SLOTS_REQUIRED",`${r}.layout.slots`));const t=new Set;o.slots.forEach((e,s)=>{const i=`${r}.layout.slots[${s}]`;lb(e?.slotNo)?t.has(e.slotNo)?n.push(rb("SLOT_NUMBER_DUPLICATE",`${i}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(rb("POSITIVE_INTEGER_REQUIRED",`${i}.slotNo`)),ab(e?.offset?.x)&&ab(e?.offset?.z)||n.push(rb("FINITE_NUMBER_REQUIRED",`${i}.offset`)),hb(e,i,n)});break}default:n.push(rb("PATTERN_INVALID",`${r}.layout.pattern`))}}),n}function ub(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(rb("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}function pb(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 fb(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:pb(t)},(t,e)=>e+1)}function mb(t,e,n,s,i="ROW_MAJOR"){switch(i){case"ROW_MAJOR":return(n-1)*e+s;case"COL_MAJOR":return(s-1)*t+n;case"SERPENTINE_ROW":return(n-1)*e+(n%2==1?s:e-s+1);case"SERPENTINE_COL":return(s-1)*t+(s%2==1?n:t-n+1)}}function gb(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}const yb=(t,e)=>e&&0!==t?-t:t;function bb(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!lb(e.slot))return null;const i=s.layout;let r,o,a;switch(i.pattern){case"SINGLE":if(1!==e.slot)return null;r=i.slot,o={x:0,z:0};break;case"ROW":{if(e.slot>i.count)return null;const t=yb((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);r=i.slot,o="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>i.rows*i.cols)return null;const{r:t,c:n}=gb(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};r=i.slot,o={x:yb((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:yb((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,anchorId:s.anchorId,mount:s.mount,tierPosition:{...s.position},tierRotation:s.rotation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function vb(t){return`t${t.tier}_s${t.slot}`}function _b(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*xb(t){for(const e of t?.tiers??[])for(const t of fb(e.layout))yield{tier:e.tierNo,slot:t}}function wb(t,e,n){if(!n)return{x:t,z:e};const s=n*Math.PI/180,i=Math.cos(s),r=Math.sin(s),o=t=>Math.round(1e9*t)/1e9;return{x:o(t*i+e*r),z:o(-t*r+e*i)}}function Mb(t){const e=wb(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 Sb=.05,Eb=t=>!!t&&cb(t.width)&&cb(t.depth)&&cb(t.height);function Ab(t,e){const n=e*Math.PI/180,s=Math.abs(Math.cos(n)),i=Math.abs(Math.sin(n)),r=t=>Math.round(1e9*t)/1e9;return{width:r(t.width*s+t.depth*i),depth:r(t.width*i+t.depth*s)}}function kb(t,e,n=0,s=.05){if(!Eb(t))return null;if(!ab(n)||!ab(s)||s<0||s>=1)return null;const i=Ab(t,e.rotation),r=Math.min(1,Math.min(e.allowed.width/i.width,e.allowed.depth/i.depth)*(1-s)),o=t.height*r;return{position:{x:0,y:("HANG"===e.mount?-1:1)*(n+o/2),z:0},rotation:0,scale:r}}function Cb(t,e,n=0,s=.05){const i=kb(t,e,n,s);if(!i)return null;const r=Mb(e);return{position:{x:r.position.x,y:r.position.y+i.position.y,z:r.position.z},rotation:r.rotation,scale:i.scale}}function Tb(t,e,n=.05){let s=0;return t.map(t=>{const i=t?Cb(t,e,s,n):null;return i&&(s+=t.height*i.scale),i})}const Ob=1e-6;function Pb(t,e){const n=Mb(t),s=t.allowed.width/2,i=t.allowed.depth/2,r=[[-s,-i],[s,-i],[s,i],[-s,i]].map(([t,e])=>{const s=wb(t,e,n.rotation);return{x:n.position.x+s.x,z:n.position.z+s.z}}),o=wb(1,0,n.rotation),a=wb(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 Ib(t,e){for(const n of[...t.axes,...e.axes]){const s=t.corners.map(t=>t.x*n.x+t.z*n.z),i=e.corners.map(t=>t.x*n.x+t.z*n.z);if(Math.min(Math.max(...s),Math.max(...i))-Math.max(Math.min(...s),Math.min(...i))<=Ob)return!1}return!0}function Db(t,e={}){const n=[],s=new Map;t.tiers.forEach((e,n)=>{const i=s.get(e.anchorId)??[];s.set(e.anchorId,i);for(const s of fb(e.layout))i.push(Pb(bb(t,{tier:e.tierNo,slot:s}),n))});for(const[t,i]of s){const s=e.anchorFaces?.[t];if(s)for(const t of i)t.corners.some(t=>Math.abs(t.x)-s.width/2>Ob||Math.abs(t.z)-s.depth/2>Ob)&&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=[...i].sort((t,e)=>t.minX-e.minX);for(let t=0;t<r.length;t++){const e=r[t];for(let s=t+1;s<r.length&&r[s].minX<e.maxX-Ob;s++){const t=r[s];if(Math.min(e.y1,t.y1)-Math.max(e.y0,t.y0)<=Ob)continue;if(!Ib(e,t))continue;const[i,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:i.tier,otherSlot:i.slot}})}}}return n}function zb(t,e,n=[],s={}){if(!t)return{verdict:"NG",reasons:["SLOT_NOT_FOUND"]};const i=s.normalizeType??(t=>null==t?"":String(t)),r=[];let o=!1;if(t.accepts){const n=i(e.type);n?t.accepts.map(i).includes(n)||r.push("TYPE_NOT_ACCEPTED"):o=!0}if(n.length+1>t.stackLimit&&r.push("STACK_LIMIT_EXCEEDED"),Eb(e.dims)){const s=Ab(e.dims,t.rotation);if(s.width>t.allowed.width&&r.push("WIDTH_EXCEEDED"),s.depth>t.allowed.depth&&r.push("DEPTH_EXCEEDED"),n.every(t=>Eb(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:[]}}const Rb=[{id:"__default__",maxCount:1/0}];function jb(t){const e={id:vb({tier:t.tier,slot:t.slotNo}),maxCount:t.stackLimit};return t.accepts&&(e.accepts=[...t.accepts]),e}function Lb(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 Fb(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 xb(t)){const s=bb(t,n);s&&e.push(jb(s))}return e}slotById(t){const e=this.slotLayout;if(e){const n=_b(t),s=n?bb(e,n):null;return s?jb(s):null}return this.slots.find(e=>e.id===t)??null}slotSeatTransform(t,e,n=0,s){const i=this.slotLayout,r=i?_b(t):null,o=r?bb(i,r):null,a=o?Cb(e,o,n,s):null;return a?{...a,anchorId:o.anchorId}:null}get arrangementStrategy(){return ib}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:Rb;for(const n of e){if(!Lb(n,t))continue;const e=n.maxCount??this.arrangementStrategy.capacity(n),s=this._countOccupied(n.id);if(!(s>=e))return Gu.log({role:"target",contract:"findSlot",component:this,args:{carrier:Qy(t)},result:{slotId:n.id,occupied:s,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 s=this._realObject?.object3d;if(!s)return;s.updateWorldMatrix(!0,!1);const i=new t.Quaternion;s.getWorldQuaternion(i);const r=new t.Quaternion(n.x,n.y,n.z,n.w);return i.clone().multiply(r)}deliveryWorldPosition(e){const n=this._realObject,s=n?.object3d;if(!s)return;s.updateWorldMatrix(!0,!1);const i=new t.Vector3;s.getWorldPosition(i);const r=this._receivingSurfaceLocalY();if(null!==r){const e=new t.Vector3(0,r,0);return s.localToWorld(e),{x:i.x,y:e.y,z:i.z}}return{x:i.x,y:i.y,z:i.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,s=n?n.state??{}:t??{},i={width:Number(s.width)||0,height:Number(s.height)||0,depth:Number(s.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:{...i}});if(!c)return null;const l=Number(this.state?.width)||0,h=Number(this.state?.height)||0,d=c.x+i.width/2-l/2,u=c.y+i.height/2-h/2,p=this._realObject,f=p?.placementMode??"floor",m="space"===f?0:"inverted"===f?-i.depth/2:i.depth/2,g=this._receivingSurfaceLocalY();let y;y=null!==g?g+m:r.localPosition&&Number.isFinite(r.localPosition.z)?r.localPosition.z+m:m-(p?.geometricOffsetY??0);const b=this.acceptanceRotation?.(n??i,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 s=this._realObject,i=s?.receivingSurfaceY??0,r=!(!n.localPosition||!Number.isFinite(n.localPosition.z));if(0===i&&!r)return null;const o=Number(e)||0,a=s?.placementMode??"floor";return t-("space"===a?0:"inverted"===a?-o/2:o/2)+(s?.geometricOffsetY??0)-i}_receivingSurfaceLocalY(){const t=this._realObject,e=t?.receivingSurfaceY;return"number"!=typeof e||0===e?null:e-(t.geometricOffsetY??0)}_slotIfAvailable(t,e){if(!t||!Lb(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 Nb(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,r=t.height??0;if(i<=0||r<=0)return[];const o="number"==typeof t.rotation?t.rotation:0,a=Math.cos(o),c=Math.sin(o),l=n+i/2,h=s+r/2,d="inbound"===e?-1:1;return[{lx:-i/2,lz:0,odx:-1,odz:0},{lx:i/2,lz:0,odx:1,odz:0},{lx:0,lz:-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:i/2}})}function $b(t,e){const n=t.left??0,s=t.top??0,i=t.width??0,r=t.height??0;if(i<=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&&i<r,l=n+i/2,h=s+r/2,d=c?r/2:i/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},E=(c?i:r)/2;return a?{inbounds:[{worldPos:_,direction:S,halfSpan:E}],outbounds:[{worldPos:v,direction:S,halfSpan:E}]}:{inbounds:[{worldPos:v,direction:M,halfSpan:E}],outbounds:[{worldPos:_,direction:M,halfSpan:E}]}}function Hb(t){const e=t.left??0,n=t.top??0,s=t.width??0,i=t.height??0;if(s<=0||i<=0)return null;const r="number"==typeof t.rotation?t.rotation:0,o="vertical"===t.orientation||"horizontal"!==t.orientation&&s<i,a=e+s/2,c=n+i/2,l=o?i/2:s/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 Bb(t){const e=t.cx??0,n=t.cy??0,s=Math.abs(t.rx??100),i=Math.abs(t.ry??100),r=t.ratio??50,o=(s+s*r/100)/2,a=(i+i*r/100)/2,c=t.startAngle??0,l=t.endAngle??Math.PI/2,h="reverse"===t.status;if(s<=0||i<=0)return{inbounds:[],outbounds:[]};const d={x:e+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 Yb(t){const e=$b(t),n=e.outbounds[0];if(!n)return{inbounds:Nb(t,"inbound"),outbounds:[]};const s=Nb(t,"inbound").filter(t=>{const e=t.worldPos.x-n.worldPos.x,s=t.worldPos.z-n.worldPos.z;return Math.hypot(e,s)>1}),i=n.direction,r=[];for(const t of s){const e=t.direction.x*i.x+t.direction.z*i.z;if(Math.abs(e)>=.1)continue;const n=t.direction.x+i.x,s=t.direction.z+i.z,o=Math.hypot(n,s)||1;r.push({worldPos:t.worldPos,direction:{x:n/o,z:s/o},halfSpan:t.halfSpan})}return{inbounds:[...s,...r],outbounds:e.outbounds}}function Gb(t,e,n={}){const s=n.distance??5,i=n.cosine??.9;if(t.direction.x*e.direction.x+t.direction.z*e.direction.z<i)return!1;const 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,i=t.direction.z;if(Math.abs(r*n+o*i)>s)return!1;const a=Math.abs(r*-i+o*n);return t.halfSpan+e.halfSpan-a>0}return Math.hypot(r,o)<=s}function Vb(t,e,n,s=0){const i=n.width??0,r=n.height??0;if(i<=0||r<=0)return!1;const o=(n.left??0)+i/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)<=i/2+s&&Math.abs(f)<=r/2+s}function Ub(t,e,n){const s=n.width??0,i=n.height??0;if(s<=0||i<=0)return 1/0;const r=(n.left??0)+s/2,o=(n.top??0)+i/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,s=l*e+h*t;a=a*t-c*e,c=n,l=l*t-h*e,h=s}const u=s/2,p=i/2;let f=-1/0,m=1/0;if(Math.abs(l)<1e-9){if(a<-u||a>u)return 1/0}else{const t=(-u-a)/l,e=(u-a)/l;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}if(Math.abs(h)<1e-9){if(c<-p||c>p)return 1/0}else{const t=(-p-c)/h,e=(p-c)/h;f=Math.max(f,Math.min(t,e)),m=Math.min(m,Math.max(t,e))}return m<f?1/0:f>=0?f:m>=0?Math.min(-f,m):-m}function Wb(t,e,n,s=6){return!!Vb(t.worldPos.x,t.worldPos.z,e,s)&&(!n||t.direction.x*n.x+t.direction.z*n.z>=0)}function qb(t,e,n){return t.outbounds.map(t=>{const s=[];for(const i of e){let e=null;for(const s of i.topology.inbounds){if(!Gb(t,s,n))continue;const i=t.worldPos.x-s.worldPos.x,r=t.worldPos.z-s.worldPos.z,o=Math.hypot(i,r);(null===e||o<e)&&(e=o)}if(null===e&&i.bounds){const s=i.topology.outbounds[0]?.direction,r=!(i.topology.outbounds&&i.topology.outbounds.length)?n?.sinkMargin??30:6;if(Wb(t,i.bounds,s,r)){const n=Ub(t.worldPos,t.direction,i.bounds);if(Number.isFinite(n))e=n+1e3;else{const n=(i.bounds.left??0)+(i.bounds.width??0)/2,s=(i.bounds.top??0)+(i.bounds.height??0)/2;e=Math.hypot(t.worldPos.x-n,t.worldPos.z-s)+1e3}}}null!==e&&s.push({id:i.id,dist:e})}return 0===s.length?null:(s.sort((t,e)=>t.dist-e.dist||(t.id<e.id?-1:1)),s[0].id)})}function Xb(t,e){const n=new Map;for(const e of t)n.set(e.id,e);const s=new Map,i=new Set;for(const n of t){const r=t.filter(t=>t.id!==n.id),o=qb(n.topology,r,e);s.set(n.id,o);for(const t of o)null!=t&&i.add(t)}const r=(t,e)=>{if(!n.has(t)||!n.has(e)||t===e)return;const r=s.get(t)??[];r.includes(e)||(r.push(e),s.set(t,r),i.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){(s.get(e.id)??[]).some(t=>null!=t)||o.add(e.id),i.has(e.id)||a.add(e.id)}return{nodes:n,out:s,sinks:o,sources:a}}function Kb(t,e){const n=new Map;return(t.out.get(e)??[]).map(e=>{if(null==e)return new Set;const s=new Set([e]);for(const i of function(t,e,n){const s=n.get(e);if(s)return s;const i=new Set,r=[e],o=new Set([e]);for(;r.length;){const e=r.shift();for(const n of t.out.get(e)??[])null!=n&&(i.add(n),o.has(n)||(o.add(n),r.push(n)))}return n.set(e,i),i}(t,e,n))s.add(i);return s})}function Qb(t,e,n,s){return e===n?0:function(t,e,n){const s=n.get(e);if(s)return s;const i=new Map([[e,0]]),r=[e];for(;r.length;){const e=r.shift(),n=i.get(e);for(const s of t.out.get(e)??[])null==s||i.has(s)||(i.set(s,n+1),r.push(s))}return n.set(e,i),i}(t,e,s).get(n)??1/0}function Jb(t,e,n){const s=t.out.get(e)??[],i=new Map,r=[];for(let e=0;e<s.length;e++){const o=s[e];if(null==o)continue;const a=o===n?0:Qb(t,o,n,i);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 Zb(t,e,n){const s=Jb(t,e,n);return s.length?s[0]:-1}function tv(t,e,n){return e===n||Jb(t,e,n).length>0}function ev(t,e){const n=new Set;for(const s of Kb(t,e))for(const e of s)t.sinks.has(e)&&n.add(e);return n}function nv(t,e,n){return sv(t,e,n).map(t=>t.index)}function sv(t,e,n){const s=n instanceof Set?n:new Set(n);if(0===s.size)return[];const i=t.out.get(e)??[],r=new Map,o=[...s].sort(),a=[];for(let e=0;e<i.length;e++){const n=i[e];if(null==n)continue;let s=1/0,c="";for(const e of o){const i=1+(n===e?0:Qb(t,n,e,r));i<s&&(s=i,c=e)}s!==1/0&&a.push({index:e,hops:s,target:c})}return a.sort((t,e)=>t.hops-e.hops||t.index-e.index),a}function iv(t,e={}){const n=[],s=e.loopCapableIds??new Set,i=e.routingTargetIds??new Set;for(const e of[...t.sources].sort()){const s=t.nodes.get(e);if(!s||!s.topology.outbounds?.length)continue;(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)||(i.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(),s=new Set,i=[],r=new Set,o=n=>{s.add(n),i.push(n),r.add(n);for(const a of t.out.get(n)??[])if(null!=a)if(r.has(a)){const t=i.indexOf(a),n=i.slice(t),s=n.indexOf([...n].sort()[0]),r=[...n.slice(s),...n.slice(0,s)],o=r.join("→");e.some(t=>t.join("→")===o)||e.push(r)}else s.has(a)||o(a);i.pop(),r.delete(n)};for(const t of n)s.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=>s.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[...i].sort())t.nodes.has(e)&&(a.has(e)||n.push({severity:"warning",code:"unreachable-target",nodeId:e,message:`RoutingTarget "${e}" 에 incoming edge 0 — 누구도 이쪽으로 carrier 를 보내지 않음`}));return n.sort((t,e)=>t.code!==e.code?t.code.localeCompare(e.code):(t.nodeId??"").localeCompare(e.nodeId??"")),n}function rv(t,e){if(!t)return[];const n=[],s=new Set,i=t=>{if(!t||s.has(t))return;if(s.add(t),t!==e&&"function"==typeof t?.getSegmentTopology){const e=t.state?.id,s=t.refid??t.state?.refid,i="string"==typeof e&&e.length>0?e:null!=s?String(s):void 0;if(i)try{const e=t.getSegmentTopology(),s=t.state??{},r={left:s.left,top:s.top,width:s.width,height:s.height,rotation:s.rotation};e&&n.push({id:i,topology:e,bounds:r})}catch{}}const r=t?.components;if(Array.isArray(r))for(const t of r)i(t)};return i(t),n}function ov(t,e){const n=t.state?.targetRef??t.state?.downstreamRef;if("string"==typeof n&&n.length>0)return n;if("function"!=typeof t.getSegmentTopology)return null;const s=t.getSegmentTopology();if(!s||0===s.outbounds.length)return null;const i=qb(s,rv(t.parent??t.rootModel??t.root,t).filter(t=>t.topology.inbounds.length>0),e);for(const t of i)if(t)return t;return null}function av(t){return!!t&&"function"==typeof t.routingConstraints}function cv(t){return!!t&&"function"==typeof t.acceptedCarrierData}function lv(t,e=16){const n=[],s=t.parent??t.rootModel??t.root;if(!s)return n;const i=ov(t);if(!i)return n;const r=uv(s,i);if(!r)return n;const o=[{segment:r,accumulated:{},pathIds:[i],visited:new Set([i])}];for(;o.length>0;){const t=o.shift();if(t.pathIds.length>e)continue;const i=av(t.segment)?t.segment.routingConstraints():null;if(i&&i.length>0)for(const e of i)for(const i of e.candidates){const r=hv(t.accumulated,i);if(!r)continue;const a=dv(t.segment,e.portId,s);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(cv(t.segment)){const e=t.segment.acceptedCarrierData(),s=t.segment.state?.id;if(0===e.length)n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:s});else for(const i of e){const e=hv(t.accumulated,i);e&&n.push({data:e,weight:1,pathIds:t.pathIds,destination:s})}continue}const e=ov(t.segment);if(!e||t.visited.has(e)){n.push({data:t.accumulated,weight:1,pathIds:t.pathIds,destination:t.pathIds[t.pathIds.length-1]});continue}const i=uv(s,e);if(!i)continue;o.push({segment:i,accumulated:t.accumulated,pathIds:[...t.pathIds,e],visited:new Set([...t.visited,e])})}}return n}function hv(t,e){const n={...t};for(const[t,s]of Object.entries(e)){if(t in n&&n[t]!==s)return null;n[t]=s}return n}function dv(t,e,n){if("straight"===e&&t.state?.downstreamRef)return uv(n,t.state.downstreamRef);const s=uv(n,e);if(s)return s;const i=ov(t);return i?uv(n,i):null}function uv(t,e){if(!t||!e)return null;if("function"==typeof t.findById)return t.findById(e);const n=new Set,s=t=>{if(!t||n.has(t))return null;if(n.add(t),t.state?.id===e)return t;const i=t.components;if(Array.isArray(i))for(const t of i){const e=s(t);if(e)return e}return null};return s(t)}function pv(t,e){return Math.hypot(t.x-e.x,t.z-e.z)}function fv(t,e,n=5,s=[],i=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 s){const e=Array.isArray(t),n=e?t:t.positions,s=e?void 0:t.kind;if(!n.length)continue;const i=l.length;l.push({pos:n[0],members:[]});for(const t of n)d.push({pos:t,pt:i});s&&u.set(i,s)}const p=(t,e)=>{const s=c(t,e),i=h.get(`${t}:${"end"===e?"start":"end"}`),r=[];for(const t of d)pv(t.pos,s)<=n&&!r.includes(t.pt)&&r.push(t.pt);for(let t=0;t<l.length;t++)pv(l[t].pos,s)<=n&&!r.includes(t)&&r.push(t);let o=r.find(t=>t!==i)??-1;o<0&&(o=l.length,l.push({pos:s,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 s=0;s<l.length;s++){const i=pv(l[s].pos,t);i<n&&(n=i,e=s)}for(const s of d){const i=pv(s.pos,t);i<n&&(n=i,e=s.pt)}return{pt:e,d:n}};for(const n of e){const{pt:e,d:s}=t(n.pos);e>=0&&s<=i&&(f.add(e),("source"===n.kind?m:g).add(e))}}for(const[t,e]of u)f.add(t),("source"===e?m:g).add(t);const y=(t,e)=>"end"===e!==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 s=l[n];if(2!==s.members.length||f.has(n))continue;const i=s.members[0],r=i.seg===t&&i.end===e?s.members[1]:i;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",s=1/0;for(let i=0;i<r;i++)for(const r of["start","end"]){const o=pv(c(i,r),t.pos);o<s&&(s=o,e=i,n=r)}if(e<0||s>i)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,s=0;for(const e of t.members)void 0!==o[e.seg]&&(y(e.seg,e.end)?n++:s++);const i=e[0];let r;0===s&&n>0?r="end"===i.end:0===n&&s>0&&(r="start"===i.end),void 0!==r&&(o[i.seg]=r,b.push(i.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 s of t)e[s]=0,n.push(s);for(;n.length;){const t=n.shift();for(const s of l[t].members){const i=h.get(`${s.seg}:${"start"===s.end?"end":"start"}`);void 0!==i&&e[i]>e[t]+1&&(e[i]=e[t]+1,n.push(i))}}return e},e=t(m),n=t(g);for(let t=0;t<r;t++){if(void 0!==o[t])continue;const s=h.get(`${t}:start`),i=h.get(`${t}:end`);if(void 0===s||void 0===i)continue;if(l[s].members.length<2||l[i].members.length<2)continue;if(e[s]===1/0||e[i]===1/0||n[s]===1/0||n[i]===1/0)continue;let r;e[s]!==e[i]?r=e[s]<e[i]:n[s]!==n[i]&&(r=n[i]<n[s]),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 mv(...t){}function gv(t){return String(t?.state?.id??t?.refid??t?.state?.refid??"?")}function yv(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*bv(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*bv(t)}function vv(t,e,n){const s=e.width??0,i=e.height??0;if(s<=0||i<=0)return!1;const r=(e.left??0)+s/2,o=(e.top??0)+i/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)<=s/2+n&&Math.abs(p)<=i/2+n}function _v(t){const e=[],n=[],s=[],i=[];for(const r of bv(t)){const t=yv(r);if(!t)continue;if(r.flowOrientable){const n=Hb(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&&i.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&&s.push({positions:t})}}for(const t of i){const i=[];for(const n of e)for(const e of[n.start,n.end])vv(e,t,16)&&i.push(e);let r=!1,o=!1;for(const e of n)vv(e.pos,t,16)&&("sink"===e.kind?r=!0:o=!0);const a=r&&!o?"sink":o&&!r?"source":void 0;(i.length>=2||a&&i.length>=1)&&s.push({positions:i,kind:a})}if(0===e.length||0===n.length)return new Map;return fv(e,n,8,s,60).directions}function xv(t){const e=t?.root;if(!e)return;if(e.__flowComputing)return;let n=e.__flowOrientation;if(!n){e.__flowComputing=!0;try{n={map:_v(e)}}finally{e.__flowComputing=!1}e.__flowOrientation=n}const s=yv(t),i=s?n.map.get(s):void 0;return"reverse"===i||"forward"!==i&&void 0}function wv(t){return!!t&&"function"==typeof t.distanceToBoardPoint}function Mv(t,e,n,s){if(!t||!e)return null;const i=[],r=t=>{if(!t||t===s)return;if(Wm(t,e)&&wv(t)){const e=function(t){const e=t?.state?.id;if("string"==typeof e&&e.length>0)return e;const n=t?.refid??t?.state?.refid;return null!=n?String(n):void 0}(t);e&&i.push({id:e,component:t,distance:t.distanceToBoardPoint(n.x,n.y)})}const o=t.components;if(Array.isArray(o))for(const t of o)r(t)};return r(t),0===i.length?null:(i.sort((t,e)=>t.distance-e.distance||t.id.localeCompare(e.id)),i[0])}function Sv(t){return!!t&&"function"==typeof t.routingDestination}function Ev(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*Av(t){if(!t)return;yield t;const e=t.components;if(Array.isArray(e))for(const t of e)yield*Av(t)}function kv(t){const e=[],n=new Map,s=new Map,i=new Set,r=[];for(const o of Av(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||Sv(o)||c||wv(o)))continue;const l=Ev(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}),s.set(l,o),Sv(o)){i.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:s,routingTargetIds:i,stationClients:r}}function Cv(t){if(!t)return null;let e=t.__flowGraph;if(!e){const{nodes:n,destToSinks:s,components:i,routingTargetIds:r,stationClients:o}=kv(t),a=Xb(n);!function(t,e){if(!t)return;const n=t=>{if(!t)return;"function"==typeof t.clearStations&&t.clearStations();const e=t.components;if(Array.isArray(e))for(const t of e)n(t)};n(t);const s=[...e].sort((t,e)=>{const n=Ev(t)??"",s=Ev(e)??"";return n.localeCompare(s)});for(const e of s){const n=e.declaredHostRef?.();let s=null;if(n&&(s=t.findById?.(n)??null),!s){const n=e.hostCapability?.(),i=e.hostFacingPoint?.();n&&i&&(s=Mv(t,n,i,e)?.component??null)}s&&"function"==typeof e.registerWithHost&&e.registerWithHost(s)}const i=e=>{if(!e)return;if(wv(e)&&"function"==typeof e.resolveDownstream&&"function"==typeof e.registerDivertStation)for(const n of e.resolveDownstream()){const s=t.findById?.(n);s&&e.registerDivertStation(n,s)}const n=e.components;if(Array.isArray(n))for(const t of n)i(t)};i(t)}(t,o);const c=new Set;for(const[t,e]of i){((e?.state?.type??e?.model?.type??"").includes("loop")||!0===e?.isLoop)&&c.add(t)}const l=new Map;for(const t of r){const e=i.get(t);if("function"==typeof e?.routingWeight){const n=e.routingWeight();"number"==typeof n&&(!Number.isFinite(n)||n<=0)&&l.set(t,n)}}const h=iv(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:s,components:i,issues:h},t.__flowGraph=e}return e}function Tv(t){return Cv(t)?.issues??[]}function Ov(t){const e=Cv(t);return e&&e.graph.nodes.size>0?e.graph:null}function Pv(t,e){return Cv(t)?.destToSinks.get(e)??[]}function Iv(t,e){return Cv(t)?.components.get(e)}function Dv(t){const e=Cv(t);return e?[...e.destToSinks.keys()]:[]}function zv(t){return Ev(t)}function Rv(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 jv(t,e,n,s,i){if(1===s.length)return s[0];switch(t){case"index":default:return s[0];case"round-robin":{const t=n.counters.get(e)??0;return n.counters.set(e,t+1),s[t%s.length]}case"weight":{const t=s.map(t=>function(t){if("function"==typeof t?.routingWeight){const e=t.routingWeight();if("number"==typeof e&&Number.isFinite(e)&&e>0)return e}return 1}(i.get(t.target))),r=t.reduce((t,e)=>t+e,0);if(r<=0)return s[0];const o=n.counters.get(e)??0;n.counters.set(e,o+1);let a=o%r;for(let e=0;e<s.length;e++){if(a<t[e])return s[e];a-=t[e]}return s[s.length-1]}case"utilization":{let t=1/0,e=s[0];for(const n of s){const s=Rv(i.get(n.target));s<t&&(t=s,e=n)}return e}}}function Lv(t,e,n){const s=t?.root;if(!s)return null;const i=e?.state?.meta?.destination;if("string"!=typeof i||0===i.length)return null;const r=Cv(s);if(!r||0===r.graph.nodes.size)return null;const o=Ev(t);if(!o)return null;let a=r.destToSinks.get(i)??[];0===a.length&&(a=[i]);const c=sv(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],s=n?r.components.get(n):null;return!s||"function"!=typeof s.canReceive||s.canReceive(e)});if(0===h.length)return l[c[0].index]??null;const d=n?.policy??function(t,e){const n=t?.state?.balancingPolicy;if(n)return n;const s=e?.state?.routingBalancingPolicy;return s||"round-robin"}(t,s),u=jv(d,o,function(t){return t.__balancingState||(t.__balancingState={counters:new Map}),t.__balancingState}(s),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,Ov(t)}catch{return null}}}catch{}function Fv(t,e,n){const s=Lv(t,e,n);if(null==s)return null;const i=t?.root,r=Iv(i,s)??i?.findById?.(s)??null;return r?{targetId:s,component:r,origin:"explicit"}:null}function Nv(t){const e=t?.root,n=Ov(e),s=zv(t);if(!n||!s)return null;const i=(n.out.get(s)??[]).find(Boolean);if(!i)return null;const r=Iv(e,i)??e?.findById?.(i)??null;return r?{id:i,component:r}:null}function $v(t){const e=zv(t);return e?Hv(t?.root,e):[]}function Hv(t,e){if(!t||!e)return[];const n=Ov(t);if(!n)return[];const s=new Set;for(const i of ev(n,e)){const e=Iv(t,i);if(Sv(e)){const t=e.routingDestination();"string"==typeof t&&t.length>0&&s.add(t)}}return[...s]}function Bv(t,e){if(!t||!e)return[];const n=Ov(t);if(!n)return[];const s=new Map;for(const t of n.out.values())for(const e of t)null!=e&&s.set(e,(s.get(e)??0)+1);const i=new Map;for(const r of ev(n,e)){const e=Iv(t,r);if(!Sv(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=s.get(r)??0,0===o&&(o=1)),i.set(n,(i.get(n)??0)+o)}return[...i].map(([t,e])=>({value:t,weight:e}))}function Yv(t){return Ov(t)}function Gv(t){const e=Ov(t);if(!e)return[];const n=new Set,s=new Set,i=t=>{if(!t)return;const r=zv(t);if(r&&e.nodes.has(r)){Sv(t)&&n.add(r);((t?.state?.type??t?.model?.type??"").includes("loop")||!0===t?.isLoop)&&s.add(r)}const o=t.components;if(Array.isArray(o))for(const t of o)i(t)};return i(t),iv(e,{routingTargetIds:n,loopCapableIds:s})}function Vv(t){if(0===t.length)return;const e=t.reduce((t,e)=>t+e.weight,0);if(e<=0)return t[Math.floor(Math.random()*t.length)].value;const n=Math.random()*e;let s=0;for(const e of t)if(s+=e.weight,n<s)return e.value;return t[t.length-1].value}const Uv={next:Fv,downstream:Nv,reachableDestinations:$v,reachableDestinationsFrom:Hv,reachableDestinationsWeightedFrom:Bv,pickWeightedDestination:Vv,graphFor:Yv,validate:Gv};function Wv(t){var e;return e=class extends t{constructor(){super(...arguments),this._items=[]}get items(){return this._items}containsItem(t){return-1!==this._items.indexOf(t)}attachPointFor(e,n){const s=t.prototype?.attachPointFor;return"function"==typeof s?s.call(this,e,n):null}addItem(t,e){if(!t||this.containsItem(t))return;const n=t.parent;if(n&&"function"==typeof n.removeItem&&n!==this&&n.removeItem(t,!0),this._items.push(t),t.parent=this,!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 s=-1===this._items.indexOf(t);if(s&&this._items.push(t),t.parent=this,s&&"function"==typeof this.trigger)try{this.trigger("hold",this,t,this._items.length-1)}catch{}const i=t._realObject,r=i?.object3d;if(r){let n,s,o=e?.toParent3D,a="world-preserve";if(!o){const i=this.attachPointFor?.(t,{slotId:e?.slotId});i?.attach&&(o=i.attach,n=i.localPosition,s=i.localRotation,a=i.carryPolicy??"world-preserve")}o&&r.parent!==o&&(o.updateWorldMatrix?.(!0,!1),r.updateWorldMatrix?.(!0,!1),o.attach(r),i.suppressTransform=!0),o&&(n&&r.position.set(n.x,n.y,n.z),"world-preserve"!==a?s?r.rotation.set(s.x,s.y,s.z):r.quaternion.identity():s&&r.rotation.set(s.x,s.y,s.z),i?.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,s,i){for(let r=this._items.length-1;r>=0;r--){const o=this._items[r],a="static"===o.position?o.capture?.(t,e,i):o.capture?.(n,s,i);if(a)return a}return null}postrender(t){super.postrender?.(t);const e=this;if("popup"===e.position)return;const n=this._items;if(!n||0===n.length)return;t.save();const s=e.bounds;!e.showOverflow&&s&&(t.beginPath(),t.rect(s.left,s.top,s.width,s.height),t.clip(),t.closePath());const{left:i=0,top:r=0}=e.state??{};t.translate(i,r),this._drawItems(t),t.translate(-i,-r),t.restore()}capture(t,e,n){const s=this,i=this._items;if(i&&i.length>0&&(!s.app||s.app.isEditMode||!s.hidden)){const i=s.fromParent?.(t,e);if(i&&s.contains?.(i.x,i.y)){const r=s.bounds,o=this._captureItems(i.x-r.left,i.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 qv(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,s={}){const i=e.slot,r=this._countOccupied(i.id),o=this.arrangementStrategy.positionAt(r,i,r,n);Gu.log({role:"target",contract:"arrangementStrategy.positionAt",component:this,args:{idx:r,slotId:i.id,occupantCount:r,carrier:Qy(n)},result:o}),n[tb]=i.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}=s;"function"==typeof this.handoverIn?this.handoverIn(n,{slotId:i.id}):this.reparent?.(n,{animated:h,duration:d,ease:u}),!h&&n._realObject&&(n._realObject.suppressTransform=!1);{const t={},e=this.placementFor?.(n,{slot:i,index:r,occupantCount:r})??null;if(Gu.log({role:"target",contract:"placementFor",component:this,args:{carrier:Qy(n),slotId:i.id,index:r},result:e}),e){const s=n.state??{},r=this.state??{};t.left=e.position.x-(Number(s.width)||0)/2+(Number(r.width)||0)/2,t.top=e.position.z-(Number(s.height)||0)/2+(Number(r.height)||0)/2;const o=this._zPosFromSeatY(e.position.y,s.depth,i);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(i.localPosition&&Number.isFinite(i.localPosition.z)){const e=this._realObject?.geometricOffsetY??0;t.zPos=i.localPosition.z+e}const e=this.acceptanceRotation?.(n,i);Gu.log({role:"target",contract:"acceptanceRotation",component:this,args:{carrier:Qy(n),slotId:i.id},result:e}),e&&Zy(t,e)}const s=this.normalizePose?.(n,i);"function"==typeof this.normalizePose&&Gu.log({role:"target",contract:"normalizePose",component:this,args:{carrier:Qy(n),slotId:i.id},result:s}),s&&Object.assign(t,s),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:i.id,preReceiveWorldPos:c,preReceiveWorldQuat:l}),Gu.log({role:"target",contract:"receive:done",component:this,args:{carrier:Qy(n),slotId:i.id}})}async dispatch(t,e,n={}){const s=new qu({source:this,target:e,carrier:t,options:n,physical:async()=>{delete t[tb]}}),i=await s.execute();"rolled-back"!==i.phase?this.trigger("transfer-dispatched",{type:"transfer-dispatched",component:t,container:this,target:e}):this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:i.rejectReason??"rejected"})}route(t){return null}resolveRoute(t,e){}rejectRoute(t,e="rejected"){this.trigger("transfer-rejected",{type:"transfer-rejected",component:t,container:this,reason:e})}canAccept(t){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 Xv(t){var e;const n=!!t.__hasCapacity,s=!!t.__hasTransferable,i=n?t:Fb(t),r=s?i:qv(i),o=[...t.capabilities??[]];n||o.push("Capacity","PlacementSurface"),s||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(Wv(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 Kv(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 Qv={x:0,y:0,z:0,w:1};function Jv(t){const e=t/2;return{x:0,y:Math.sin(e),z:0,w:Math.cos(e)}}function Zv(t,e){const n=t.rotation,s=e.rotation,i=e.position,r=n.w*i.x+n.y*i.z-n.z*i.y,o=n.w*i.y+n.z*i.x-n.x*i.z,a=n.w*i.z+n.x*i.y-n.y*i.x,c=-n.x*i.x-n.y*i.y-n.z*i.z,l=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*s.x+n.x*s.w+n.y*s.z-n.z*s.y,y:n.w*s.y-n.x*s.z+n.y*s.w+n.z*s.x,z:n.w*s.z+n.x*s.y-n.y*s.x+n.z*s.w,w:n.w*s.w-n.x*s.x-n.y*s.y-n.z*s.z};return{position:{x:t.position.x+l,y:t.position.y+h,z:t.position.z+d},rotation:u}}const t_={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 e_(t){const{carrierWorld:e,width:n,depth:s,entryHeight:i,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:{...Qv}}:void 0,u=n/2,p=s/2;return a.map(t=>{const n=t_[t],s="string"==typeof c?c:c[t]??"unknown",r={position:{x:n.axis.x*("east"===t||"west"===t?u:0),y:i,z:n.axis.z*("north"===t||"south"===t?p:0)},rotation:Jv(n.yaw)},a={position:{x:r.position.x+n.axis.x*o,y:i,z:r.position.z+n.axis.z*o},rotation:Jv(n.yaw)};return{id:`entry-${n.idSuffix}`,toolType:s,approach:Zv(e,a),engage:Zv(e,r),...d?{mount:d}:{},tolerance:l,priority:h}})}function n_(t){const{carrierWorld:e,topY:n,approachDistance:s,toolType:i,mountLocalY:r,tolerance:o,priority:a,id:c}=t,l={position:{x:0,y:n,z:0},rotation:{...Qv}};return{id:c??"top",toolType:i,approach:Zv(e,{position:{x:0,y:n+s,z:0},rotation:{...Qv}}),engage:Zv(e,l),..."number"==typeof r?{mount:{position:{x:0,y:r,z:0},rotation:{...Qv}}}:{},tolerance:o,priority:a}}function s_(t,e){return t.filter(t=>t.toolType===e.toolType)}function i_(t,e){if(0===t.length)return null;const n=t.map(t=>{const n=t.approach.position.x-e.x,s=t.approach.position.y-e.y,i=t.approach.position.z-e.z;return{f:t,dist:Math.sqrt(n*n+s*s+i*i)}});return n.sort((t,e)=>{const n=t.f.priority??0,s=e.f.priority??0;return n!==s?n-s:t.dist-e.dist}),n[0].f}class r_{constructor(t){this.owner=t}positionAt(t,e,n,s){if(0!==t)return null;const i=this.owner?.state?.width??0,r=this.owner?.state?.height??0,o=s?.state?.width??0,a=s?.state?.height??0;return{x:Math.max(0,(i-o)/2),y:Math.max(0,(r-a)/2),z:0}}capacity(t){return t.maxCount??1}}let o_=1;function a_(t,e){return t.startSimMs<e.endSimMs&&e.startSimMs<t.endSimMs}const c_={resolveConflict:(t,e)=>t.priority!==e.priority?t.priority<e.priority?"b-yields":"a-yields":t.id<e.id?"b-yields":"a-yields"};class l_{constructor(t=c_){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-"+o_++},n=(this._byResource.get(e.resource)??[]).filter(t=>a_(t.timeWindow,e.timeWindow));if(0===n.length)return this._insert(e),this._emit({kind:"added",reservation:e}),{ok:!0,reservation:e};const s=n.map(t=>{const n=this._yieldPolicy.resolveConflict(e,t);return{a:e,b:t,decision:n}});if(s.every(t=>"b-yields"===t.decision)){const s=n.slice();for(const t of s)this._remove(t),this._emit({kind:"evicted",reservation:t,by:e});return this._insert(e),this._emit({kind:"added",reservation:e}),this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:s,outcome:"preempted"}),{ok:"preempted",reservation:e,evicted:s}}return this._appendConflictLog({simTime:e.timeWindow.startSimMs,resource:e.resource,proposed:t,existing:n.slice(),outcome:"rejected"}),{ok:!1,conflicts:s}}conflictLog(){return[...this._conflictLog]}setMaxConflictLog(t){this._maxConflictLog=Math.max(1,t)}_appendConflictLog(t){this._conflictLog.push(t),this._conflictLog.length>this._maxConflictLog&&this._conflictLog.shift()}conflicts(t,e){return(this._byResource.get(t)??[]).filter(t=>a_(t.timeWindow,e))}release(t){this._remove(t)&&this._emit({kind:"released",reservation:t})}releaseAllOf(t){const e=(this._byReserver.get(t)??[]).slice();for(const t of e)this._remove(t),this._emit({kind:"released",reservation:t});return e}forResource(t){return[...this._byResource.get(t)??[]]}forReserver(t){return[...this._byReserver.get(t)??[]]}all(){const t=[];for(const e of this._byResource.values())t.push(...e);return t}clear(){this._byResource.clear(),this._byReserver.clear(),this._conflictLog.length=0}subscribe(t){return this._listeners.add(t),()=>{this._listeners.delete(t)}}_insert(t){let e=this._byResource.get(t.resource);e||(e=[],this._byResource.set(t.resource,e));const n=e.findIndex(e=>e.timeWindow.startSimMs>t.timeWindow.startSimMs);n<0?e.push(t):e.splice(n,0,t);let s=this._byReserver.get(t.reserverId);s||(s=[],this._byReserver.set(t.reserverId,s)),s.push(t)}_remove(t){const e=this._byResource.get(t.resource);if(!e)return!1;const n=e.findIndex(e=>e.id===t.id);if(n<0)return!1;e.splice(n,1),0===e.length&&this._byResource.delete(t.resource);const s=this._byReserver.get(t.reserverId);if(s){const e=s.findIndex(e=>e.id===t.id);e>=0&&s.splice(e,1),0===s.length&&this._byReserver.delete(t.reserverId)}return!0}_emit(t){this._listeners.forEach(e=>e(t))}}const h_=new l_;"undefined"!=typeof globalThis&&(globalThis.__THINGS_SCENE_RESERVATION_TABLE__=h_);class d_{constructor(){this.nodes=new Map,this.edges=new Map,this.laneEndpoints=new Map}addNode(t){this.nodes.has(t.id)||(this.nodes.set(t.id,t),this.edges.set(t.id,[]))}addEdge(t){const e=this.edges.get(t.fromNode);if(!e)throw new Error(`NavGraph.addEdge: source node not found: ${t.fromNode}`);if(!this.nodes.has(t.toNode))throw new Error(`NavGraph.addEdge: target node not found: ${t.toNode}`);e.push(t)}edgesFrom(t){return this.edges.get(t)??[]}findNearestNode(t){let e=null,n=1/0;for(const s of this.nodes.values()){const i=u_(s.position,t);i<n&&(n=i,e=s)}return e}}function u_(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}function p_(t,e){return Math.sqrt(u_(t,e))}function f_(t,e,n={}){const s=new d_,i=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`;s.addNode({id:n,position:t[0],type:"lane-start"}),s.addNode({id:r,position:t[t.length-1],type:"lane-end"}),s.laneEndpoints.set(e.id,{startNodeId:n,endNodeId:r});let o=0;for(let e=1;e<t.length;e++)o+=p_(t[e-1],t[e]);const a=o/(e.speedLimit??i)*1e3;s.addEdge({fromNode:n,toNode:r,resource:e.id,distance:o,durationMs:a,forward:!0}),"twoway"===e.direction&&s.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 i=s.laneEndpoints.get(n);if(!i)continue;const r=s.nodes.get(i.startNodeId).position,o=s.nodes.get(i.endNodeId).position;let a=0,c=0,l=0;for(const e of t.lanes){if(e===n)continue;const t=s.laneEndpoints.get(e);if(!t)continue;const i=s.nodes.get(t.startNodeId).position,h=s.nodes.get(t.endNodeId).position;a+=Math.min(u_(r,i),u_(r,h)),c+=Math.min(u_(o,i),u_(o,h)),l++}if(0===l)continue;const h=a<c?i.startNodeId:i.endNodeId;e.push({laneId:n,nodeId:h,pos:s.nodes.get(h).position})}for(let n=0;n<e.length;n++)for(let i=0;i<e.length;i++){if(n===i)continue;const r=e[n],o=e[i],a=p_(r.pos,o.pos);s.addEdge({fromNode:r.nodeId,toNode:o.nodeId,resource:t.id,distance:a,durationMs:t.crossingTimeMs,forward:!0})}}return s}function m_(t,e,n,s={}){const i=t.nodes.get(e),r=t.nodes.get(n);if(!i||!r)return null;const o=s.speed?.max??100,a=e=>{const n=t.nodes.get(e);var s,i;return(s=n.position,i=r.position,Math.sqrt(function(t,e){const n=t.x-e.x,s=t.y-e.y,i=t.z-e.z;return n*n+s*s+i*i}(s,i)))/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=s.startSimMs??0,p=s.deadlineSimMs;for(;l.size>0;){let e=null,s=null;for(const t of l){const n=c.get(t);(!s||n.fScore<s.fScore||n.fScore===s.fScore&&t<e)&&(s=n,e=t)}if(!s||!e)return null;if(e===n){const t=[];let e=s,n=0;for(;e&&e.cameFromEdge;){const s=e.cameFromEdge,i=u+(e.gScore-s.durationMs);t.unshift({resource:s.resource,timeWindow:{startSimMs:i,endSimMs:i+s.durationMs},fromPos:s.fromPos,toPos:s.toPos}),n+=s.distance,e=c.get(s.fromNodeId)}const i=s.gScore;return void 0!==p&&u+i>p?null:{segments:t,totalDurationMs:i,totalDistance:n}}l.delete(e),h.add(e);for(const n of t.edgesFrom(e)){if(h.has(n.toNode))continue;const e=s.gScore+n.durationMs,i=c.get(n.toNode);if(!i||e<i.gScore){const s=t.nodes.get(n.fromNode),i=t.nodes.get(n.toNode),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:s.position,toPos:i.position}};c.set(n.toNode,r),l.add(n.toNode)}}}return null}function g_(t,e,n=0,s){return t.segments.map(t=>({resource:t.resource,timeWindow:t.timeWindow,reserverId:e,priority:n,metadata:s}))}const y_={closed:!0,round:0,divisions:24};class b_{constructor(t,e){this.points=t,this.closed=e;const n=[0];for(let e=1;e<t.length;e++){const s=t[e].x-t[e-1].x,i=t[e].y-t[e-1].y;n.push(n[e-1]+Math.sqrt(s*s+i*i))}this.cumulative=n,this.length=n[n.length-1]??0}sample(t){const e=this.length;if(0===this.points.length)return{x:0,y:0,theta:0};if(0===e)return{x:this.points[0].x,y:this.points[0].y,theta:0};let n=t;this.closed?n=(t%e+e)%e:n<0?n=0:n>e&&(n=e);const s=this.cumulative;let i=0,r=s.length-2;for(;i<r;){const t=i+r>>1;s[t+1]<=n?i=t+1:r=t}const o=s[i+1]-s[i],a=o>0?(n-s[i])/o:0,c=this.points[i],l=this.points[i+1],h=l.x-c.x,d=l.y-c.y;return{x:c.x+h*a,y:c.y+d*a,theta:0===h&&0===d?0:Math.atan2(d,h)}}}function v_(t,e={}){const n={...y_,...e},s=t.length;if(0===s)return new b_([],n.closed);if(1===s)return new b_([{x:t[0].x,y:t[0].y}],n.closed);const i=[],r=(t,e)=>{if(i.length>0){const n=i[i.length-1];if(Math.abs(n.x-t)<1e-9&&Math.abs(n.y-e)<1e-9)return}i.push({x:t,y:e})},o=(n.closed,s);for(let e=0;e<o;e++){const i=0===e?n.closed?s-1:-1:e-1,o=e===s-1?n.closed?0:-1:e+1,a=i>=0?t[i]: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,s=1-e;r(s*s*d+2*s*e*c.x+e*e*p,s*s*u+2*s*e*c.y+e*e*f)}else d===p&&u===f||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),s=0!==e?Math.atan2(c.x-l.x,c.y-l.y):0,i=Math.min(t,e/2),o=Kr({x:p,y:f},{x:Math.sin(s)*i+l.x,y:Math.cos(s)*i+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 s=e/n.divisions,i=o.startAngle+t*s;r(o.cx+o.radius*Math.cos(i),o.cy+o.radius*Math.sin(i))}}}}if(n.closed&&i.length>0){const t=i[0],e=i[i.length-1];(Math.abs(e.x-t.x)>1e-9||Math.abs(e.y-t.y)>1e-9)&&i.push({x:t.x,y:t.y})}return new b_(i,n.closed)}function __(t,e){return v_(t,e).length}function x_(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 w_(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 M_(t,e=!0){const n=t.constructor?.name??t.state?.type??"Component",s={type:n,id:t.state?.id??`?${t._id??Math.random().toString(36).slice(2,7)}`,category:x_(n),parentId:t.parent?.state?.id,parentPath:w_(t)},i=t._realObject?.object3d;if(i){i.updateWorldMatrix?.(!0,!1);const t=i.matrixWorld?.elements;t&&(s.pose={position:{x:t[12],y:t[13],z:t[14]},rotation:{x:0,y:0,z:0,w:1}})}if(!0===t.isItem&&(s.isItem=!0),!0===t.isMover&&(s.isMover=!0),"function"!=typeof t.canReceive&&"function"!=typeof t.canAccept||(s.isHolder=!0),"function"==typeof t.pickupFrames)try{s.isPickable=t.pickupFrames().length>0}catch{s.isPickable=!1}if("string"==typeof t.toolType||"function"==typeof t.toolType?s.toolType="function"==typeof t.toolType?t.toolType():t.toolType:void 0!==t.toolType&&(s.toolType=String(t.toolType)),t.state&&"object"==typeof t.state){const e={};for(const[n,s]of Object.entries(t.state))"string"!=typeof s&&"number"!=typeof s&&"boolean"!=typeof s&&null!==s||(e[n]=s);s.state=e}if(e){const e=t.components??[];s.childIds=e.map(t=>t.state?.id).filter(Boolean)}return s}function S_(t){function e(t,n){if(!t)return;n.push(M_(t));const s=t.components??[];for(const t of s)e(t,n)}function n(t,e){if(!e)return null;if(e.state?.id===t)return e;const s=e.components??[];for(const e of s){const s=n(t,e);if(s)return s}return null}return{version:"0.1.0",collectComponents(){const n=[];return e(t?.rootModel??t,n),n},getComponent(e){const s=n(e,t?.rootModel??t);if(!s)return null;const i={...M_(s)};if("function"==typeof s.pickupFrames)try{i.pickupFrames=s.pickupFrames()}catch{}if("object"==typeof s.slots)try{i.slots=Array.isArray(s.slots)?s.slots:"function"==typeof s.slots?s.slots():[]}catch{}if("function"==typeof s.acceptanceRotation)try{i.acceptanceWorldQuat=s.deliveryWorldRotation?.(null)??void 0}catch{}if("function"==typeof s.deliveryWorldPosition)try{i.deliveryWorldPosition=s.deliveryWorldPosition(null)}catch{}return i},simStatus(){let e=0;const n=[t?.rootModel??t];for(;n.length>0;){const t=n.pop();if(!t)continue;!0===t.isItem&&e++;const s=t.components??[];for(const t of s)n.push(t)}return{simTime: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=[...h_.all()],e={},n={};for(const s of t)(e[s.resource]??=[]).push(s),(n[s.reserverId]??=[]).push(s);for(const t of Object.values(e))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);for(const t of Object.values(n))t.sort((t,e)=>t.timeWindow.startSimMs-e.timeWindow.startSimMs);return{simTime:Dr.now,all:t,byResource:e,byReserver:n}},conflicts(){const t=h_.conflictLog(),e={},n={};let s=0,i=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?s++:i++;return{simTime:Dr.now,log:[...t],total:t.length,rejected:s,preempted:i,byResource:e,byReserver:n}}}}function E_(t){const e=S_(t);return"undefined"!=typeof window&&(window.__SCENE_INSPECTOR__=e),e}let A_=0;const k_=new FinalizationRegistry(()=>{A_--});class C_{static get residents(){return A_}static get residentsCount(){return A_}constructor(t,e){this.counters={},this.references={},this.creator=t,this.disposer=e,A_++,k_.register(this,A_)}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,Zs("RELEASED",t)},e(n)},n):n(Error("Reference id("+t+") could not be created. Reference creator should be defined."))})}add(t,e){const n=new Promise((n,s)=>{const i=this.references[t];if(i)i===e?s(Error("Reference ID and target duplicate")):e?s(Error("Reference ID duplicate")):n(i);else{const i=e=>{e.release=()=>{this.release(e)},this.references[t]=e,this.counters[t]=1,n(e)};if(e)i(e);else{if(!this.creator)return void s(Error("Reference id("+t+") is not allowed. Reference creator should be defined."));this.creator(t,i,s)}}});return this.references[t]||(this.references[t]=n),n}async get(t,e=!1){let n=this.references[t];if(n){if(!(n instanceof Promise)){if(!(t in this.counters))throw new Error("No Reference Count");return this.counters[t]++,n}if(e)return n=await n,this.counters[t]++,n}if(e)return await this.add(t);throw new Error("No References for "+t)}_id(t){for(const e in this.references){if(this.references[e]===t)return e}}release(t){const e=this._id(t);if(!e)return void Qs("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,Zs("RELEASED",e)))}}const T_={},O_={};let P_=[];function I_(t){const e=t.target,n="SCRIPT"===e.tagName?T_:O_,s=e.src||e.href;n[s]=!0,P_.forEach((t,e)=>{if(!t)return;const{resolve:i,scripts:r,styles:o}=t;if(n===T_){const t=r.indexOf(s);t>-1&&t<r.length-1&&z_(r[t+1])}r.some(t=>!T_[t])||o?.some(t=>!O_[t])||(i(),P_[e]=null)}),P_=P_.filter(Boolean)}function D_(t){if("string"==typeof t)return;const e=t.target,n=e.src,s="SCRIPT"===e.tagName?T_:O_;P_.forEach((e,i)=>{if(!e)return;const{reject:r,scripts:o,styles:a}=e;(s===T_&&o.includes(n)||s===O_&&!!a?.includes(n))&&(r(t),P_[i]=null)}),P_=P_.filter(Boolean),delete s[n],document.head.removeChild(e)}function z_(t){T_[t]=!1;const e=document.createElement("script");e.onload=I_,e.onerror=D_,e.type="text/javascript",e.src=t,document.head.appendChild(e)}class R_{static load(t,e){const n="string"==typeof t?[t]:t,s="string"==typeof e?[e]:e;return new Promise(function(t,e){if(n&&!Array.isArray(n)||s&&!Array.isArray(s))return void e(new Error("invalid sources for load"));let i,r=!0;if(s?.forEach(t=>{t in O_||function(t){O_[t]=!1;const e=document.createElement("link");e.onload=I_,e.onerror=D_,e.type="text/css",e.rel="stylesheet",e.media="screen,print",e.href=t,document.head.appendChild(e)}(t),O_[t]||(r=!1)}),n&&n.length>0)for(const t of n)t in T_?T_[t]||(r=!1):i??=t;if(i)z_(i);else if(r)return void t();P_.push({resolve:t,reject:e,scripts:n,styles:s})})}}const j_="0.0.0";function L_(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 F_(e){const{lineWidth:n=0}=e.state;let{width:s,height:i}=e.bounds;s+=n,i+=n;const r=L_(2*s),o=L_(2*i),a=Bp(r,o),c=new t.CanvasTexture(a);return N_(a,e,2),c.needsUpdate=!0,c.wrapS=t.RepeatWrapping,c.wrapT=t.RepeatWrapping,c.offset.set(0,1-2*i/o),c.repeat.set(2*s/r,2*i/o),c.magFilter=t.NearestFilter,c.minFilter=t.LinearFilter,c.colorSpace=t.SRGBColorSpace,c}function N_(t,e,n){const{lineWidth:s=0}=e.state;let{left:i,top:r}=e.bounds;i-=s/2,r-=s/2;const o=t.getContext("2d");o.scale(n,n),o.translate(-i,-r),e.render(o),e.postrender(o)}function $_(t,e,n=2){const s=t.getContext("2d");s&&(s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,t.width,t.height),N_(t,e,n))}const H_=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class B_ 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 s=Id(this.component.state.material3d),i=new t.PlaneGeometry(1,1);i.rotateX(-Math.PI/2),this.object3d.geometry=i;const r=F_(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,s),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=s.castShadow,this.object3d.receiveShadow=s.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&&($_(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(!H_.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 Y_=new Map;function G_(t){return Math.round(1e3*t)/1e3}function V_(e){return new t.Color(e).getHexString()}const U_={material(e,n,s){const i=e+"::"+function(t){const e=[];return null!=t.color&&e.push("c"+V_(t.color)),null!=t.metalness&&e.push("m"+G_(t.metalness)),null!=t.roughness&&e.push("r"+G_(t.roughness)),null!=t.opacity&&e.push("o"+G_(t.opacity)),null!=t.emissive&&e.push("E"+V_(t.emissive)),null!=t.emissiveIntensity&&e.push("I"+G_(t.emissiveIntensity)),null!=t.envMapIntensity&&e.push("e"+G_(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=Y_.get(i);return r||Y_.set(i,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==s?r:Qd(r,{color:s})},get size(){return Y_.size},has(t){const e=t+"::";for(const t of Y_.keys())if(t.startsWith(e))return!0;return!1},dispose(){for(const t of Y_.values())Zd(t),t.dispose();Y_.clear()}};class W_ 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 s=Mu.buildFillStyleTexture(this.component);s?(n.map&&n.map.dispose(),s.needsUpdate=!0,n.map=s,n.needsUpdate=!0):"string"==typeof t&&(n.map&&(n.map.dispose(),n.map=null,n.needsUpdate=!0),"transparent"!==t&&"none"!==t&&n.color.set(su(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 s=this.object3d.geometry;if(!s?.getAttribute("position"))return;const i=new t.EdgesGeometry(s),r=new t.LineBasicMaterial({color:n}),o=new t.LineSegments(i,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 s=this.object3d.geometry.boundingBox;if(s){const i=s.max.x-s.min.x,r=s.max.y-s.min.y,o=s.max.z-s.min.z;this.setDimensionScale(t/i,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,s={shared:e,required:n,violated:n&&!e};return void 0!==t&&(s.reason=t),e&&(s.bankKey=this.materialBankKey),s}get materialBankKey(){return`mesh|${this.component.state.type??"unknown"}`}materialSpec(){const t=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?su(t):void 0;Jd(this.object3d),this.object3d.material=U_.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 q_(t,e,n,s){return[["bold",t],["italic",e],[n+"px",!0],[s,!0]].filter(t=>t[1]).map(t=>t[0]).join(" ")}function X_(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 K_(t,e,n){const{bold:s=!1,italic:i=!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=q_(s,i,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 Q_(e,n,s,i){const r=X_(2*n),o=X_(2*s),a=Bp(r,o),c=a.getContext("2d"),{fillStyle:l}=i||{};if(l&&"object"==typeof l&&l.colorStops?.length){const t=du(l,2*n,2*s);t&&c.drawImage(t,0,0)}c.scale(2,2),"string"==typeof l&&""!==l&&"transparent"!==l&&(c.fillStyle=l,c.fillRect(0,0,n,s)),K_(a,e,i);const h=new t.CanvasTexture(a);return h.needsUpdate=!0,h.wrapS=t.RepeatWrapping,h.wrapT=t.RepeatWrapping,h.offset.set(0,1-2*s/o),h.repeat.set(2*n/r,2*s/o),h.minFilter=t.LinearFilter,h.colorSpace=t.SRGBColorSpace,h}function J_(e,n,s,i,r,o,a){const c=new Image;c.crossOrigin="anonymous",c.onload=()=>{const e=2*s,l=2*i,h=X_(e),d=X_(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),s=2*(o.offsetX||0),i=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=s+r,d=i+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 s=h>0?h-Math.ceil(h/t)*t:h;for(let i=d>0?d-Math.ceil(d/n)*n:d;i<l;i+=n)for(let r=s;r<e;r+=t)p.drawImage(c,0,0,c.naturalWidth,c.naturalHeight,r,i,t,n);p.restore()}}n&&(p.scale(2,2),K_(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=Q_(n,s,i,r);a(t)},c.src=e}function Z_(t,e){let{bold:n=!1,italic:s=!1,fontFamily:i="Serif",fontSize:r=10,lineHeight:o="normal"}=e||{};t=void 0===t||""==t?" ":String(t);const a=document.createElement("span");a.style.font=q_(n,s,r,i),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 tx extends W_{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,s=Math.abs(e)||1,i=Math.abs(n)||1;this.object3d.geometry&&this.object3d.geometry.dispose();const r=new t.PlaneGeometry(s,i);r.rotateX(-Math.PI/2),this.object3d.geometry=r}updateText(){const t=this.object3d.material;if(!t)return;const{width:e,height:n,bold:s=!1,italic:i=!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:s,italic:i,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 J_(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=Q_(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(su(h)):t.opacity=0)}updateAlpha(){const t=this.object3d.material;t.opacity=1,t.transparent=!0,super.applyMaterialOpacity()}}Jp("text",t=>new tx(t));const ex={input:"css3d",select:"css3d",textarea:"css3d",button:"css3d",iframe:"css3d",video:"css3d",label:"texture",table:"texture",progress:"texture"};function nx(t){const e=t.model?.type??"";return"texture"===(ex[e]??"css3d")?new B_(t):new Xp(t)}Jp("html-overlay-element",nx),Jp("html-overlay-container",nx);class sx{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,s,i,r){const o=n[3*s],a=n[3*s+1],c=n[3*i],l=n[3*i+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,s,i,r,o){const a=n[3*s],c=n[3*s+1],l=n[3*s+2],h=n[3*i],d=n[3*i+1],u=n[3*i+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 ix(t,e){const n=t/2,s=e/2;return{points:[{x:-n,y:-s},{x:n,y:-s},{x:n,y:s},{x:-n,y:s}]}}function rx(t,e,n){const s=Math.max(3,Math.floor(n)),i=[];for(let n=0;n<s;n++){const r=n/s*Math.PI*2;i.push({x:t*Math.cos(r),y:e*Math.sin(r)})}return{points:i,segments:s}}function ox(t){if(0===t.length)return[];let e=1/0,n=1/0,s=-1/0,i=-1/0;for(const r of t)r.x<e&&(e=r.x),r.x>s&&(s=r.x),r.y<n&&(n=r.y),r.y>i&&(i=r.y);const r=(e+s)/2,o=(n+i)/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 ax 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 s=ox(n);return s.length<3?null:{points:s}}get outlineDivisions(){return 12}get boundUVGenerator(){return this._boundUVGenerator||(this._boundUVGenerator=new sx),this._boundUVGenerator}build(){super.build();const e=this.effectiveDepth,n=this.shape;if(!n)return;const s=this.boundUVGenerator;s&&s.setShape({extrudedShape:n,extrudedOptions:{depth:e}});const i=this.createGeometry(n),r=this.createMaterials();this._mesh=new t.Mesh(i,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:s=0}=this.component.state,i={steps:1,depth:n,bevelEnabled:s>0,bevelThickness:0,bevelSize:s,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,i);return r.center(),r}createMaterials(){const e=Id(this.component.state.material3d),n=new t.MeshStandardMaterial;Rd(n,e);const s=new t.MeshStandardMaterial;return Rd(s,e),[n,s]}createTexture(){const{width:e,height:n}=this.component.bounds,s=X_(e),i=X_(n),r=Bp(s,i);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/i),o.repeat.set(e/s,n/i),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,s=this.getMaterials();s&&(nu(s[0],0,e),nu(s[1],0,n))}updateStrokeStyle(){const t=this.getMaterials();if(!t)return;const{strokeStyle:e}=this.component.state;t[1].color.set(su(e))}updateFillStyle(){this._applyCapTexture()}updateText(){this._applyCapTexture()}_applyCapTexture(){const t=this.getMaterials();if(!t)return;const e=t[0],{fillStyle:n}=this.component.state,s=this.component.hasTextProperty?this.component.text:"";if(!s){const t=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(su(n))),void(e.needsUpdate=!0)}const{bold:i=!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:i,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 J_(this.component.app.url(n.image),s,y,b,v,n,t=>{e.map&&e.map.dispose(),e.map=t,e.color.set(16777215),e.needsUpdate=!0})}e.map&&e.map.dispose();const _=Q_(s,y,b,v);e.map=_,e.color.set(16777215),e.needsUpdate=!0}updateDimension(){super.updateDimension()}onchange(t,e){if("path"in t&&this._mesh){const t=this._mesh.geometry,e=this.shape;if(e){const n=this.createGeometry(e);this._mesh.geometry=n,t.dispose()}}super.onchange(t,e)}}class cx extends ax{get shape(){const{cx:e=0,cy:n=0,rx:s=1,ry:i=1,startAngle:r=0,endAngle:o=2*Math.PI,anticlockwise:a=!1}=this.component.state,c=new t.EllipseCurve(e,n,Math.abs(s),Math.abs(i),r,o,a,0);return new t.Shape(c.getPoints(50))}}Jp("ellipse",t=>new cx(t));class lx extends ax{get shape(){const{width:e,height:n,round:s=0}=this.component.state,i=Oc(s,e,n);if(i>0){const s=i,r=new t.Path;return r.moveTo(s,0),r.lineTo(e-s,0),r.quadraticCurveTo(e,0,e,s),r.lineTo(e,n-s),r.quadraticCurveTo(e,n,e-s,n),r.lineTo(s,n),r.quadraticCurveTo(0,n,0,n-s),r.lineTo(0,s),r.quadraticCurveTo(0,0,s,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 hx(e,n={}){const s=n.round??0,i=n.divisions??24;if(!e||0===e.length)return new t.Shape;const r=e.some(t=>Xr(t)),o=s>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 i=e[(t-1+e.length)%e.length],r=e[t],o=e[(t+1)%e.length];if(i.x===r.x&&i.y===r.y)continue;const a=Zr(r,s);let c=Math.sqrt((i.x-r.x)**2+(i.y-r.y)**2),l=0!==c?Math.atan2(i.x-r.x,i.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,s),e=Math.sqrt((r.x-o.x)**2+(r.y-o.y)**2),i=0!==e?Math.atan2(r.x-o.x,r.y-o.y):0,a=Kr({x:u,y:p},{x:Math.sin(i)*Math.min(t,e/2)+o.x,y:Math.cos(i)*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(i))}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 lx(t));class dx extends ax{get shape(){const{path:t=[],round:e=0}=this.component.state;return hx(t,{round:e,divisions:24})}build(){Object.getPrototypeOf(ax.prototype).build.call(this);const e=this.effectiveDepth,n=this.shape;if(!n)return;const s=this.boundUVGenerator,i=this.minMax;if(s&&void 0!==i.minX&&void 0!==i.maxX&&void 0!==i.minY&&void 0!==i.maxY){const n=new t.Shape;n.moveTo(i.minX,i.minY),n.lineTo(i.maxX,i.minY),n.lineTo(i.maxX,i.maxY),n.lineTo(i.minX,i.maxY),n.closePath(),s.setShape({extrudedShape:n,extrudedOptions:{depth:e}})}else s&&s.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:s=0}=this.component.state,i={steps:1,depth:n,bevelEnabled:s>0,bevelThickness:0,bevelSize:s,bevelSegments:1,UVGenerator:this.boundUVGenerator},r=new t.ExtrudeGeometry(e,i),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,s,i;t.forEach((t,r)=>{if(0==r)return e=s=t.x,void(n=i=t.y);e=Math.min(e,t.x),s=Math.max(s,t.x),n=Math.min(n,t.y),i=Math.max(i,t.y)}),this._minMax={minX:e,minY:n,maxX:s,maxY:i}}return this._minMax}}Jp("polygon",t=>new dx(t));class ux extends ax{get shape(){const{cx:e=0,cy:n=0,rx:s=1,ry:i=1,ratio:r=50,startAngle:o=0,endAngle:a=2*Math.PI,anticlockwise:c=!1}=this.component.state,l=Math.abs(s),h=Math.abs(i),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 s=new t.EllipseCurve(e,n,p,f,o,a,c,0),i=new t.Path(s.getPoints(50));u.holes.push(i)}return u}}Jp("donut",t=>new ux(t));class px extends ax{get shape(){const{x1:e=0,y1:n=0,x2:s=0,y2:i=0,x3:r=0,y3:o=0,round:a=0}=this.component.state,c=[{x:e,y:n},{x:s,y:i},{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],s=c[t],i=c[(t+1)%c.length];let r=Math.sqrt((n.x-s.x)**2+(n.y-s.y)**2),o=0!==r?Math.atan2(n.x-s.x,n.y-s.y):0;const l=Math.sin(o)*Math.min(a,r/2)+s.x,h=Math.cos(o)*Math.min(a,r/2)+s.y;r=Math.sqrt((i.x-s.x)**2+(i.y-s.y)**2),o=0!==r?Math.atan2(i.x-s.x,i.y-s.y):0;const d=Math.sin(o)*Math.min(a,r/2)+s.x,u=Math.cos(o)*Math.min(a,r/2)+s.y;0===t?e.moveTo(l,h):e.lineTo(l,h),e.quadraticCurveTo(s.x,s.y,d,u)}return new t.Shape(e.getPoints(12))}const l=new t.Shape;return l.moveTo(e,n),l.lineTo(s,i),l.lineTo(r,o),l.closePath(),l}}Jp("triangle",t=>new px(t));class fx extends ax{get shape(){const{ratio:e=30,wing:n=5,cx:s=0,cy:i=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(s+r*Math.cos(-a),i+o*Math.sin(-a)),d.lineTo(s+(r-l)*(Math.cos(c-a)+Math.cos(0-a))/2,i+(o-h)*(Math.sin(c-a)+Math.sin(0-a))/2);for(let t=1;t<n;t++)d.lineTo(s+r*Math.cos(c*t-a),i+o*Math.sin(c*t-a)),d.lineTo(s+(r-l)*(Math.cos(c*(t+1)-a)+Math.cos(c*t-a))/2,i+(o-h)*(Math.sin(c*(t+1)-a)+Math.sin(c*t-a))/2);return d.closePath(),d}}Jp("star",t=>new fx(t));const mx=new Map;function gx(t){return t.userData.__bankOwned=!0,t}const yx={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 s=mx.get(n);return s||mx.set(n,s=gx(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))),s},shaped(t,e){const n="shaped::"+t;let s=mx.get(n);return s||mx.set(n,s=gx(e())),s},owns:t=>!0===t.userData?.__bankOwned,get size(){return mx.size},has:t=>mx.has("primitive::"+t)||mx.has("shaped::"+t),dispose(){for(const t of mx.values())t.dispose();mx.clear()}},bx=[8,12,16],vx={cylinder:25,sphere:32},_x=3,xx=128;function wx(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(xx,Math.max(3,Math.floor(t))):e}function Mx(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.min(xx,Math.max(2,Math.floor(t))):Math.max(2,Math.round(e/2))}function Sx(t){return bx.includes(t)}const Ex={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 Ax extends W_{buildGeometry(){const t=this.component.state,e=wx(t.segments,vx.sphere),n=Mx(t.heightSegments,e);this.object3d.geometry=yx.primitive({kind:"sphere",segments:e,heightSegments:n})}updateDimension(){const{rx:t=0,ry:e=0,rz:n}=this.component.state,s=n??t;this.setDimensionScale(2*t,2*s,2*e)}get effectiveDepth(){const{rx:t=0,rz:e}=this.component.state,n=e??t;return Math.max(2*n,1)}topOutline(){const{rx:t=0,ry:e=0}=this.component.state;if(!(t>0&&e>0))return null;return rx(t,e,wx(this.component.state.segments,vx.sphere))}}let kx=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Ax(this)}get nature(){return Ex}};kx=tg([Ny("sphere")],kx);class Cx 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(),s=this.component.parent?._realObject;return t+n+e/2-(s?.geometricOffsetY??0)}get geometricOffsetY(){const{height:t=0}=this.component.bounds;return t/2}updateAlpha(){const{alpha:t=1,fillStyle:e}=this.component.state;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(su(t)):e.opacity=0)}}class Tx extends Cx{buildMaterial(){const e=this.object3d.material;e&&e.dispose(),this.object3d.material=new t.SpriteMaterial({map:F_(this.component),alphaTest:.01,sizeAttenuation:!1})}get scale(){const{width:t,height:e}=this.component.bounds,n=this.threeContainer,{width:s=1,height:i=1}=n?.bounds??{},{scale:r=1}=this.component.state;return{x:r*t/s,y:r*e/i,z:r}}update(){this.build(),this.updateHidden()}updateFillStyle(){this.update()}updateStrokeStyle(){this.update()}updateAlpha(){this.update()}updateText(){this.update()}}const Ox={mutable:!1,resizable:!0,rotatable:!0,properties:[]};let Px=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Tx(this)}get nature(){return Ox}};Px=tg([Ny("sprite")],Px);const Ix={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/cube"};class Dx extends W_{buildGeometry(){this.object3d.geometry=yx.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?ix(t,e):null}}let zx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Dx(this)}get nature(){return Ix}};zx=tg([Ny("cube")],zx);const Rx={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"segments",name:"segments",property:"segments"}],help:"scene/component/cylinder"};class jx extends W_{buildGeometry(){const t=wx(this.component.state.segments,vx.cylinder);this.object3d.geometry=yx.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 rx(t,e,wx(this.component.state.segments,vx.cylinder))}}let Lx=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new jx(this)}get nature(){return Rx}};Lx=tg([Ny("cylinder")],Lx);const Fx={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"color",label:"box-color",name:"boxColor",property:"boxColor"}],help:"scene/component/banner"};class Nx 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 s=this.createTextureBoard(t,n);s.position.set(0,0,.5*e+1),this.object3d.add(s)}createCube(e,n,s){const{boxColor:i="#ccaa76"}=this.component.state,r=Id(this.component.state.material3d),o=new t.BoxGeometry(e,s,n),a=new t.MeshStandardMaterial({color:i,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 s=Id(this.component.state.material3d),{fillStyle:i="#ccaa76"}=this.component.state,r=Mu.buildFillStyleTexture(this.component),o=new t.MeshStandardMaterial(r?{map:r}:{color:i||"#ccaa76",side:t.FrontSide});Rd(o,s);const a=new t.PlaneGeometry(e,n,1,1),c=new t.Mesh(a,o);return c.castShadow=s.castShadow,c.receiveShadow=s.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 $x=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return Fx}buildRealObject(){return new Nx(this)}};var Hx;$x=tg([Ny("banner")],$x);const Bx={far:1e5,fov:80,near:1,zoom:1},Yx={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 Gx extends Mu{getObject3dInstance(){return new t.Mesh}updateCamera(){const{near:e=Bx.near,far:n=Bx.far,fov:s=Bx.fov,zoom:i=Bx.zoom,showHelper:r}=this.component.state;this.camera.far=n,this.camera.fov=s,this.camera.near=e,this.camera.zoom=i,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:s=0,fillStyle:i="lightgray"}=this.component.state;this.object3d.geometry=new t.BoxGeometry(e,s,n);const r=Id(this.component.state.material3d),o=new t.MeshStandardMaterial({color:i});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 Vx=Hx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}static get image(){return Hx._image||(Hx._image=new Image,Hx._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=="),Hx._image}render(t){const{left:e,top:n,width:s,height:i}=this.bounds;t.beginPath(),this.drawImage(t,Hx.image,e,n,s,i)}buildRealObject(){return new Gx(this)}get nature(){return Yx}};Vx=Hx=tg([Ny("camera")],Vx);const Ux={mutable:!1,resizable:!0,rotatable:!0,properties:[...Ly],"value-property":"source",help:"scene/component/gltf-object"};let Wx=class extends(Fy(Pc(Tc))){get nature(){return Ux}};Wx=tg([Ny("gltf-object")],Wx);const qx={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 Xx extends Mu{updatePointLight(){const{lightType:e="point",distance:n=0,intensity:s=10,decay:i=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=i),this.object3d.intensity=s,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 Kx=class extends Eg{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Xx(this)}get anchors(){return[]}get nature(){return qx}};Kx=tg([Ny("light")],Kx);const Qx={mutable:!1,resizable:!0,rotatable:!0,properties:[{type:"number",label:"depth",name:"depth",property:"depth"}],help:"scene/component/wall"};class Jx extends W_{buildGeometry(){this.object3d.geometry=yx.primitive({kind:"box"})}topOutline(){const{width:t=0,height:e=0}=this.component.state;return t>0&&e>0?ix(t,e):null}}let Zx=class extends(Pc(Tc)){get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new Jx(this)}get nature(){return Qx}};Zx=tg([Ny("wall")],Zx);const tw={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 ew 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:s}=t,i=n>=.9&&"none"!==s;return{receive:e?.receiveShadow??!0,cast:e?.castShadow??i}}updateHidden(){const t=this.component.state,e=!!this.component.app?.isViewMode;this.object3d.visible=!(t.hidden||e&&t.hideIn3DView)}clear(){return this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0),this._mesh=void 0,super.clear()}build(){super.build();const{width:e,height:n,depth:s=1}=this.component.state;if(!e||!n)return;const i=Math.abs(e),r=Math.abs(n),o=Math.max(s,.5),a=new t.BoxGeometry(i,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,s=Id(this.component.state.material3d),i=Mu.buildFillStyleTexture(this.component);if(i){this._topTexture=i;const e=new t.MeshStandardMaterial({map:i,side:t.DoubleSide});return nu(e,0,n),e.depthWrite=e.opacity>=.9,Rd(e,s),e}const r="string"==typeof n&&"none"!==n?su(n):"#e0e0e0",o=new t.MeshStandardMaterial({color:r,side:t.DoubleSide});return nu(o,0,n),o.depthWrite=o.opacity>=.9,Rd(o,s),o}_buildSideMaterial(){const{strokeStyle:e,alpha:n=1}=this.component.state,s="string"==typeof e&&e?su(e):"#999999",i=Id(this.component.state.material3d),r=new t.MeshStandardMaterial({color:s});return Rd(r,i),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,s=this._mesh.material;for(let t=0;t<s.length;t++){const i=s[t];nu(i,0,2===t?e:n),i.depthWrite=i.opacity>=.9}}updateFillStyle(){if(!this._mesh)return;this._topTexture&&(this._topTexture.dispose(),this._topTexture=void 0);const t=this._mesh.material;t[2].dispose(),t[2]=this._buildTopMaterial()}updateStrokeStyle(){if(!this._mesh)return;const t=this._mesh.material,e=this._buildSideMaterial();for(let n=0;n<t.length;n++)2!==n&&(t[n].dispose(),t[n]=e)}}let nw=class extends rh{get hasTextProperty(){return!1}is3dish(){return!0}buildRealObject(){return new ew(this)}get nature(){return tw}get hidden(){return!!this.getState("hideIn2DView")||super.hidden}};nw.requires3d=!0,nw=tg([Ny("floor-plate")],nw);function sw(e,n={}){const s=n.size??5,i=n.color??4500172,r=n.emissive??2245734,o=new t.SphereGeometry(s,16,12),a=new t.MeshStandardMaterial({color:i,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 iw extends W_{get zPriority(){return gu.DECAL}get syncZPosOffset(){return this.effectiveDepth}get geometricOffsetY(){return this.effectiveDepth}buildGeometry(){const{width:e,height:n}=this.component.state,s=Math.abs(e)||1,i=Math.abs(n)||1,r=new t.PlaneGeometry(s,i);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,s=Math.abs(e)||1,i=Math.max(2,.04*Math.min(n,s));this.object3d.add(sw(this.component,{size:i,position:[n/2-i,i,-s/2+i]}))}}const rw={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/decal"};let ow=class extends(Ry(Pc(Tc))){buildRealObject(){return new iw(this)}get nature(){return rw}};ow=tg([Ny("decal")],ow);class aw extends Mu{getObject3dInstance(){return new t.Group}get allowedGizmoModes(){return this.component.isGroup?.()?["translate"]:null}}const cw="#dde2e8",lw="#9c9c9c",hw="#e8e8ec",dw=.35;function uw(e,n,s,i,r){if(!n.visible)return new t.MeshStandardMaterial({transparent:!0,opacity:0,depthWrite:!1});const o=n.alpha*s,a="wall"===i?cw:"floor"===i?lw:hw,c=new t.MeshStandardMaterial({metalness:0,roughness:"wall"===i?.6:.85,transparent:o<1,opacity:o,side:r?t.BackSide:t.DoubleSide});return function(t,e,n,s,i,r){if("string"==typeof n&&n&&"transparent"!==n)t.color.set(n);else{if(n&&"object"==typeof n){const s=!r,o=Mu.buildFillStyleTexture(e,n,{mirror:s,rotation:i});if(o)return t.map&&t.map.dispose(),t.map=o,void t.color.set("#ffffff")}t.color.set(s)}}(c,e,n.fillStyle,a,n.rotation,n.mirror),c}class pw extends aw{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,s=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,s=e.height)}const i=this.effectiveDepth||Math.min(n,s)||200,r=e.alpha??1,o=!1!==e.seeThrough,a={east:this._resolveFace("east",cw,!0,dw),west:this._resolveFace("west",cw,!0,dw),north:this._resolveFace("north",cw,!0,dw),south:this._resolveFace("south",cw,!0,dw),floor:this._resolveFace("floor",lw,!0,1),ceiling:this._resolveFace("ceiling",hw,!0,1)},c=[uw(this.component,a.east,r,"wall",o),uw(this.component,a.west,r,"wall",o),uw(this.component,a.ceiling,r,"ceiling",o),uw(this.component,a.floor,r,"floor",o),uw(this.component,a.south,r,"wall",o),uw(this.component,a.north,r,"wall",o)],l=new t.BoxGeometry(n,i,s),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,s,i));this.object3d.add(sw(this.component,{size:d,position:[n/2,i/2+d,-s/2]}))}_resolveFace(t,e,n,s){const i=this.component.state,r=i.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:s,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 fw={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 mw=class extends(Ry(Pc(Tc))){buildRealObject(){return new pw(this)}get nature(){return fw}added(t){super.added?.(t),this.state.fitToBoard&&(this._syncFromRoot(!0),this._attachRootListener())}async ready(){await super.ready(),this.state.fitToBoard&&this._syncFromRoot(!1)}removed(t){this._detachRootListener(),super.removed?.(t)}dispose(){this._detachRootListener(),super.dispose?.()}onchange(t,e){"fitToBoard"in t&&(t.fitToBoard?(this._syncFromRoot(!0),this._attachRootListener()):this._detachRootListener()),super.onchange?.(t,e)}_syncFromRoot(t=!1){const e=this.rootModel;if(!e||e===this)return;const n=e.state;if(!n)return;const s={},i=Number.isFinite(n.width)?n.width:this.state.width,r=Number.isFinite(n.height)?n.height:this.state.height;i!==this.state.width&&(s.width=i),r!==this.state.height&&(s.height=r);const o=Number.isFinite(n.left)?n.left:0,a=Number.isFinite(n.top)?n.top:0;if(o!==this.state.left&&(s.left=o),a!==this.state.top&&(s.top=a),t){const t=this.state.depth;if(!("number"==typeof t&&Number.isFinite(t)&&t>0)){const e=Math.min(i,r);e!==t&&(s.depth=e)}}Object.keys(s).length>0&&this.set(s)}_attachRootListener(){if(this._onRootChange)return;const t=this.rootModel;t&&t!==this&&(this._onRootChange=t=>{("width"in t||"height"in t||"left"in t||"top"in t)&&this._syncFromRoot()},t.on?.("change",this._onRootChange))}_detachRootListener(){if(!this._onRootChange)return;const t=this.rootModel;t?.off?.("change",this._onRootChange),this._onRootChange=void 0}};function gw(t,e){return"none"===t?0:t.endsWith("arrow")?1.5*e:0}function yw(e,n,s,i){const r=[];for(let o=1;o<=i;o++){const a=o/i,c=1-a;r.push(new t.Vector3(c*c*e.x+2*c*a*n.x+a*a*s.x,c*c*e.y+2*c*a*n.y+a*a*s.y,c*c*e.z+2*c*a*n.z+a*a*s.z))}return r}mw=tg([Ny("backdrop")],mw);class bw 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 s=[];s.push(e[0]);for(let i=1;i<e.length;i++){const r=e[i-1],o=e[i],a=e[i+1];if(!a){s.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();s.push(b),s.push(...yw(b,o,v,8))}return s}_buildLine(){const e=this.smoothedPath;if(e.length<2)return;const{strokeStyle:n,lineWidth:s=2,alpha:i=1,lineDash:r,begin:o="none",beginSize:a="size5",end:c="none",endSize:l="size5"}=this.component.state,h=Math.max(s,1),d="string"==typeof n&&"transparent"!==n?su(n):"#000000",u=new t.Color(d),p=this._getResolution(),f=o,m=c,g=gw(f,h),y=gw(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(),E=[...e];g>0&&(E[0]=b.clone().add(_.clone().multiplyScalar(g))),y>0&&(E[E.length-1]=v.clone().add(x.clone().multiplyScalar(y)));const A=new S;A.setPositions(E.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:i<1,opacity:i,resolution:p,dashed:!!k,dashSize:k?.dashSize??1,gapSize:k?.gapSize??1,dashScale:1});if(this._line2=new w(A,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,i,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,i,p)}}}_placeTip(t,e,n,s,i,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(s),e.transparent=i<1,e.opacity=i}else if(t.line2){const e=t.line2.material;e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution.copy(r)}else t.group&&t.group.traverse(t=>{if(t.material){const e=t.material;e.color&&e.color.copy(s),e.transparent=i<1,e.opacity=i,e.resolution&&e.resolution.copy(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 s=this.object3d,{width:i=0,height:r=0}=e.parent?.bounds??{},{x:o,y:a}=e.center,c=s.position,l=s.rotation,h=s.scale,d=this.position;if(Math.abs(c.x-d.x)<.001&&Math.abs(c.y-d.y)<.001&&Math.abs(c.z-d.z)<.001&&Math.abs(l.x)<.001&&Math.abs(l.y)<.001&&Math.abs(l.z)<.001&&Math.abs(h.x-1)<.001&&Math.abs(h.y-1)<.001&&Math.abs(h.z-1)<.001)return;const u=bw.computeBakedPath(n,{x:o,y:a},{width:i,height:r},s);this._suppressOnchange=!0,e.set({rotation:0,rotationX:0,rotationY:0,zPos:0}),e.mutatePath(null,()=>u),this._suppressOnchange=!1,this.update()}static computeBakedPath(e,n,s,i){const r=s.width,o=s.height,a=n.x,c=n.y;return i.updateMatrixWorld(!0),e.map(e=>{const n=new t.Vector3(e.x-a,e.z||0,e.y-c).applyMatrix4(i.matrixWorld),s={x:n.x+r/2,y:n.z+o/2};return Math.abs(n.y)>.001&&(s.z=n.y),s})}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 vw extends bw{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center,i=this.component,r=i.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=i.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((i,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(i.x-n,i.z||r+(o-r)*c,i.y-s)})}}Jp("line",t=>new vw(t));class _w extends bw{get worldPath(){const e=this.component.path;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center;return e.map(e=>new t.Vector3(e.x-n,e.z||0,e.y-s))}}Jp("polyline",t=>new _w(t));class xw extends bw{get worldPath(){const e=this.component.drawPath;if(!e||e.length<2)return[];const{x:n,y:s}=this.component.center,i=this.component,r=i.fromEnd?.component?._realObject?.object3d?.position?.y??0,o=i.toEnd?.component?._realObject?.object3d?.position?.y??0;return e.map((i,a)=>{const c=e.length>1?a/(e.length-1):0;return new t.Vector3(i.x-n,i.z||r+(o-r)*c,i.y-s)})}}function ww(t,e=16){let n=Math.max(e,1);for(;n<t;)n*=2;return n}Jp("ortholine",t=>new xw(t)),Jp("group",t=>new aw(t));class Mw{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=ww(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=ww(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=Mw;n._p.set(e.position.x,e.position.y,e.position.z);const s=e.rotation;n._e.set(s?.x??0,s?.y??0,s?.z??0),n._q.setFromEuler(n._e);const i=e.scale;"number"==typeof i?n._s.set(i,i,i):n._s.set(i?.x??1,i?.y??1,i?.z??1),n._m.compose(n._p,n._q,n._s),this._mesh.setMatrixAt(t,n._m)}_writeColor(t,e){Mw._c.set(e),this._mesh.setColorAt(t,Mw._c)}}function Sw(t,e,n){const s=Math.max(1,Math.floor(t.x??1)),i=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<i;t++)for(let e=0;e<r;e++)for(let n=0;n<s;n++)u.push({position:{x:l+n*o,y:h+t*a,z:d+e*c}});return u}Mw._m=new t.Matrix4,Mw._p=new t.Vector3,Mw._q=new t.Quaternion,Mw._e=new t.Euler,Mw._s=new t.Vector3,Mw._c=new t.Color;class Ew extends Mu{build(){super.build()}update(){}}const Aw={far:1e5,fov:80,near:1,zoom:1};class kw extends Mu{build(){super.build()}update(){super.update(),this.updateCamera()}getObject3dInstance(){return new t.PerspectiveCamera}updateCamera(){const{near:t=Aw.near,far:e=Aw.far,fov:n=Aw.fov,zoom:s=Aw.zoom}=this.component.state;this.object3d.far=e,this.object3d.fov=n,this.object3d.near=t,this.object3d.zoom=s}}class Cw extends W_{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 Tw 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 Ow=new Set(["cx","cy","cz","zPos","left","top","width","height","depth","lineWidth","rotationX","rotationY","rotation","scale","hidden","alpha","material3d","screenFixed"]);class Pw 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 s=Id(this.component.state.material3d),i=new t.PlaneGeometry(1,1);i.rotateX(-Math.PI/2),this.object3d.geometry=i;const r=F_(this.component),o=new t.MeshStandardMaterial({map:r});Rd(o,s),o.transparent=!0,this.object3d.material=o,this.object3d.castShadow=s.castShadow,this.object3d.receiveShadow=s.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&&($_(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(!Ow.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 Iw={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 Dw=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:s,threed:i}=this.state;let{width:r,height:o}=this.bounds;if(r=Math.floor(r),o=Math.floor(o),i){if(this._capability.isInitialized||this.init_scene3d(),this._capability.noSupportWebgl)return void this._capability.showWebglNoSupportText(t,this.state.width,this.state.height);if(!this._capability.renderer3d)return;this._capability.renderThreeD();const i=this._capability.domElement;if(!i||!i.width||!i.height)return;t.drawImage(i,0,0,i.width,i.height,e,n,r,o),s&&this._capability.showDebugFPS(t)}else super.postrender(t)}dispose(){this._capability.dispose(),super.dispose()}get layout(){return Lc.get("three")}get nature(){return Iw}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()}};Dw=tg([Ny("3d-container")],Dw),Zp(t=>new B_(t));const zw=["x","y","z"],Rw=["Capacity","Holdable","Transferable","FlowNode"],jw=Object.freeze({Transferable:["Capacity","FlowNode"]}),Lw=["S","M","L","XL"],Fw=[8,12,16,24,32,48],Nw=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function $w(t,e){const n="shape"in t?t.shape:void 0,s=n?.extrusion?.section,i="revolve"===n?.provider&&!!n.revolution||"extrude"===n?.provider&&("ellipse"===s?.kind||"rectangle"===s?.kind&&Object.values(s.corner??{}).some(t=>t>0));if(!i||"full"===e)return t.segments;const r=t.segments??12,o=Math.ceil(r/("medium"===e?2:4));return Math.min(r,Fw.find(t=>t>=o)??r)}function Hw(t,e){if("full"===e)return t;let n=!1;const s=t.geometry.map(t=>{const s=$w(t,e);return s===t.segments?t:(n=!0,{...t,segments:s})});return n?{...t,geometry:s}:t}class Bw extends Error{code;path;details;constructor(t,e,n,s){super(`${t}: ${e}: ${n}`),this.name="FigureContractError",this.code=t,this.path=e,void 0!==s&&(this.details=s)}}const Yw=Object.freeze({x:["y","z"],y:["z","x"],z:["x","y"]}),Gw=1e-6,Vw=256,Uw=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function Ww(t,e){return t<e?`${t}~${e}`:`${e}~${t}`}const qw=t=>Yw[t],Xw=t=>!!t.corner&&Object.values(t.corner).some(t=>(t??0)>0);function Kw(t,e){const[n,s]=qw(e);if("rectangle"===t.kind){const e=[];for(const i of[n,s]){const n=t.size[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`size.${i}`})}if(!t.corner)return e;for(const i of[n,s]){const n=t.corner[i];"number"==typeof n&&Number.isFinite(n)?n<0?e.push({code:"CORNER_NEGATIVE",axis:i}):Number.isFinite(t.size[i])&&n>t.size[i]/2+Gw&&e.push({code:"CORNER_TOO_LARGE",axis:i,max:t.size[i]/2}):e.push({code:"NON_FINITE",at:`corner.${i}`})}return e.length||t.corner[n]>0==t.corner[s]>0||e.push({code:"CORNER_ONE_AXIS",axis:t.corner[n]>0?n:s}),e}if("ellipse"===t.kind){const e=[];for(const i of[n,s]){const n=t.radius[i];"number"==typeof n&&Number.isFinite(n)?n>0||e.push({code:"SIZE_NOT_POSITIVE",axis:i}):e.push({code:"NON_FINITE",at:`radius.${i}`})}return e}return function(t,e){const[n,s]=qw(e),i=[],r=new Set;for(const e of t){"string"==typeof e.id&&Uw.test(e.id)?r.has(e.id)?i.push({code:"DUPLICATE_POINT_ID",point:e.id}):r.add(e.id):i.push({code:"BAD_POINT_ID",point:String(e.id)});for(const t of[n,s])"number"==typeof e[t]&&Number.isFinite(e[t])||i.push({code:"NON_FINITE",at:`${e.id}.${t}`})}t.length<3&&i.push({code:"TOO_FEW_POINTS",count:t.length});t.length>Vw&&i.push({code:"TOO_MANY_POINTS",count:t.length,limit:Vw});if(i.length)return i;const o=t.length,a=function(t,e){const[n,s]=qw(e);return t.map(t=>[t[n],t[s]])}(t,e),c=e=>Ww(t[e].id,t[(e+1)%o].id),l=Gw,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&&i.push({code:"ZERO_LENGTH_SIDE",side:c(e)})}),i.length)return i;for(let t=0;t<o;t++){const e=a[t],n=a[(t+1)%o],s=a[(t+2)%o],r=(n[0]-e[0])*(s[1]-n[1])-(n[1]-e[1])*(s[0]-n[0]),d=(n[0]-e[0])*(s[0]-n[0])+(n[1]-e[1])*(s[1]-n[1]);Math.abs(r)<=l*h[t]&&d<0&&i.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=Zw(a[t],a[(t+1)%o],a[e],a[(e+1)%o],l);n&&i.push({code:"cross"===n?"SIDES_CROSS":"SIDES_TOUCH",sides:[c(t),c(e)]})}if(i.length)return i;Math.abs(function(t){let e=0;for(let n=0;n<t.length;n++){const[s,i]=t[n],[r,o]=t[(n+1)%t.length];e+=s*o-r*i}return e}(a))/2<=l&&i.push({code:"ZERO_AREA"});return i}(t.points,e)}const Qw=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]);function Jw(t,e,n){const s=n[0]-e[0],i=n[1]-e[1],r=s*s+i*i,o=r?Math.max(0,Math.min(1,((t[0]-e[0])*s+(t[1]-e[1])*i)/r)):0;return Math.hypot(t[0]-e[0]-o*s,t[1]-e[1]-o*i)}function Zw(t,e,n,s,i){const r=Qw(n,s,t),o=Qw(n,s,e),a=Qw(t,e,n),c=Qw(t,e,s),l=Math.hypot(e[0]-t[0],e[1]-t[1]),h=(t,e,n)=>t>i*n&&e<-i*n||t<-i*n&&e>i*n;if(h(r,o,Math.hypot(s[0]-n[0],s[1]-n[1]))&&h(a,c,l))return"cross";return Math.min(Jw(t,n,s),Jw(e,n,s),Jw(n,t,e),Jw(s,t,e))<=i?"touch":null}function tM(t,e){const[n,s]=qw(e);if("ellipse"===t.kind)return[{id:"round",shape:"curved"}];if("rectangle"===t.kind){const[e,i]=[n,s].sort(),r=[e,i].flatMap(t=>[`${t}-`,`${t}+`]).map(t=>({id:t,shape:"flat"}));if(!Xw(t))return r;const o=["-","+"].flatMap(t=>["-","+"].map(n=>({id:`corner:${e}${t}${i}${n}`,shape:"curved"})));return[...r,...o]}const i=t.points;return i.map((t,e)=>{const n=i[(e+1)%i.length];return{id:Ww(t.id,n.id),shape:"flat",from:t.id,to:n.id}})}function eM(t,e,n){const[s,i]=qw(e);if("polygon"===t.kind)return{refused:"SECTION_KIND"};const r=[s,i].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={[s]:(o(`${s}-`)-o(`${s}+`))/2,[i]:(o(`${i}-`)-o(`${i}+`))/2};if("rectangle"===t.kind){const e={[s]:a(s,t.size[s]),[i]:a(i,t.size[i])};if(!(e[s]>0&&e[i]>0))return{refused:"NO_ROOM_INSIDE"};if(!Xw(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={[s]:n(s),[i]:n(i)};return{section:{kind:"rectangle",size:e,...r[s]>0&&r[i]>0?{corner:r}:{}},centre:c}}const l={[s]:a(s,2*t.radius[s])/2,[i]:a(i,2*t.radius[i])/2};return l[s]>0&&l[i]>0?{section:{kind:"ellipse",radius:l},centre:c}:{refused:"NO_ROOM_INSIDE"}}const nM=(t,e)=>Object.fromEntries(zw.map(n=>[n,n===t?e:0]));function sM(t,e,n){const[s,i]=Yw[e];if("polygon"!==t.kind){const t=n.id.slice(0,-1);return nM(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[s]-r[s],c=o[i]-r[i],l=Math.hypot(a,c),h={x:0,y:0,z:0};return h[s]=c/l||0,h[i]=-a/l||0,h}const iM=(t,e,n)=>{throw new Bw(t,e,n)},rM=t=>Array.isArray(t)&&3===t.length&&1===t[0]&&0===t[1]&&0===t[2],oM=Object.freeze({x:["left","right"],y:["bottom","top"],z:["back","front"]}),aM=["rectangle","ellipse","polygon","portal"],cM=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function lM(t,e){const n=t??{},s=n.axis;zw.includes(s)||iM("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`);const i=n.section;aM.includes(i)||iM("PARAM",e,`section is ${aM.join(", ")}, not ${String(n.section)}`);const r=[...Yw[s]].sort(),[o,a]=r,c="round"===n.corner;void 0===n.corner||c&&"rectangle"===i||iM("PARAM",e,"corner is `round`, and only a rectangle has corners");const l="polygon"===i?String(n.points??"").split("."):[];"polygon"===i?((l.length<3||l.some(t=>!cM.test(t)))&&iM("PARAM",e,"a drawn section names three points or more, joined by `.`"),new Set(l).size!==l.length&&iM("PARAM",e,"a point is named twice")):void 0!==n.points&&iM("PARAM",e,"only a drawn section has points");let h=2;const d=()=>h++,u={start:0,length:1};let p;if("rectangle"!==i&&"ellipse"!==i&&"portal"!==i||(u.across={[o]:d(),[a]:d()}),c&&(u.corner={[o]:d(),[a]:d()}),"portal"===i&&(u.jamb=d(),u.head=d()),"polygon"===i&&(u.point=Object.fromEntries(l.map(t=>[t,{[o]:d(),[a]:d()}]))),void 0!==n.cavity){"rectangle"!==i&&"ellipse"!==i&&iM("SECTION_KIND",e,`a ${i} section has no inside yet (ADR-0100 stage 4)`);const t=t=>{const s=n[t];return"open"!==s&&"closed"!==s&&iM("PARAM",e,`${t} is open or closed`),s};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"]||iM("PARAM",e,"the ends of an inside need the inside");return{axis:s,plane:r,section:i,points:l,rounded:c,...p?{cavity:p}:{},arg:u,count:h}}const hM=(t,e=1)=>[{arg:t,k:e}];function dM(t,e){const n={lo:[{arg:0,k:1}],hi:[{arg:0,k:1},{arg:1,k:1}]};if(!e)return n;const s=t.args?.[0],i=t.args?.[1],r=e.nodes.find(t=>t.outputs&&Object.values(t.outputs).includes(s));return"mul@1"!==r?.op||2!==r.args.length||r.args[0]!==i||-.5!==e.constants.find(t=>t.id===r.args[1])?.value?n:{lo:[{arg:1,k:-.5}],hi:[{arg:1,k:.5}]}}function uM(t,e){const n=lM(t.params,t.id),[s,i]=n.plane,r={},o={},a={},[c,l]=oM[n.axis],h=dM(t,e);if(r[n.axis]=hM(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[s,i])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[s,i])r[t]=hM(d[t],u),o[t]={arg:d[t],k:u};if(void 0!==t.args?.[d[s]]&&t.args[d[s]]===t.args[d[i]]&&(o[i]={arg:d[i],k:u,sameAs:s}),"portal"===n.section){const[t,e]=oM[s],[c,l]=oM[i];return a[t]={axis:s,normal:-1,plane:[{arg:d[s],k:-.5}]},a[e]={axis:s,normal:1,plane:[{arg:d[s],k:.5}]},a[c]={axis:i,normal:-1,plane:[]},a[l]={axis:i,normal:1,plane:[{arg:d[i],k:1}]},a[`opening-${t}`]={axis:s,normal:1,plane:[{arg:d[s],k:-.5},{arg:n.arg.jamb,k:1}]},a[`opening-${e}`]={axis:s,normal:-1,plane:[{arg:d[s],k:.5},{arg:n.arg.jamb,k:-1}]},a[`opening-${l}`]={axis:i,normal:-1,plane:[{arg:d[i],k:1},{arg:n.arg.head,k:-1}]},{measure:r,edit:o,faces:a,kind:"portal"}}const p="ellipse"===n.section?1:.5,f="ellipse"===n.section?{contact:"line"}:{};for(const t of[s,i]){const[e,n]=oM[t];a[e]={axis:t,normal:-1,plane:[{arg:d[t],k:-p}],...f},a[n]={axis:t,normal:1,plane:[{arg:d[t],k:p}],...f}}if(n.cavity){const t=n.arg.wall;for(const e of[s,i]){const[n,s]=oM[e];a[`inside-${n}`]={axis:e,normal:1,plane:[{arg:d[e],k:-p},{arg:t[`${e}-`],k:1}],...f},a[`inside-${s}`]={axis:e,normal:-1,plane:[{arg:d[e],k:p},{arg:t[`${e}+`],k:-1}],...f}}void 0!==n.arg.startClosed&&(a[`inside-${c}`]={axis:n.axis,normal:1,plane:[...h.lo,{arg:n.arg.startClosed,k:1}]}),void 0!==n.arg.endClosed&&(a[`inside-${l}`]={axis:n.axis,normal:-1,plane:[...h.hi,{arg:n.arg.endClosed,k:-1}]})}return{measure:r,edit:o,faces:a,kind:n.section}}function pM(t,e){const n=t??{},s=n.axis;return zw.includes(s)||iM("PARAM",e,`axis is x, y or z, not ${String(n.axis)}`),"half-ellipse"!==n.profile&&"taper"!==n.profile&&iM("PARAM",e,`profile is half-ellipse or taper, not ${String(n.profile)}`),{axis:s,profile:n.profile,count:"taper"===n.profile?4:2}}function fM(t,e){const n=pM(t.params,t.id),[s,i]=[...Yw[n.axis]].sort(),r={},o={};if("half-ellipse"===n.profile)return r[n.axis]=hM(1,2),o[n.axis]={arg:1,k:2},r[s]=r[i]=hM(0,2),o[s]={arg:0,k:2},o[i]={arg:0,k:2,sameAs:s},{measure:r,edit:o,faces:{},kind:"sphere"};const[a,c]=oM[n.axis];r[n.axis]=hM(1),o[n.axis]={arg:1,k:1};r[s]=r[i]=[{arg:2,k:2},{arg:3,k:2}],o[s]={arg:3,k:2,with:[2]},o[i]={arg:3,k:2,with:[2],sameAs:s};const l=dM(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 mM(t,e){const n=t??{};"polygon"!==n.section&&iM("PARAM",e,`a loft starts from a drawn section, not ${String(n.section)}`),void 0===n.corner&&void 0===n.cavity||iM("PARAM",e,"a loft has no corners and no inside");const s=lM(n,e),[i,r]=s.plane;return{...s,apex:{[i]:s.count,[r]:s.count+1},count:s.count+2}}function gM(t,e){const n=mM(t.params,t.id),s={},i={},[r]=oM[n.axis];s[n.axis]=hM(1),i[n.axis]={arg:1,k:1};for(const t of n.plane)s[t]="profile",i[t]={refused:"SECTION_CORNERS"};return{measure:s,edit:i,faces:{[r]:{axis:n.axis,normal:-1,plane:dM(t,e).lo}},kind:"pyramid"}}function yM(t,e){return"extrude@1"===t?.op?uM(t,e):"revolve@1"===t?.op?fM(t,e):"loft@1"===t?.op?gM(t,e):void 0}const bM=(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 vM(t,e,n){const s=zw.find(t=>t!==e&&t!==n),[i,r]=Yw[s];let o=0;for(let e=0;e<t.length;e++){const n=t[e],s=t[(e+1)%t.length];o+=n[i]*s[r]-s[i]*n[r]}return o>0?t:[t[0],...t.slice(1).reverse()]}function _M(t,e){const[n,s]=Yw[e];let i=0;const r=t.points;for(let t=0;t<r.length;t++){const e=r[t],o=r[(t+1)%r.length];i+=e[n]*o[s]-o[n]*e[s]}return i}function xM(t,e,n){const s=lM(n.params,e),[i,r]=s.plane,o=t[0],a=t[1];a>0||iM("GEOMETRY_DOMAIN",e,`a push of positive length required, not ${a}`);const c={start:o,length:a};let l;if("polygon"===s.section){const e=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[r]:t[s.arg.point[e][r]]}));e.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${r}`]=t[r]}),l={kind:"polygon",points:e}}else if("portal"===s.section){const n=t[s.arg.across[i]],o=t[s.arg.across[r]],a=t[s.arg.jamb],h=t[s.arg.head];n>0&&o>0&&a>0&&h>0&&2*a<n&&h<o||iM("GEOMETRY_DOMAIN",e,"positive measures, jambs narrower than half the width and a head lower than the height required"),Object.assign(c,{[`size.${i}`]:n,[`size.${r}`]:o,jamb:a,head:h}),l=function(t,e,n,s,i,r){const o=-n/2,a=n/2,c=o+i,l=a-i,h=s-r,d=(n,s,i)=>({id:n,[t]:s,[e]:i});return{kind:"polygon",points:vM([d("p1",o,0),d("p2",o,s),d("p3",a,s),d("p4",a,0),d("p5",l,0),d("p6",l,h),d("p7",c,h),d("p8",c,0)],t,e)}}(i,r,n,o,a,h)}else{const e={[i]:t[s.arg.across[i]],[r]:t[s.arg.across[r]]},n="ellipse"===s.section?"radius":"size";if(c[`${n}.${i}`]=e[i],c[`${n}.${r}`]=e[r],"ellipse"===s.section)l={kind:"ellipse",radius:e};else if(l={kind:"rectangle",size:e},s.rounded){const n={[i]:t[s.arg.corner[i]],[r]:t[s.arg.corner[r]]};c[`corner.${i}`]=n[i],c[`corner.${r}`]=n[r],(n[i]>0||n[r]>0)&&(l={kind:"rectangle",size:e,corner:n})}}const h=Kw(l,s.axis);h.length&&iM("GEOMETRY_DOMAIN",e,`the section is not valid: ${h.map(t=>t.code).join(", ")}`),"polygon"!==l.kind||"polygon"!==s.section||_M(l,s.axis)>0||iM("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const d={axis:s.axis,section:l,start:o,end:o+a};let u;if(s.cavity){const n=Object.fromEntries(Object.entries(s.arg.wall).map(([e,n])=>[e,t[n]]));u={id:s.cavity.id,wall:n,start:"open"===s.cavity.start?"open":{closed:t[s.arg.startClosed]},end:"open"===s.cavity.end?"open":{closed:t[s.arg.endClosed]}};for(const[t,e]of Object.entries(n))c[`wall.${t}`]=e;"open"!==u.start&&(c["closed.start"]=u.start.closed),"open"!==u.end&&(c["closed.end"]=u.end.closed);const i=function(t,e=[]){const{axis:n,section:s,start:i,end:r}=t;if(!(r-i>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=eM(s,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-i-e(o.start)-e(o.end)>0))return{refused:{code:"CAVITY_NO_LENGTH",cavity:o.id}}}const c=tM(s,n),l=[{id:"start-face",kind:"plane",normal:nM(n,-1),..."open"===o?.start?{open:!0}:{}},{id:"end-face",kind:"plane",normal:nM(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:sM(s,n,t)}:{id:`side-face:${t.id}`,kind:"curved"}),l.push({id:`edge:start:${t.id}`,kind:"edge"},{id:`edge:end:${t.id}`,kind:"edge"});if("polygon"===s.kind)for(const t of s.points)l.push({id:`edge:${t.id}`,kind:"edge"});else if("rectangle"===s.kind&&!c.some(t=>"curved"===t.shape)){const[t,e]=[...Yw[n]].sort();for(const n of["-","+"])for(const s of["-","+"])l.push({id:`edge:${t}${n}${e}${s}`,kind:"edge"})}if(o&&a){for(const t of tM(a,n)){const e=`cavity-wall:${o.id}:${t.id}`;if("curved"===t.shape)l.push({id:e,kind:"curved"});else{const s=sM(a,n,t);l.push({id:e,kind:"plane",normal:{x:-s.x||0,y:-s.y||0,z:-s.z||0}})}}"open"!==o.start&&l.push({id:`cavity-start:${o.id}`,kind:"plane",normal:nM(n,1)}),"open"!==o.end&&l.push({id:`cavity-end:${o.id}`,kind:"plane",normal:nM(n,-1)})}return l.push({id:"centre",kind:"point"}),{features:l}}(d,[u]);"refused"in i&&iM("GEOMETRY_DOMAIN",e,`the inside is not valid: ${i.refused.code}${"refused"in i.refused?` ${i.refused.refused}`:""}`)}return{provider:"extrude",dimensions:c,extrusion:d,...u?{cavity:u}:{},faces:bM(uM(n).faces,t)}}function wM(t,e,n){const s=pM(n.params,e),i=bM(fM(n).faces,t);if("half-ellipse"===s.profile){const[n,r]=t;return n>0&&r>0||iM("GEOMETRY_DOMAIN",e,"positive radii required"),{provider:"revolve",dimensions:{radial:n,axial:r},revolution:{axis:s.axis,profile:{kind:"half-ellipse",radial:n,axial:r}},faces:i}}const[r,o,a,c]=t;return o>0&&a>=0&&c>=0&&a+c>0||iM("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:s.axis,profile:{kind:"taper",start:r,end:r+o,startRadius:a,endRadius:c}},faces:i}}function MM(t,e,n){const s=mM(n.params,e),[i,r]=s.plane,o=t[0],a=t[1];a>0||iM("GEOMETRY_DOMAIN",e,`a loft of positive length required, not ${a}`);const c={start:o,length:a},l=s.points.map(e=>({id:e,[i]:t[s.arg.point[e][i]],[r]:t[s.arg.point[e][r]]}));l.forEach(t=>{c[`point.${t.id}.${i}`]=t[i],c[`point.${t.id}.${r}`]=t[r]});const h={kind:"polygon",points:l},d=Kw(h,s.axis);d.length&&iM("GEOMETRY_DOMAIN",e,`the section is not valid: ${d.map(t=>t.code).join(", ")}`),_M(h,s.axis)>0||iM("SECTION_WINDING",e,"a drawn section runs counter-clockwise seen from its push axis; write it with normalizeFigureSection");const u={[i]:t[s.apex[i]],[r]:t[s.apex[r]]};return Number.isFinite(u[i])&&Number.isFinite(u[r])||iM("GEOMETRY_DOMAIN",e,"a finite apex required"),c[`apex.${i}`]=u[i],c[`apex.${r}`]=u[r],{provider:"loft",dimensions:c,loft:{axis:s.axis,section:h,start:o,end:o+a,apex:u},faces:bM(gM(n).faces,t)}}function SM(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 EM={"extrude@1":{ports:["shape"],params:["frame","axis","section"],optionalParams:["points","corner","cavity","cavity-start","cavity-end"],types(t,e,n){const s=lM(n.params,e);return t.length===s.count&&t.every(rM)||iM("TYPE",e,`a ${s.section} push takes ${s.count} lengths, not ${t.length}`),[SM("extrude",n,uM(n).faces)]},run:(t,e,n)=>[xM(t,e,n)]},"revolve@1":{ports:["shape"],params:["frame","axis","profile"],types(t,e,n){const s=pM(n.params,e);return t.length===s.count&&t.every(rM)||iM("TYPE",e,`a ${s.profile} turn takes ${s.count} lengths, not ${t.length}`),[SM("revolve",n,fM(n).faces)]},run:(t,e,n)=>[wM(t,e,n)]},"loft@1":{ports:["shape"],params:["frame","axis","section","points"],types(t,e,n){const s=mM(n.params,e);return t.length===s.count&&t.every(rM)||iM("TYPE",e,`a loft of ${s.points.length} points takes ${s.count} lengths, not ${t.length}`),[SM("loft",n,gM(n).faces)]},run:(t,e,n)=>[MM(t,e,n)]}};function AM(t){const e={};if(t.extrusion){const n=t.extrusion,[s,i]=Yw[n.axis];e[n.axis]={min:n.start,max:n.end};const r=n.section;for(const t of[s,i])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 Yw[n.axis]){const s=[...n.section.points.map(e=>e[t]),n.apex[t]];e[t]={min:Math.min(...s),max:Math.max(...s)}}return e}const n=t.revolution,[s,i]=Yw[n.axis];if("half-ellipse"===n.profile.kind){e[n.axis]={min:-n.profile.axial,max:n.profile.axial};for(const t of[s,i])e[t]={min:-n.profile.radial,max:n.profile.radial}}else{const t=Math.max(n.profile.startRadius,n.profile.endRadius);e[n.axis]={min:n.profile.start,max:n.profile.end};for(const n of[s,i])e[n]={min:-t,max:t}}return e}function kM(t,e){"string"!=typeof t&&CM("PARAM",e,"layout required"),t.startsWith("L")||CM("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)))&&CM("PARAM",e,"layout is six groups of term counts, each with one candidate or more"),n}const CM=(t,e,n)=>{throw new Bw(t,e,n)},TM={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]},OM=[1,0,0],PM=[0,0,0],IM=[0,1,0],DM={kind:"count"},zM={kind:"flag"};TM.count=[DM,1];const RM=(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 jM(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||CM("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||CM("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||CM("SCHEMA",s,`unknown ${i}`)}function LM(t,e){return"string"==typeof t&&/^[a-zA-Z][a-zA-Z0-9_.-]*$/.test(t)||CM("ID",e,"invalid id"),t}function FM(t,e){return"number"==typeof t&&Number.isFinite(t)||CM("NON_FINITE",e,String(t)),t}function NM(t,e){return Object.hasOwn(TM,t)||CM("UNIT",e,String(t)),TM[t]}function $M(t,e,n){(t.length!==e.length||t.some((t,n)=>!RM(t,e[n])))&&CM("TYPE",n,`expected ${JSON.stringify(e)}, got ${JSON.stringify(t)}`)}const HM={"add@1":{ports:["value"],types:(t,e)=>(2===t.length&&t.every(Array.isArray)&&RM(t[0],t[1])||CM("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)||CM("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)||CM("TYPE",e,"two scalar arguments"),[t[0].map((e,n)=>e-t[1][n])]),run:([t,e],n)=>(0===e&&CM("DOMAIN",n,"zero denominator"),[t/e])},"sin@1":{ports:["value"],types:(t,e)=>($M(t,[IM],e),[PM]),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=>RM(e,t[0])))&&CM("TYPE",e,"geometric mean needs two or three scalars of the same dimension"),[t[0]]),run:(t,e)=>(t.some(t=>t<0)&&CM("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))&&CM("TYPE",e,"x and at least two (at, value) key pairs, all scalars");for(let n=1;n<t.length;n+=2)RM(t[n],t[0])||CM("TYPE",e,`key ${(n-1)/2}: at must have the dimension of x`),RM(t[n+1],t[2])||CM("TYPE",e,`key ${(n-1)/2}: every value must have one dimension`);return[t[2]]},run:(t,e)=>{const n=t[0],s=(t.length-1)/2,i=e=>t[1+2*e],r=e=>t[2+2*e];for(let t=1;t<s;t++)i(t)>i(t-1)||CM("DOMAIN",e,`keys out of order: at[${t}] = ${i(t)} is not after at[${t-1}] = ${i(t-1)}`);if(n<=i(0))return[r(0)];if(n>=i(s-1))return[r(s-1)];let o=0;for(;o<s-2&&i(o+1)<=n;)o++;const a=(n-i(o))/(i(o+1)-i(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)&&RM(t[0],t[1])||CM("TYPE",e,"at-least compares two scalars of the same dimension"),[zM]),run:([t,e])=>[t>=e]},"max@1":{ports:["value"],types:(t,e)=>((t.length<2||!t.every(Array.isArray)||!t.every(e=>RM(e,t[0])))&&CM("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=>RM(e,t[0])))&&CM("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 s=kM(n.params.layout,e);let i=0;for(const n of s)for(const s of n){RM(t[i++],OM)||CM("TYPE",e,`candidate constant ${i-1} is a length`);for(let n=0;n<s;n++)RM(t[i++],OM)||CM("TYPE",e,`term value ${i-1} is a length`),RM(t[i++],PM)||CM("TYPE",e,`term ratio ${i-1} is a ratio`)}return i!==t.length&&CM("TYPE",e,`the layout takes ${i} arguments; ${t.length} were given`),Array(6).fill(OM)},run:(t,e,n)=>{const s=kM(n.params.layout,e);let i=0;return s.map((e,n)=>{const s=e.map(e=>{let n=t[i++];for(let s=0;s<e;s++)n+=t[i++]*t[i++];return n});return n%2==0?Math.min(...s):Math.max(...s)})}},"between@1":{ports:["length","center"],types:(t,e)=>($M(t,[OM,OM,OM,OM],e),[OM,OM]),run:([t,e,n,s],i)=>{(n<0||s<0)&&CM("DOMAIN",i,"negative margin");const r=e-t-n-s;return r>0||CM("NO_SPACE",i,`available=${e-t}; margins=${n+s}; deficit=${Math.max(0,-r)}; positive length required`),[r,(t+e+n-s)/2]}},"box@1":{ports:["xMin","xMax","yMin","yMax","zMin","zMax"],types:(t,e)=>($M(t,[OM,OM,OM],e),Array(6).fill(OM)),run:([t,e,n],s)=>([t,e,n].some(t=>!(t>0))&&CM("GEOMETRY_DOMAIN",s,"positive width,height,depth required"),[-t/2,t/2,-e/2,e/2,-n/2,n/2]),geometry:([t,e,n])=>({provider:"box@1",dimensions:{width:t,height:e,depth:n}})},"cylinder@1":{ports:["start","end","radialMin","radialMax"],types:(t,e)=>($M(t,[OM,OM],e),Array(4).fill(OM)),run:([t,e],n)=>(t>0&&e>0||CM("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}})}},BM=(t,e)=>({kind:"transform",from:t,to:e}),YM=()=>[[1,0,0],[0,1,0],[0,0,1]],GM=t=>t[0].map((e,n)=>t.map(t=>t[n])),VM=(t,e)=>t.reduce((t,n,s)=>t+n*e[s],0),UM=(t,e,n,s)=>0+t[0]*e+t[1]*n+t[2]*s,WM=(t,e)=>3===t.length&&3===e.length?[UM(t[0],e[0],e[1],e[2]),UM(t[1],e[0],e[1],e[2]),UM(t[2],e[0],e[1],e[2])]:t.map(t=>VM(t,e)),qM=(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=>GM(e).map(e=>VM(t,e)));const[n,s,i]=e;return t.map(t=>[UM(t,n[0],s[0],i[0]),UM(t,n[1],s[1],i[1]),UM(t,n[2],s[2],i[2])])},XM=(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]),KM=(t,e)=>({r:qM(t.r,e.r),t:XM(WM(t.r,e.t),t.t)}),QM=t=>{const e=GM(t.r);return{r:e,t:WM(e,t.t.map(t=>-t))}};function JM(t,e,n=[]){jM(t.params,e,n,t.id);for(const s of[...e,...n.filter(e=>Object.hasOwn(t.params,e))])LM(t.params[s],t.id)}function ZM(t,e,n){(t.length!==n||t.some(t=>"transform"!==t.kind))&&CM("TYPE",e,"rigid transforms required")}Object.assign(HM,{"fit-pitch@1":{ports:["layout"],types:(t,e)=>($M(t,[OM,OM,OM,OM,OM,PM,DM],e),[{kind:"layout"}]),run:([t,e,n,s,i,r,o],a)=>{t>=0&&e>=0&&n>=0&&s>0&&i>0&&r>=0&&r<=1&&Number.isSafeInteger(o)&&o>=0&&o<=1e4||CM("LAYOUT_DOMAIN",a,"invalid length, margins, extent, pitch, alignment or limit");const c=t-e-n,l=c<s?0:1+Math.floor((c-s)/i);l>o&&CM("RESOURCE_LIMIT",a,`count=${l}, limit=${o}`);const h=l?c-s-(l-1)*i:0;return[{centers:Array.from({length:l},(t,n)=>e+s/2+r*h+n*i),count:l}]}},"fixed-count@1":{ports:["layout"],types:(t,e)=>($M(t,[DM,OM,OM,OM,OM,PM,DM],e),[{kind:"layout"}]),run:([t,e,n,s,i,r,o],a)=>{if(Number.isSafeInteger(t)&&t>=0&&Number.isSafeInteger(o)&&o>=0&&o<=1e4&&e>=0&&n>=0&&s>=0&&i>0&&r>=0&&r<=1||CM("LAYOUT_DOMAIN",a,"invalid fixed count layout"),t>o&&CM("RESOURCE_LIMIT",a,"fixed count exceeds limit"),!t)return[{centers:[],count:0}];const c=e-n-s-i;return(c<0||t>1&&c/(t-1)<i)&&CM("NO_SPACE",a,"fixed count non-overlapping items do not fit"),[{centers:1===t?[n+i/2+r*c]:Array.from({length:t},(e,s)=>n+i/2+s*c/(t-1)),count:t}]}},"assembly@1":{ports:["assembly"],types:(t,e)=>(t.length&&!t.some(e=>"placed"!==e.kind&&"collection"!==e.kind||e.frame!==t[0].frame)||CM("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)||CM("AXIS",e,n.params.axis);const s=4===t.length;return!s||["x","y","z"].includes(n.params.riseAxis)&&n.params.riseAxis!==n.params.axis&&RM(t[3],OM)||CM("FRAME_TYPE",e,"a rise is a length along an axis other than the row's"),(3!==t.length&&!s||"layout"!==t[0].kind||"assembly"!==t[1].kind||"transform"!==t[2].kind||t[2].from!==t[1].frame)&&CM("FRAME_TYPE",e,"layout, assembly and compatible placement required"),[{kind:"collection",frame:t[2].to}]},run:([t,e,n,s],i,r)=>{t.count*e.members.length>1e4&&CM("RESOURCE_LIMIT",i,"expanded geometry count > 10000");const o=["x","y","z"].indexOf(r.params.axis),a=["x","y","z"].indexOf(r.params.riseAxis),c=[];for(let i=0;i<t.count;i++)for(const l of e.members){const e=[0,0,0];e[o]=t.centers[i],void 0!==s&&(e[a]=i*s);const h=[r.id,i,...l.path??[l.key]];c.push({id:JSON.stringify(h),path:h,key:l.key,index:i,shape:l.shape,pose:KM(KM(n,{r:YM(),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&&RM(t[1],DM)||CM("TYPE",e,"collection and count index required"),[{kind:"placed",frame:t[0].frame}]),run:([t,e],n,s)=>{const i=t.items.find(t=>t.index===e&&t.key===s.params.member);return i||CM("TARGET_ABSENT",n,`${s.params.member}[${e}]`),[{shape:i.shape,pose:i.pose}]}},"rigid@1":{ports:["pose"],params:["from","to"],types:(t,e,n)=>($M(t,[OM,OM,OM,IM,IM,IM],e),[BM(n.params.from,n.params.to)]),run:([t,e,n,s,i,r])=>{const o=Math.cos(s),a=Math.sin(s),c=Math.cos(i),l=Math.sin(i),h=Math.cos(r),d=Math.sin(r);return[{r:qM(qM([[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)=>($M(t,[PM,PM,PM,IM],e),[BM(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const r=Math.hypot(t,e,n);Math.abs(r-1)>1e-6&&CM("AXIS",i,"unit axis required");const o=t/r,a=e/r,c=n/r,l=Math.cos(s),h=Math.sin(s),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)=>($M(t,[PM,PM,PM,OM],e),[BM(n.params.from,n.params.to)]),run:([t,e,n,s],i)=>{const r=Math.hypot(t,e,n);return Math.abs(r-1)>1e-6&&CM("AXIS",i,"unit axis required"),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:[t/r*s,e/r*s,n/r*s]}]}},"compose@1":{ports:["pose"],types:(t,e)=>(ZM(t,e,2),t[1].to!==t[0].from&&CM("FRAME_TYPE",e,"composition intermediate frame mismatch"),[BM(t[1].from,t[0].to)]),run:([t,e])=>[KM(t,e)]},"attach@1":{ports:["pose"],types(t,e){ZM(t,e,3);const[n,s,i]=t;return n.from===s.to&&s.from===i.from||CM("FRAME_TYPE",e,"A O inverse(B) frame mismatch"),[BM(i.to,n.to)]},run:([t,e,n])=>[KM(KM(t,e),QM(n))]},"point@1":{ports:["point"],params:["frame"],types:(t,e,n)=>($M(t,[OM,OM,OM],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||CM("FRAME_TYPE",e,"point frame must match transform source"),[{kind:"point",frame:t[0].to}]),run:([t,e])=>[XM(WM(t.r,e),t.t)]},"distance@1":{ports:["length"],types:(t,e)=>(2===t.length&&"point"===t[0].kind&&RM(t[0],t[1])||CM("FRAME_TYPE",e,"distance requires points in same frame"),[OM]),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||CM("TYPE",e,"shape required");const s=Object.keys(t[0].faces);return[...s,"centre",..."revolve"!==t[0].provider||s.length?[]:["left","right","bottom","top","back","front"]].includes(n.params.name)||CM("UNKNOWN_FEATURE",e,n.params.name),[BM(n.params.frame,t[0].frame)]},run:([t],e,n)=>{const s=function(t,e){const n=AM(t),s=zw.map(t=>(n[t].min+n[t].max)/2);if("centre"===e)return s;const i=t.faces[e],r={x:0,y:1,z:2};if(i){const n=[...s];if(n[r[i.axis]]=i.at,t.loft)for(const e of Yw[t.loft.axis]){const s=t.loft.section.points.map(t=>t[e]);n[r[e]]=(Math.min(...s)+Math.max(...s))/2}if(e.startsWith("inside-")&&t.cavity&&t.extrusion){const e=t.extrusion,o=t.cavity,a=o.wall;for(const t of Yw[e.axis])t!==i.axis&&(n[r[t]]=s[r[t]]+(a[`${t}-`]-a[`${t}+`])/2);if(i.axis!==e.axis){const t=e.start+("open"===o.start?0:o.start.closed),s=e.end-("open"===o.end?0:o.end.closed);n[r[e.axis]]=(t+s)/2}}return n}if("half-ellipse"===t.revolution?.profile.kind){const t=Object.entries(oM).flatMap(([t,[e,n]])=>[[e,t,-1],[n,t,1]]).find(([t])=>t===e);if(!t)return;const i=[...s];return i[r[t[1]]]=t[2]<0?n[t[1]].min:n[t[1]].max,i}}(t,n.params.name);return s||CM("UNKNOWN_FEATURE",e,n.params.name),[{r:[[1,0,0],[0,1,0],[0,0,1]],t:s}]}},"place@1":{ports:["placed"],types:(t,e)=>(2===t.length&&"shape"===t[0].kind&&"transform"===t[1].kind&&t[0].frame===t[1].from||CM("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})}}),HM["member@1"]={...HM["place@1"],geometry:void 0},Object.assign(HM,EM);for(const[t,e]of Object.entries(HM))e.state="fit-pitch@1"===t||"fixed-count@1"===t?"refuses":"follows";const tS=[];for(const[t,e]of Object.entries(HM))e.pure=!tS.includes(t);const eS=["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(HM))e.pure&&eS.includes(t)&&(e.poseForm="run");function nS(t,e,n){return Array.isArray(e)?FM(t,n):"flag"===e.kind?("boolean"!=typeof t&&CM("FLAG",n,"boolean required"),t):"count"===e.kind?((!Number.isSafeInteger(t)||t<0)&&CM("COUNT",n,"nonnegative safe integer required"),t):("transform"===e.kind&&aS(t)?lS(t,n):"placed"===e.kind&&oS(t,"shape","pose")&&dS.has(t.shape)&&aS(t.pose)?lS(t.pose,n):(hS(t,n),"shape"===e.kind&&t&&"object"==typeof t&&dS.add(t)),t)}function sS(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++)sS(t[e]);else for(const e in t)sS(t[e]);return t}function iS(t,e){if(!t||"object"!=typeof t||Object.isFrozen(t))return t;let n=e.get(t);if(n)return n;if(aS(t)){const e=new Array(t.r.length);for(let n=0;n<e.length;n++)e[n]=Object.freeze(t.r[n].slice());n={r:Object.freeze(e),t:Object.freeze(t.t.slice())}}else if(Array.isArray(t)){n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=iS(t[s],e)}else{n={};for(const s in t)n[s]=iS(t[s],e)}return Object.freeze(n),e.set(t,n),n}Object.freeze(Object.keys(HM).filter(t=>!HM[t].poseForm)),Object.freeze(Object.fromEntries(Object.entries(HM).map(([t,e])=>[t,e.state]))),Object.freeze(Object.fromEntries(Object.entries(HM).map(([t,e])=>[t,e.pure]))),Object.freeze(Object.keys(HM));const rS=(t,e)=>Array.isArray(t)?t:[{id:e,...t}],oS=(t,e,n)=>{if(!t||"object"!=typeof t||Array.isArray(t))return!1;let s=0;for(const i in t)if(Object.hasOwn(t,i)){if(s>1||i!==(0===s?e:n))return!1;s++}return 2===s},aS=t=>oS(t,"r","t")&&Array.isArray(t.r)&&Array.isArray(t.t);function cS(t,e){for(let n=0;n<t.length;n++){if(!(n in t))continue;const s=t[n];"number"==typeof s?Number.isFinite(s)||CM("NON_FINITE",e,String(s)):hS(s,e)}}function lS(t,e){for(let n=0;n<t.r.length;n++){if(!(n in t.r))continue;const s=t.r[n];Array.isArray(s)?cS(s,e):hS(s,e)}cS(t.t,e)}function hS(t,e){if("number"==typeof t)Number.isFinite(t)||CM("NON_FINITE",e,String(t));else if(Array.isArray(t))for(let n=0;n<t.length;n++)n in t&&hS(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]])))&&dS.has(t))return;for(let s=0;s<n.length;s++)hS(t[n[s]],e)}}const dS=new WeakSet,uS=["transform","placed","assembly","collection","point"],pS=t=>Array.isArray(t)||uS.includes(t?.kind)?void 0:String(t?.kind??"value");function fS(t){return function(t){jM(t,["version","inputs","constants","nodes"],[],"model"),["r3-scalar-1","r3-spatial-1"].includes(t.version)||CM("VERSION","model",t.version);for(const e of["inputs","constants","nodes"])Array.isArray(t[e])||CM("SCHEMA",e,"array required");const e=structuredClone(t),n=new Map,s=new Map,i=new Map,r=new Map,o=[],a=[],c=(t,e)=>{LM(t,e),n.has(t)&&CM("DUPLICATE_WRITER",t,`${n.get(t)} and ${e}`),n.set(t,e)};for(const t of e.inputs)jM(t,["id","unit","min","max"],["role"],"input"),c(t.id,"input"),s.set(t.id,NM(t.unit,t.id)[0]),t.role&&!["design","state"].includes(t.role)&&CM("SCHEMA",t.id,"unknown input role"),"state"===t.role&&i.set(t.id,new Set([t.id])),FM(t.min,t.id)>FM(t.max,t.id)&&CM("RANGE",t.id,"min > max"),"count"===t.unit&&(nS(t.min,DM,t.id),nS(t.max,DM,t.id));for(const t of e.constants)jM(t,["id","unit","value"],[],"constant"),c(t.id,"constant"),s.set(t.id,NM(t.unit,t.id)[0]),nS(t.value,s.get(t.id),t.id);for(const t of e.nodes){jM(t,["id","op","args","outputs"],["params"],"node"),LM(t.id,"node"),r.has(t.id)&&CM("DUPLICATE_NODE",t.id,"node id"),Object.hasOwn(HM,t.op)||CM("OPERATOR",t.id,t.op),HM[t.op].params?JM(t,HM[t.op].params,HM[t.op].optionalParams):Object.hasOwn(t,"params")&&CM("SCHEMA",t.id,"unexpected params"),Array.isArray(t.args)||CM("SCHEMA",t.id,"args array required"),t.args.forEach(e=>LM(e,t.id)),jM(t.outputs,HM[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)&&CM("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 i=e.args[t.at];if(n.has(i)||CM("UNKNOWN_REFERENCE",e.id,i),!s.has(i)){u(n.get(i));continue}t.inputTypes.push(s.get(i)),t.at++;continue}const r=HM[e.op],c=r.types(t.inputTypes,e.id,e),p=new Set;for(const t of e.args)for(const e of i.get(t)??[])p.add(e);p.size&&(void 0===r.state&&CM("STATE_POLICY",e.id,`${e.op} declares no policy for a state-dependent argument (${[...p].join(", ")})`),"refuses"===r.state&&CM("TOPOLOGY_STATE",e.id,`${e.op} must depend on design inputs only; it depends on ${[...p].join(", ")}`)),r.ports.forEach((t,n)=>s.set(e.outputs[t],c[n])),p.size&&Object.values(e.outputs).forEach(t=>i.set(t,new Set(p))),d.pop(),a.pop(),h.delete(e.id),l.add(e.id),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)||CM("SCHEMA","input values","object required");for(const n of e.inputs)Object.hasOwn(t,n.id)||CM("SCHEMA","input values",`missing ${n.id}`);for(const e of Object.keys(t))m.has(e)||CM("SCHEMA","input values",`unknown ${e}`)}function y(t,e){const n=FM(e,t.id);return(n<t.min||n>t.max)&&CM("INPUT_RANGE",t.id,`${n} outside [${t.min},${t.max}]`),nS(n*NM(t.unit,t.id)[1],s.get(t.id),t.id)}function b(t,n){g(t);const i=new Map,r=[],a=new Map,c=new Set;for(const n of e.inputs)i.set(n.id,y(n,t[n.id])),c.add(n.id);for(const t of e.constants)i.set(t.id,FM(t.value*NM(t.unit,t.id)[1],t.id));for(const t of o){const e=HM[t.op],n=t.args.map(t=>i.get(t)),o=e.run(n,t.id,t);if(e.ports.forEach((e,n)=>{i.set(t.outputs[e],nS(o[n],s.get(t.outputs[e]),t.id)),c.add(t.outputs[e])}),e.geometry){const s=rS(e.geometry(n,o,t),t.id);a.set(t.id,s),r.push(...s)}}return{result:{values:Object.fromEntries(i),geometry:r},kept:{input:{...t},values:i,bodies:a}}}return{outputTypes:Object.fromEntries([...s].map(([t,e])=>[t,structuredClone(e)])),dependence:Object.fromEntries([...i].map(([t,e])=>[t,[...e].sort()])),order:o.map(t=>t.id),evaluate:t=>b(t).result,evaluator(t={}){let e,n,s=0,i=[],r=0;const o=(t,e)=>{const n=e||t.length!==i.length||t.some((t,e)=>t!==i[e]);return n&&s++,i=t,n},a=(t,e)=>(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 s=E(t,n,!0);return e=n,a(s,!1)},l=(t,n)=>{const i=++r,a=e;e=void 0;const c=a?.fast;let l;a?(l=E(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 A=0;for(const t of v)(d.bodies[t]??[]).forEach((e,n)=>{w[A]=g[t]+n,S[A]=e.shape??null;const s=12*A;if(e.pose){const t=e.pose.r,n=e.pose.t;M[s]=t[0][0],M[s+1]=t[0][1],M[s+2]=t[0][2],M[s+3]=t[1][0],M[s+4]=t[1][1],M[s+5]=t[1][2],M[s+6]=t[2][0],M[s+7]=t[2][1],M[s+8]=t[2][2],M[s+9]=n[0],M[s+10]=n[1],M[s+11]=n[2]}else M.fill(NaN,s,s+12);A++});const k=d.epoch,C=()=>{r!==i&&CM("STEP_EXPIRED","advance","read a step's changes before the next call on its evaluator")};return{kind:"changes",generation:s,why:n,...y?{structure:{ids:u,keys:p,paths:f,indexes:m}}:{},bodies:w,poses:M,shapes:S,read:t=>{C();const e=h().slot.get(t);return void 0===e&&CM("TARGET_ABSENT",t,"no such value"),iS(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(i,o){if(e&&!o){const o=++r,a=e;e=void 0;const h=S(i,a,n??=x(t.reads));if(e=a,"result"in h){const{read:t,changed:e}=h.result,n=()=>{r!==o&&CM("STEP_EXPIRED","advance","read a pose step before the next call on its evaluator")};return{...h.result,generation:s,read:e=>(n(),t(e)),changed:t=>(n(),e(t))}}if(t.changes)return l(i,h.why);return{kind:"evaluation",result:c(i),generation:s,why:h.why}}const a={code:!!e?o:"NOT_BOUND"};if(t.changes)return l(i,a);return{kind:"evaluation",result:c(i),generation:s,why:a}},poseInputs:()=>x(t.reads).inputs.map(t=>({...t})),value(t){e||CM("NOT_BOUND",t,"evaluate before reading a value");const n=h().slot.get(t);void 0===n&&CM("TARGET_ABSENT",t,"no such value");const s=e.fast;if(!s)return iS(e.slots[n],new Map);const i=h().nodes.find(t=>t.outs.includes(n));if(i&&s.wrote.has(i.index)&&!s.moved.has(n)){return iS(i.op.run(i.args.map(t=>s.slots[t]),i.n.id,i.n)[i.outs.indexOf(n)],new Map)}return iS(s.slots[n],new Map)}}}};function v(){if(p)return p;const t=new Map,n=[],i=e=>{t.set(e,n.length),n.push(e)};e.inputs.forEach(t=>i(t.id)),e.constants.forEach(t=>i(t.id));const r=o.map((e,n)=>{const r=HM[e.op];return r.ports.forEach(t=>i(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=>s.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 s of a[t])e[s]||(e[s]=1,n.push(...r[s].outs))}const s=[];return e.forEach((t,e)=>t&&s.push(e)),s},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"===s.get(t)?.kind)},p}function _(t,n=!0){const s=v(),i=s.keys.map(e=>t.values.get(e));i.forEach((t,e)=>s.shapeSlot[e]&&sS(t));const r=s.nodes.map(e=>t.bodies.get(e.n.id));if(!n){const n={};for(const t of s.keys)n[t]=void 0;return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:r,shown:r.map(()=>{}),values:n,geometry:[],mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set(s.shapes.filter(t=>r[t])),slots:new Set(s.keys.keys())}}}const o=new Map,a=r.map(t=>t?.map(t=>iS(t,o))),c={};s.keys.forEach((t,e)=>c[t]=iS(i[e],o));const l=[];for(const t of s.shapes)a[t]&&l.push(...a[t]);return{raw:e.inputs.map(e=>t.input[e.id]),slots:i,bodies:r,shown:a,values:c,geometry:l,mark:new Int32Array(s.keys.length),ran:new Int32Array(s.nodes.length),epoch:0,pending:{nodes:new Set,slots:new Set}}}function x(t={}){const n=JSON.stringify([t.forbidden??{},[...t.external??[]].sort()]),i=f.get(n);if(i)return i;const r=v(),o=t.forbidden??{},a=new Set(t.external??[]),c={inputs:e.inputs.map((t,e)=>{const n=pS(s.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,s]of e.outs.entries()){const i=pS(e.types[n]);if(i)return{fast:!1,code:"INPUT_NOT_POSE",input:t.id,node:e.n.id,reaches:i};const a=r.keys[s];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 s=t.join();let i=e.visits.get(s);if(!i){const r=new Set;for(const e of t)for(const t of n.reach[e])r.add(t);i=[...r].sort((t,e)=>t-e),e.visits.size<256&&e.visits.set(s,i)}return i}function M(t){const e=v(),n=new Int32Array(e.nodes.length).fill(-1);let s=0;for(const i of e.shapes)n[i]=s,s+=t.bodies[i]?.length??0;return{raw:t.raw.slice(),slots:t.slots.slice(),mark:new Int32Array(e.keys.length),epoch:0,start:n,bodyCount:s,prefix:new Map,wrote:new Set,moved:new Set}}function S(t,n,s){const i=v();g(t);const r=n.fast?.raw??n.raw,o=[],a=[];for(let n=0;n<e.inputs.length;n++){const s=e.inputs[n],i=t[s.id];i!==r[n]&&(a.push(y(s,i)),o.push(n))}for(const t of o)if(!s.inputs[t].fast)return{why:s.inputs[t]};const c=n.fast??=M(n),l=++c.epoch;o.forEach((n,s)=>{c.raw[n]=t[e.inputs[n].id],c.slots[n]=a[s],c.mark[n]=l});const h=w(o,s),d=new Int32Array(c.bodyCount),u=new Float64Array(12*c.bodyCount);let p=0;const f=(t,e)=>{const n=e.r,s=e.t,i=12*p;d[p++]=t,u[i]=n[0][0],u[i+1]=n[0][1],u[i+2]=n[0][2],u[i+3]=n[1][0],u[i+4]=n[1][1],u[i+5]=n[1][2],u[i+6]=n[2][0],u[i+7]=n[2][1],u[i+8]=n[2][2],u[i+9]=s[0],u[i+10]=s[1],u[i+11]=s[2]};for(const t of h){const e=i.nodes[t];let n=!1;for(const t of e.args)if(c.mark[t]===l){n=!0;break}if(!n)continue;const r=new Array(e.args.length);for(let t=0;t<e.args.length;t++)r[t]=c.slots[e.args[t]];if(s.terminal[t]){const[n,s,i,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(KM(i,{r:YM(),t:e}))}c.prefix.set(t,d)}let u=c.start[t];for(let t=0;t<n.count;t++)for(const n of s.members){const s=KM(d[t],n.pose);hS(s,e.n.id),f(u++,s)}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]=nS(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),s=Array.isArray(n)?n:[n];let i=c.start[t];for(const t of s)f(i++,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=i.slot.get(t);return void 0===e&&CM("TARGET_ABSENT",t,"no such value"),iS(c.slots[e],new Map)},changed:t=>{const e=i.slot.get(t);return void 0!==e&&c.mark[e]===l}}}}function E(t,n,s){const i=v();g(t),n.fast=void 0;const r=++n.epoch,o=[];let a,c=-1,l=!1;if(e.inputs.forEach((e,s)=>{const i=t[e.id];i!==n.raw[s]&&(n.slots[s]=y(e,i),n.raw[s]=i,n.mark[s]=r,o.push(s),c>=0&&(l=!0),c=s)}),l||i.always.length){const t=[];for(const e of[...o.map(t=>i.reach[t]),i.always])for(const s of e)n.ran[s]!==r&&(n.ran[s]=r,t.push(s));a=t.sort((t,e)=>t-e)}else a=c>=0?i.reach[c]:[];const h=[];for(const t of a){const e=i.nodes[t];if(e.op.pure&&!e.args.some(t=>n.mark[t]===r))continue;const s=e.args.map(t=>n.slots[t]),a=e.op.run(s,e.n.id,e.n);e.outs.forEach((t,s)=>{n.slots[t]=nS(a[s],e.types[s],e.n.id),i.shapeSlot[t]&&sS(n.slots[t]),n.mark[t]=r,o.push(t)}),e.op.geometry&&(n.bodies[t]=rS(e.op.geometry(s,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(!s){for(const t of h)n.shown[t]=void 0;h.length&&(n.geometry=[]);for(const t of o)n.values[i.keys[t]]=void 0;return h}return A(n),{values:{...n.values},geometry:n.geometry.slice()}}function A(t){const e=v(),{nodes:n,slots:s}=t.pending;if(!n.size&&!s.size)return;const i=new Map;for(const e of[...n].sort((t,e)=>t-e))t.shown[e]=t.bodies[e].map(t=>iS(t,i));for(const n of s)t.values[e.keys[n]]=iS(t.slots[n],i);if(n.size){const n=[];for(const s of e.shapes){const e=t.shown[s];e&&n.push(...e)}t.geometry=n}n.clear(),s.clear()}}(t)}function mS(t,e,n){const s=function(t,e){const n=t.find(t=>t.id===e);if(!n)return{code:"TARGET_ABSENT",message:`${String(e)} is not an input of the figure`};if("state"===n.role)return{code:"PUBLIC_INPUT",message:`${e} is a state input; a board sets it as a parameter`};if(/^(sizing\.)?size\.[xyz]$/.test(e))return{code:"PUBLIC_INPUT",message:`${e} is the figure's size; a board sets it from the instance's bounds`};const s=t=>Number.isFinite(t)&&Math.abs(t)<1e12&&t!==Number.MIN_VALUE;return s(n.min)&&s(n.max)?null:{code:"PUBLIC_INPUT",message:`${e} has no range to hold a board's value to; give it one first`}}(t,e);if(s)throw new Bw(s.code,n,s.message)}const gS=(t,e,n)=>{throw new Bw(t,e,n)},yS={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 bS(t,e,n){const{types:s,writers:i,model:r,assetFrame:o}=t;e&&"object"==typeof e&&!Array.isArray(e)||gS("SCHEMA",n,"object required");for(const t of["placement","feature"])Object.hasOwn(e,t)||gS("SCHEMA",n,`missing ${t}`);for(const t of Object.keys(e))["placement","feature"].includes(t)||gS("SCHEMA",n,`unknown ${t}`);const a=t=>("string"==typeof t&&t.trim()||gS("SCHEMA",n,"nonempty string required"),Object.hasOwn(s,t)||gS("TARGET_ABSENT",n,t),s[t]),c=a(e.placement),l=a(e.feature),h=i.get(e.placement),d=i.get(e.feature);let u,p=h;if("select-item@1"===h?.op){const t=i.get(h.args[0]),e="repeat@1"===t?.op?i.get(t.args[1]):null;"assembly@1"===e?.op&&e.args.includes(h.params.member)||gS("SURFACE_PROVENANCE",n,"selected member must belong to the referenced repeat assembly"),p=i.get(h.params.member),"member@1"!==p?.op&&gS("SURFACE_PROVENANCE",n,"selected source must be a declared template member"),r.inputs.some(t=>t.id===h.args[1]&&"state"===t.role)&&gS("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&&gS("SURFACE_PROVENANCE",n,"actual placement or selected repeated member required");"feature@1"!==d?.op&&gS("SURFACE_PROVENANCE",n,"provider feature required"),"placed"===c.kind&&c.frame===o&&"transform"===l.kind||gS("FRAME_TYPE",n,"contact must be in asset frame"),p.args[0]!==d.args[0]&&gS("SURFACE_OWNER",n,"feature belongs to a different shape declaration");const f=s[d.args[0]].provider,m=d.params.name,g=s[d.args[0]].faces,y=g?.[m];y||gS("SURFACE_UNSUPPORTED",n,"feature is not a supported planar surface"),"line"===y[2]&&gS("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 vS(t,e,n,s,i={}){const[r,o]=Yw[e],a=(t,s)=>{const a={x:0,y:0,z:0};return a[e]=n,a[r]=t+(i[r]??0),a[o]=s+(i[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:s},(e,n)=>{const i=2*Math.PI*n/s;return a(t.radius[r]*Math.cos(i),t.radius[o]*Math.sin(i))});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 s=0;s<=8;s++){const i=n+s/8*(Math.PI/2);u.push(a(t*(c-h)+h*Math.cos(i),e*(l-d)+d*Math.sin(i)))}return u}function _S(t,e){return function(t,e){const n=t.extrusion;if(n){const s=[...vS(n.section,n.axis,n.start,e),...vS(n.section,n.axis,n.end,e)],i=t.cavity;if(i){const t=eM(n.section,n.axis,i.wall);if("section"in t){const r=n.start+("open"===i.start?0:i.start.closed),o=n.end-("open"===i.end?0:i.end.closed);s.push(...vS(t.section,n.axis,r,e,t.centre),...vS(t.section,n.axis,o,e,t.centre))}}return s}const s=t.loft;if(s){const t={x:0,y:0,z:0,...s.apex,[s.axis]:s.end};return[...vS(s.section,s.axis,s.start,e),[t.x,t.y,t.z]]}const i=t.revolution,[r,o]=Yw[i.axis],a=(t,n)=>vS({kind:"ellipse",radius:{[r]:n,[o]:n}},i.axis,t,e);if("taper"===i.profile.kind)return[...a(i.profile.start,Math.max(i.profile.startRadius,1e-9)),...a(i.profile.end,Math.max(i.profile.endRadius,1e-9))];const{radial:c,axial:l}=i.profile,h=[];for(let t=1;t<6;t++){const e=t/6*Math.PI;h.push(...a(l*Math.cos(e),c*Math.sin(e)))}return h.push(...a(l,1e-9).slice(0,1),...a(-l,1e-9).slice(0,1)),h}(t,e??12)}function xS(t,e,n){return t.map(([t,s,i])=>[e[0][0]*t+e[0][1]*s+e[0][2]*i+n[0],e[1][0]*t+e[1][1]*s+e[1][2]*i+n[1],e[2][0]*t+e[2][1]*s+e[2][2]*i+n[2]])}function wS(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 MS=Object.freeze({x:"size.x",y:"size.y",z:"size.z"});function SS(t,e,n){return n?{code:t,path:e,params:n}:{code:t,path:e}}const ES=t=>"number"==typeof t&&Number.isFinite(t),AS=t=>ES(t)&&t>0,kS=t=>Number.isSafeInteger(t)&&t>0;function CS(t,e,n){const s=t?.allowed;if(s&&"object"==typeof s)for(const t of["width","depth","height"])AS(s[t])||n.push(SS("POSITIVE_NUMBER_REQUIRED",`${e}.allowed.${t}`));else n.push(SS("OBJECT_REQUIRED",`${e}.allowed`));void 0===t?.stackLimit||kS(t.stackLimit)||t.stackLimit===1/0||n.push(SS("POSITIVE_INTEGER_REQUIRED",`${e}.stackLimit`)),void 0===t?.rotation||ES(t.rotation)||n.push(SS("FINITE_NUMBER_REQUIRED",`${e}.rotation`)),void 0===t?.accepts||Array.isArray(t.accepts)||n.push(SS("ARRAY_REQUIRED",`${e}.accepts`))}function TS(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 OS(t){return"CUSTOM"===t.pattern?t.slots.map(t=>t.slotNo).sort((t,e)=>t-e):Array.from({length:TS(t)},(t,e)=>e+1)}const PS=(t,e)=>e&&0!==t?-t:t;function IS(t,e,n={}){const s=t?.tiers?.find(t=>t?.tierNo===e?.tier);if(!s||!kS(e.slot))return null;const i=s.layout;let r,o,a;switch(i.pattern){case"SINGLE":if(1!==e.slot)return null;r=i.slot,o={x:0,z:0};break;case"ROW":{if(e.slot>i.count)return null;const t=PS((e.slot-1-(i.count-1)/2)*i.pitch,"MAX"===i.origin);r=i.slot,o="X"===i.axis?{x:t,z:0}:{x:0,z:t};break}case"GRID":{if(e.slot>i.rows*i.cols)return null;const{r:t,c:n}=function(t,e,n,s="ROW_MAJOR"){const i=n-1;switch(s){case"ROW_MAJOR":return{r:Math.floor(i/e)+1,c:i%e+1};case"COL_MAJOR":return{r:i%t+1,c:Math.floor(i/t)+1};case"SERPENTINE_ROW":{const t=Math.floor(i/e)+1,n=i%e+1;return{r:t,c:t%2==1?n:e-n+1}}case"SERPENTINE_COL":{const e=Math.floor(i/t)+1,n=i%t+1;return{r:e%2==1?n:t-n+1,c:e}}}}(i.rows,i.cols,e.slot,i.order),s=i.origin??{x:"MIN",z:"MIN"};r=i.slot,o={x:PS((n-1-(i.cols-1)/2)*i.pitch.x,"MAX"===s.x),z:PS((t-1-(i.rows-1)/2)*i.pitch.z,"MAX"===s.z)};break}case"CUSTOM":{const t=i.slots.find(t=>t.slotNo===e.slot);if(!t)return null;r=t,o={...t.offset},a=t.name;break}}return{tier:s.tierNo,slotNo:e.slot,name:a,anchorId:s.anchorId,mount:s.mount,tierPosition:{...s.position},tierRotation:s.rotation,offset:o,allowed:{...r.allowed},accepts:r.accepts?[...r.accepts]:void 0,stackLimit:r.stackLimit??n.defaultStackLimit??1,rotation:r.rotation??0}}function DS(t){return`t${t.tier}_s${t.slot}`}function zS(t){const e=function(t,e,n){if(!n)return{x:t,z:e};const s=n*Math.PI/180,i=Math.cos(s),r=Math.sin(s),o=t=>Math.round(1e9*t)/1e9;return{x:o(t*i+e*r),z:o(-t*r+e*i)}}(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}}function RS(t){if(!t?.layout||!Array.isArray(t.anchors))return[];const e=new Map(t.anchors.map(t=>[t.id,t])),n=[];for(const s of function*(t){for(const e of t?.tiers??[])for(const t of OS(e.layout))yield{tier:e.tierNo,slot:t}}(t.layout)){const i=IS(t.layout,s),r=i&&e.get(i.anchorId);if(!i||!r)continue;const o=DS(s);n.push({id:o,label:`${t.label} ${o}`,role:t.role,frame:r.frame,pose:{...r.pose},anchorId:r.id,accepts:[...i.accepts??[]],capacity:i.stackLimit,tier:i.tier,slot:i.slotNo,...i.name?{name:i.name}:{},tierPosition:{...i.tierPosition},tierRotation:i.tierRotation,offset:{...i.offset},rotation:i.rotation,mount:i.mount,allowed:{...i.allowed}})}return n}const jS=["floor","ceiling","center","wall"],LS=(t,e,n)=>{throw new Bw(t,e,n)},FS={left:"x",right:"x",bottom:"y",top:"y",back:"z",front:"z"},NS=["fixed","revolute","prismatic"],$S={left:-1,right:1,bottom:-1,top:1,back:-1,front:1};function HS(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 BS(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 YS={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 GS=(t,e)=>t.nodes.find(t=>t.id===e),VS=(t,e)=>t.nodes.find(t=>Object.values(t.outputs).includes(e));function US(t,e,n){const s=GS(t,e),i="member@1"===s?.op&&(!!GS(t,`${e}.repeat`)||void 0!==function(t,e){const n=GS(t,e);if("member@1"!==n?.op||GS(t,`${e}.repeat`))return;const s=t.nodes.find(t=>"assembly@1"===t.op&&t.args.includes(n.outputs.placed));return s?String(s.id).replace(/\.assembly$/,""):void 0}(t,e));s&&("place@1"===s.op||i)||LS("TARGET_ABSENT",n,`${e} is not a placed part`);const r=VS(t,s.args[0]);r||LS("TARGET_ABSENT",n,`${e} has no shape`);const o=GS(t,`${e}.pose`);return o&&"rigid@1"===o.op||LS("EDIT_TARGET",n,`${e} is not posed by a rigid@1 this command can read`),{place:s,shape:r,pose:o}}function WS(t,e,n,s){return US(t,n,s).pose.args.slice(3,6).map(n=>function(t,e,n){const s=t.constants.find(t=>t.id===n);if(s)return s.value;const i=t.inputs.find(t=>t.id===n);return i&&"state"!==i.role?e.designInputs[n]??null:null}(t,e,n))}const qS=t=>zw.map((e,n)=>`${e.toUpperCase()} ${t[n]??"?"}°`).join(", ");function XS(t,e,n,s,i){const r=WS(t,e,n,s);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)&&LS("EDIT_TARGET",s,`${n} is turned (${qS(r)}); only quarter turns keep its faces level with the axes`);const o=KS(r);{const i=US(t,n,s).pose,o=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...r.map(e=>aE(t,"deg",e,"a"))];for(const s of o)mE(e,s,fE(t,n,s)?s:void 0)}return o}function KS(t){const[e,n,s]=t.map(t=>t*Math.PI/180),i=t=>Math.round(Math.cos(t)),r=t=>Math.round(Math.sin(t)),o=[[1,0,0],[0,i(e),-r(e)],[0,r(e),i(e)]],a=[[i(n),0,r(n)],[0,1,0],[-r(n),0,i(n)]],c=[[i(s),-r(s),0],[r(s),i(s),0],[0,0,1]];return QS(QS(o,a),c)}const QS=(t,e)=>t.map(t=>e[0].map((n,s)=>t.reduce((t,n,i)=>t+n*e[i][s],0))),JS=t=>t.map(t=>({ref:t.ref,k:-t.k})),ZS=t=>t.map(t=>({ref:t.ref,k:t.k/2})),tE={x:["left","right"],y:["bottom","top"],z:["back","front"]};function eE(t,e,n){const{shape:s}=US(t,e,n),i=function(t,e){const n=yM(t,e);return n&&Object.keys(n.faces).length?n.faces:void 0}(s,t);return i||LS("EDIT_TARGET",n,`${e} is a ${s.op}; it has no flat face to fasten by`),{shape:s,faces:i}}function nE(t,e){if("centre"!==e.body1.face)return e.body1.face;const n=`joints.${e.id}.body1.face`;"part"in e.body0||LS("JOINT_SCHEMA",n,"a part stands on the mounting plane by a face of its own, not by its centre");const s=e.body0.face;if(Object.hasOwn(FS,s))return Object.keys(FS).find(t=>FS[t]===FS[s]&&$S[t]===-$S[s]);const i=eE(t,e.body0.part,n).faces[e.body0.face];return i||LS("JOINT_SCHEMA",n,`${e.body0.part} has no face ${e.body0.face}`),Object.keys(FS).find(t=>FS[t]===i.axis&&$S[t]===-i.normal)}const sE=(t,e)=>e.plane.map(e=>({ref:t.args[e.arg],k:e.k}));function iE(t,e,n){const{shape:s,faces:i}=eE(t,e,n),r={},o=yM(s,t).measure;for(const t of zw){const[e,n]=tE[t].map(t=>i[t]),a=o[t],c=a&&"profile"!==a?sE(s,{plane:a}):void 0;if(!e&&!n)continue;if(!(e&&n||c))continue;const l=e?sE(s,e):[...sE(s,n),...JS(c)],h=n?sE(s,n):[...sE(s,e),...c];r[t]={lo:l,hi:h,centred:JSON.stringify(l)===JSON.stringify(JS(h))}}return r}function rE(t,e,n,s){const i=iE(t,n,s),r=XS(t,e,n,s),o={};return zw.forEach((t,e)=>{const n=r[e].findIndex(t=>0!==t),s=i[zw[n]];s&&(o[t]=r[e][n]>0?s:{lo:JS(s.hi),hi:JS(s.lo),centred:s.centred})}),o}function oE(t,e){const n=new Set([...t.nodes.map(t=>t.id),...t.nodes.flatMap(t=>Object.values(t.outputs)),...t.constants.map(t=>t.id),...t.inputs.map(t=>t.id)]);return t=>{let s=`${e}.${t}`;for(let i=2;n.has(s)||n.has(`${s}.value`);i++)s=`${e}.${t}.${i}`;return n.add(s),n.add(`${s}.value`),s}}function aE(t,e,n,s){const i=t.constants.find(t=>t.unit===e&&t.value===n);if(i)return i.id;const r=`${s}.${e}.${String(n).replace(/[^0-9a-zA-Z]/g,"_")}`;return t.constants.push({id:r,unit:e,value:n}),r}function cE(t,e,n,s,i,r){let o=n;if(1!==s){const n=e(`${r}.times`);t.nodes.push({id:n,op:"mul@1",args:[o,aE(t,"ratio",s,"k")],outputs:{value:`${n}.value`}}),o=`${n}.value`}if(0!==i){const n=e(`${r}.plus`);t.nodes.push({id:n,op:"add@1",args:[o,aE(t,"mm",i,"d")],outputs:{value:`${n}.value`}}),o=`${n}.value`}return o}function lE(t,e,n,s,i,r){if(void 0===s)return aE(t,"mm",0,"d");if("number"==typeof s)return Number.isFinite(s)||LS("SCHEMA",r,"a finite length is required"),aE(t,"mm",s,"d");s&&"object"==typeof s&&(Object.hasOwn(s,"sum")||s.from)||LS("SCHEMA",r,"a length is a number of millimetres, or something to follow");const{terms:o,plus:a,sum:c}=BS(s),l=hE(t,e,o,a,r);return c?cE(t,n,dE(t,n,l,`${i}.sum`),1,a,i):cE(t,n,l[0].ref,l[0].k,a,i)}function hE(t,e,n,s,i){return Array.isArray(n)&&n.length||LS("SCHEMA",i,"a sum has one term or more"),Number.isFinite(s)||LS("SCHEMA",i,"finite times and plus required"),n.map((s,r)=>{const o=n.length>1?`${i}.sum.${r}`:i;return s&&"object"==typeof s&&s.from||LS("SCHEMA",o,"a length is a number of millimetres, or something to follow"),Number.isFinite(s.times??1)||LS("SCHEMA",o,"finite times and plus required"),{ref:uE(t,e,s.from,o),k:s.times??1}})}function dE(t,e,n,s){const i=n.filter(t=>0!==t.k);if(!i.length)return aE(t,"mm",0,"d");let r="";for(const[n,o]of i.entries()){const i=cE(t,e,o.ref,o.k,0,`${s}.${n}`);if(r){const o=e(`${s}.${n}.sum`);t.nodes.push({id:o,op:"add@1",args:[r,i],outputs:{value:`${o}.value`}}),r=`${o}.value`}else r=i}return r}function uE(t,e,n,s){if(n&&"object"==typeof n||LS("SCHEMA",s,"a dimension source is required"),"instance"===n.of){const i=`size.${n.axis}`;return t.inputs.some(t=>t.id===i)||LS("TARGET_ABSENT",s,`the instance has no ${i}; declare it before following it`),"uniform"===e.sizing?function(t,e,n){const s=GS(t,`sizing.size.${e}`);return s||LS("TARGET_ABSENT",n,`the figure grows by one ratio but has no sizing.size.${e}`),s.outputs.value}(t,n.axis,s):i}if("input"===n.of){const e=t.inputs.find(t=>t.id===n.input);return e||LS("TARGET_ABSENT",s,`${n.input} is not an input of this asset`),"state"===e.role&&LS("EDIT_TARGET",s,`${n.input} is a state input; a dimension that follows state is a different declaration`),n.input}return"part"===n.of?pE(t,n.part,n.axis,s):LS("SCHEMA",s,`${String(n.of)} is not a dimension source`)}function pE(t,e,n,s){const i=US(t,e,s).shape,r=yM(i);if(r){const o=r.edit[n];if("refused"in o)return LS("EDIT_TARGET",s,`${e} is a drawn section; its measures are its points, which no measure can follow`);if(o.sameAs)return pE(t,e,o.sameAs,s);const a=`${e}.dimension.${n}`,c=`${a}.value`;if(GS(t,a))return c;const l=i.args[o.arg],h=aE(t,"ratio",1,"k");t.nodes.push({id:a,op:"mul@1",args:[l,h],outputs:{value:c}}),i.args=i.args.map(t=>t===l?c:t);const d=GS(t,`${e}.start`);return d&&(d.args=d.args.map(t=>t===l?c:t)),c}return LS("EDIT_TARGET",s,`${e} is a ${i.op}; it is not a shape with measures`)}const fE=(t,e,n)=>!!n&&n.startsWith(`${e}.`)&&t.inputs.some(t=>t.id===n&&"design"===t.role);function mE(t,e,n){const s=t.document.model,i=new Set([...VE(t.occupancy),...VE(t.document.capabilities),...VE(t.joints)]),r=t=>s.nodes.some(e=>e.args.includes(t)||Object.values(e.params??{}).includes(t))||i.has(t);if(r(e))return;const o=s.inputs.findIndex(t=>t.id===e);if(o>=0){if(e!==n)return;return s.inputs.splice(o,1),delete t.designInputs[e],void delete t.stateDefaults[e]}const a=VS(s,e);if(a&&"place@1"!==a.op&&!Object.values(a.outputs).some(t=>t!==e&&r(t))){s.nodes=s.nodes.filter(t=>t!==a);for(const e of a.args)mE(t,e)}}function gE(t,e){if(!GS(t,`${e}.chain`)&&!GS(t,`${e}.repeat`))return null;const n=GS(t,`${e}.seat.rigid`)??GS(t,`${e}.motion`),s=/^(.*)\.local$/.exec(String(n?.params?.to));return s&&s[1]!==e?s[1]:null}function yE(t,e,n){const s=t.document.model,i=e.to,r=`${e.part} to ${i?.plane??i?.part}`;if(i&&"object"==typeof i||LS("SCHEMA",r,"a target face, or the plane the figure is mounted on, is required"),void 0!==i.plane)return function(t,e,n){const s=t.document.model,i=e.to;"mounting-plane"!==i.plane&&LS("SCHEMA",n,`${String(i.plane)} is not a plane a part can stand on`);void 0!==e.facing&&"meet"!==e.facing&&LS("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)||LS("ATTACH_FACE",n,"wall"===r?`${String(e.face)} faces along ${FS[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 ${FS[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`);gE(s,e.part)&&!e.replace&&LS("ATTACH_REPLACED",n,`${e.part} is already fastened to ${gE(s,e.part)}; pass replace to stand it on the plane instead`);const c=rE(s,t,e.part,n);c[a]&&Object.hasOwn(eE(s,e.part,n).faces,e.face)||LS("EDIT_TARGET",n,`${e.part} has no flat ${e.face} face`);const l=oE(s,`${e.part}.on.plane`),h="top"===e.face?-1:1,d=lE(s,t,l,e.gap,`gap.${a}`,n),u={x:"",y:"",z:""};u[a]=dE(s,l,[...JS(h>0?c[a].lo:c[a].hi),{ref:d,k:h}],`stand.${a}`);const p=aE(s,"mm",0,"d"),f={x:p,y:p,z:p};f[a]=u[a];for(const i of zw.filter(t=>t!==a)){const r=e.align?.[i]??"centre",o=c[i];if("centre"===r)u[i]=aE(s,"mm",0,"d");else if("object"==typeof r&&r&&Object.hasOwn(r,"mm"))u[i]=lE(s,t,l,r.mm,`align.${i}`,n);else{if(("min"===r||"max"===r)&&_E(s,i)){o||LS("ATTACH_FACE",n,`${e.part} has no edges along ${i} to line up with the figure's side`);const a="min"===r?-1:1;u[i]=dE(s,l,[{ref:uE(s,t,{of:"instance",axis:i},n),k:.5*a}],`figure-edge.${i}`),f[i]=dE(s,l,JS("min"===r?o.lo:o.hi),`own-edge.${i}`);continue}LS("SCHEMA",n,`the plane has no edges to line ${e.part} up with on ${i}; declare the figure's size, or give the centre or a measured offset`)}o&&!o.centred&&(f[i]=dE(s,l,JS([...ZS(o.lo),...ZS(o.hi)]),`own-centre.${i}`))}const m=zw.map(t=>t===a?p:u[t]);return vE(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===i.part&&LS("ATTACH_CYCLE",r,"a part cannot be fastened to itself");const o="centre"===e.face;o||Object.hasOwn(FS,String(e.face))||LS("SCHEMA",r,`${String(e.face)} is not a face`);const a=eE(s,i.part,r),c=Object.hasOwn(a.faces,String(i.face))?a.faces[i.face]:void 0;c||LS("SCHEMA",r,`${i.part} has no face ${String(i.face)}; it has ${Object.keys(a.faces).join(", ")}`);const l=e.facing??"meet";"meet"!==l&&"flush"!==l&&LS("SCHEMA",r,`${String(l)} is neither meet nor flush`);const h=c.axis,d=c.normal;o&&"meet"!==l&&LS("ATTACH_FACE",r,`${e.part} fastened by its centre sits on ${i.face}; flush has no meaning for a centre`),o&&(e={...e,face:Object.keys(FS).find(t=>FS[t]===h&&$S[t]===-d)}),FS[e.face]!==h&&LS("ATTACH_FACE",r,`${e.face} faces along ${FS[e.face]} and ${i.face} along ${h}; fastening them would need a turn, which this command does not do`);const u=Object.keys(FS).find(t=>FS[t]===h&&$S[t]===("meet"===l?-d:d));"meet"===l&&e.face!==u&&LS("ATTACH_FACE",r,`to meet ${i.face}, ${e.part} offers its ${u}; pass flush to lay ${e.face} in the same plane instead`),"flush"===l&&e.face!==u&&LS("ATTACH_FACE",r,`to lie flush with ${i.face}, ${e.part} offers its ${u}`),gE(s,e.part)&&!e.replace&&LS("ATTACH_REPLACED",r,`${e.part} is already fastened to ${gE(s,e.part)}; pass replace to move it, or detach it first`);for(let t=i.part;t;t=gE(s,t))t===e.part&&LS("ATTACH_CYCLE",r,`${i.part} already hangs from ${e.part}`);const p=iE(s,i.part,r),f=rE(s,t,e.part,r),m=f[h];m&&Object.hasOwn(eE(s,e.part,r).faces,e.face)||o||LS("EDIT_TARGET",r,`${e.part} has no flat ${e.face} face`);const g=oE(s,`${e.part}.on.${i.part}`),y="meet"===l?d:-d,b=lE(s,t,g,e.gap,`gap.${h}`,r),v=aE(s,"mm",0,"d"),_={x:"",y:"",z:""},x={x:v,y:v,z:v};_[h]=dE(s,g,[...sE(a.shape,c),...o?[{ref:b,k:y}]:[]],`seat.${h}`);const w=o?m&&!m.centred?[...ZS(m.lo),...ZS(m.hi)]:[]:$S[e.face]>0?m.hi:m.lo;x[h]=o?w.length?dE(s,g,JS(w),`along.${h}`):v:dE(s,g,[...JS(w),{ref:b,k:y}],`along.${h}`);for(const n of zw.filter(t=>t!==h)){const o=e.align?.[n]??"centre",a=p[n],c=f[n],l=t=>t&&!t.centred?[...ZS(t.lo),...ZS(t.hi)]:[],h=(t,e)=>l(t).length?dE(s,g,l(t),e):aE(s,"mm",0,"d"),d=()=>l(c).length?dE(s,g,JS(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=lE(s,t,g,o.mm,`align.${n}`,r);_[n]=l(a).length?dE(s,g,[...l(a),{ref:e,k:1}],`align.${n}.from-centre`):e,x[n]=d()}else"min"===o||"max"===o?(a||LS("ATTACH_FACE",r,`${i.part} has no edges along ${n} to line ${e.part} up with; give the centre or a measured offset`),c||LS("ATTACH_FACE",r,`${e.part} has no edges along ${n} to line up; give the centre or a measured offset`),_[n]=dE(s,g,"min"===o?a.lo:a.hi,`edge.${n}`),x[n]=dE(s,g,JS("min"===o?c.lo:c.hi),`own-edge.${n}`)):LS("SCHEMA",r,`${String(o)} is not an alignment`)}if(n&&n.deg){const[o,a]=DE[h];for(const t of[o,a]){const s=e.align?.[t]??"centre";"min"!==s&&"max"!==s||LS("ATTACH_FACE",r,`${e.part} is twisted ${bE(n.deg)}° about ${h}; its sides are not level with ${i.part}'s edges -- place it by the centre or a distance`)}const c=n=>{const i=e.align?.[n]??"centre",o=f[n],a=o&&!o.centred?JS([...ZS(o.lo),...ZS(o.hi)]):[];return"object"==typeof i&&i&&Object.hasOwn(i,"mm")?[{ref:lE(s,t,g,i.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(bE(n.deg)).replace("-","m").replace(".","_"),y=t=>{const e=`twist.${t}.${m}`,i=n.deg*Math.PI/180;return s.constants.some(t=>t.id===e)||s.constants.push({id:e,unit:"ratio",value:u("cos"===t?Math.cos(i):"sin"===t?Math.sin(i):-Math.sin(i))}),e},b=(t,e,n)=>{const i=g(n);return s.nodes.push({id:i,op:"mul@1",args:[t,e],outputs:{value:`${i}.value`}}),`${i}.value`},v=(t,e,n)=>{const i=g(n);return s.nodes.push({id:i,op:"add@1",args:[t,e],outputs:{value:`${i}.value`}}),`${i}.value`};for(const t of[o,a]){const e=p[t];_[t]=e&&!e.centred?dE(s,g,[...ZS(e.lo),...ZS(e.hi)],`twist-centre.${t}`):aE(s,"mm",0,"d")}const w=dE(s,g,l,`twist-own.${o}`),M=dE(s,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 vE(t,e.part,`${i.part}.local`,{seat:[_.x,_.y,_.z],pose:[x.x,x.y,x.z]}),t}const bE=t=>Math.round(1e6*t)/1e6;function vE(t,e,n,s){const i=t.document.model,{place:r,pose:o}=US(i,e,e),a=s?o.args.slice(0,3):[];s&&(o.args=[...s.pose,...o.args.slice(3)]),o.params={...o.params,to:`${e}.seat`};const c=GS(i,`${e}.motion`),l=aE(i,"mm",0,"d"),h=aE(i,"deg",0,"a");let d=GS(i,`${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:{}},i.nodes.push(d));const u=s?d.args.slice(0,3):[];s&&(d.args=[...s.seat,...d.args.slice(3)]),d.params={from:c?`${e}.joint`:`${e}.seat`,to:n};let p=GS(i,`${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`}},i.nodes.push(p))):p&&(i.nodes=i.nodes.filter(t=>t!==p));let f=GS(i,`${e}.chain`);f||(f={id:`${e}.chain`,op:"compose@1",args:["",""],outputs:{pose:`${e}.chain.value`}},i.nodes.push(f)),f.args=[d.outputs.pose,c?p.outputs.pose:o.outputs.pose];const m=/^(.*)\.local$/.exec(n);let g=GS(i,`${e}.world`);if(m&&m[1]!==e){const t=GS(i,`${m[1]}.world`)?.outputs?.pose??GS(i,`${m[1]}.chain`)?.outputs?.pose??GS(i,`${m[1]}.turned`)?.outputs?.pose??GS(i,`${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`}},i.nodes.push(g)),r.args=[r.args[0],g.outputs.pose]}else g&&(i.nodes=i.nodes.filter(t=>t!==g)),r.args=[r.args[0],f.outputs.pose];for(const n of[...a,...u])mE(t,n,fE(i,e,n)?n:void 0)}const _E=(t,e)=>t.inputs.find(t=>t.id===MS[e]),xE=t=>t.state?.id??t.id;function wE(t,e){const n=t.document.model,s=`joints.${String(e?.id)}`;e&&"string"==typeof e.id&&e.id.trim()||LS("JOINT_SCHEMA","joints","a joint has an id"),function(t,e){const n=(t,e,n)=>{if(t&&"object"==typeof t&&!Array.isArray(t))for(const[s,i]of Object.entries(t))void 0===i||e.includes(s)||LS("JOINT_SCHEMA",n,`${s} is a field this kernel does not know`)},s=(t,e)=>n(t,YS.source,e),i=(t,e)=>{if(t&&"object"==typeof t&&(n(t,YS.measure,e),s(t.from,`${e}.from`),Array.isArray(t.sum)))for(const[i,r]of t.sum.entries())n(r,YS.term,`${e}.sum.${i}`),s(r?.from,`${e}.sum.${i}.from`)};n(t,YS.joint,e),n(t.body0,YS.body0,`${e}.body0`),n(t.body1,YS.body1,`${e}.body1`);const r=t.origin;if(n(r,YS.origin,`${e}.origin`),r&&"object"==typeof r){i(r.gap,`${e}.origin.gap`),n(r.turn,YS.axes,`${e}.origin.turn`),n(r.align,YS.axes,`${e}.origin.align`);for(const[t,s]of Object.entries(r.align&&"object"==typeof r.align?r.align:{}))n(s,YS.alignment,`${e}.origin.align.${t}`),i(s?.mm,`${e}.origin.align.${t}.mm`)}if(t.travel&&"object"==typeof t.travel&&(n(t.travel,YS.travel,`${e}.travel`),s(t.travel.source,`${e}.travel.source`),Array.isArray(t.travel.sum)&&i({sum:t.travel.sum},`${e}.travel`)),n(t.state,YS.state,`${e}.state`),n(t.mimic,YS.mimic,`${e}.mimic`),Array.isArray(t.mimic?.sum))for(const[s,i]of t.mimic.sum.entries())n(i,YS.leader,`${e}.mimic.sum.${s}`);n(t.repeat,YS.repeat,`${e}.repeat`),t.repeat&&"object"==typeof t.repeat&&(i(t.repeat.pitch,`${e}.repeat.pitch`),n(t.repeat.rise,YS.rise,`${e}.repeat.rise`))}(e,s),NS.includes(e.type)||LS("JOINT_SCHEMA",s,`${String(e.type)} is not a joint type; ${NS.join(", ")}`),e.body1&&"string"==typeof e.body1.part||LS("JOINT_SCHEMA",s,"a joint carries a part (body1)"),US(n,e.body1.part,s),e.body0&&("plane"in e.body0||"string"==typeof e.body0.part)||LS("JOINT_SCHEMA",s,"a joint hangs from a part or the mounting plane (body0)"),"part"in e.body0&&US(n,e.body0.part,s);const i=(t.joints??[]).filter(t=>t.id!==e.id),r=i.find(t=>t.body1.part===e.body1.part);if(r&&LS("JOINT_TREE",s,`${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=>i.find(e=>e.body1.part===t)?.body0;for(let n=e.body0.part;n;){n===e.body1.part&&LS("ATTACH_CYCLE",s,`${e.body0.part} already hangs from ${e.body1.part}; ${e.body1.part} would hang from itself`);const i=t(n);n=i&&"part"in i?i.part:void 0}}const o="fixed"!==e.type,a=void 0!==e.lowerLimit||void 0!==e.upperLimit;if(o&&!["X","Y","Z"].includes(e.axis)&&LS("JOINT_SCHEMA",s,`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||LS("JOINT_SCHEMA",s,"a fixed joint has no axis, limits, mimic or travel"),void 0!==e.travel&&"prismatic"!==e.type&&LS("JOINT_SCHEMA",s,"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||LS("JOINT_SCHEMA",s,`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||LS("JOINT_SCHEMA",s,"a mimic sum follows one joint or more");const t=new Set;for(const n of HS(e)){const r=i.find(t=>t.id===n?.joint);r&&"fixed"!==r.type||LS("JOINT_SCHEMA",s,`${String(n?.joint)} is not a moving joint to follow`),t.has(r.id)&&LS("JOINT_SCHEMA",s,`${r.id} is followed twice; a sum names each joint once`),t.add(r.id),r.mimic&&LS("JOINT_SCHEMA",s,`${r.id} follows another joint; follow the one it follows`),"prismatic"===r.type!=("prismatic"===e.type)&&LS("JOINT_SCHEMA",s,`${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)||LS("JOINT_SCHEMA",s,"a mimic has a multiplier")}void 0===e.mimic.offset||Number.isFinite(e.mimic.offset)||LS("JOINT_SCHEMA",s,"a mimic's offset is a number in the joint's unit")}void 0===e.origin?.twist||Number.isFinite(e.origin.twist)||LS("JOINT_SCHEMA",`${s}.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)&&LS("JOINT_SCHEMA",`${s}.origin.turn`,"a turn is in quarter turns; an angle about the face's normal is its twist");const c=[...i,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 i=t(e.body1.part).map(t=>c.find(e=>e.body1.part===t)).filter(t=>t.repeat),r=[...n,...i].find(t=>t.repeat.axis===e.repeat.axis);r&&LS("JOINT_SCHEMA",`${s}.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,i=`${s}.repeat`;"part"in e.body0||LS("JOINT_SCHEMA",i,"a row fills the part it is fastened to; the mounting plane has no length to fill"),["X","Y","Z"].includes(n.axis)||LS("JOINT_SCHEMA",i,`a row runs along X, Y or Z, not ${String(n.axis)}`),n.axis.toLowerCase()===FS[nE(t.document.model,e)]&&LS("JOINT_SCHEMA",i,`a row runs across the face it is fastened to; ${n.axis} is out of that face`),("number"==typeof n.pitch?Number.isFinite(n.pitch)&&n.pitch>0:(t=>{const e=BS(t)?.terms;return Array.isArray(e)&&e.length>0&&e.every(t=>!!t?.from)})(n.pitch))||LS("GEOMETRY_DOMAIN",i,"a row has a positive pitch, or one that follows a length"),void 0===n.count||Number.isSafeInteger(n.count)&&n.count>=1&&n.count<=100||LS("GEOMETRY_DOMAIN",i,"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||LS("JOINT_SCHEMA",`${i}.rise`,`a row rises along X, Y or Z other than the one it runs along (${n.axis})`),Number.isFinite(n.rise.mm)&&0!==n.rise.mm||LS("GEOMETRY_DOMAIN",`${i}.rise`,"a rise is a length in mm, not zero"))}}function ME(t,e){const n=t.document.model,s=e.body1.part,{pose:i}=US(n,s,s),r="part"in e.body0?e.body0.part:void 0,o=`joints.${e.id}`,a=r?AE(OE(t,r,o)):SE,c=!EE(a),l=zw.map(t=>e.origin?.turn?.[t]??0),h=nE(n,e),d=FS[h],u=e.origin?.twist?QS(zE(d,e.origin.twist),KS(l)):KS(l),p=QS(a,u),f=RE(kE(a,CE[h]),`${e.body1.part}'s ${h}`,r??"",a,o),m=kE(a,zw.map(t=>t===d?1:0)),g=(e.origin?.twist??0)*Math.sign(m[zw.indexOf(f.axis)]),{quarter:y,deg:b}=function(t,e,n,s){const i=zw.indexOf(e),[r,o]=DE[e].map(t=>zw.indexOf(t));let a;for(const e of jE){const s=QS(t,AE(e));if(Math.abs(s[i][i]-1)>1e-9)continue;const c=180*Math.atan2(s[o][r],s[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||LS("ATTACH_FACE",s,`the part would stand turned about more than the face's normal (${qS(LE(t))})`);return{quarter:a.quarter,deg:a.off<1e-6?n:bE(a.deg)}}(p,f.axis,g,o),v=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...(c||e.origin?.twist?IE(y):l).map(t=>aE(n,"deg",t,"a"))];for(const e of v)mE(t,e,fE(n,s,e)?e:void 0);const _=t=>c&&Object.hasOwn(CE,t)?TE(RE(kE(a,CE[t]),t,r??"",a,o).vector):t;if(yE(t,{kind:"attach",part:s,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?FE(r?AE(PE(t,r,o)):a,e.origin.align,o):e.origin.align}:{},replace:!0},b?{deg:b}:void 0),b){const e=i.args.slice(3,6);i.args=[...i.args.slice(0,3),...LE(p).map(t=>aE(n,"deg",t,"a"))];for(const n of e)mE(t,n)}if(e.repeat&&c&&LS("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&&NE(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=HS(e).map(e=>({leader:(t.joints??[]).find(t=>t.id===e.joint),k:e.multiplier})),E=kE(a,zw.map(t=>t===e.axis.toLowerCase()?1:0)),A=E.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);A<0&&LS("JOINT_SCHEMA",o,`${r} stands twisted; the axis ${e.axis} is not level with an axis in it`),function(t,e,n,s=1){const i=t.document.model,r=e.part;US(i,e.part,r),(!e.motion||"slide"!==e.motion.kind&&"turn"!==e.motion.kind)&&LS("SCHEMA",r,"a slide or a turn is required");zw.includes(e.motion.axis)||LS("SCHEMA",r,`${String(e.motion.axis)} is not an axis`);GS(i,`${e.part}.motion`),0;GS(i,`${e.part}.motion`)&&GE(t,{part:e.part});const o=e.motion.frame??"attachment",a=YE(t,e.part);"asset"===o&&a!==t.document.capabilities.assetFrame?LS("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&&LS("SCHEMA",r,`${String(o)} is not a frame for the axis`);const c=e.state,l=oE(i,`${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(i.nodes.push({id:n,op:"mul@1",args:[e.of,aE(i,"ratio",e.k,"k")],outputs:{value:`${n}.value`}}),t){const e=l(`mimic.${t}.sum`);i.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");i.nodes.push({id:t,op:"mul@1",args:[n.terms[0].of,aE(i,"ratio",n.terms[0].k,"k")],outputs:{value:`${t}.value`}}),h=`${t}.value`}if(n.c){const t=l("mimic.offset"),s="slide"===e.motion.kind?"mm":"deg";i.nodes.push({id:t,op:"add@1",args:[h,aE(i,s,n.c,"d")],outputs:{value:`${t}.value`}}),h=`${t}.value`}}else{c&&"string"==typeof c.id&&c.id.trim()||LS("SCHEMA",r,"a state input id is required");const n=i.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(i.inputs.some(t=>t.id===c.id)){if((i.nodes.some(t=>t.args.includes(c.id))||(t.drivers??[]).some(t=>t.state===c.id)||t.appearance.some(t=>t.visibility===c.id))&&LS("DUPLICATE_WRITER",r,`${c.id} already exists`),i.inputs=i.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 s="turn"===e.motion.kind?["deg"]:["mm","ratio"];s.includes(c.unit)||LS("SCHEMA",r,`a ${e.motion.kind} takes a ${s.join(" or ")} control, not ${String(c.unit)}`),Number.isFinite(c.min)&&Number.isFinite(c.max)&&c.max>c.min||LS("SCHEMA",r,"a range with max above min is required");const o=c.start??c.min;o>=c.min&&o<=c.max||LS("SCHEMA",r,"the starting value is outside the range"),n||(i.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||LS("SCHEMA",r,"a ratio control needs travel: how far the part goes at 1");const n=e.travel;let s;if(Object.hasOwn(n,"sum")){const e=n.plus??0;s=cE(i,l,dE(i,l,hE(i,t,n.sum,e,`${r}.travel`),"travel.sum"),1,e,"travel")}else{const e=n.source?uE(i,t,n.source,r):aE(i,"mm",n.plus??0,"d");s=n.source?cE(i,l,e,n.times??1,n.plus??0,"travel"):e}const o=l("distance");i.nodes.push({id:o,op:"mul@1",args:[h,s],outputs:{value:`${o}.value`}}),h=`${o}.value`}else"slide"===e.motion.kind&&e.travel&&LS("SCHEMA",r,"a mm control is the distance; travel would say it twice");const d=zw.map(t=>aE(i,"ratio",t===e.motion.axis?s:0,"axis"));if(i.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}}),vE(t,e.part,a),e.clip){const n=e.clip;"string"==typeof n.name&&n.name.trim()||LS("SCHEMA",r,"a clip is named"),Number.isFinite(n.duration)&&n.duration>0||LS("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:s,motion:{kind:x,axis:zw[A]},state:{id:xE(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:GS(n,`${t.body1.part}.motion`)?.args[3]??xE(t),k:e})),c:e.mimic.offset??0,sum:Object.hasOwn(e.mimic,"sum")}:void 0,E[A]>0?1:-1),e.repeat&&NE(t,e)}const SE=[[1,0,0],[0,1,0],[0,0,1]],EE=t=>t.every((t,e)=>t.every((t,n)=>Math.abs(t-(e===n?1:0))<1e-12)),AE=t=>t[0].map((e,n)=>t.map(t=>t[n])),kE=(t,e)=>t.map(t=>t.reduce((t,n,s)=>t+n*e[s],0)),CE={left:[-1,0,0],right:[1,0,0],bottom:[0,-1,0],top:[0,1,0],back:[0,0,-1],front:[0,0,1]},TE=t=>Object.keys(CE).find(e=>CE[e].every((e,n)=>e===t[n]));function OE(t,e,n){const s=(t.joints??[]).find(t=>t.body1.part===e),i=s?zw.map(t=>s.origin?.turn?.[t]??0):WS(t.document.model,t,e,n);i.some(t=>null===t||!Number.isFinite(t)||Math.abs(t/90-Math.round(t/90))>1e-9)&&LS("EDIT_TARGET",n,`${e} is turned (${qS(i)}); fastening to a turned part by its faces is covered only for quarter turns`);const r=i.every(t=>0===t)?SE:KS(i);return s?.origin?.twist?QS(zE(FS[nE(t.document.model,s)],s.origin.twist),r):r}function PE(t,e,n){const s=(t.joints??[]).find(t=>t.body1.part===e);if(!s?.origin?.twist)return OE(t,e,n);const i=zw.map(t=>s.origin?.turn?.[t]??0);return i.every(t=>0===t)?SE:KS(i)}function IE(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(!KS(n).every((e,n)=>e.every((e,s)=>e===t[n][s])))throw new Error(`no turn gives ${JSON.stringify(t)}`);return n}const DE={x:["y","z"],y:["z","x"],z:["x","y"]};function zE(t,e){const n=Math.cos(e*Math.PI/180),s=Math.sin(e*Math.PI/180),[i,r]=DE[t].map(t=>zw.indexOf(t)),o=[[1,0,0],[0,1,0],[0,0,1]];return o[i][i]=n,o[i][r]=-s,o[r][i]=s,o[r][r]=n,o}function RE(t,e,n,s,i){const r=t.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);return r<0&&LS("ATTACH_FACE",i,`${n} stands twisted (${qS(LE(AE(s)))}); ${e} is not level with an axis in it`),{axis:zw[r],vector:t.map(t=>Math.abs(t)<1e-9?0:Math.sign(t))}}const jE=(()=>{const t=[];for(const e of[0,90,180,270])for(const n of[0,90,180,270])for(const s of[0,90,180,270]){const i=KS([e,n,s]);t.some(t=>t.every((t,e)=>t.every((t,n)=>t===i[e][n])))||t.push(i)}return t})();function LE(t){const e=t=>{const e=bE(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 FE(t,e,n){const s={};for(const[i,r]of Object.entries(e)){const e=kE(t,zw.map(t=>t===i?1:0)),o=e.findIndex(t=>Math.abs(Math.abs(t)-1)<1e-9);o<0&&LS("ATTACH_FACE",n,`the parent stands twisted; placing along ${i} is not level with an axis in it -- place it by the centre`);const a=Math.sign(e[o]),c=zw[o];"centre"===r||a>0?s[c]=r:"min"===r||"max"===r?s[c]="min"===r?"max":"min":"number"==typeof r.mm?s[c]={mm:-r.mm}:LS("SCHEMA",n,`an offset that follows another value cannot be turned over onto ${c}; give it as a number`)}return s}function NE(t,e){const n=t.document.model,s=e.body1.part,i=e.body0.part,r=`joints.${e.id}.repeat`,o=e.repeat.axis.toLowerCase(),a=zw.indexOf(o),c=iE(n,i,r)[o];c||LS("EDIT_TARGET",r,`${i} has no two faces along ${o}; there is no length to fill`);const l=rE(n,t,s,r)[o],h=l?void 0:function(t,e,n,s,i){const{shape:r}=US(t,n,i),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=XS(t,e,n,i),c=zw[a[zw.indexOf(s)].findIndex(t=>0!==t)];if(c===o.along)return;const l=`${n}.width.${c}`;if(!GS(t,l)){const e=aE(t,"mm",0,"d"),n=aE(t,"ratio",2,"k"),[s,i]=o.radii;t.nodes.push({id:l,op:"affine-bounds@1",args:[e,e,s,n,e,i,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,s,o,r);l||h||LS("EDIT_TARGET",r,`${s} has no two faces along ${o}; its copies cannot be spaced`);const{place:d,pose:u}=US(n,s,r),p=GS(n,`${s}.seat.rigid`),f=oE(n,`${s}.row`),m=aE(n,"mm",0,"d");p.args=p.args.map((t,e)=>e===a?dE(n,f,c.lo,"start"):t);const g=h||l.centred?m:dE(n,f,JS([...ZS(l.lo),...ZS(l.hi)]),"own-centre");u.args=u.args.map((t,e)=>e===a?g:t);const y=dE(n,f,[...c.hi,...JS(c.lo)],"length"),b=h??dE(n,f,[...l.hi,...JS(l.lo)],"extent"),v=aE(n,"ratio",.5,"k"),_=aE(n,"count",100,"limit"),x=e.repeat.count;n.nodes.push(void 0===x?{id:`${s}.layout`,op:"fit-pitch@1",args:[y,m,m,b,lE(n,t,f,e.repeat.pitch,"pitch",r),v,_],outputs:{layout:`${s}.layout.value`}}:{id:`${s}.layout`,op:"fixed-count@1",args:[aE(n,"count",x,"count"),y,m,m,b,v,_],outputs:{layout:`${s}.layout.value`}}),d.op="member@1",d.args=[d.args[0],GS(n,`${s}.turned`)?.outputs?.pose??u.outputs.pose],n.nodes.push({id:`${s}.assembly`,op:"assembly@1",args:[d.outputs.placed],outputs:{assembly:`${s}.assembly.value`}});const w=GS(n,`${i}.world`)?.outputs?.pose??GS(n,`${i}.chain`)?.outputs?.pose??GS(n,`${i}.turned`)?.outputs?.pose??GS(n,`${i}.pose`)?.outputs?.pose;let M=p.outputs.pose;w&&(n.nodes.push({id:`${s}.row`,op:"compose@1",args:[w,p.outputs.pose],outputs:{pose:`${s}.row.value`}}),M=`${s}.row.value`),n.nodes=n.nodes.filter(t=>t.id!==`${s}.chain`&&t.id!==`${s}.world`);const S=e.repeat.rise;n.nodes.push({id:`${s}.repeat`,op:"repeat@1",args:[`${s}.layout.value`,`${s}.assembly.value`,M,...S?[aE(n,"mm",S.mm,"rise")]:[]],outputs:{collection:`${s}.repeat.value`},params:{axis:o,...S?{riseAxis:S.axis.toLowerCase()}:{}}})}function $E(t,e){const n=t.document.model,s=e.body1.part;!function(t,e){const n=t.document.model,s=GS(n,e);if("member@1"!==s?.op||!GS(n,`${e}.repeat`))return;const i=GS(n,`${e}.layout`),r=GS(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)),s.op="place@1";for(const e of[...i?.args??[],...r?[r]:[]])mE(t,e)}(t,s),GS(n,`${s}.motion`)&&GE(t,{part:s});const{pose:i,place:r}=US(n,s,s),o=new Set([`${s}.seat.rigid`,`${s}.chain`,`${s}.world`,`${s}.turned`]);n.nodes=n.nodes.filter(t=>!o.has(t.id)&&!t.id.startsWith(`${s}.on.`));const a=aE(n,"mm",0,"d"),c=i.args.slice(0,3);i.args=[a,a,a,...i.args.slice(3)],i.params={...i.params,to:t.document.capabilities.assetFrame};for(const e of c)mE(t,e,fE(n,s,e)?e:void 0);r.args=[r.args[0],i.outputs.pose]}function HE(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=BS(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 s=t.origin.align[n];s&&"object"==typeof s&&Object.hasOwn(s,"mm")&&e.push({at:`align.${n}`,get:()=>s.mm,set:t=>s.mm=t})}return e}function BE(t){const e=t.joints??[];for(const n of e)for(const{at:e,get:s}of HE(n))for(const i of BS(s())?.terms??[])"part"===i?.from?.of&&pE(t.document.model,i.from.part,i.from.axis,`joints.${n.id}.${e}`);const n=function(t){const e=new Set,n=[],s=new Map(t.map(t=>[t.body1.part,t]));for(;n.length<t.length;){const i=t.filter(t=>{if(e.has(t.id))return!1;const n="part"in t.body0?s.get(t.body0.part):void 0;return(!n||e.has(n.id))&&HS(t).every(t=>e.has(t.joint))});i.length||LS("JOINT_TREE","joints","the joints do not make a tree");for(const t of i)e.add(t.id),n.push(t)}return n}(e),s={...t.stateDefaults};for(const e of t.document.model.nodes)"member@1"!==e.op||GS(t.document.model,`${e.id}.repeat`)||(e.op="place@1");for(const e of[...n].reverse())$E(t,e);for(const e of n)ME(t,e);!function(t,e){const n=t.document.model;for(const t of e.filter(t=>t.repeat)){const s=GS(n,`${t.body1.part}.assembly`),i=r=>{for(const o of e.filter(t=>"part"in t.body0&&t.body0.part===r)){if(o.repeat){const e=GS(n,`${o.body1.part}.repeat`);e.params={...e.params,within:`${t.body1.part}.repeat`},s.args.push(e.outputs.collection);continue}const e=GS(n,o.body1.part);e.op="member@1",s.args.push(e.outputs.placed),i(o.body1.part)}};i(t.body1.part)}}(t,e);for(const e of n)"fixed"===e.type||e.mimic||void 0===s[xE(e)]||(t.stateDefaults[xE(e)]=s[xE(e)])}const YE=(t,e)=>{const n=gE(t.document.model,e);return n?`${n}.local`:t.document.capabilities.assetFrame};function GE(t,e){const n=t.document.model,s=GS(n,`${e.part}.motion`);s||LS("EDIT_TARGET",e.part,`${e.part} does not move`);const i=s.args[3],r=GS(n,`${e.part}.seat.rigid`)?.params?.to??s.params.to,o=n.inputs.find(t=>t.id===i&&"state"===t.role)??n.inputs.find(t=>"state"===t.role&&(VS(n,i)?.args??[]).includes(t.id));return n.nodes=n.nodes.filter(t=>t!==s),vE(t,e.part,r),mE(t,i,i),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 VE=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 UE(t){const e=t.document.model,n=t=>e.constants.find(e=>e.id===t)?.value,s=t.document.capabilities.bindings.map(t=>{const s="string"==typeof t.pose?null:t.pose,i=s?e.nodes.find(t=>"place@1"===t.op&&t.outputs.placed===s.placement):null,r=s?VS(e,s.feature):null,o=(t.region?.dimensions??[]).map(n);return{id:t.id,label:t.label,role:t.role,part:i?.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}}),i=RS(t.document.capabilities.slotLayout).map(t=>{const n=e.nodes.find(e=>"place@1"===e.op&&e.outputs.placed===t.pose.placement),s=VS(e,t.pose.feature);return{id:t.id,label:t.label,role:t.role,part:n?.id??null,face:s?.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[...s,...i]}const WE=(t,e,n)=>{throw new Bw(t,e,n)};function qE(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||WE("SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||WE("SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||WE("SCHEMA",s,`unknown ${i}`)}const XE=(t,e)=>{"string"==typeof t&&t.trim()||WE("SCHEMA",e,"nonempty string required")};function KE(t,e){return function(t,e){const n=fS(t),s=structuredClone(e),i=n.outputTypes,r=new Map(t.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,structuredClone(t)]))),o=new Map;qE(s,["version","assetFrame","bindings"],["names","slotLayout"],"capabilities"),"r3-capability-3"!==s.version&&WE("VERSION","capabilities",s.version);if(XE(s.assetFrame,"assetFrame"),void 0!==s.names){Array.isArray(s.names)||WE("SCHEMA","names","array required");for(const t of s.names)Rw.includes(t)||WE("CAPABILITY_NAME","names",`${String(t)} is not one of ${Rw.join(", ")}`);new Set(s.names).size!==s.names.length&&WE("CAPABILITY_NAME","names","duplicate capability name");for(const[t,e]of Object.entries(jw))s.names.includes(t)&&!e.some(t=>s.names.includes(t))&&WE("CAPABILITY_NAME","names",`${t} needs one of ${e.join(", ")} with it`)}Array.isArray(s.bindings)||WE("SCHEMA","bindings","array required");const a=new Set,c=(t,e)=>(XE(t,e),Object.hasOwn(i,t)||WE("TARGET_ABSENT",e,t),i[t]),l=(t,e,n)=>{const i=c(t,e);("transform"!==i.kind||i.to!==s.assetFrame||void 0!==n&&i.from!==n)&&WE("FRAME_TYPE",e,"transform must map declared local frame to assetFrame")},h=(e,n)=>bS({types:i,writers:r,model:t,assetFrame:s.assetFrame},e,n),d=new Map;for(const t of s.bindings){qE(t,["id","label","role","frame","pose","accepts","capacity"],["region","contacts"],"binding");for(const e of["id","label","frame"])XE(t[e],e);if(a.has(t.id)&&WE("DUPLICATE_BINDING",t.id,"duplicate id"),a.add(t.id),["seat","grip"].includes(t.role)||WE("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&&WE("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||WE("SCHEMA",t.id,"nonempty accepts required"),t.accepts.forEach(e=>XE(e,t.id)),new Set(t.accepts).size!==t.accepts.length&&WE("SCHEMA",t.id,"duplicate accepted type"),(!Number.isSafeInteger(t.capacity)||t.capacity<1)&&WE("CAPACITY",t.id,"positive integer capacity required"),Object.hasOwn(t,"region")){qE(t.region,["kind","dimensions"],[],t.id+".region"),"centered-box"!==t.region.kind&&WE("REGION",t.id,"only centered-box is specified"),Array.isArray(t.region.dimensions)&&3===t.region.dimensions.length||WE("SCHEMA",t.id,"three dimension references required");for(const e of t.region.dimensions)"[1,0,0]"!==JSON.stringify(c(e,t.id))&&WE("TYPE",t.id,"region dimensions must be lengths")}if(void 0!==t.contacts){Array.isArray(t.contacts)||WE("SCHEMA",t.id,"contact array required");const e=new Set,n=[];for(const s of t.contacts){const i=h(s,t.id),r=JSON.stringify([s.placement,s.feature]);e.has(r)&&WE("DUPLICATE_CONTACT",t.id,r),e.add(r),n.push(i)}o.set(t.id,n)}}const u=[];if(void 0!==s.slotLayout){const t=s.slotLayout;qE(t,["label","role","anchors","layout"],[],"slotLayout"),XE(t.label,"slotLayout.label"),["seat","grip"].includes(t.role)||WE("ROLE","slotLayout","explicit seat or grip required; slot is ambiguous"),Array.isArray(t.anchors)&&t.anchors.length||WE("SCHEMA","slotLayout.anchors","at least one anchor required");const e=new Map;t.anchors.forEach((t,n)=>{const s=`slotLayout.anchors[${n}]`;qE(t,["id","frame","pose"],[],s),XE(t.id,`${s}.id`),XE(t.frame,`${s}.frame`),e.has(t.id)&&WE("SCHEMA",`${s}.id`,`duplicate anchor ${t.id}`),"string"==typeof t.pose&&WE("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a face of a part");const i=h(t.pose,s);i.frame!==t.frame&&WE("FRAME_TYPE",s,"anchor frame must be the selected feature frame");const r=i.normal[1];r||WE("SLOT_LAYOUT_FACE",`${s}.pose`,"an anchor is a horizontal face (its normal along Y)"),e.set(t.id,{surface:i,up:r})});const n=function(t,e={}){const n=[];if(!t||!Array.isArray(t.tiers)||0===t.tiers.length)return[SS("TIERS_REQUIRED","tiers")];const s=e.anchors?new Set(e.anchors):null,i=new Set;return t.tiers.forEach((t,e)=>{const r=`tiers[${e}]`;if(!t||"object"!=typeof t)return void n.push(SS("OBJECT_REQUIRED",r));if(kS(t.tierNo)?i.has(t.tierNo)?n.push(SS("TIER_NUMBER_DUPLICATE",`${r}.tierNo`,{tierNo:t.tierNo})):i.add(t.tierNo):n.push(SS("POSITIVE_INTEGER_REQUIRED",`${r}.tierNo`)),"string"==typeof t.anchorId&&t.anchorId.trim()?s&&!s.has(t.anchorId)&&n.push(SS("ANCHOR_UNKNOWN",`${r}.anchorId`,{anchorId:t.anchorId})):n.push(SS("ANCHOR_REQUIRED",`${r}.anchorId`)),["ON","IN","HANG"].includes(t.mount)||n.push(SS("MOUNT_INVALID",`${r}.mount`)),t.position&&"object"==typeof t.position)for(const e of["x","y","z"])ES(t.position[e])||n.push(SS("FINITE_NUMBER_REQUIRED",`${r}.position.${e}`));else n.push(SS("OBJECT_REQUIRED",`${r}.position`));ES(t.rotation)||n.push(SS("FINITE_NUMBER_REQUIRED",`${r}.rotation`));const o=t.layout;switch(o?.pattern){case"SINGLE":CS(o.slot,`${r}.layout.slot`,n);break;case"ROW":kS(o.count)||n.push(SS("POSITIVE_INTEGER_REQUIRED",`${r}.layout.count`)),AS(o.pitch)||n.push(SS("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch`)),"X"!==o.axis&&"Z"!==o.axis&&n.push(SS("AXIS_INVALID",`${r}.layout.axis`)),CS(o.slot,`${r}.layout.slot`,n);break;case"GRID":kS(o.rows)||n.push(SS("POSITIVE_INTEGER_REQUIRED",`${r}.layout.rows`)),kS(o.cols)||n.push(SS("POSITIVE_INTEGER_REQUIRED",`${r}.layout.cols`)),AS(o.pitch?.x)||n.push(SS("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.x`)),AS(o.pitch?.z)||n.push(SS("POSITIVE_NUMBER_REQUIRED",`${r}.layout.pitch.z`)),CS(o.slot,`${r}.layout.slot`,n);break;case"CUSTOM":{if(!Array.isArray(o.slots)){n.push(SS("ARRAY_REQUIRED",`${r}.layout.slots`));break}o.slots.length||n.push(SS("SLOTS_REQUIRED",`${r}.layout.slots`));const t=new Set;o.slots.forEach((e,s)=>{const i=`${r}.layout.slots[${s}]`;kS(e?.slotNo)?t.has(e.slotNo)?n.push(SS("SLOT_NUMBER_DUPLICATE",`${i}.slotNo`,{slotNo:e.slotNo})):t.add(e.slotNo):n.push(SS("POSITIVE_INTEGER_REQUIRED",`${i}.slotNo`)),ES(e?.offset?.x)&&ES(e?.offset?.z)||n.push(SS("FINITE_NUMBER_REQUIRED",`${i}.offset`)),CS(e,i,n)});break}default:n.push(SS("PATTERN_INVALID",`${r}.layout.pattern`))}}),n}(t.layout,{anchors:e.keys()}),i=n.length?n:function(t,e=""){const n=[],s=(t,e)=>{if("number"!=typeof t||Number.isFinite(t)){if(Array.isArray(t))t.forEach((t,n)=>s(t,`${e}[${n}]`));else if(t&&"object"==typeof t)for(const[n,i]of Object.entries(t))s(i,e?`${e}.${n}`:n)}else n.push(SS("NOT_PERSISTABLE",e,{value:String(t)}))};return s(t,e),n}(t.layout);i.length&&WE("SLOT_LAYOUT",`slotLayout.layout.${i[0].path}`,i.map(t=>`${t.code} at ${t.path}`).join("; "));for(const n of RS(t)){n.accepts.length||WE("SCHEMA",n.id,"nonempty accepts required"),n.accepts.forEach(t=>XE(t,n.id)),new Set(n.accepts).size!==n.accepts.length&&WE("SCHEMA",n.id,"duplicate accepted type"),(!Number.isSafeInteger(n.capacity)||n.capacity<1)&&WE("CAPACITY",n.id,"positive integer capacity required"),a.has(n.id)&&WE("DUPLICATE_BINDING",n.id,"duplicate id"),a.add(n.id);const t=e.get(n.anchorId);d.set(n.id,t.surface),u.push({...n,up:t.up})}}const p=[...s.bindings,...u];function f(t,e){const n=t.pose.r,s=zS(e),i=[s.position.x,s.position.y*e.up,s.position.z],r=n.map((e,n)=>t.pose.t[n]+e.reduce((t,e,n)=>t+e*i[n],0)),o=s.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,s)=>t+e*l[s][n],0)));return{...t,pose:{r:h,t:r}}}function m(t,e,n){const s=t=>function(t,e){const n=t[e.placement],s=t[e.feature],i=n.pose.r,r=i.map(t=>t.reduce((t,n,s)=>t+n*e.normal[s],0)),o=i.map((t,e)=>n.pose.t[e]+t.reduce((t,e,n)=>t+e*s.t[n],0));let a=e.geometryId;if(e.selection){const n=e.selection,s=t[n.collection].items.find(e=>e.index===t[n.index]&&e.key===n.member);s||gS("TARGET_ABSENT",e.placement,"selected repeated item is absent"),a=s.id}return{placement:e.placement,feature:e.feature,geometryId:a,provider:e.provider,face:e.face,pose:{r:i.map(t=>[...t]),t:o},normal:r,provenance:"verified-planar-surface"}}(e,t);let i=null;if(t.allowed)i={kind:"centered-box",dimensions:[t.allowed.width,t.allowed.height,t.allowed.depth]};else if(t.region){const n=t.region.dimensions.map(t=>e[t]);n.some(t=>!Number.isFinite(t)||t<=0)&&WE("REGION_DOMAIN",t.id,"positive region dimensions required"),i={kind:t.region.kind,dimensions:n}}let r={status:"unverified",reason:"NO_REQUEST"};if(Object.hasOwn(n,t.id)){const e=n[t.id];qE(e,["type","occupied"],[],t.id+".request"),XE(e.type,t.id),(!Number.isSafeInteger(e.occupied)||e.occupied<0)&&WE("OCCUPANCY",t.id,"nonnegative integer occupancy snapshot required");const s=[];t.accepts.includes(e.type)||s.push("TYPE_NOT_ACCEPTED"),e.occupied>=t.capacity&&s.push("CAPACITY_FULL"),r={status:s.length?"failed":"satisfied",reasons:s}}const a=(o.get(t.id)??[]).map(s),c=d.has(t.id)?s(d.get(t.id)):null,l=c&&t.allowed?f(c,t):c;return{id:t.id,label:t.label,role:t.role,frame:t.frame,pose:l?l.pose:e[t.pose],...l?{targetGeometryId:l.geometryId}:{},region:i,contacts:a,checks:{declaration:{status:"satisfied"},eligibility: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 qE(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(i),dependence:structuredClone(n.dependence),evaluate:(t,e={})=>g(n,t,e),evaluator(t={}){const e=n.evaluator({reads:_,changes:!!t.changes});return{evaluate:(t,n={})=>g(e,t,n),advance:(t,n={})=>{qE(n,[],[...a],"requests");const s=Object.keys(n).length>0,i=e.advance(t,s?"REQUESTS":void 0);if("evaluation"===i.kind)return{...i,result:y(i.result,n)};if("changes"===i.kind){const t=p.filter(t=>s||i.structure||v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{...i,places:t}}const r=p.filter(t=>v.get(t.id).some(t=>i.changed(t))).map(t=>m(t,Object.fromEntries(v.get(t.id).map(t=>[t,i.read(t)])),n));return{kind:"poses",generation:i.generation,bodies:i.bodies,poses:i.poses,places:r}},poseInputs:()=>e.poseInputs(),place:(t,n={})=>{const s=p.find(e=>e.id===t);return s||WE("TARGET_ABSENT",t,"no such place"),qE(n,[],[...a],"requests"),m(s,Object.fromEntries(v.get(t).map(t=>[t,e.value(t)])),n)}}}}}(t,e)}const QE=1048576;function JE(t,e){throw new Bw(t,"document",e)}function ZE(t){return(new TextEncoder).encode(t).byteLength}function tA(t){const e=new Set;!function t(n,s){if(s>64&&JE("DOCUMENT_LIMIT","nesting exceeds 64"),null===n||"string"==typeof n||"boolean"==typeof n)return;if("number"==typeof n)return void(Number.isFinite(n)||JE("JSON_VALUE","nonfinite number"));"object"!=typeof n&&JE("JSON_VALUE","only JSON values are allowed"),e.has(n)&&JE("JSON_VALUE","cycle");const i=Array.isArray(n);i||function(t){const e=Object.getPrototypeOf(t);return null===e||null===Object.getPrototypeOf(e)&&"function"==typeof e.hasOwnProperty}(n)||JE("JSON_VALUE","plain objects required"),e.add(n);const r=Object.getOwnPropertyDescriptors(n);for(const e of Reflect.ownKeys(r)){if(i&&"length"===e)continue;"string"!=typeof e&&JE("JSON_VALUE","symbols unsupported");const o=r[e];o.enumerable&&Object.hasOwn(o,"value")||JE("JSON_VALUE","hidden properties and accessors unsupported"),!i||/^(0|[1-9][0-9]*)$/.test(e)&&Number(e)<n.length||JE("JSON_VALUE","extra array property"),t(o.value,s+1)}i&&Object.keys(n).length!==n.length&&JE("JSON_VALUE","sparse array"),e.delete(n)}(t,0)}function eA(t){if(tA(t),!t||Array.isArray(t)||"object"!=typeof t||3!==Object.keys(t).length||!["version","model","capabilities"].every(e=>Object.hasOwn(t,e)))throw new Bw("SCHEMA","document","expected version, model, capabilities only");if("figure-prototype-1"!==t.version)throw new Bw("VERSION","document","unsupported document version");if(ZE(JSON.stringify(t))>QE)throw new Bw("DOCUMENT_LIMIT","document","over 1 MiB");const e=t;if(!Array.isArray(e.model?.nodes)||e.model.nodes.length>8192)throw new Bw("DOCUMENT_LIMIT","document","maximum 8192 nodes");return KE(e.model,e.capabilities)}const nA=(t,e,n)=>{throw new Bw(t,e,n)};function sA(t){return new Map(t.document.model.inputs.filter(t=>"state"===t.role).map(t=>[t.id,t.unit]))}function iA(t,e){const n=t.keys;if(e<=n[0].at)return n[0].value;const s=n[n.length-1];if(e>=s.at)return s.value;let i=0;for(;i<n.length-2&&n[i+1].at<=e;)i++;const r=n[i],o=n[i+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 rA(t,e,n="other"){Number.isFinite(e)||nA("DRIVER_TIME",t.id,"finite time required");const s=Math.max(0,e),i=t.time.duration,r=t.keys[0].value,o=t.keys[t.keys.length-1];let a;if("hold"===t.loop)a=iA(t,Math.min(s/i,1));else{const e=Math.floor(s/i);a=iA(t,(s-e*i)/i),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,s=n/2,i=((t+s)%n+n)%n-s;return i===s?-s:i}(a,n):nA("DRIVER_STATE",t.id,"an accumulating driver needs an angle unit"):a}const oA=(t,e,n)=>{throw new Bw(t,e,n)};function aA(t,e,n,s){t&&"object"==typeof t&&!Array.isArray(t)||oA("ASSET_SCHEMA",s,"object required");for(const n of e)Object.hasOwn(t,n)||oA("ASSET_SCHEMA",s,`missing ${n}`);for(const i of Object.keys(t))[...e,...n].includes(i)||oA("ASSET_SCHEMA",s,`unknown ${i}`)}function cA(t){return function(t){tA(t);const e=lA(t);ZE(JSON.stringify(e))>QE&&oA("DOCUMENT_LIMIT","asset","over 1 MiB");aA(e,["version","name","document","designInputs","stateDefaults","palette","appearance"],["occupancy","placement","drivers","stateInputs","sizing","detailLevel","joints","publicInputs"],"asset"),void 0===e.placement||jS.includes(e.placement)||oA("ASSET_SCHEMA","placement",`one of ${jS.join(", ")} required`);"figure-asset-1"!==e.version&&oA("VERSION","asset",e.version);"string"==typeof e.name&&e.name.trim()||oA("ASSET_SCHEMA","name","nonempty name required");const n=structuredClone(e),s=eA(n.document),i=n.document.model,r=i.inputs.filter(t=>"state"!==t.role).map(t=>t.id),o=i.inputs.filter(t=>"state"===t.role).map(t=>t.id);aA(n.designInputs,r,[],"designInputs"),void 0===n.detailLevel||(t=>Lw.includes(t))(n.detailLevel)||oA("ASSET_SCHEMA","detailLevel",`${String(n.detailLevel)} is not a detail level; ${Lw.join(", ")}`);if(void 0!==n.sizing){"uniform"!==n.sizing&&oA("ASSET_SCHEMA","sizing",`${String(n.sizing)} is not a sizing rule; 'uniform' is`);for(const t of["x","y","z"])i.inputs.some(e=>e.id===`size.${t}`&&"design"===e.role)||oA("ASSET_SCHEMA","sizing",`a figure that grows uniformly declares its instance size; size.${t} is missing`)}if(aA(n.stateDefaults,o,[],"stateDefaults"),void 0!==n.publicInputs){Array.isArray(n.publicInputs)||oA("ASSET_SCHEMA","publicInputs","a list of the inputs a board may set");const t=new Set;for(const[e,s]of n.publicInputs.entries()){const n=`publicInputs[${e}]`;aA(s,["input","label"],["hint"],n),mS(i.inputs,s.input,`${n}.input`),"string"==typeof s.label&&s.label.trim()||oA("ASSET_SCHEMA",`${n}.label`,"a name shown on the board"),void 0!==s.hint&&"string"!=typeof s.hint&&oA("ASSET_SCHEMA",`${n}.hint`,"one line"),t.has(s.input)&&oA("PUBLIC_INPUT",`${n}.input`,`${s.input} is listed twice`),t.add(s.input)}}n.palette&&"object"==typeof n.palette&&!Array.isArray(n.palette)||oA("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)||oA("PALETTE","palette","six digit hex color required");const a=t=>{"string"==typeof t&&Object.hasOwn(n.palette,t)||oA("PALETTE",String(t),"unresolved color token")},c=new Map(i.nodes.flatMap(t=>Object.values(t.outputs).map(e=>[e,t]))),l=new Map(i.nodes.filter(t=>["place@1","member@1"].includes(t.op)).map(t=>[t.id,t])),h=new Map;Array.isArray(n.appearance)||oA("ASSET_SCHEMA","appearance","array required");for(const t of n.appearance){if(aA(t,["target","material"],["segments","visibility"],"appearance"),void 0!==t.visibility){const e=s.outputTypes[t.visibility];"string"==typeof t.visibility&&e&&"flag"===e.kind||oA("VISIBILITY","appearance.visibility",`${String(t.visibility)} is not a flag value in the graph`)}if(l.has(t.target)&&!h.has(t.target)||oA("APPEARANCE_TARGET",String(t.target),"unknown or duplicate source placement"),aA(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)||oA("MATERIAL","preset","unknown preset"),void 0!==t.material.transparent&&"boolean"!=typeof t.material.transparent&&oA("MATERIAL","transparent","boolean required"),void 0!==t.material.emissive){const e=t.material.emissive;aA(e,["token","intensity","on"],[],"emissive"),a(e.token),("boolean"!=typeof e.on||!Number.isFinite(e.intensity)||e.intensity<0||e.intensity>5)&&oA("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)||oA("QUALITY","segments","explicit supported cylinder segment count required"):void 0!==t.segments&&oA("QUALITY","segments","segments unsupported on this provider"),h.set(t.target,t)}h.size!==l.size&&oA("APPEARANCE_MISSING","appearance","every source placement/member requires appearance");if(void 0!==n.occupancy){if(aA(n.occupancy,["bounds"],["contact"],"occupancy"),void 0!==n.occupancy.contact){const t=n.occupancy.contact;aA(t,["plane","surface"],[],"occupancy.contact"),"mounting-plane"!==t.plane&&oA("OCCUPANCY","occupancy.contact",`${String(t.plane)} is not a plane the figure can be mounted on`),bS({types:s.outputTypes,writers:c,model:i,assetFrame:n.document.capabilities.assetFrame},t.surface,"occupancy.contact.surface")}aA(n.occupancy.bounds,["x","y","z"],[],"occupancy.bounds");const t=JSON.stringify([1,0,0]);for(const e of["x","y","z"]){aA(n.occupancy.bounds[e],["min","max"],[],`occupancy.bounds.${e}`);for(const i of["min","max"]){const r=`occupancy.bounds.${e}.${i}`,o=n.occupancy.bounds[e][i];"string"==typeof o&&JSON.stringify(s.outputTypes[o])===t||oA("OCCUPANCY",r,`${String(o)} is not a length value in the graph`),s.dependence[o]?.length&&oA("OCCUPANCY_STATE",r,`${o} depends on state input ${s.dependence[o].join(", ")}; the occupancy is state-independent`)}}}(function(t){const e=t.drivers;if(void 0===e)return;Array.isArray(e)||nA("DRIVER","drivers","array required");const n=sA(t),s=new Set,i=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"])&&nA("DRIVER",e,"exactly id, clip, state, time, keys, interpolation, loop, accumulates required"),"string"==typeof t.id&&t.id.trim()||nA("DRIVER",e,"id required"),s.has(t.id)&&nA("DRIVER",e,"duplicate driver id"),s.add(t.id),"string"==typeof t.clip&&t.clip.trim()||nA("DRIVER",e,"clip required; the playback group is declared, not read out of the id"),n.has(t.state)||nA("DRIVER_STATE",e,`${String(t.state)} is not a state input of this asset`),i.has(t.state)&&nA("DRIVER_STATE",e,`two drivers write ${t.state}; one writer per state`),i.add(t.state),JSON.stringify(o(t.time))===JSON.stringify(["duration","unit"])&&"s"===t.time.unit||nA("DRIVER_TIME",e,'time must be { unit: "s", duration }'),Number.isFinite(t.time.duration)&&t.time.duration>0||nA("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&&nA("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)&&nA("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"])&&nA("DRIVER_KEYS",e,"a key is { at, value }"),Number.isFinite(n.at)&&n.at>=0&&n.at<=1||nA("DRIVER_KEYS",e,"key at must be a fraction of the duration in [0, 1]"),n.at>c||nA("DRIVER_KEYS",e,"key at values must strictly increase"),c=n.at,Number.isFinite(n.value)||nA("DRIVER_KEYS",e,"finite key value required");0!==t.keys[0].at&&nA("DRIVER_KEYS",e,"the first key is at 0"),["linear","step"].includes(t.interpolation)||nA("DRIVER",e,"interpolation is linear or step"),["wrap","hold"].includes(t.loop)||nA("DRIVER",e,"loop is wrap or hold"),"boolean"!=typeof t.accumulates&&nA("DRIVER",e,"accumulates must be a boolean");const l=n.get(t.state);t.accumulates&&"deg"!==l&&"rad"!==l&&nA("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)||nA("STATE_INPUT","stateInputs","object required");const n=sA(t);for(const[t,s]of Object.entries(e)){const e=`stateInputs.${t}`;n.has(t)||nA("STATE_INPUT",e,`${t} is not a state input of this asset`),s&&"object"==typeof s&&!Array.isArray(s)||nA("STATE_INPUT",e,"object required");for(const t of Object.keys(s))"label"!==t&&"sweep"!==t&&nA("STATE_INPUT",e,`unknown ${t}`);void 0===s.label||"string"==typeof s.label&&s.label.trim()||nA("STATE_INPUT",e,"label must be a nonempty string"),void 0===s.sweep||Number.isFinite(s.sweep)&&s.sweep>=0||nA("STATE_INPUT",e,"sweep must be a number of seconds, zero or more")}}(n),void 0===n.joints||Array.isArray(n.joints)||oA("ASSET_SCHEMA","joints","joints is a list");function d(t={}){aA(t,[],o,"state overrides");const e={...n.designInputs,...n.stateDefaults,...t},i=s.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=i.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||oA("APPEARANCE_MISSING",t.id,"no source appearance"),{...t,material:structuredClone(n.material),visible:void 0===n.visibility||i.values[n.visibility],...void 0!==n.segments?{segments:n.segments}:{}}});return{...i,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)wE({...n,joints:e.filter(e=>e.id!==t.id).concat(t)},t);BE(n);const s=t=>JSON.stringify({nodes:[...t.nodes].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0),inputs:[...t.inputs].sort((t,e)=>t.id<e.id?-1:t.id>e.id?1:0)});s(n.document.model)!==s(t.document.model)&&LS("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 lA(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&&oA("PLACEMENT_CONFLICT","placement",`the asset says ${String(e.placement)} and its room says ${String(n)}; keep one`);const{placement:s,...i}=e.occupancy;return{...e,placement:n,occupancy:i}}const hA="0.4.3";function dA(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 uA=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,dA(t),!1!==t.visible]);function pA(t,e){const n=function(t,e){const n=e??eA(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=wS(t),r=t=>{const e=void 0===t?void 0:s.get(t);return!e||Object.values(e.outputs).some(t=>(n[t]?.length??0)>0)};return t=>{const{key:e,path:n}=t;return!!r("string"==typeof n?.[0]?n[0]:t.id)||!!e&&r(i.get(e))}}(t,e),s=wS(t),i=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?s.get(r.key):r.id;void 0!==t&&i.has(t)||e.add(r.id)}return e}}const fA=t=>`${dA(t)}|${!1!==t.visible?"shown":"hidden"}`;function mA(t,e={}){const n=[],s=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 i=s.get(t)??[];i.push(e),s.set(t,i)}const i=[],r=[];for(const[t,e]of s){const s=new Map;for(const t of e){const e=uA(t),n=s.get(e);n?n.push(t.id):s.set(e,[t.id])}for(const[o,a]of s)a.length>1?i.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 s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of n){const n=s.get(t);if(!n||!e.still.has(t)||n.material.transparent)continue;const r=fA(n),o=i.get(r);o?o.push(t):i.set(r,[t])}const r=new Set;for(const[t,e]of i)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 s=new Map(t.map(t=>[t.id,t])),i=new Map;for(const t of n){const n=s.get(t),r=e.carried.get(t);if(!n||void 0===r||e.still?.has(t)||n.material.transparent)continue;const o=`${r}|${fA(n)}`,a=i.get(o);a?a.ids.push(t):i.set(o,{carrier:r,ids:[t]})}const r=new Set;for(const[t,{carrier:e,ids:n}]of i)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:i,merged:o,carried:a,alone:n,unbatched:r}}const gA=Fw[0];function yA(t,e,n,s={}){const[i,r]=Yw[e],o=s[i]??0,a=s[r]??0;let c;if("polygon"===t.kind)c=t.points.map(t=>[t[i],t[r]]);else if("ellipse"===t.kind){const e=t.radius[i],s=t.radius[r];c=Array.from({length:n},(t,i)=>{const r=2*Math.PI*i/n;return[e*Math.cos(r),s*Math.sin(r)]})}else{const e=t.size[i]/2,n=t.size[r]/2,s=t.corner?.[i]??0,o=t.corner?.[r]??0;if(s>0&&o>0){c=[];for(const[t,i,r]of[[1,-1,-Math.PI/2],[1,1,0],[-1,1,Math.PI/2],[-1,-1,Math.PI]])for(let a=0;a<=gA;a++){const l=r+a/gA*(Math.PI/2);c.push([t*(e-s)+s*Math.cos(l),i*(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]),bA(c)<0?c.reverse():c}const bA=t=>t.reduce((e,n,s)=>e+n[0]*t[(s+1)%t.length][1]-t[(s+1)%t.length][0]*n[1],0)/2;function vA(t){const e=[...t].sort((t,e)=>t[0]-e[0]||t[1]-e[1]).map(([t,e])=>[t,e]);if(e.length<3)return e;const n=(t,e,n)=>(e[0]-t[0])*(n[1]-t[1])-(e[1]-t[1])*(n[0]-t[0]),s=[];for(const t of e){for(;s.length>=2&&n(s[s.length-2],s[s.length-1],t)<=1e-9;)s.pop();s.push(t)}const i=[];for(let t=e.length-1;t>=0;t--){const s=e[t];for(;i.length>=2&&n(i[i.length-2],i[i.length-1],s)<=1e-9;)i.pop();i.push(s)}return s.slice(0,-1).concat(i.slice(0,-1))}const _A=t=>"shape"in t&&"pose"in t&&!!t.shape;function xA(t,e,n,s={}){const[i,r]=Yw.y;return yA(t,"y",n,s).map(([t,n])=>{const s={x:0,y:e,z:0};return s[i]=t,s[r]=n,[s.x,s.y,s.z]})}let wA=null;function MA(t){wA=t}function SA(t,e=[],n){wA?.registerType?.(t,e,n)}function EA(t){if(Array.isArray(t))return`[${t.map(EA).join(",")}]`;if(t&&"object"==typeof t){const e=t;return`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${EA(e[t])}`).join(",")}}`}return JSON.stringify(t)}const AA=new Map;function kA(t){const e=function(t){const e=EA(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}|${hA}`,s=AA.get(n);if(s)return AA.delete(n),AA.set(n,s),s;const i=lA(structuredClone(t)),r=new Map;for(const t of i.document.model.nodes)for(const e of Object.values(t.outputs))r.set(e,t.id);const o={key:n,fingerprint:e,kernel:hA,compiled:cA(i),document:eA(i.document),looks:new Map(i.appearance.map(t=>[t.target,t])),writers:r,asset:i};return AA.set(n,o),AA.size>256&&AA.delete(AA.keys().next().value),o}const CA=new Map;function TA(t,e){cA(e);const n={type:t,compiled:kA(e)};return CA.set(t,n),SA(t,e.document.capabilities.names??[],lA(e).placement),n}function OA(t){return CA.get(t)??null}function PA(t){return CA.has(t)}function IA(t){return CA.delete(t)}function DA(){CA.clear()}const zA=["x","y","z"],RA=new WeakMap;function jA(t){let e=RA.get(t);return e||RA.set(t,e=function(t){const e=t.document.model.inputs,n=t.designInputs,s=zA.every(t=>"number"==typeof n[Nw[t]]&&e.some(e=>e.id===Nw[t])),i={};if(s)for(const t of zA){const n=e.find(e=>e.id===Nw[t]);i[t]={min:n.min??0,max:n.max??1/0}}const r=fS(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 zA)n[Nw[t]]=e[t];const s=r.evaluate(n).values,i=t=>Math.max((s[o[t].max]??0)-(s[o[t].min]??0),1e-6);return{x:i("x"),y:i("y"),z:i("z")}},c=s?{x:n[Nw.x],y:n[Nw.y],z:n[Nw.z]}:null,l=!s||"uniform"===t.sizing,h=a(c),d={};if(c&&l){const t=Math.min(2,...zA.map(t=>i[t].max/c[t])),e=Math.max(.5,...zA.map(t=>i[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 zA)d[e]=(t[e]-h[e])/(c[e]*(n-1))}}else if(c)for(const t of zA){const{min:e,max:n}=i[t],s=c[t],r=n>s?Math.min(n,2*s):e<s?Math.max(e,s/2):s;if(r===s)continue;const o=a({...c,[t]:r});d[t]=(o[t]-h[t])/(r-s)}return{evaluated:s,proportional:l,limits:i,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 LA(t){return jA(t).proportional}function FA(t,e,n=[]){const s=jA(t),i=n.find(t=>void 0!==e[t])??"x",r=(t,e)=>{const n=s.limits[t];return n?Math.min(Math.max(e,n.min),n.max):e};if(!s.evaluated){const t=Math.max(e[i]/s.authored[i],1e-6);return{inputs:null,scale:t,occupancy:{x:s.authored.x*t,y:s.authored.y*t,z:s.authored.z*t}}}const o=s.authoredInputs;let a;if(s.proportional){let t=Math.max(s.inputFor(i,e[i])/o[i],1e-6);for(const e of zA){const n=s.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",s.inputFor("x",e.x)),y:r("y",void 0!==e.y?s.inputFor("y",e.y):o.y),z:r("z",s.inputFor("z",e.z))};return{inputs:a,scale:1,occupancy:s.occupancyAt(a)}}const NA=Math.cos(40*Math.PI/180);function $A(e){const[n,s]=Yw[e];return([i,r],o)=>{const a={x:0,y:0,z:0};return a[n]=i,a[s]=r,a[e]=o,new t.Vector3(a.x,a.y,a.z)}}class HA{constructor(){this.positions=[],this.normals=[]}tri(t,e,n,s,i,r){for(const[o,a]of[[t,s],[e,i],[n,r]])this.positions.push(o.x,o.y,o.z),this.normals.push(a.x,a.y,a.z)}facing(e,n,s,i){(new t.Vector3).subVectors(n,e).cross((new t.Vector3).subVectors(s,e)).dot(i)<0?this.tri(e,s,n,i,i,i):this.tri(e,n,s,i,i,i)}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 BA(e,n,s,i,r,o){const a=$A(s),c=n.length,l=n.map((t,e)=>{const s=n[(e+1)%c],i=s[0]-t[0],r=s[1]-t[1],a=Math.hypot(i,r)||1;return[o*r/a,-o*i/a]}),h=t=>a(t,0),d=(t,e)=>{const n=l[t],s=l[e];return n[0]*s[0]+n[1]*s[1]<NA?h(n):h([n[0]+s[0],n[1]+s[1]]).normalize()};for(let s=0;s<c;s++){const o=n[s],u=n[(s+1)%c],p=d(s,(s-1+c)%c),f=d(s,(s+1)%c),m=a(o,i),g=a(u,i),y=a(u,r),b=a(o,r),v=h(l[s]);(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 YA(e,n,s,i,r,o){const a=$A(s),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,s]of d)e.facing(a(u[t],i),a(u[n],i),a(u[s],i),c)}const GA=new Map;let VA=0,UA=67108864;function WA(){return{entries:GA.size,bytes:VA,limit:UA}}function qA(t,e=12){const n=Object.keys(t.dimensions).sort().map(e=>`${e}=${Math.round(1e6*t.dimensions[e])/1e6}`).join(","),s=t.extrusion,i=t.cavity,r=t.revolution,o=t.loft,a=s?`${s.axis}:${s.section.kind}:${i?`${"open"===i.start?"o":"c"}${"open"===i.end?"o":"c"}`:"-"}`:r?`${r.axis}:${r.profile.kind}`:o?`${o.axis}:point`:"";return`${t.provider}|${a}|${n}|s${e}|p1`}function XA(t,e=12,n=1/0){const s=qA(t,e),i=GA.get(s);if(i)return i.users++,i.geometry;const r=QA(t,e),o=function(t){return Object.values(t.attributes).reduce((t,e)=>t+e.array.byteLength,t.index?.array.byteLength??0)}(r);if(VA+o>UA||o>n)throw r.dispose(),new Error("figure: geometry bank budget exceeded");return r.userData.figureKey=s,GA.set(s,{geometry:r,users:1,bytes:o}),VA+=o,r}function KA(t){const e=t.userData.figureKey;if(!e)return;const n=GA.get(e);n&&--n.users<=0&&(GA.delete(e),VA-=n.bytes,n.geometry.dispose())}function QA(e,n=12){if("extrude"===e.provider&&e.extrusion)return function(t,e){const n=t.extrusion,s=yA(n.section,n.axis,e),i=new HA;BA(i,s,n.axis,n.start,n.end,1);const r=t.cavity,o=r&&eM(n.section,n.axis,r.wall);if(!r||!o||!("section"in o))return YA(i,s,n.axis,n.start,-1),YA(i,s,n.axis,n.end,1),i.geometry();const a=yA(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 BA(i,a,n.axis,c,l,-1),"open"===r.start?YA(i,s,n.axis,n.start,-1,a):(YA(i,s,n.axis,n.start,-1),YA(i,a,n.axis,c,1)),"open"===r.end?YA(i,s,n.axis,n.end,1,a):(YA(i,s,n.axis,n.end,1),YA(i,a,n.axis,l,-1)),i.geometry()}(e,n);if("revolve"===e.provider&&e.revolution)return function(e,n){const s=e.profile;let i;return"half-ellipse"===s.kind?i=new t.SphereGeometry(1,n,Math.max(2,Math.round(n/2))).scale(s.radial,s.axial,s.radial):(i=new t.CylinderGeometry(s.endRadius,s.startRadius,s.end-s.start,n),i.translate(0,(s.start+s.end)/2,0)),"x"===e.axis&&i.rotateZ(-Math.PI/2),"z"===e.axis&&i.rotateX(Math.PI/2),i}(e.revolution,n);const s=e.loft;return"loft"===e.provider&&s?function(e){const[n,s]=Yw[e.axis],i=$A(e.axis),r=yA(e.section,e.axis,0),o=i([e.apex[n],e.apex[s]],e.end),a=new HA;YA(a,r,e.axis,e.start,e.end>e.start?-1:1);const c=r.length;for(let n=0;n<c;n++){const s=i(r[n],e.start),l=i(r[(n+1)%c],e.start),h=(new t.Vector3).subVectors(l,s).cross((new t.Vector3).subVectors(o,s)).normalize();a.tri(s,l,o,h,h,h)}return a.geometry()}(s):new t.BufferGeometry}const JA=new Map;let ZA=0,tk=0,ek=67108864;function nk(e,n=1/0){const s=(t=>t.map(t=>qA(t.shape,t.segments)).join(";"))(e),i=function(t){const e=new Float64Array(12*t.length);return t.forEach((t,n)=>{const s=t.pose.r,i=t.pose.t;e.set([s[0][0],s[0][1],s[0][2],s[1][0],s[1][1],s[1][2],s[2][0],s[2][1],s[2][2],i[0],i[1],i[2]],12*n)}),e}(e),r=JA.get(s),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,i));if(o)return o.users++,o;const a=e.map(t=>XA(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(tk+l>ek)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:s}=t.pose;p.set(n[0][0],n[0][1],n[0][2],s[0],n[1][0],n[1][1],n[1][2],s[1],n[2][0],n[2][1],n[2][2],s[2],0,0,0,1),f.getNormalMatrix(p);const i=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),s=c.getZ(t);if(h[3*m]=i[0]*e+i[4]*n+i[8]*s+i[12],h[3*m+1]=i[1]*e+i[5]*n+i[9]*s+i[13],h[3*m+2]=i[2]*e+i[6]*n+i[10]*s+i[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:i};return g.userData.figureMergedKey=s,g.userData.figureMergedEntry=y,r?r.push(y):JA.set(s,[y]),ZA++,tk+=l,y}finally{for(const t of a)KA(t)}}function sk(t){const e=t.userData.figureMergedKey,n=t.userData.figureMergedEntry,s=void 0===e?void 0:JA.get(e);!n||!s?.includes(n)||--n.users>0||(s.splice(s.indexOf(n),1),s.length||JA.delete(e),ZA--,tk-=n.bytes,n.geometry.dispose())}function ik(){let t=0;for(const e of JA.values())for(const n of e)t+=n.users;return{entries:ZA,users:t,bytes:tk,limit:ek}}const rk=t=>1e-9*Math.round(t/1e-9)+0;class ok{static carrierJudgeOf(t){let e=ok.carrierJudges.get(t);return e||ok.carrierJudges.set(t,e=function(t,e){const n=e??eA(t.document).dependence,s=new Map(t.document.model.nodes.map(t=>[t.id,t])),i=new Map;for(const e of t.document.model.nodes)for(const t of Object.values(e.outputs))i.set(t,e);const 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=i.get(t),s="compose@1"!==n?.op||"string"!=typeof n.args[0]||o(n.args[1])?t:c(n.args[0]);return a.set(t,s),s};return t=>{const e=new Map;for(const n of t){if(!("pose"in n)||n.key||r.has(n.id))continue;const t=s.get(n.id),i="place@1"===t?.op?t.args[1]:void 0;"string"==typeof i&&o(i)&&!o(t.args[0])&&e.set(n.id,c(i))}return e}}(t.asset,t.document.dependence)),e}static stillJudgeOf(t){let e=ok.stillJudges.get(t);return e||ok.stillJudges.set(t,e=pA(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=kA(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 s=this.slots[t];if(s&&"mesh"in s)return n.copy(s.mesh.matrix);if(s&&"entry"in s)return s.entry.set.mesh.getMatrixAt(s.index,n),n;if(s&&"rides"in s){const t=s.rides,i=12*t.ids.indexOf(e.id),r=t.relative;return n.set(r[i],r[i+1],r[i+2],r[i+9],r[i+3],r[i+4],r[i+5],r[i+10],r[i+6],r[i+7],r[i+8],r[i+11],0,0,0,1),n.premultiply(t.mesh.matrix)}return"pose"in e?n.copy(ok.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((s,i)=>{if(!("shape"in s)||!("pose"in s)||!1===s.visible)return;let r=ok.shapeBounds.get(s.shape);if(!r){const e=AM(s.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)),ok.shapeBounds.set(s.shape,r)}this.semanticBounds.union(n.copy(r).applyMatrix4(this.bodyMatrix(i,s,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,s=this.lastDrawn;if(this.lastLodError=void 0,!s||s.geometry.every(t=>$w(t,n)===$w(t,e)))return this._renderLevel=e,!0;const i=new t.Matrix4,r=s.geometry.map((t,e)=>{if(!("pose"in t))return t;const n=this.bodyMatrix(e,t,i).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={...s,geometry:r},a=Hw(o,e),c=[],l=[],h=WA().bytes+ik().bytes,d=()=>ok.LOD_TRANSITION_LIMIT_BYTES-(WA().bytes+ik().bytes-h);try{const e=new Set;for(const t of a.geometry){if(!("shape"in t))continue;const n=qA(t.shape,t.segments);e.has(n)||(e.add(n),c.push(XA(t.shape,t.segments,d())))}const n=mA(a.geometry,this.merge?{still:this.stillOf,carried:this.carriedOf}:{}),s=new Map(a.geometry.map(t=>[t.id,t]));for(const e of[...n.merged,...n.carried]){let n=e.ids.map(t=>s.get(t));if("carrier"in e){const e=(new t.Matrix4).copy(ok.matrixOf(n[0].pose)).invert(),s=new t.Matrix4;n=n.map(t=>{const n=s.multiplyMatrices(e,ok.matrixOf(t.pose)).elements,i=t=>rk(n[t]);return{...t,pose:{r:[[i(0),i(4),i(8)],[i(1),i(5),i(9)],[i(2),i(6),i(10)]],t:[i(12),i(13),i(14)]}}})}const i=nk(n,d());i&&l.push(i.geometry)}if(WA().bytes+ik().bytes-h>ok.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)sk(t);for(const t of c)KA(t);return!1}try{return this._renderLevel=e,this.draw(o,this.generation),!0}finally{for(const t of l)sk(t);for(const t of c)KA(t)}}get base(){const t=this.asset.designInputs,e=e=>"number"==typeof t[e];return e(Nw.x)&&e(Nw.y)&&e(Nw.z)?{x:t[Nw.x],y:t[Nw.y],z:t[Nw.z]}:null}setSize(t){if(this.clamped=[],!t)return void(this.size=null);const e=this.asset.document.model.inputs,n={...t};for(const s of["x","y","z"]){const i=e.find(t=>t.id===Nw[s]);if(!i)continue;const r=t[s],o=Math.min(Math.max(r,i.min??-1/0),i.max??1/0);o!==r&&this.clamped.push({axis:s,asked:r,used:o,bound:o>r?"min":"max"}),n[s]=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)),s=new Map(this.asset.document.model.inputs.map(t=>[t.id,t])),i={};for(const[r,o]of Object.entries(t??{})){const t=s.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&&(i[r]=this.design[r])):i[r]=o}try{this.compiled.document.evaluate({...this.evaluationInputs(),...i}),this.design=i}catch(t){for(const[n,s]of Object.entries(i))e.push({input:n,value:s,reason:t instanceof Error?t.message:String(t)})}this.designRefused=e}get designValues(){return{...this.design}}setState(t){this.external={...t}}static clipOf(t){return t.clip}get clips(){return[...new Set((this.asset.drivers??[]).map(t=>ok.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 s=t.get(e.state);n[e.state]=rA(e,this.clipTime(ok.clipOf(e)),"deg"===s||"rad"===s?s:"other")}for(const[t,s]of Object.entries(this.external))e.has(t)&&(n[t]=s);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 s="changes"===e.kind?this.fromChanges(e,t):null;this.draw(s??this.dress(this.evaluator.evaluate(t),t),e.generation)}fromChanges(t,e){const n=this.lastDrawn;if(!t.structure&&!n)return null;const s=new Set;for(const e of this.compiled.looks.values()){const n=e.visibility;if(void 0===n||s.has(n)||!t.structure&&!t.changed(n))continue;const i=!0===t.read(n);this.flags.get(n)!==i&&s.add(n),this.flags.set(n,i)}const i=t.structure?new Array(t.structure.ids.length):n.geometry.slice(),r=new Int32Array(i.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<i.length;e++){const n=r[e],o=i[e];if(n<0&&!(o&&s.size&&void 0!==this.flagOf(o)&&s.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,s=12*n;l.shape=t.shapes[n],l.pose={r:[[e[s],e[s+1],e[s+2]],[e[s+3],e[s+4],e[s+5]],[e[s+6],e[s+7],e[s+8]]],t:[e[s+9],e[s+10],e[s+11]]}}else l.shape=o.shape,l.pose=o.pose;i[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:i,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,s=this.compiled.looks.get(n);if(!s)throw new Error(`figure: no appearance for ${n}`);const i=void 0===s.visibility||e(s.visibility);let r=this.materials.get(n);r||this.materials.set(n,r=structuredClone(s.material));const o={...t,material:r,visible:i};return void 0!==s.segments&&(o.segments=s.segments),{dressed:o,visible:i,ref:s.visibility}}evaluation(){return this.evaluate()}movesMerged(t){if(!this.merged.size)return!1;for(let e=0;e<t.length;e++){const n=this.slots[t[e]];if(n&&"merged"in n)return!0}return!1}movePoses(t){t.bodies.length&&this._lodRevision++;const e=ok.matrix,n=new Set;for(let s=0;s<t.bodies.length;s++){const i=this.slots[t.bodies[s]];if(!i)continue;const r=t.poses,o=12*s;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 i)&&!("rides"in i))if("mesh"in i){i.mesh.matrix.copy(e),i.mesh.matrixWorldNeedsUpdate=!0;const t=this.drawnWith.get(i.id);t&&(t.pose=void 0)}else i.entry.set.setMatrix(i.index,e),n.add(i.entry)}for(const t of this.batches.values())n.has(t)?(t.settled=!1,t.set.commitMatrices(),t.set.mesh.boundingSphere=null,t.set.mesh.frustumCulled=!1):t.settled||(t.set.commit(),t.set.mesh.frustumCulled=!0,t.settled=!0);for(const e of t.places){const t=this.places.get(e.id);t&&ok.pose(t,e.pose)}}draw(e,n){this.lastDrawn=e,this._lodRevision++,this._lodGeometryRevision++,e=Hw(e,this._renderLevel);const s=this.planOf(e.geometry),i=new Map(e.geometry.filter(t=>"pose"in t).map(t=>[t.id,t])),r=this.drawCarried(s,i,this.drawMerged(s,i)),o=new Set;for(const e of r){const n=i.get(e);if(!("pose"in n))continue;o.add(e);let s=this.meshes.get(e);const r=!1!==n.visible,a=this.drawnWith.get(e);if(!s||!a||a.shape!==n.shape||a.segments!==n.segments){const i=XA(n.shape,n.segments);s?s.geometry!==i?(KA(s.geometry),s.geometry=i):KA(i):(s=new t.Mesh(i,this.materialFor(n)),s.name=e,s.matrixAutoUpdate=!1,this.meshes.set(e,s),r&&this.group.add(s))}a&&a.pose===n.pose||ok.pose(s,n.pose),this.drawnWith.set(e,{shape:n.shape,segments:n.segments,pose:n.pose}),s.castShadow=r,r&&s.parent!==this.group?this.group.add(s):r||s.parent!==this.group||this.group.remove(s)}for(const[t,e]of this.meshes)o.has(t)||(e.parent===this.group&&this.group.remove(e),KA(e.geometry),this.meshes.delete(t),this.drawnWith.delete(t));const a=new Set;for(const t of s.batches){a.add(t.key);const e=i.get(t.ids[0]);if(!("pose"in e))continue;let n=this.batches.get(t.key);if(!n){const s=XA(e.shape,e.segments);n={set:new Mw({geometry:s,material:this.materialFor(e),capacity:t.ids.length,name:`figure-batch:${t.member}`,castShadow:!0}),ids:[],geometry:s},this.batches.set(t.key,n)}const{set:s}=n,r=s.count!==t.ids.length;s.setCount(t.ids.length);const o=s.mesh.instanceMatrix.array;let c=!1;t.ids.forEach((t,e)=>{const n=i.get(t);if(!("pose"in n))return;ok.matrixOf(n.pose);const r=ok.matrix.elements;for(let t=0;t<16&&!c;t++)o[16*e+t]!==Math.fround(r[t])&&(c=!0);s.setMatrix(e,ok.matrix)}),n.ids=t.ids,r||!c&&!n.settled?(s.commit(),s.mesh.frustumCulled=!0,n.settled=!0):c&&(n.settled=!1,s.commitMatrices(),s.mesh.boundingSphere=null,s.mesh.frustumCulled=!1);const l=!1!==e.visible;l&&s.object3d.parent!==this.group?this.group.add(s.object3d):l||s.object3d.parent!==this.group||this.group.remove(s.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(),KA(e.geometry),this.batches.delete(t));for(const t of e.bindings){const e=this.places.get(t.id);e&&ok.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 s=[...e.alone],i=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=nk(e.map(t=>({shape:t.shape,segments:t.segments,pose:t.pose})));if(!n){s.push(...r.ids);continue}if(o)sk(o.mesh.geometry),o.mesh.geometry=n.geometry,o.ids=r.ids,o.starts=n.starts;else{const s=new t.Mesh(n.geometry,this.materialFor(e[0]));s.name=`figure-merged:${this.merged.size}`,s.matrixAutoUpdate=!1,s.castShadow=!0,o={mesh:s,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}))}i.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)i.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),sk(e.mesh.geometry),this.merged.delete(t));return s}drawCarried(e,n,s){const i=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(ok.matrixOf(e[0].pose)).invert();const c=e.map(t=>{const e=o.multiplyMatrices(r,ok.matrixOf(t.pose)).elements,n=t=>rk(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=nk(e.map((t,e)=>({shape:t.shape,segments:t.segments,pose:c[e]})));if(!n){s.push(...a.ids);continue}if(h)sk(h.mesh.geometry),h.mesh.geometry=n.geometry,h.ids=a.ids,h.starts=n.starts;else{const s=new t.Mesh(n.geometry,this.materialFor(e[0]));s.name=`figure-carried:${this.carried.size}`,s.matrixAutoUpdate=!1,s.castShadow=!0,h={mesh:s,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}ok.pose(h.mesh,e[0].pose),i.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)i.has(t)||(e.mesh.parent===this.group&&this.group.remove(e.mesh),sk(e.mesh.geometry),this.carried.delete(t));return this.carriedAt=this.designKey(),s}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(!UE(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 s=this.evaluator&&this.lastDrawn?this.placeNow(e):this.evaluation().bindings.find(t=>t.id===e);return s&&ok.pose(n,s.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(ok.matrixOf(e)),t.matrixWorldNeedsUpdate=!0}planOf(t){const e=this.planned,n=t.filter(t=>"pose"in t);if(e&&e.ids.length===n.length&&n.every((t,n)=>t.id===e.ids[n]&&t.shape===e.shapes[n]&&t.segments===e.segments[n]&&!1!==t.visible===e.shown[n]))return e.plan;const s=n.map(t=>t.id);!this.merge||e?.still&&e.ids.length===s.length&&s.every((t,n)=>t===e.ids[n])||(this.stillOf=ok.stillJudgeOf(this.compiled)(t),this.carriedOf=ok.carrierJudgeOf(this.compiled)(t));const i=this.merge?this.stillOf:void 0,r=mA(t,i?{still:i,carried:this.carriedOf}:{});return this.planned={ids:s,shapes:n.map(t=>t.shape),segments:n.map(t=>t.segments),shown:n.map(t=>!1!==t.visible),plan:r,still:i},r}static matrixOf(t){const e=t.r,n=t.t;return ok.matrix.set(e[0][0],e[0][1],e[0][2],n[0],e[1][0],e[1][1],e[1][2],n[1],e[2][0],e[2][1],e[2][2],n[2],0,0,0,1)}bodyAt(t,e,n){if(t.isMesh&&this.meshes.get(t.name)===t)return t.name;for(const n of this.batches.values())if(n.set.mesh===t&&void 0!==e){const t=n.set.indexOf(e);return t>=0?n.ids[t]:void 0}for(const e of[...this.merged.values(),...this.carried.values()]){if(e.mesh!==t||void 0===n)continue;const{starts:s}=e;if(n<0||n>=s[s.length-1])return;let i=0,r=e.ids.length-1;for(;i<r;){const t=i+r+1>>1;s[t]<=n?i=t:r=t-1}return e.ids[i]}}drawOf(t){const e=this.meshes.get(t);if(e)return e.parent===this.group?{kind:"alone",object:e}:void 0;for(const e of this.batches.values()){const n=e.ids.indexOf(t);if(n>=0)return e.set.object3d.parent===this.group?{kind:"copy",object:e.set.mesh,index:n}:void 0}for(const e of this.merged.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"merged",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}for(const e of this.carried.values()){const n=e.ids.indexOf(t);if(n>=0)return e.mesh.parent===this.group?{kind:"carried",object:e.mesh,triangles:{start:e.starts[n],count:e.starts[n+1]-e.starts[n]}}:void 0}}get draws(){let t=0;for(const e of this.batches.values())e.set.object3d.parent===this.group&&(t+=e.set.count);return{batches:[...this.batches.values()].filter(t=>t.set.object3d.parent===this.group).length,merged:[...this.merged.values()].filter(t=>t.mesh.parent===this.group).length,carried:[...this.carried.values()].filter(t=>t.mesh.parent===this.group).length,alone:[...this.meshes.values()].filter(t=>t.parent===this.group).length,instances:t}}evaluationInputs(){const t={...this.asset.designInputs,...this.design,...this.asset.stateDefaults,...this.stateOverrides()};return this.size&&(t[Nw.x]=this.size.x,t[Nw.y]=this.size.y,t[Nw.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,s=new Map,i=t.geometry.map(e=>{const i=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),i&&i.body===e&&i.visible===r.visible?(s.set(e.id,i),i.dressed):(s.set(e.id,{body:e,visible:r.visible,dressed:r.dressed}),r.dressed)});return this.dressed=s,{geometry:i,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,s=!!e.emissive?.on,i=s&&e.emissive?this.colourOf(e.emissive.token):this.colourOf(e.token),r=s&&e.emissive?e.emissive.intensity:0,o=`figure|${this.compiled.fingerprint}|${e.token}|${e.preset??"default"}|${e.transparent?"t":"o"}|${s?"on":"off"}|${i}|${r}`;return U_.material(o,{color:i,metalness:n.metalness,roughness:n.roughness,envMapIntensity:n.envMapIntensity,flatShading:!0,transparent:e.transparent??!1,opacity:e.transparent?n.opacity??.3:1,emissive:i,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),KA(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(),KA(t.geometry);this.batches.clear();for(const t of this.merged.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),sk(t.mesh.geometry);this.merged.clear();for(const t of this.carried.values())t.mesh.parent===this.group&&this.group.remove(t.mesh),sk(t.mesh.geometry);this.carried.clear();for(const t of this.places.values())this.group.remove(t);this.places.clear()}}ok.shapeBounds=new WeakMap,ok.LOD_TRANSITION_LIMIT_BYTES=16777216,ok.matrix=new t.Matrix4,ok.carrierJudges=new WeakMap,ok.stillJudges=new WeakMap;class ak 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 OA(this.component.state.type)}getObject3dInstance(){return new t.Group}build(){super.build();const t=this.figure;t&&(this.rig=new ok(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,s=this.component.state.depth;return FA(t,{x:e,z:n,y:"number"==typeof s&&Number.isFinite(s)&&s>0?s: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,s="ceiling"===t?n:"center"===t?n/2:0;this.rig.group.position.y=-this.effectiveDepth/2+s}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 s=!1;for(const i of e.clips){const r=n[i]??0;Number.isFinite(r)&&0!==r&&(e.setClipTime(i,e.clipTime(i)+t/1e3*r),s=!0)}s&&(e.update(),this.component.invalidate?.())}advance(t){this.tick(t)}placeAttachment(t,e){const n=this.rig,s=n?.placeNode(t);if(!n||!s)return;const i=UE(n.asset).find(e=>e.id===t)?.face,r=i&&yS[i]||[0,0,0],o=t=>{const n=Number(e?.state?.[t]);return Number.isFinite(n)&&n>0?n/2:0};return{attach:s,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 ck(t,e,n=1){const s=new ok(t.compiled.asset);s.setSize(e);const i=s.evaluateOnce(),r=function(t,e){const n=[];for(const s of t){if(!1===s.visible||!_A(s))continue;let t;try{t=xS(_S(s.shape,s.segments),s.pose.r,s.pose.t)}catch{continue}if(t.length<3)continue;const i=t=>t.map(t=>[t[0],t[2]]),r=Math.abs(s.pose.r[1][1]-1)<1e-6,o=s.shape.extrusion;let a;const c=[];if(r&&"y"===o?.axis){const t=(t,e)=>i(xS(xA(t,o.end,s.segments??12,e),s.pose.r,s.pose.t));a=t(o.section);const e=s.shape.cavity;if(e&&"open"===e.end){const n=eM(o.section,"y",e.wall);"section"in n&&c.push(t(n.section,n.centre))}}else a=vA(i(t));const l=s.material,h=l.emissive?.on?l.emissive.token:l.token;n.push({id:s.id,color:e[h]??"#9a9a9a",outline:a,holes:c,top:Math.max(...t.map(t=>t[1])),transparent:!!l.transparent})}return n.sort((t,e)=>t.top-e.top)}(i.geometry,i.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:s.drawnSize}}const lk=Rw,hk=Object.freeze({Capacity:t=>Fb(t),Holdable:t=>Wv(t),Transferable:t=>qv(t),FlowNode:t=>Xv(t)}),dk=Object.freeze({Capacity:"자리를 갖는다 — 물건이 앉을 곳과 몇 개까지인지를 정한다",Holdable:"물건을 보유한다 — 담긴 것을 함께 들고 그린다",Transferable:"주고받는다 — 자리를 잡아 두고 넘겨받는다. Capacity 가 있어야 자리를 찾는다",FlowNode:"흐름의 마디다 — 담는 것에 더해 문(port)으로 받고 보낸다. 위의 셋을 스스로 포함한다"});function uk(t){return t.map(t=>({id:t.id,maxCount:t.capacity,allowedTypes:[...t.accepts]}))}const pk=new Map;function fk(t,e=[],n){const s=new Set(e),i=[...s].filter(t=>!lk.includes(t));if(i.length>0)throw new Error(`모르는 능력이다: ${i.join(" · ")} — 쓸 수 있는 것은 ${lk.join(" · ")}`);for(const[t,e]of Object.entries(jw))if(s.has(t)&&!e.some(t=>s.has(t)))throw new Error(`${t} 은 혼자 설 수 없다 — ${e.join(" 이나 ")} 가 함께 있어야 한다`);const r=`${[...s].sort().join("+")}|${n??""}`,o=pk.get(r);if(o)return o;const a=0===s.size?t:(c=function(t,e){const n=t.capabilities??[],s=[...new Set([...n,...e])];return Object.defineProperty(t,"capabilities",{value:Object.freeze(s),configurable:!0}),t}(function(t,e){if(e.has("FlowNode"))return hk.FlowNode(t);let n=t;for(const t of["Capacity","Transferable","Holdable"])e.has(t)&&(n=hk[t](n));return n}(t,s),s),class extends c{get _places(){const t=OA(this.state?.type)?.compiled.asset;return t?UE(t):null}get slots(){const t=this._places;return t?.length?uk(t):super.slots??[]}attachPointFor(t,e){const n=()=>super.attachPointFor?super.attachPointFor(t,e):null,s=e?.slotId??t?.[tb],i=this._places;return i&&s&&i.some(t=>t.id===s)?this._realObject?.placeAttachment?.(s,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 pk.set(r,l),l}function mk(){pk.clear()}const gk={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 yk extends(Pc(Tc)){static registerType(t,e=[],n){const s=Cc.register(t);if(s&&!(s===yk||s.prototype instanceof yk))throw new Error(`figure type '${t}' is already registered by a non-figure component — refusing to replace it`);const i=fk(yk,e,n);Cc.register(t,i)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){const t=OA(this.state.type);if(!t)return gk;const e=t.compiled.asset,n=e.document.model.inputs,s=(e.publicInputs??[]).flatMap(t=>{const s=n.find(e=>e.id===t.input);return s?[{key:t.input,label:t.label,unit:s.unit,min:s.min,max:s.max,default:e.designInputs[t.input]}]:[]}),i=n.filter(t=>"state"===t.role).map(t=>({key:t.id,label:e.stateInputs?.[t.id]?.label??t.id,unit:t.unit,min:t.min,max:t.max,default:e.stateDefaults[t.id]})),r=[...new Set((e.drivers??[]).map(t=>t.clip))].map(t=>({key:t,label:t,min:0,max:3})),o=[...gk.properties];return s.length&&o.push({type:"number-map",label:"design-inputs",name:"designInputs",property:{entries:s}}),i.length&&o.push({type:"number-map",label:"state-values",name:"parameters",property:{entries:i}}),r.length&&o.push({type:"number-map",label:"clip-speeds",name:"clips",property:{entries:r}}),o.length===gk.properties.length?gk:{...gk,properties:o}}buildRealObject(){return PA(this.state.type)?new ak(this):void 0}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state,r=OA(this.state.type);if(!r)return void this.renderPlace(t,e,n,s,i);const o=this.topView(r,s,i),a=e+s/2,c="wall"===r.compiled.asset.placement?n:n+i/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 s=FA(t.compiled.asset,{x:e,z:n,y:this.askedDepth}),i=s.inputs,r=`${t.compiled.fingerprint}|${i?`${i.x}|${i.y}|${i.z}`:`x${s.scale}`}`;return this._top?.key!==r&&(this._top={key:r,view:ck(t,i,s.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 s=OA(this.state.type);if(!s)return super.adjustResize(t,e,n);const i=s.compiled.asset,r=LA(i),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}=FA(i,{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=OA(this.state.type);if(!e)return;const n=e.compiled.asset,s=LA(n),{width:i=0,height:r=0}=this.state,{occupancy:o}=FA(n,{x:i,z:r,y:this.askedDepth},t),a={};Math.abs(o.x-i)>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||s&&void 0===c&&t.includes("y"))&&(a.depth=o.y),Object.keys(a).length&&this.set(a)}renderPlace(t,e,n,s,i){t.save(),t.strokeStyle="#e53935",t.lineWidth=1,t.setLineDash([4,4]),t.beginPath(),t.rect(e,n,s,i),t.stroke(),t.restore()}postrender(t){Cc.prototype.postrender.call(this,t)}}MA(yk);const bk={"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"},vk=new Map([["default",bk]]);let _k="default",xk=0;function wk(){return xk}function Mk(t,e){vk.set(t,e),t===_k&&xk++}function Sk(t){if(!vk.has(t))throw new Error(`등록되지 않은 팔레트다: '${t}'. 등록된 것 — ${[...vk.keys()].join(", ")}`);t!==_k&&(_k=t,xk++)}function Ek(){return _k}function Ak(){return vk.get(_k)}function kk(t){const e=Ak()[t];if(void 0===e)throw new Error(`팔레트에 없는 토큰이다: '${t}' (팔레트 '${_k}'). 쓸 수 있는 것 — ${Object.keys(Ak()).join(", ")}`);return e}const Ck=bk["palette.neutral"];function Tk(){vk.clear(),vk.set("default",bk),_k="default",xk++}const Ok={mutable:!1,resizable:!0,rotatable:!0,properties:[],help:"scene/component/figure-part"},Pk=["shape","segments"],Ik=["color","preset","transparent","glow"];function Dk(e,n){let s;try{s=QA(e,n)}catch{return null}if(!s?.getAttribute("position"))return null;const i=s.clone();s.dispose(),i.computeBoundingBox();const r=i.boundingBox,o=r.getCenter(new t.Vector3),a=r.getSize(new t.Vector3);return i.translate(-o.x,-o.y,-o.z),i.scale(1/(a.x||1),1/(a.y||1),1/(a.z||1)),i.computeBoundingBox(),i.getAttribute("normal")||i.computeVertexNormals(),{geometry:i,extent:a,centre:o}}class zk extends Mu{build(){super.build();const e=this.component.state,n=e.shape?Dk(e.shape,e.segments):null;if(!n)return;const s=new t.Mesh(n.geometry,this.material());s.castShadow=!0,s.receiveShadow=!0,this.object3d.add(s),this.mesh=s,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(Pk)?this.update():(super.onchange(t,e),n(Ik)&&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",s=t.transparent??!1,i=t.glow,r=i?i.color:n,o=i?i.intensity:0;return U_.material(`figure-part|${n}|${t.preset??"default"}|${s}|${i?`${i.color}:${o}`:"-"}`,{color:r,metalness:e.metalness,roughness:e.roughness,envMapIntensity:e.envMapIntensity,flatShading:!0,transparent:s,opacity:s?e.opacity??.3:1,emissive:r,emissiveIntensity:o})}}class Rk extends(Pc(Tc)){static registerType(){Cc.register("figure-part",Rk)}get hasTextProperty(){return!1}is3dish(){return!0}get nature(){return Ok}buildRealObject(){return new zk(this)}render(t){const{left:e=0,top:n=0,width:s=0,height:i=0}=this.state;t.beginPath(),t.rect(e,n,s,i),t.fillStyle=this.state.color??"#9a9a9a",t.fill()}}var jk;Rk.registerType(),function(t){t.compile=Bl,t.duplicate=Yl,t.select=ec,t.match=Ja}(jk||(jk={})),js.registerResidents(()=>({componentResidentsCount:Cc.residentsCount,sceneResidentsCount:Ju.residentsCount,referenceMapResidentsCount:C_.residentsCount,sceneResidents:Cc.residents}));var Lk=Object.freeze({__proto__:null,AbsoluteLayout:Nc,Animation:Ea,AudioPlayer:ry,BULGE_EPSILON:qr,get Banner(){return $x},Banner3D:Nx,BoxSelectionManager:Lf,CAPABILITY_MIXINS:hk,COMMON_PLACEHOLDER_PROPERTIES:kg,CORE_PLACEHOLDER_TYPES:Pg,get Camera(){return Vx},Camera3D:Gx,CameraBookmarkManager:jf,CameraManager:xf,Capacity:Fb,CapacityEventTracker:By,CardLayout:Hc,CenteringQueueStrategy:Gy,CenteringSlotStrategy:r_,Component:Cc,Connectable:lm,Container:lg,ContainerAbstract:rh,ControlsManager:Ef,get Cube(){return zx},Cube3D:Dx,get Cylinder(){return Lx},Cylinder3D:jx,DEFAULT:Ki,DEFAULT_CEILING:_u,DEFAULT_PALETTE:bk,DEFAULT_PLACEMENT:fu,DEFAULT_SEAT_MARGIN:Sb,DPPX:Wi,DataLagTracker:hh,DataSource:zy,DefaultLoadingOverlayRenderer:Vd,Donut:Sy,DonutExtrude:ux,Ellipse:Eg,EllipseExtrude:cx,EventManager3D:Af,EventMap:fl,FIGURE_CAPABILITIES:lk,FIGURE_CAPABILITY_NOTES:dk,FPS:$p,FigureInstance:yk,FigurePart:Rk,FigurePartRealObject:zk,FixedSlotStrategy:sb,get FloorPlate(){return nw},FlowEngine:Uv,FlowNode:Xv,GESTURES:qi,get GLTFObject(){return Wx},GLTF_BASE_URL_ALIAS:jy,GenericObject:Og,GeometryBank:yx,GifView:sy,GizmoManager:Cf,GizmoOperationManager:Pf,GlobalRef:py,GltfComponent:Fy,GridStacking:Wy,Group:cy,HOLDER_ANCHOR:ob,HTMLAbsoluteLayout:Fc,HTMLOverlayContainer:dy,HTMLOverlayElement:Vg,Holdable:Wv,ImageView:Gg,InfoWindow:Rc,InstancedSet:Mw,InteractionManager:If,ItemsDataBinding:nb,KEYEVENTS:Xi,Layer:bp,Layout:Lc,LightManager:Mf,LightObject:Xx,Line:Mg,Line3D:vw,LinearHorizontalLayout:Yc,LinearVerticalLayout:Vc,LoadTracker:ph,LoadingOverlay:Ld,LocalRef:hy,MATERIAL_PRESETS:Pd,MAX_SEGMENTS:xx,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:U_,get Model(){return jk},MoveHandle:sh,NOTHING:Fi,NavGraph:d_,Node:Ty,OrthoLine:Bg,OrthoLine3D:xw,PIXEL_RATIO:Hp,PLACEHOLDER_THEMES:Ag,Path:vy,PatternStacking:Uy,PlacementManager:Df,get PointLight(){return Kx},Polygon:Rg,PolygonContainer:Lg,PolygonExtrude:dx,PolygonPathPolyline:b_,Polyline:$g,Polyline3D:_w,Popup:gy,PopupContainer:by,Pose6DOF:_l,RealObject:Mu,RealObjectCamera:kw,RealObjectDomElement:Xp,RealObjectDomTexture:B_,RealObjectDummy:Ew,RealObjectExternalModel:Au,RealObjectExtrude:ax,RealObjectGLTF:Ou,RealObjectGroup:aw,RealObjectLine:bw,RealObjectMesh:W_,RealObjectPlane:Cw,RealObjectPlane2D:Pw,RealObjectScene:Tw,RealObjectService:Oy,RealObjectSprite:Cx,RealObjectSprite2D:Tx,RealObjectText:tx,Rect:um,RectExtrude:lx,RectPath:Pc,ReferenceMap:C_,RendererManager:wf,ReservationTable:l_,RootContainer:lh,Ruler:fm,SCALE_MIN:tu,SCENE_MODE:Vi,SEGMENT_DEFAULTS:vx,SEGMENT_PRESETS:bx,SHORTCUT_SECTIONS:em,Scene:Ju,SceneManager:_f,ScenePopup:yp,SceneSearchEngine:Ru,ScriptLoader:R_,SearchOverlay:Lu,ServiceComponent:Iy,Shape:Tc,get Sphere(){return kx},Sphere3D:Ax,get Sprite(){return Px},Star:ky,StarExtrude:fx,TRANSFER_SLOT_KEY:tb,TableLayout:Uc,Text:oy,ThreeCapability:qf,get ThreeContainer(){return Dw},ThreeDOnly:Ry,Tracker:Nu,Transfer:qu,TransitionEffect:nh,Triangle:xy,TriangleExtrude:px,UNIT_DIMENSION:iu,UNIT_ROTATE:au,UNIT_SCALE:ru,UNIT_TRANSLATE:ou,UNTOKENED_COLOR:Ck,ValueHolder:Dy,VertexGizmoManager:Bf,VolumeStacking:qy,get Wall(){return Zx},Wall3D:Jx,Z_PRIORITY:gu,acquireFigureGeometry:XA,activePalette:Ak,activePaletteName:Ek,addressOfSlotId:_b,allDestinations:Dv,anchorsConnect:Gb,animate:Sa,applyAlpha:nu,applyMaterial3dProps:Rd,applyPolicy:jv,applySeatingRotation:Zy,applyStackLayout:Xy,applyZPriorityToMaterials:bu,arcSegmentTopology:Bb,autoWireBackPressure:Yy,buildArrow3D:Wp,buildContractInspector:S_,buildCoordinateGround:of,buildFigureGeometry:QA,buildFlowGraph:Xb,buildNavGraph:f_,buildShapeFromPolygonPath:hx,buildTether:cp,bulgeFromDrag:Jr,bulgeHandlePosition:Qr,canReach:tv,capability:qm,centerOnBBox:ox,chooseNearestPickupFrame:i_,clearTether:hp,collectAdjacentSegments:rv,compile:ka,componentForNode:Iv,computeArcParams:Kr,computeFlowMap:_v,computeStackPositions:Vy,cornerHandlePosition:to,cornerRadiusFromDrag:eo,create:tp,createCanvas:Bp,createCanvasTexture:F_,createFloor:yf,createRealObjectFor:tf,createSelectionHandle3D:sw,dataLagTracker:dh,debug:Zs,deliversInto:Wb,delta:wa,disposeCoordinateGround:hf,disposeObject3D:hu,disposeTether:dp,downstream:Nv,drawTextTexture:K_,effectiveCornerRadius:Zr,ellipseOutline:rx,enumerateDataScenarios:lv,error:Qs,figureClassFor:fk,figureSectionOutline:yA,fillStyleOpacity:eu,filterByToolType:s_,filterShortcuts:nm,findNearestWithCapability:Mv,flattenPolygonPath:v_,flowGraphFor:Ov,flowGraphIssues:Tv,flowReverseFor:xv,fontStyle:q_,footprint2D:Ky,frameClock:Rr,ftId:gv,ftrace:mv,getAllCapabilityMeta:Jm,getCapabilityMeta:Qm,getFigure:OA,getPose:El,getWorldPose:Al,globalSimClock:Dr,gltfNatureProperties:Ly,graphFor:Yv,gridCellOf:gb,gridPlacements:Sw,gridSlotNo:mb,hasArc:Xr,hasCapability:Wm,hasCapacity:$y,hasFigure:PA,inferCapacity:Hy,inferDownstreamId:ov,inferFlowDirections:fv,initFontFamilyWatcher:Ji,inspector:jd,installContractInspector:E_,isFlowNode:Kv,isGenericPlaceholder:Ig,isGeometricHost:wv,isParted:Su,isRoutingTarget:Sv,isSegmentPreset:Sx,isStateDriven:mu,isThreedEnabled:Iu,judgeItemFit:zb,layoutIssue:rb,matchOutbounds:qb,metrics:js,next:Fv,nextHop:Zb,nextHops:Jb,nextHopsToAny:nv,nextHopsToAnyDetailed:sv,niceGridStep:sf,nodeIdOf:zv,opaqueColor:su,paletteVersion:wk,partAtByIndex:Eu,persistenceIssues:ub,pickWeightedDestination:Vv,planPathAStar:m_,planToReservations:g_,pointInRotatedRect:Vb,polygonOffsetForPriority:yu,polygonPathLength:__,projectToScreen:ip,quatFromYaw:Jv,rayAbsDistanceToRect:Ub,reachableByOutbound:Kb,reachableDestinations:$v,reachableDestinationsFrom:Hv,reachableDestinationsWeightedFrom:Bv,reachableSinks:ev,receiptToJSON:Uu,recommendsLogarithmicDepthForSky:vf,rectFaceAnchors:Nb,rectOutline:ix,rectangularFootprintFrames:e_,registerCapabilityMeta:Km,registerDefaultRealObjectFactory:Zp,registerFigure:TA,registerFigureType:SA,registerPalette:Mk,registerRealObjectFactory:Jp,registerTypeResolver:Rl,releaseFigureGeometry:KA,renderCanvasTexture:N_,renderPlaceholder:Cg,reservationTable:h_,resetFigureClasses:mk,resetFigures:DA,resetPalettes:Tk,resolveAnchorWorldPosition:ap,resolveHeightSegments:Mx,resolveMaterial3d:Id,resolveNextHop:Lv,resolveSegments:wx,resolveSlot:bb,resolveToken:kk,resolveUnknownTypes:Ll,resolveVariant:Qd,rotatedFootprint:Ab,sceneComponent:Ny,seatInSlot:kb,seatTransform:Cb,setActivePalette:Sk,setPose:kl,setThreedEnabled:Du,setWorldPose:Cl,sinksForDestination:Pv,slotAddresses:xb,slotCount:pb,slotFrame:Mb,slotIdOf:vb,slotNumbers:fb,slotSpaceWarnings:Db,slotsFromBindings:uk,stackSeatTransforms:Tb,standardYieldPolicy:c_,stopFPSMeasure:Np,straightSegmentEndpoints:Hb,straightSegmentMultiInbound:Yb,straightSegmentTopology:$b,textBounds:Z_,textTexture:Q_,toThreeSide:zd,topApproachFrame:n_,transferLog:Xu,transferTracer:Gu,uniformZ:no,unitFigurePartGeometry:Dk,unknownTypesOf:jl,unregisterFigure:IA,unresolvedReasonOf:Dl,updateDefaultFontFamily:Qi,updateTether:lp,useFigureComponent:MA,validate:Gv,validateFlowGraph:iv,validateSlotLayout:db,version:j_,warn:Js});const Fk=globalThis;"undefined"==typeof globalThis||Fk.scene||(Fk.scene=Lk);export{Nc as AbsoluteLayout,Ea as Animation,ry as AudioPlayer,qr as BULGE_EPSILON,$x as Banner,Nx as Banner3D,Lf as BoxSelectionManager,hk as CAPABILITY_MIXINS,kg as COMMON_PLACEHOLDER_PROPERTIES,Pg as CORE_PLACEHOLDER_TYPES,Vx as Camera,Gx as Camera3D,jf as CameraBookmarkManager,xf as CameraManager,Fb as Capacity,By as CapacityEventTracker,Hc as CardLayout,Gy as CenteringQueueStrategy,r_ as CenteringSlotStrategy,Cc as Component,lm as Connectable,lg as Container,rh as ContainerAbstract,Ef as ControlsManager,zx as Cube,Dx as Cube3D,Lx as Cylinder,jx as Cylinder3D,Ki as DEFAULT,_u as DEFAULT_CEILING,bk as DEFAULT_PALETTE,fu as DEFAULT_PLACEMENT,Sb as DEFAULT_SEAT_MARGIN,Wi as DPPX,hh as DataLagTracker,zy as DataSource,Vd as DefaultLoadingOverlayRenderer,Sy as Donut,ux as DonutExtrude,Eg as Ellipse,cx as EllipseExtrude,Af as EventManager3D,fl as EventMap,lk as FIGURE_CAPABILITIES,dk as FIGURE_CAPABILITY_NOTES,$p as FPS,yk as FigureInstance,Rk as FigurePart,zk as FigurePartRealObject,sb as FixedSlotStrategy,nw as FloorPlate,Uv as FlowEngine,Xv as FlowNode,qi as GESTURES,Wx as GLTFObject,jy as GLTF_BASE_URL_ALIAS,Og as GenericObject,yx as GeometryBank,sy as GifView,Cf as GizmoManager,Pf as GizmoOperationManager,py as GlobalRef,Fy as GltfComponent,Wy as GridStacking,cy as Group,ob as HOLDER_ANCHOR,Fc as HTMLAbsoluteLayout,dy as HTMLOverlayContainer,Vg as HTMLOverlayElement,Wv as Holdable,Gg as ImageView,Rc as InfoWindow,Mw as InstancedSet,If as InteractionManager,nb as ItemsDataBinding,Xi as KEYEVENTS,bp as Layer,Lc as Layout,Mf as LightManager,Xx as LightObject,Mg as Line,vw as Line3D,Yc as LinearHorizontalLayout,Vc as LinearVerticalLayout,ph as LoadTracker,Ld as LoadingOverlay,hy as LocalRef,Pd as MATERIAL_PRESETS,xx as MAX_SEGMENTS,Ui as MAX_UNDO_SIZE,_x as MIN_SEGMENTS,Bi as MODE_ADD,$i as MODE_EDIT,Gi as MODE_PASTE_DATABIND,Yi as MODE_PASTE_STYLE,Hi as MODE_SHIFT,Ni as MODE_VIEW,U_ as MaterialBank,jk as Model,sh as MoveHandle,Fi as NOTHING,d_ as NavGraph,Ty as Node,Bg as OrthoLine,xw as OrthoLine3D,Hp as PIXEL_RATIO,Ag as PLACEHOLDER_THEMES,vy as Path,Uy as PatternStacking,Df as PlacementManager,Kx as PointLight,Rg as Polygon,Lg as PolygonContainer,dx as PolygonExtrude,b_ as PolygonPathPolyline,$g as Polyline,_w as Polyline3D,gy as Popup,by as PopupContainer,_l as Pose6DOF,Mu as RealObject,kw as RealObjectCamera,Xp as RealObjectDomElement,B_ as RealObjectDomTexture,Ew as RealObjectDummy,Au as RealObjectExternalModel,ax as RealObjectExtrude,Ou as RealObjectGLTF,aw as RealObjectGroup,bw as RealObjectLine,W_ as RealObjectMesh,Cw as RealObjectPlane,Pw as RealObjectPlane2D,Tw as RealObjectScene,Oy as RealObjectService,Cx as RealObjectSprite,Tx as RealObjectSprite2D,tx as RealObjectText,um as Rect,lx as RectExtrude,Pc as RectPath,C_ as ReferenceMap,wf as RendererManager,l_ as ReservationTable,lh as RootContainer,fm as Ruler,tu as SCALE_MIN,Vi as SCENE_MODE,vx as SEGMENT_DEFAULTS,bx as SEGMENT_PRESETS,em as SHORTCUT_SECTIONS,Ju as Scene,_f as SceneManager,yp as ScenePopup,Ru as SceneSearchEngine,R_ as ScriptLoader,Lu as SearchOverlay,Iy as ServiceComponent,Tc as Shape,kx as Sphere,Ax as Sphere3D,Px as Sprite,ky as Star,fx as StarExtrude,tb as TRANSFER_SLOT_KEY,Uc as TableLayout,oy as Text,qf as ThreeCapability,Dw as ThreeContainer,Ry as ThreeDOnly,Nu as Tracker,qu as Transfer,nh as TransitionEffect,xy as Triangle,px as TriangleExtrude,iu as UNIT_DIMENSION,au as UNIT_ROTATE,ru as UNIT_SCALE,ou as UNIT_TRANSLATE,Ck as UNTOKENED_COLOR,Dy as ValueHolder,Bf as VertexGizmoManager,qy as VolumeStacking,Zx as Wall,Jx as Wall3D,gu as Z_PRIORITY,XA as acquireFigureGeometry,Ak as activePalette,Ek as activePaletteName,_b as addressOfSlotId,Dv as allDestinations,Gb as anchorsConnect,Sa as animate,nu as applyAlpha,Rd as applyMaterial3dProps,jv as applyPolicy,Zy as applySeatingRotation,Xy as applyStackLayout,bu as applyZPriorityToMaterials,Bb as arcSegmentTopology,Yy as autoWireBackPressure,Wp as buildArrow3D,S_ as buildContractInspector,of as buildCoordinateGround,QA as buildFigureGeometry,Xb as buildFlowGraph,f_ as buildNavGraph,hx as buildShapeFromPolygonPath,cp as buildTether,Jr as bulgeFromDrag,Qr as bulgeHandlePosition,tv as canReach,qm as capability,ox as centerOnBBox,i_ as chooseNearestPickupFrame,hp as clearTether,rv as collectAdjacentSegments,ka as compile,Iv as componentForNode,Kr as computeArcParams,_v as computeFlowMap,Vy as computeStackPositions,to as cornerHandlePosition,eo as cornerRadiusFromDrag,tp as create,Bp as createCanvas,F_ as createCanvasTexture,yf as createFloor,tf as createRealObjectFor,sw as createSelectionHandle3D,dh as dataLagTracker,Zs as debug,Wb as deliversInto,wa as delta,hf as disposeCoordinateGround,hu as disposeObject3D,dp as disposeTether,Nv as downstream,K_ as drawTextTexture,Zr as effectiveCornerRadius,rx as ellipseOutline,lv as enumerateDataScenarios,Qs as error,fk as figureClassFor,yA as figureSectionOutline,eu as fillStyleOpacity,s_ as filterByToolType,nm as filterShortcuts,Mv as findNearestWithCapability,v_ as flattenPolygonPath,Ov as flowGraphFor,Tv as flowGraphIssues,xv as flowReverseFor,q_ as fontStyle,Ky as footprint2D,Rr as frameClock,gv as ftId,mv as ftrace,Jm as getAllCapabilityMeta,Qm as getCapabilityMeta,OA as getFigure,El as getPose,Al as getWorldPose,Dr as globalSimClock,Ly as gltfNatureProperties,Yv as graphFor,gb as gridCellOf,Sw as gridPlacements,mb as gridSlotNo,Xr as hasArc,Wm as hasCapability,$y as hasCapacity,PA as hasFigure,Hy as inferCapacity,ov as inferDownstreamId,fv as inferFlowDirections,Ji as initFontFamilyWatcher,jd as inspector,E_ as installContractInspector,Kv as isFlowNode,Ig as isGenericPlaceholder,wv as isGeometricHost,Su as isParted,Sv as isRoutingTarget,Sx as isSegmentPreset,mu as isStateDriven,Iu as isThreedEnabled,zb as judgeItemFit,rb as layoutIssue,qb as matchOutbounds,js as metrics,Fv as next,Zb as nextHop,Jb as nextHops,nv as nextHopsToAny,sv as nextHopsToAnyDetailed,sf as niceGridStep,zv as nodeIdOf,su as opaqueColor,wk as paletteVersion,Eu as partAtByIndex,ub as persistenceIssues,Vv as pickWeightedDestination,m_ as planPathAStar,g_ as planToReservations,Vb as pointInRotatedRect,yu as polygonOffsetForPriority,__ as polygonPathLength,ip as projectToScreen,Jv as quatFromYaw,Ub as rayAbsDistanceToRect,Kb as reachableByOutbound,$v as reachableDestinations,Hv as reachableDestinationsFrom,Bv as reachableDestinationsWeightedFrom,ev as reachableSinks,Uu as receiptToJSON,vf as recommendsLogarithmicDepthForSky,Nb as rectFaceAnchors,ix as rectOutline,e_ as rectangularFootprintFrames,Km as registerCapabilityMeta,Zp as registerDefaultRealObjectFactory,TA as registerFigure,SA as registerFigureType,Mk as registerPalette,Jp as registerRealObjectFactory,Rl as registerTypeResolver,KA as releaseFigureGeometry,N_ as renderCanvasTexture,Cg as renderPlaceholder,h_ as reservationTable,mk as resetFigureClasses,DA as resetFigures,Tk as resetPalettes,ap as resolveAnchorWorldPosition,Mx as resolveHeightSegments,Id as resolveMaterial3d,Lv as resolveNextHop,wx as resolveSegments,bb as resolveSlot,kk as resolveToken,Ll as resolveUnknownTypes,Qd as resolveVariant,Ab as rotatedFootprint,Ny as sceneComponent,kb as seatInSlot,Cb as seatTransform,Sk as setActivePalette,kl as setPose,Du as setThreedEnabled,Cl as setWorldPose,Pv as sinksForDestination,xb as slotAddresses,pb as slotCount,Mb as slotFrame,vb as slotIdOf,fb as slotNumbers,Db as slotSpaceWarnings,uk as slotsFromBindings,Tb as stackSeatTransforms,c_ as standardYieldPolicy,Np as stopFPSMeasure,Hb as straightSegmentEndpoints,Yb as straightSegmentMultiInbound,$b as straightSegmentTopology,Z_ as textBounds,Q_ as textTexture,zd as toThreeSide,n_ as topApproachFrame,Xu as transferLog,Gu as transferTracer,no as uniformZ,Dk as unitFigurePartGeometry,jl as unknownTypesOf,IA as unregisterFigure,Dl as unresolvedReasonOf,Qi as updateDefaultFontFamily,lp as updateTether,MA as useFigureComponent,Gv as validate,iv as validateFlowGraph,db as validateSlotLayout,j_ as version,Js as warn};
51
51
  //# sourceMappingURL=things-scene.mjs.map