@layoutit/polycss 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/elements.js CHANGED
@@ -1,4 +1,4 @@
1
- import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,VOXEL_CAMERA_CULL_NORMAL_LIMIT as Tl,cameraCullNormalKey as Al,cameraCullVisibleSignature as Ml,clipPolygonToConvex2D as wl,computeSceneBbox as Ll,convexHull2D as Hr,ensureCcw2D as Lo,findOverlappingPolygonDuplicates as _l,inverseRotateVec3 as Ir,isAxisAlignedSurfaceNormal as Rl,isVoxelCameraCullableNormalGroups as Dl,normalFacesCamera as kl,optimizeMeshPolygons as Ol,parseHex as Fl,parseHexColor as _o,polygonCssSurfaceNormal as Vr,projectCssVertexToGround as Hl}from"@layoutit/polycss-core";import{packTextureAtlasPlansWithScaleCore as Ti}from"@layoutit/polycss-core";function Ai(e){if(!e)return!1;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return t?t("(pointer: coarse)").matches||t("(hover: none)").matches:!1}function $t(e,n,t){return Ti(e,n,Ai(t))}import{buildTextureEdgeRepairSets as ks,buildSeamBleedPolygonEdges as Os,buildSeamBleedPolygonSet as Fs}from"@layoutit/polycss-core";import{TEXTURE_TRIANGLE_BLEED as Mi,TEXTURE_EDGE_REPAIR_ALPHA_MIN as wi,TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN as Li,TEXTURE_EDGE_REPAIR_RADIUS as Yo}from"@layoutit/polycss-core";import{tintToCss as _i}from"@layoutit/polycss-core";import{expandClipPoints as Ri}from"@layoutit/polycss-core";import{BASIS_EPS as Di}from"@layoutit/polycss-core";var St=new Map;function ki(e){let n=St.get(e);return n||(n=new Promise((t,o)=>{let r=new Image;r.decoding="async",r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=()=>o(new Error(`texture load failed: ${e}`)),r.src=e}),St.set(e,n),n.then(()=>{St.get(e)===n&&St.delete(e)},()=>{St.get(e)===n&&St.delete(e)})),n}function Ye(e,n,t=1,o=0,r=0,i=1,l=0,c=0){e.setTransform(t*n,o*n,r*n,i*n,l*n,c*n)}function Oi(e,n,t,o,r,i,l){Math.abs(i.r-1)<.001&&Math.abs(i.g-1)<.001&&Math.abs(i.b-1)<.001||(e.save(),Ye(e,l),e.globalCompositeOperation="multiply",e.fillStyle=_i(i),e.fillRect(n,t,o,r),e.restore())}function Fi(e,n,t,o,r,i,l){let c=n.naturalWidth||n.width||1,a=n.naturalHeight||n.height||1,m=Math.max(r/c,i/a),f=c*m,h=a*m;Ye(e,l),e.drawImage(n,t+(r-f)/2,o+(i-h)/2,f,h)}function Ct(e,n){return Math.max(0,Math.min(n,e))}function jo(e,n,t,o,r,i,l,c){let a=n.naturalWidth||n.width||1,m=n.naturalHeight||n.height||1,f=Ct(Math.min(t.minU,t.maxU)*a,a),h=Ct(Math.max(t.minU,t.maxU)*a,a),g=Ct(Math.min(t.minV,t.maxV)*m,m),x=Ct(Math.max(t.minV,t.maxV)*m,m),y=Math.floor(f),P=Math.floor(g),v=Math.ceil(h)-y,E=Math.ceil(x)-P;v<1&&(y=Math.floor(Ct((t.minU+t.maxU)/2*a,a-1)),v=1),E<1&&(P=Math.floor(Ct((t.minV+t.maxV)/2*m,m-1)),E=1),y=Math.max(0,Math.min(a-1,y)),P=Math.max(0,Math.min(m-1,P)),v=Math.max(1,Math.min(a-y,v)),E=Math.max(1,Math.min(m-P,E)),Ye(e,c),e.drawImage(n,y,P,v,E,o,r,i,l)}function qo(e){return e==="repeat"||e==="mirrored-repeat"}function Xo(e,n){return qo(e)?Math.floor(n):0}function Wo(e,n){return qo(e)?Math.ceil(n)-1:0}function Zo(e,n){return e==="mirrored-repeat"&&Math.abs(n%2)===1}function Qo(e,n,t,o,r,i,l){let c=r?Xo(i,r.minU):0,a=r?Wo(i,r.maxU):0,m=r?Xo(l,r.minV):0,f=r?Wo(l,r.maxV):0;for(let h=c;h<=a;h++)for(let g=m;g<=f;g++){let x=Zo(i,h),y=Zo(l,g);if(!x&&!y){e.drawImage(n,h*t,g*o);continue}e.save(),e.translate((x?h+1:h)*t,(y?g+1:g)*o),e.scale(x?-1:1,y?-1:1),e.drawImage(n,0,0),e.restore()}}function lo(e,n,t,o){for(let r=0;r<o.length;r+=2){let i=n+o[r],l=t+o[r+1];r===0?e.moveTo(i,l):e.lineTo(i,l)}e.closePath()}function un(e,n,t,o,r,i){for(let l=0;l<o.length;l+=2){let c=n+o[l]+r,a=t+o[l+1]+i;l===0?e.moveTo(c,a):e.lineTo(c,a)}e.closePath()}function Hi(e,n,t,o){Ye(e,o),e.beginPath(),lo(e,n.x,n.y,n.screenPts),e.clip(),Ye(e,o),e.fillStyle=t==="dynamic"?n.polygon.color??"#cccccc":n.shadedColor,e.fillRect(n.x,n.y,n.canvasW,n.canvasH)}function dn(e,n,t,o,r){n.polygon.textureAlphaMode==="opaque"&&(Ye(e,t),e.fillStyle=n.polygon.color??"#cccccc",e.fillRect(n.x+o,n.y+r,n.canvasW,n.canvasH))}function Ii(e,n,t,o,r=0,i=0){if(n.textureTriangles?.length){let l=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1;for(let a of n.textureTriangles){let m=Ri(a.screenPts,Mi);e.save(),Ye(e,o),e.beginPath(),un(e,n.x,n.y,m,r,i),e.clip(),dn(e,n,o,r,i),a.uvAffine?(Ye(e,o,a.uvAffine.a/l,a.uvAffine.c/l,a.uvAffine.b/c,a.uvAffine.d/c,n.x+a.uvAffine.e+r,n.y+a.uvAffine.f+i),Qo(e,t,l,c,a.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t)):a.uvSampleRect&&jo(e,t,a.uvSampleRect,n.x+r,n.y+i,n.canvasW,n.canvasH,o),e.restore()}}else if(n.uvAffine){let l=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1,a=n.polygon.textureAlphaMode==="opaque";a&&(e.save(),Ye(e,o),e.beginPath(),un(e,n.x,n.y,n.screenPts,r,i),e.clip(),dn(e,n,o,r,i)),Ye(e,o,n.uvAffine.a/l,n.uvAffine.c/l,n.uvAffine.b/c,n.uvAffine.d/c,n.x+n.uvAffine.e+r,n.y+n.uvAffine.f+i),Qo(e,t,l,c,n.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t),a&&e.restore()}else if(n.uvSampleRect){let l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),Ye(e,o),e.beginPath(),un(e,n.x,n.y,n.screenPts,r,i),e.clip(),dn(e,n,o,r,i)),jo(e,t,n.uvSampleRect,n.x+r,n.y+i,n.canvasW,n.canvasH,o),l&&e.restore()}else{let l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),Ye(e,o),e.beginPath(),un(e,n.x,n.y,n.screenPts,r,i),e.clip(),dn(e,n,o,r,i)),Fi(e,t,n.x+r,n.y+i,n.canvasW,n.canvasH,o),l&&e.restore()}}function Vi(e,n,t,o,r,i){let l=r-t,c=i-o,a=l*l+c*c;if(a<=Di)return Math.hypot(e-t,n-o);let m=Math.max(0,Math.min(1,((e-t)*l+(n-o)*c)/a));return Math.hypot(e-(t+l*m),n-(o+c*m))}function zi(e,n,t,o){let r=1/0,i=t.length/2;for(let l of o){if(l<0||l>=i)continue;let c=l*2,a=(l+1)%i*2;r=Math.min(r,Vi(e,n,t[c],t[c+1],t[a],t[a+1]))}return r}function Bi(e,n,t,o,r,i){let l=Math.max(0,o-i),c=Math.min(n-1,o+i),a=Math.max(0,r-i),m=Math.min(t-1,r+i),f=null,h=1/0;for(let g=a;g<=m;g++)for(let x=l;x<=c;x++){if(x===o&&g===r)continue;let y=x-o,P=g-r,v=y*y+P*P;if(v>i*i||v>=h)continue;let E=(g*n+x)*4;e[E+3]<Li||(f=E,h=v)}return f}function Ni(e,n,t){if(!n.textureEdgeRepair||!n.texture||!n.textureEdgeRepairEdges||n.textureEdgeRepairEdges.size===0)return;let o=e.canvas;if(!o)return;let r=Math.max(0,Math.floor(n.x*t)),i=Math.max(0,Math.floor(n.y*t)),l=Math.max(1,Math.min(o.width-r,Math.ceil(n.canvasW*t))),c=Math.max(1,Math.min(o.height-i,Math.ceil(n.canvasH*t)));if(l<=0||c<=0)return;let a;try{a=e.getImageData(r,i,l,c)}catch{return}let m=a.data,f=new Uint8ClampedArray(m),h=Math.max(Yo,Yo/t),g=Math.max(2,Math.ceil(h*t)+1),x=!1;for(let y=0;y<c;y++)for(let P=0;P<l;P++){let v=(y*l+P)*4,E=m[v+3];if(E<wi||E===255)continue;let H=(r+P+.5)/t-n.x,k=(i+y+.5)/t-n.y;if(zi(H,k,n.screenPts,n.textureEdgeRepairEdges)>h)continue;let N=Bi(f,l,c,P,y,g);N!==null&&(m[v]=f[N],m[v+1]=f[N+1],m[v+2]=f[N+2],m[v+3]=255,x=!0)}x&&e.putImageData(a,r,i)}function Ui(e){if(typeof e.toBlob=="function")return new Promise(n=>{e.toBlob(t=>{n(t?URL.createObjectURL(t):null)},"image/png")});try{return Promise.resolve(e.toDataURL("image/png"))}catch{return Promise.resolve(null)}}async function $i(e,n,t,o){let r=t.createElement("canvas");r.width=Math.max(1,Math.ceil(e.width*o)),r.height=Math.max(1,Math.ceil(e.height*o));let i=e.entries.some(f=>f.textureEdgeRepair&&f.texture&&f.textureEdgeRepairEdges&&f.textureEdgeRepairEdges.size>0),l=r.getContext("2d",i?{willReadFrequently:!0}:void 0);if(!l)return{width:e.width,height:e.height,url:null};let c=Array.from(new Set(e.entries.flatMap(f=>f.texture?[f.texture]:[]))),a=new Map;await Promise.all(c.map(async f=>{a.set(f,await ki(f))}));for(let f of e.entries){let h=f.texture?a.get(f.texture):null;if(!f.texture){l.save(),Hi(l,f,n,o),l.restore();continue}h&&(l.save(),Ye(l,o),l.beginPath(),lo(l,f.x,f.y,f.screenPts),l.clip(),Ii(l,f,h,o),l.restore()),f.texture&&n==="baked"&&(l.save(),Ye(l,o),l.beginPath(),lo(l,f.x,f.y,f.screenPts),l.clip(),Oi(l,f.x,f.y,f.canvasW,f.canvasH,f.textureTint,o),l.restore()),Ni(l,f,o)}let m=await Ui(r);return r.width=1,r.height=1,{width:e.width,height:e.height,url:m}}async function Gt(e,n,t,o,r){let i=[];for(let l of e){if(r())break;i.push(await $i(l,n,t,o))}return i}import{isFullRectSolid as ot,isSolidTrianglePlan as pt,isProjectiveQuadPlan as rt,fullRectBounds as Fc,safariCssProjectiveUnsupported as Ko,incrementCount as Hc,dominantCountKey as Ic,filterAtlasPlans as Vc,getSolidPaintDefaultsForPlansCore as Yi}from"@layoutit/polycss-core";import{parseHex as ji,rgbKey as Xi}from"@layoutit/polycss-core";import{computeTextureAtlasPlan as Uc,buildBasisHints as $c}from"@layoutit/polycss-core";import{resolveProjectiveQuadGuards as Gi}from"@layoutit/polycss-core";function Et(e){let t=e?.defaultView?.__polycssProjectiveQuadGuards;return Gi(t)}function Yt(e){if(!!!(e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0))?.supports?.("border-shape","polygon(0 0, 100% 0, 0 100%) circle(0)"))return!1;let r=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return r?r("(pointer: fine)").matches&&r("(hover: hover)").matches:!0}function Jo(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Ko(t):!0}function jt(e){let n=e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0);return!!n?.supports?.("corner-top-left-shape","bevel")&&!!n.supports("corner-top-right-shape","bevel")&&!!n.supports("corner-bottom-right-shape","bevel")&&!!n.supports("corner-bottom-left-shape","bevel")}function Wi(e){let n=e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0);return!!n?.supports?.("corner-top-left-shape","bevel")&&!!n.supports("corner-top-right-shape","bevel")}function Zi(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return/\bFirefox\//.test(t)}function it(e,n){return n?.disable?.includes("u")?null:Wi(e)?"corner-bevel":Jo(e)?Zi(e)?"border-large":"border":null}function Xt(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Ko(t):!0}function mn(e,n,t,o,r){let i=new Set(o?.disable??[]);return Yi(e,n,i,{solidTriangleSupported:Jo(t),projectiveQuadSupported:Xt(t),cornerShapeSupported:jt(t),borderShapeSupported:Yt(t)},ji,Xi,r)}import{ASYNC_RENDER_BUDGET_MS as Ps,DEFAULT_TILE as Ss,PROJECTIVE_QUAD_DENOM_EPS as Cs,PROJECTIVE_QUAD_MAX_WEIGHT_RATIO as Es,PROJECTIVE_QUAD_BLEED as Ts}from"@layoutit/polycss-core";import{buildBasisHints as Eo,buildSeamBleedPolygonEdges as As,computeTextureAtlasPlan as Kt}from"@layoutit/polycss-core";import{cornerShapeGeometryForPlan as qt}from"@layoutit/polycss-core";import{formatCssLength as pn,formatMatrix3dValues as qi,formatSolidQuadMatrix as Ki}from"@layoutit/polycss-core";import{shadePolygon as Ji}from"@layoutit/polycss-core";import{parseHex as er,rgbKey as tr}from"@layoutit/polycss-core";function Oe(e,n,t){let o=e.getAttribute("style")??"",r=`${n}:${t}`,i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(^|;)\\s*${i}\\s*:[^;]*`,"i"),c=l.test(o)?o.replace(l,(a,m)=>`${m}${r}`):`${o}${o.trim()&&!o.trim().endsWith(";")?";":""}${r}`;c!==o&&e.setAttribute("style",c)}function ft(e,n){let t=e.getAttribute("style")??"";if(!t||!t.toLowerCase().includes(n.toLowerCase()))return;let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\s*${o}\\s*:`,"i"),i=t.split(";").map(l=>l.trim()).filter(l=>l&&!r.test(l)).join(";");i?e.setAttribute("style",i):e.removeAttribute("style")}function Wt(e,n,t,o=!1){if(n==="dynamic"){let r=er(e.polygon.color??"#cccccc"),i=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return tr(r)!==t?.dynamicColorKey&&(i+=`;--psr:${(r.r/255).toFixed(4)};--psg:${(r.g/255).toFixed(4)};--psb:${(r.b/255).toFixed(4)}`),i}return e.shadedColor&&e.shadedColor!==t?.paintColor?`;color:${e.shadedColor}`:""}function Qi(e,n){Oe(e,"--pnx",n.normal[0].toFixed(4)),Oe(e,"--pny",n.normal[1].toFixed(4)),Oe(e,"--pnz",n.normal[2].toFixed(4))}function Tt(e,n,t,o){if(t==="dynamic"){ft(e,"color"),ft(e,"background"),Qi(e,n);let r=er(n.polygon.color??"#cccccc");tr(r)===o?.dynamicColorKey?(ft(e,"--psr"),ft(e,"--psg"),ft(e,"--psb")):(Oe(e,"--psr",(r.r/255).toFixed(4)),Oe(e,"--psg",(r.g/255).toFixed(4)),Oe(e,"--psb",(r.b/255).toFixed(4)))}else n.shadedColor!==o?.paintColor?(ft(e,"background"),Oe(e,"color",n.shadedColor)):(ft(e,"background"),ft(e,"color"))}import{formatBorderShapeElementStyle as nr,formatCornerShapeElementStyle as or}from"@layoutit/polycss-core";import{atlasCanonicalSizeForEntry as gt}from"@layoutit/polycss-core";import{computeProjectiveQuadMatrix as es,stableBasisFromPlan as ts}from"@layoutit/polycss-core";import{DEFAULT_LIGHT_DIR as ns,DEFAULT_LIGHT_COLOR as os,DEFAULT_LIGHT_INTENSITY as rs,DEFAULT_AMBIENT_COLOR as is,DEFAULT_AMBIENT_INTENSITY as ss}from"@layoutit/polycss-core";var ao=new WeakMap,co=new WeakMap;function Fe(e,n){let t=ao.get(e),o=co.get(e);if(!n.data&&(!t||t.length===0)){e.__polycssHasDataAttrs=!1;return}let r=new Map;if(n.data)for(let[l,c]of Object.entries(n.data))r.set(l,String(c));if(t)for(let l of t)r.has(l)||e.removeAttribute(`data-${l}`);for(let[l,c]of r)o?.get(l)!==c&&e.setAttribute(`data-${l}`,c);let i=Array.from(r.keys());i.length>0?ao.set(e,i):ao.delete(e),r.size>0?co.set(e,r):co.delete(e),e.__polycssHasDataAttrs=i.length>0}function At(e){return e.__polycssHasDataAttrs===!0}function uo(e,n,t,o,r=t==="dynamic"){if(!n.url)return;let i=`url(${n.url})`,l=o.canvasW||1,c=o.canvasH||1,a=gt(o),m=`${pn(-o.x/l*a)} ${pn(-o.y/c*a)}`,f=`${pn(n.width/l*a)} ${pn(n.height/c*a)}`,h=`transform:matrix3d(${o.atlasMatrix});--polycss-atlas-size:${a}px`,g=`${h};--polycss-atlas-position:${m};--polycss-atlas-image-size:${f}`;if(t==="dynamic"){let x=r?`;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`:"";e.setAttribute("style",g+`;--polycss-atlas-url:${i}`+x)}else e.setAttribute("style",h+`;background:${i} ${m} / ${f} no-repeat`)}function rr(e,n,t,o){if(n.texture){if(!t.texture||n.texture!==t.texture)return!1}else if(t.texture)return!1;let r=ir(n,t);return r?(e.style.visibility="",Oe(e,"transform",`matrix3d(${r.matrix})`),o==="dynamic"&&(Oe(e,"--pnx",r.normal[0].toFixed(4)),Oe(e,"--pny",r.normal[1].toFixed(4)),Oe(e,"--pnz",r.normal[2].toFixed(4))),Fe(e,t),!0):(e.style.visibility="hidden",Fe(e,t),!0)}function mo(e,n,t,o,r){if(o!=="baked")return{...e,polygon:n,normal:t};let i=r.directionalLight,l=r.ambientLight,c=i?.direction??ns,a=i?.color??os,m=Math.max(0,i?.intensity??rs),f=l?.color??is,h=Math.max(0,l?.intensity??ss),g=Math.hypot(c[0],c[1],c[2])||1,x=c[0]/g,y=c[1]/g,P=c[2]/g,v=m*Math.max(0,t[0]*x+t[1]*y+t[2]*P);return{...e,polygon:n,normal:t,shadedColor:Ji(n.color??"#cccccc",v,a,f,h)}}function ir(e,n){let t=sr(e,n);if(!t)return null;let{normal:o,xAxis:r,yAxis:i,tx:l,ty:c,tz:a}=t;return{normal:o,matrix:qi([r[0]*e.canvasW/gt(e),r[1]*e.canvasW/gt(e),r[2]*e.canvasW/gt(e),0,i[0]*e.canvasH/gt(e),i[1]*e.canvasH/gt(e),i[2]*e.canvasH/gt(e),0,o[0],o[1],o[2],0,l,c,a,1])}}var sr=ts;function ls(e,n,t){if(e.screenPts.length!==8||n.vertices.length!==4)return null;let o=sr(e,n);if(!o)return null;let r=es(e.screenPts,o.xAxis,o.yAxis,o.normal,o.tx,o.ty,o.tz,t);return r?{matrix:r,normal:o.normal}:null}function po(e,n,t,o,r=!1){let i=t.createElement("b");return i.setAttribute("style",`transform:matrix3d(${Ki(e)})`+Wt(e,n,o,r)),Fe(i,e.polygon),i}function fo(e,n,t,o,r=!1){let i=t.createElement("i");return i.setAttribute("style",nr(e)+Wt(e,n,o,r)),Fe(i,e.polygon),i}function go(e,n,t,o,r,i=!1){let l=o.createElement("u");return l.setAttribute("style",or(e,n)+Wt(e,t,r,i)),Fe(l,e.polygon),l}function ho(e,n,t,o,r=!1){let i=t.createElement("b");return i.setAttribute("style",`transform:matrix3d(${e.projectiveMatrix})`+Wt(e,n,o,r)),Fe(i,e.polygon),i}function lr(e,n,t,o,r,i,l){let c=n.projectiveMatrix?ls(n,t,i):ir(n,t);if(!c)return!1;let a=mo(n,t,c.normal,o,r);return e.style.visibility="",e.style.transform=`matrix3d(${c.matrix})`,Tt(e,a,o,l),Fe(e,a.polygon),!0}function ar(e,n,t,o){e.style.visibility="",e.setAttribute("style",nr(n)),Tt(e,n,t,o),Fe(e,n.polygon)}function cr(e,n,t,o,r){e.style.visibility="",e.setAttribute("style",or(n,t)),Tt(e,n,o,r),Oe(e,"background","currentColor"),Fe(e,n.polygon)}function yo(e,n,t,o=!1){let r=t.createElement("s"),i=gt(e),l=n==="dynamic"&&!o?`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`:"";return r.setAttribute("style",`transform:matrix3d(${e.atlasMatrix});--polycss-atlas-size:${i}px;opacity:0`+l),Fe(r,e.polygon),r}import{computeSolidTriangleColorPlan as Ms}from"@layoutit/polycss-core";import{computeSolidTrianglePlanFromCssPoints as as,computeSolidTrianglePlan as cs}from"@layoutit/polycss-core";function xt(e,n,t,o={}){let r=o.primitive!=null?void 0:(()=>{let i=t.doc??(typeof document<"u"?document:null);return i?it(i,t.strategies)??"border":"border"})();return cs(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??r})}function bo(e,n,t,o,r,i,l,c,a,m,f,h,g){let x=o.primitive!=null?void 0:(()=>{let y=t.doc??(typeof document<"u"?document:null);return y?it(y,t.strategies)??"border":"border"})();return as(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??x},r,i,l,c,a,m,f,h,g)}import{buildSeamBleedPolygonEdges as us,DEFAULT_TILE as su,SOLID_TRIANGLE_CORNER_CLASS as ds,SOLID_TRIANGLE_LARGE_BORDER_CLASS as ms}from"@layoutit/polycss-core";import{rgbEqual as ps,stepRgbToward as fs,rgbToCss as gs,colorErrorScore as hs}from"@layoutit/polycss-core";import{computeSolidTriangleColorPlan as ys}from"@layoutit/polycss-core";import{stableTriangleMatrixDecimals as ur}from"@layoutit/polycss-core";var bs=1.5;function dr(e,n){return us(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function mr(e,n,t){return n?{...t,seamBleed:n.has(e)?bs:void 0,seamEdges:n.get(e)}:t}function vo(e){return{updatesDisabled:e.stableTriangleColorFreezeFrames===0,freezeFrames:Math.max(1,Math.floor(e.stableTriangleColorFreezeFrames??1)),colorFrame:Math.max(0,Math.floor(e.stableTriangleColorFrame??0)),maxStep:Math.max(0,Math.floor(e.stableTriangleColorMaxStep??0))}}function pr(e,n){return!n.updatesDisabled&&(n.freezeFrames<=1||(n.colorFrame+e)%n.freezeFrames===0)}function Mt(e,n,t,o,r,i){return t?i.updatesDisabled||o==="plan-only"||o==="transform-only"?!1:r==="adaptive"||e.__polycssSolidTriangleColor===void 0?!0:pr(n,i):!0}function xo(e,n){let t=e;t.__polycssSolidTrianglePrimitive!==n&&(e.classList.toggle(ds,n==="corner-bevel"),e.classList.toggle(ms,n==="border-large"),t.__polycssSolidTrianglePrimitive=n)}function Po(e){let n=e;n.__polycssSolidTriangleHidden&&(e.style.visibility="",n.__polycssSolidTriangleHidden=!1)}function Zt(e){let n=e;n.__polycssSolidTriangleHidden||(e.style.visibility="hidden",n.__polycssSolidTriangleHidden=!0)}function fn(e,n){e.setAttribute("style",n.styleText),xo(e,n.primitive);let t=e;t.__polycssSolidTriangleBasis=n.basis,t.__polycssSolidTriangleHidden=!1,n.colorComputed&&(t.__polycssSolidTriangleColor=n.bakedColor??"",t.__polycssSolidTriangleColorRgb=n.bakedRgb,t.__polycssSolidTriangleColorAlpha=n.bakedAlpha),t.__polycssSolidTriangleColorFrame=void 0,(n.polygon.data||At(e))&&Fe(e,n.polygon)}function fr(e,n,t,o){if(!n.colorComputed){(n.polygon.data||At(e))&&Fe(e,n.polygon);return}let r=e,i=n.bakedColor??"",l=n.bakedRgb,c=n.bakedAlpha??1,a=r.__polycssSolidTriangleColor,m=r.__polycssSolidTriangleColorRgb,f=r.__polycssSolidTriangleColorAlpha??1,h=o??pr(n.index,t);if(!t.updatesDisabled&&a!==i&&(a===void 0||h)){let g=i,x=l;if(t.maxStep>0&&m&&l&&f===c){let y=fs(m,l,t.maxStep);x=y,g=gs(y,c)}(g!==a||!ps(x,m))&&(e.style.color=g),r.__polycssSolidTriangleColor=g,r.__polycssSolidTriangleColorRgb=x,r.__polycssSolidTriangleColorAlpha=c,r.__polycssSolidTriangleColorFrame=t.colorFrame}(n.polygon.data||At(e))&&Fe(e,n.polygon)}function gn(e,n,t,o){let r=e;xo(e,n.primitive),r.__polycssSolidTriangleBasis!==n.basis&&(r.__polycssSolidTriangleBasis=n.basis),Po(e),e.style.transform=n.transformText,(n.colorComputed||n.polygon.data||At(e))&&fr(e,n,t,o)}function So(e,n,t,o){Po(e),fr(e,n,t,o)}function hn(e,n){let t=e;xo(e,n.primitive),t.__polycssSolidTriangleBasis!==n.basis&&(t.__polycssSolidTriangleBasis=n.basis),Po(e),e.style.transform=n.transformText,(n.polygon.data||At(e))&&Fe(e,n.polygon)}function vs(e,n){let t=n.stableTriangleColorBudget;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t<=1?Math.max(1,Math.ceil(e*t)):Math.max(1,Math.floor(t));let o=Math.max(1,Math.floor(n.stableTriangleColorFreezeFrames??1));return Math.max(1,Math.ceil(e/o))}function gr(e,n,t){if(t.stableTriangleColorPolicy!=="adaptive")return null;if(t.stableTriangleColorFreezeFrames===0)return new Set;let o=Math.max(0,Math.floor(t.stableTriangleColorFrame??0)),r=Math.max(1,Math.floor(t.stableTriangleColorFreezeFrames??1));if(r<=1&&!Number.isFinite(t.stableTriangleColorBudget))return null;let i=vs(e.length,t),l=Math.max(1,Math.floor(t.stableTriangleColorMaxAge??Math.max(2,r*2))),c=[];for(let a=0;a<e.length;a++){let m=e[a],f=n[a];if(m.kind!=="triangle"||!f)continue;let h=m.element,g=h.__polycssSolidTriangleColor,x=f.bakedColor??"";if(g===x)continue;let y=h.__polycssSolidTriangleColorFrame??0,P=Math.max(0,o-y),v=hs(g,x);c.push({index:a,score:(P>=l?1e6:0)+v*1e4+P})}return c.length===0?new Set:(c.sort((a,m)=>m.score-a.score),new Set(c.slice(0,i).map(a=>a.index)))}function yn(e,n){let t=n.createElement("u");return fn(t,e),t}function xs(e,n){let t=n.createElement("u");return Zt(t),e.data&&Fe(t,e),t}function hr(e,n,t,o,r,i){let l=t,c=l.stableTriangleDebug,a=o&&r==="color-only";if(l.stableTriangleColorPolicy==="adaptive"||e.length!==n.length)return!1;let m=ur(l.stableTriangleMatrixDecimals),f=t.doc??(typeof document<"u"?document:null),h=f?it(f,t.strategies)??"border":"border";for(let x=0;x<e.length;x++){let y=e[x];if(y.kind!=="triangle"||y.polygonIndex!==x||!n[x])return!1}let g=dr(n,t);for(let x=0;x<e.length;x++){let y=e[x].element,P=n[x];if(a){if(Mt(y,x,o,c,l.stableTriangleColorPolicy,i)){let E=ys(P,x,t);if(!E)continue;So(y,E,i)}continue}let v=xt(P,x,mr(x,g,t),{basis:y.__polycssSolidTriangleBasis,matrixDecimals:m,primitive:h,includeColor:r!=="plan-only"&&r!=="transform-only"&&Mt(y,x,o,c,l.stableTriangleColorPolicy,i)});if(!v){Zt(y);continue}o&&r==="plan-only"||(o&&r==="transform-only"?hn(y,v):o?gn(y,v,i):fn(y,v))}return!0}function Qt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=it(t,n.strategies);if(!o||e.some(c=>c.texture||c.vertices.length!==3))return null;let r=ur(n.stableTriangleMatrixDecimals),i=[],l=dr(e,n);for(let c=0;c<e.length;c+=1){let a=e[c],m=xt(a,c,mr(c,l,n),{matrixDecimals:r,primitive:o}),f=m?yn(m,t):xs(a,t);i.push({polygonIndex:c,element:f,kind:"triangle",dispose:()=>{}})}return{rendered:i,dispose(){}}}import{stableTriangleMatrixDecimals as yr}from"@layoutit/polycss-core";var br=1.5;function vr(){return new Promise(e=>setTimeout(e,0))}async function Co(e){return performance.now()-e<Ps?e:(await vr(),performance.now())}function xr(e,n){return e.seamBleedEdges?.size?{...n,seamBleed:br,seamEdges:e.seamBleedEdges}:{...n,seamBleed:void 0,seamEdges:void 0}}function Pr(e,n){return As(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function Sr(e,n,t){return n?{...t,seamBleed:n.has(e)?br:void 0,seamEdges:n.get(e)}:t}function wt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{};let o=Eo(e,n),r=Et(t),i=e.map((l,c)=>Kt(l,c,n,r,o[c]));return mn(i,n.textureLighting??"baked",t,n.strategies)}function Jt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=n.textureLighting??"baked",r=n,i=o==="dynamic"&&r.skipDynamicNormalVars===!0,l=new Set(n.strategies?.disable??[]),c=!l.has("b"),a=c&&Xt(t),m=it(t,n.strategies),f=m!==null,h=!l.has("i")&&jt(t),g=!l.has("i")&&Yt(t),x=Eo(e,n),y=Et(t),P=Pr(e,n),v=e.map((u,p)=>Kt(u,p,Sr(p,P,n),y,x[p])),E=n.solidPaintDefaults??(r.computeSolidPaintDefaults?mn(v,o,t,n.strategies):void 0),H=E?{...n,solidPaintDefaults:E}:n,k=v.map(u=>u&&f&&pt(u)?xt(u.polygon,u.index,xr(u,H),{primitive:m??void 0}):null),N=v.map(u=>u&&h&&!pt(u)&&!(c&&ot(u))&&!(a&&rt(u))?qt(u):null),R=v.map((u,p)=>u&&(u.texture||!(c&&ot(u))&&!k[p]&&!(a&&rt(u))&&!N[p]&&!g?u:null)),{packed:K,atlasScale:z}=$t(R,n.textureQuality,t),O=new Map,$=[],U=!1,ie=[];for(let u=0;u<e.length;u++){let p=v[u],C=k[u],A=N[u];if(!p)continue;let w=K.entries[u];if(w){let M=yo(w,o,t,i);O.set(u,M),$.push({polygonIndex:u,element:M,kind:"atlas",plan:w,dispose:()=>{}})}else if(!p.texture&&c&&ot(p)){let M=po(p,o,t,E,i);$.push({polygonIndex:u,element:M,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&C){let M=yn(C,t);$.push({polygonIndex:u,element:M,kind:"triangle",plan:p,dispose:()=>{}})}else if(!p.texture&&a&&rt(p)){let M=ho(p,o,t,E,i);$.push({polygonIndex:u,element:M,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&A){let M=go(p,A,o,t,E,i);$.push({polygonIndex:u,element:M,kind:"corner",plan:p,dispose:()=>{}})}else if(!p.texture&&g){let M=fo(p,o,t,E,i);$.push({polygonIndex:u,element:M,kind:"border",plan:p,dispose:()=>{}})}}return $.sort((u,p)=>u.polygonIndex-p.polygonIndex),Gt(K.pages,o,t,z,()=>U).then(u=>{if(U){for(let p of u)p.url?.startsWith("blob:")&&URL.revokeObjectURL(p.url);return}ie=u.flatMap(p=>p.url?.startsWith("blob:")?[p.url]:[]);for(let p=0;p<K.pages.length;p++){let C=K.pages[p],A=u[p];if(A)for(let w of C.entries){let M=O.get(w.index);!M||!A.url||uo(M,A,o,w,!i)}}}).catch(()=>{if(!U)for(let u of O.values())Oe(u,"opacity","0.5"),Oe(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")}),{rendered:$,solidPaintDefaults:E??{},dispose(){U=!0;for(let u of ie)URL.revokeObjectURL(u);ie=[]}}}async function bn(e,n={},t=()=>!1){let o=n.doc??(typeof document<"u"?document:null);if(!o||t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let r=n.textureLighting??"baked",l=r==="dynamic"&&n.skipDynamicNormalVars===!0,c=new Set(n.strategies?.disable??[]),a=!c.has("b"),m=a&&Xt(o),f=it(o,n.strategies),h=f!==null,g=!c.has("i")&&jt(o),x=!c.has("i")&&Yt(o);if(await vr(),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let y=Eo(e,n),P=Et(o),v=Pr(e,n),E=performance.now(),H=new Array(e.length);for(let u=0;u<e.length;u++)if(H[u]=Kt(e[u],u,Sr(u,v,n),P,y[u]),E=await Co(E),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let k=n.solidPaintDefaults??mn(H,r,o,n.strategies),N=new Array(H.length),R=new Array(H.length),K=new Array(H.length);for(let u=0;u<H.length;u++){let p=H[u],C=p&&h&&pt(p)?xt(p.polygon,p.index,xr(p,{...n,solidPaintDefaults:k}),{primitive:f??void 0}):null;N[u]=C;let A=p&&g&&!pt(p)&&!(a&&ot(p))&&!(m&&rt(p))?qt(p):null;if(R[u]=A,K[u]=p&&(p.texture||!(a&&ot(p))&&!C&&!(m&&rt(p))&&!A&&!x?p:null),E=await Co(E),t())return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}let{packed:z,atlasScale:O}=$t(K,n.textureQuality,o),$=new Map,U=[],ie=!1,xe=[];for(let u=0;u<e.length;u++){let p=H[u],C=N[u],A=R[u];if(!p)continue;let w=z.entries[u];if(w){let M=yo(w,r,o,l);$.set(u,M),U.push({polygonIndex:u,element:M,kind:"atlas",plan:w,dispose:()=>{}})}else if(!p.texture&&a&&ot(p)){let M=po(p,r,o,k,l);U.push({polygonIndex:u,element:M,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&C){let M=yn(C,o);U.push({polygonIndex:u,element:M,kind:"triangle",plan:p,dispose:()=>{}})}else if(!p.texture&&m&&rt(p)){let M=ho(p,r,o,k,l);U.push({polygonIndex:u,element:M,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&A){let M=go(p,A,r,o,k,l);U.push({polygonIndex:u,element:M,kind:"corner",plan:p,dispose:()=>{}})}else if(!p.texture&&x){let M=fo(p,r,o,k,l);U.push({polygonIndex:u,element:M,kind:"border",plan:p,dispose:()=>{}})}if(E=await Co(E),t()){for(let M of U)M.dispose();return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}}return U.sort((u,p)=>u.polygonIndex-p.polygonIndex),Gt(z.pages,r,o,O,()=>ie||t()).then(u=>{if(ie||t()){for(let p of u)p.url?.startsWith("blob:")&&URL.revokeObjectURL(p.url);return}xe=u.flatMap(p=>p.url?.startsWith("blob:")?[p.url]:[]);for(let p=0;p<z.pages.length;p++){let C=z.pages[p],A=u[p];if(A)for(let w of C.entries){let M=$.get(w.index);!M||!A.url||uo(M,A,r,w,!l)}}}).catch(()=>{if(!(ie||t()))for(let u of $.values())Oe(u,"opacity","0.5"),Oe(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")}),{rendered:U,solidPaintDefaults:k,dispose(){ie=!0;for(let u of xe)URL.revokeObjectURL(u);xe=[]}}}function vn(e,n,t,o={}){let r=o.textureLighting??"baked",i=o,l=i.optimizeStableTriangleStyle===!0&&r==="baked";if(!l||i.stableTriangleColorPolicy==="adaptive"||e.length!==t.polygonCount||n.length!==t.polygonCount||t.vertices.length<t.polygonCount*9)return!1;let c=i.stableTriangleDebug,a=i.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full");if(a==="color-only")return!1;let m=yr(i.stableTriangleMatrixDecimals),f=vo(i),h=o.tileSize??Ss,g=o.layerElevation??h,x=o.doc??(typeof document<"u"?document:null),y=x?it(x,o.strategies)??"border":"border";for(let v=0;v<e.length;v++){let E=e[v],H=n[v];if(E.kind!=="triangle"||E.polygonIndex!==v||!H||H.vertices.length!==3||H.texture||H.material?.texture)return!1}let P=t.vertices;for(let v=0;v<e.length;v++){let E=e[v].element,H=n[v],k=v*9,N=P[k+1]*h,R=P[k]*h,K=P[k+2]*g,z=P[k+4]*h,O=P[k+3]*h,$=P[k+5]*g,U=P[k+7]*h,ie=P[k+6]*h,xe=P[k+8]*g,u=bo(H,v,o,{basis:E.__polycssSolidTriangleBasis,matrixDecimals:m,primitive:y,color:t.colors?.[v],includeColor:a!=="plan-only"&&a!=="transform-only"&&Mt(E,v,l,c,i.stableTriangleColorPolicy,f)},N,R,K,z,O,$,U,ie,xe);if(!u){Zt(E);continue}a!=="plan-only"&&(a==="transform-only"?hn(E,u):gn(E,u,f))}return!0}function xn(e,n,t={}){if(e.length!==n.length)return!1;let o=t.doc??(typeof document<"u"?document:null),r=t.textureLighting??"baked",i=new Set(t.strategies?.disable??[]),l=!i.has("b"),c=!!o&&l&&Xt(o),a=!!o&&!i.has("i")&&jt(o),m=!!o&&!i.has("i")&&Yt(o),f=o?Et(o):{denomEps:Cs,maxWeightRatio:Es,bleed:Ts,disableGuards:!1},h=t.optimizeStableTriangleStyle===!0&&r==="baked",g=t,x=g.stableTriangleDebug,y=g.stableTriangleUpdateMode??(x==="plan-only"||x==="transform-only"?x:"full"),P=h&&y==="color-only",v=vo(g),E=yr(g.stableTriangleMatrixDecimals),H=o?it(o,t.strategies)??"border":"border";if(hr(e,n,t,h,y,v))return!0;let k=[],N=[],R=[];for(let z=0;z<e.length;z++){let O=e[z];if(O.polygonIndex!==z)return!1;let $=n[z];if(!$||P&&O.kind!=="triangle")return!1;if(O.kind==="atlas"){if(!O.plan||!rr(O.element,O.plan,$,r))return!1;continue}if(O.kind==="triangle"){let U=O.element;if(P){let xe=g.stableTriangleColorPolicy==="adaptive"||Mt(U,z,h,x,g.stableTriangleColorPolicy,v);N[z]=xe?Ms($,z,t):null;continue}let ie=xt($,z,t,{basis:U.__polycssSolidTriangleBasis,matrixDecimals:E,primitive:H,includeColor:y!=="plan-only"&&y!=="transform-only"&&Mt(U,z,h,x,g.stableTriangleColorPolicy,v)});if(!ie){k[z]=null;continue}k[z]=ie;continue}if(O.kind==="solid"){if(!O.plan||$.texture||$.vertices.length!==O.plan.polygon.vertices.length)return!1;R[z]=O.plan;continue}if(O.kind==="border"){let U=Kt($,z,t,f);if(!U||U.texture||!m||l&&ot(U)||c&&rt(U)||a&&qt(U))return!1;R[z]=U;continue}if(O.kind==="corner"){let U=Kt($,z,t,f);if(!U||U.texture||!a||pt(U)||l&&ot(U)||c&&rt(U)||!qt(U))return!1;R[z]=U;continue}return!1}let K=h&&y!=="plan-only"&&y!=="transform-only"?gr(e,P?N:k,g):null;for(let z=0;z<e.length;z++){let O=e[z];if(O.kind==="triangle"){if(P){let U=N[z];U&&So(O.element,U,v,K?.has(z));continue}let $=k[z];if(!$){Zt(O.element);continue}if(h&&y==="plan-only")continue;h&&y==="transform-only"?hn(O.element,$):h?gn(O.element,$,v,K?.has(z)):fn(O.element,$)}else if(O.kind==="solid"){let $=R[z];if(!$||!lr(O.element,$,n[z],r,t,f,g.solidPaintDefaults))return!1}else if(O.kind==="border"){let $=R[z];if(!$)return!1;ar(O.element,$,r,g.solidPaintDefaults)}else if(O.kind==="corner"){let $=R[z],U=$?qt($):null;if(!$||!U)return!1;cr(O.element,$,U,r,g.solidPaintDefaults)}}return!0}import{computeTextureAtlasPlanPublic as Hs}from"@layoutit/polycss-core";import{formatMatrix3d as Is,formatCssLengthPx as Vs,formatSolidQuadEntryMatrix as zs}from"@layoutit/polycss-core";import{formatBorderShapeEntryMatrix as Bs,cssBorderShapeForPlan as Ns}from"@layoutit/polycss-core";import{BASE_TILE as He,computeProjectiveQuadMatrix as Us,normalFacesCamera as $s,parsePureColor as Lr,PROJECTIVE_QUAD_BLEED as Gs,resolveProjectiveQuadGuards as Ys,rotateVec3 as Cr,SOLID_QUAD_CANONICAL_SIZE as js}from"@layoutit/polycss-core";var Xs=[.4,-.7,.59],Ws="#ffffff",Zs=1,Qs="#ffffff",qs=.4,_r=1,Ks=8,Js=Gs,ct=1e-6,el=Ys({bleed:0}),Rr={t:[0,0,1],b:[0,0,-1],fl:[0,1,0],br:[0,-1,0],fr:[1,0,0],bl:[-1,0,0]},Mo=["t","b","bl","br","fr","fl"],tl=new Map([["0,0,1","t"],["0,0,-1","b"],["0,1,0","fl"],["0,-1,0","br"],["1,0,0","fr"],["-1,0,0","bl"]]);function Er(e){let n=[];for(let t of Mo)$s(Rr[t],e)&&n.push(t);return n.join("|")}function nl(e,n,t){let o=e.__polycssVoxelBrushState??(e.__polycssVoxelBrushState={});o.color!==n&&(e.style.color=n,o.color=n),o.transform!==t&&(e.style.transform=t,o.transform=t)}function ol(e){let n=e.vertices;if(n.length<3)return null;let t=n[0],o=0,r=0,i=0;for(let c=1;c+1<n.length;c+=1){let a=n[c],m=n[c+1],f=a[1]-t[1],h=a[0]-t[0],g=a[2]-t[2],x=m[1]-t[1],y=m[0]-t[0],P=m[2]-t[2];o-=h*P-g*y,r-=g*x-f*P,i-=f*y-h*x}let l=Math.hypot(o,r,i);return l<=1e-9?null:[Math.round(o/l),Math.round(r/l),Math.round(i/l)]}function rl(e){if(e.texture||e.material||e.uvs||e.textureTriangles||e.vertices.length!==4)return null;let n=ol(e),t=n?tl.get(n.join(",")):void 0;if(!t)return null;let o=1/0,r=1/0,i=1/0,l=-1/0,c=-1/0,a=-1/0;for(let h of e.vertices)o=Math.min(o,h[0]),r=Math.min(r,h[1]),i=Math.min(i,h[2]),l=Math.max(l,h[0]),c=Math.max(c,h[1]),a=Math.max(a,h[2]);let m=1e-6,f=ul(e.color);return Math.abs(a-i)<=m?{axis:"z",face:t,left:r*He,top:o*He,width:Math.max(0,(c-r)*He),height:Math.max(0,(l-o)*He),z:i*He,baseColor:f,bleed:To()}:Math.abs(l-o)<=m?{axis:"x",face:t,left:r*He,top:i*He,width:Math.max(0,(c-r)*He),height:Math.max(0,(a-i)*He),z:-o*He,baseColor:f,bleed:To()}:Math.abs(c-r)<=m?{axis:"y",face:t,left:i*He,top:o*He,width:Math.max(0,(a-i)*He),height:Math.max(0,(l-o)*He),z:-r*He,baseColor:f,bleed:To()}:null}function To(){return{left:0,right:0,top:0,bottom:0}}function il(e){let n=o=>String(Number(o.toFixed(6))),t=`${e.item.baseColor}|${e.variableAxis}`;for(let o=0;o<3;o+=1)o!==e.variableAxis&&(t+=`|${o}:${n(e.fixed[o])}`);return t}function Tr(e){return[e[1]*He,e[0]*He,e[2]*He]}function Ar(e,n){return e.axis==="x"?[n[0],n[2]]:e.axis==="y"?[n[2],n[1]]:[n[0],n[1]]}function sl(e,n,t){let o=e.left,r=e.left+e.width,i=e.top,l=e.top+e.height;if(Math.abs(n[0]-t[0])<=ct){if(Math.abs(n[0]-o)<=ct)return"left";if(Math.abs(n[0]-r)<=ct)return"right"}if(Math.abs(n[1]-t[1])<=ct){if(Math.abs(n[1]-i)<=ct)return"top";if(Math.abs(n[1]-l)<=ct)return"bottom"}return null}function ll(e,n){let t=null;for(let o=0;o<3;o+=1)if(!(Math.abs(e[o]-n[o])<=ct)){if(t!==null)return null;t=o}return t}function al(e,n,t){let o=n.vertices,r=Tr(o[t]),i=Tr(o[(t+1)%o.length]),l=sl(e,Ar(e,r),Ar(e,i));if(!l)return null;let c=ll(r,i);if(c===null)return null;let a=Math.min(r[c],i[c]),m=Math.max(r[c],i[c]);return m-a>ct?{item:e,side:l,variableAxis:c,fixed:r,start:a,end:m}:null}function Mr(e){e.item.bleed[e.side]=Math.max(e.item.bleed[e.side],Js)}function cl(e,n){let t=new Map;for(let o of n){let r=e[o.sourceIndex];if(r)for(let i=0;i<r.vertices.length;i+=1){let l=al(o,r,i);if(!l)continue;let c=il(l),a=t.get(c);a?a.push(l):t.set(c,[l])}}for(let o of t.values()){if(o.length<2)continue;o.sort((i,l)=>i.start-l.start||i.end-l.end);let r=[];for(let i of o){r=r.filter(l=>l.end>i.start+ct);for(let l of r)l.item.sourceIndex!==i.item.sourceIndex&&(Mr(l),Mr(i));r.push(i)}}}function Ao(e){let n=Lr(e);return n?{r:n.rgb[0],g:n.rgb[1],b:n.rgb[2],alpha:n.alpha}:{r:255,g:255,b:255,alpha:1}}function ul(e){if(!e)return"#cccccc";let n=Lr(e);if(!n)return e;let t={r:n.rgb[0],g:n.rgb[1],b:n.rgb[2],alpha:n.alpha};if(t.alpha<1){let o=Math.round(Math.max(0,t.alpha)*1e3)/1e3;return`rgba(${Lt(t.r)}, ${Lt(t.g)}, ${Lt(t.b)}, ${o})`}return Dr(t)}function Dr({r:e,g:n,b:t}){let o=r=>Math.round(Math.max(0,Math.min(255,r))).toString(16).padStart(2,"0");return`#${o(e)}${o(n)}${o(t)}`}function Lt(e){return Math.round(Math.max(0,Math.min(255,e)))}function dl(e,n,t,o){let r=Ao(n),i=Ao(t?.color??Ws),l=Ao(o?.color??Qs),c=t?.direction??Xs,a=Math.hypot(c[0],c[1],c[2])||1,m=c[0]/a,f=c[1]/a,h=c[2]/a,g=Math.max(0,t?.intensity??Zs)*Math.max(0,e[0]*m+e[1]*f+e[2]*h),x=Math.max(0,o?.intensity??qs),y=l.r/255*x+i.r/255*g,P=l.g/255*x+i.g/255*g,v=l.b/255*x+i.b/255*g,E={r:r.r*y,g:r.g*P,b:r.b*v,alpha:r.alpha};return E.alpha<1?`rgba(${Lt(E.r)}, ${Lt(E.g)}, ${Lt(E.b)}, ${E.alpha})`:Dr(E)}function ml(e){if(!e?.length)return[];let n=[];for(let t=0;t<e.length;t+=1){let o=e[t],r=rl(o);if(!r||r.width<=0||r.height<=0)return[];n.push({...r,sourceIndex:t})}return cl(e,n),n}function pl(e){return e.axis==="x"?{xAxis:[1,0,0],yAxis:[0,0,1],normal:[0,-1,0],tx:0,ty:-e.z,tz:0}:e.axis==="y"?{xAxis:[0,0,1],yAxis:[0,1,0],normal:[-1,0,0],tx:-e.z,ty:0,tz:0}:{xAxis:[1,0,0],yAxis:[0,1,0],normal:[0,0,1],tx:0,ty:0,tz:e.z}}function fl(e){let n=e.left,t=e.top,o=e.left+e.width,r=e.top+e.height;return[n,t,o,t,o,r,n,r]}function gl(e){return new Map([[0,e.bleed.top],[1,e.bleed.right],[2,e.bleed.bottom],[3,e.bleed.left]])}function hl(e,n){let t=e.split(",").map(Number);if(t.length!==16||t.some(r=>!Number.isFinite(r)))return null;let o=js/n;for(let r=0;r<8;r+=1)t[r]*=o;return`matrix3d(${t.map(r=>Number(r.toFixed(6))).join(",")})`}function wr(e,n){let t=e.left-e.bleed.left,o=e.top-e.bleed.top,r=e.width+e.bleed.left+e.bleed.right,i=e.height+e.bleed.top+e.bleed.bottom,l=e.z,c=r/n,a=i/n;return`matrix3d(${(e.axis==="x"?[c,0,0,0,0,0,a,0,0,-1,0,0,t,-l,o,1]:e.axis==="y"?[0,0,c,0,0,a,0,0,-1,0,0,0,-l,o,t,1]:[c,0,0,0,0,a,0,0,0,0,1,0,t,o,l,1]).map(f=>Number(f.toFixed(6))).join(",")})`}function yl(e,n){let{xAxis:t,yAxis:o,normal:r,tx:i,ty:l,tz:c}=pl(e),a=Us(fl(e),t,o,r,i,l,c,el,gl(e));return a?hl(a,n)??wr(e,n):wr(e,n)}function bl(e){let n=e.defaultView?.matchMedia;return n?n("(pointer: coarse)").matches||n("(hover: none)").matches:!1}function vl(e){return bl(e)?Ks:_r}function xl(e){return e.axis==="x"?[e.left+e.width/2,-e.z,e.top+e.height/2]:e.axis==="y"?[-e.z,e.top+e.height/2,e.left+e.width/2]:[e.left+e.width/2,e.top+e.height/2,e.z]}function Pl(e,n){let t=xl(e),o=n.meshRotation;o&&(t=Cr(t,o[0]??0,o[1]??0,o[2]??0));let[r,i]=Cr(t,n.rotX,0,n.rotY);return{x:r,y:i}}function Sl(e,n,t){let o=e.filter(g=>n.has(g.face)).map(g=>({item:g,...Pl(g,t)}));if(o.length===0)return[];let r=1/0,i=-1/0,l=1/0,c=-1/0;for(let g of o)r=Math.min(r,g.x),i=Math.max(i,g.x),l=Math.min(l,g.y),c=Math.max(c,g.y);let a=4,m=Math.max(1e-6,i-r),f=Math.max(1e-6,c-l),h=new Map;for(let g of o){let x=Math.min(a-1,Math.max(0,Math.floor((g.x-r)/m*a))),y=Math.min(a-1,Math.max(0,Math.floor((g.y-l)/f*a))),P=`${x}:${y}`,v=h.get(P);v||(v={tx:x,ty:y,sourceIndex:g.item.sourceIndex,items:[]},h.set(P,v)),v.items.push(g.item),v.sourceIndex=Math.min(v.sourceIndex,g.item.sourceIndex)}return Array.from(h.values()).sort((g,x)=>g.ty-x.ty||g.tx-x.tx||g.sourceIndex-x.sourceIndex).flatMap(g=>g.items)}function kr(e){let{doc:n,wrapper:t,polygons:o,directionalLight:r,ambientLight:i}=e,l=ml(o);if(l.length===0)return null;let c=new Set(l.map(u=>u.face));t.classList.add("polycss-voxel-mesh");let a=vl(n);a!==_r&&t.style.setProperty("--polycss-voxel-primitive",`${a}px`);let m=new Map,f=(u,p)=>{let C=`${u}|${p}`,A=m.get(C);if(A)return A;let w=dl(Rr[u],p,r,i);return m.set(C,w),w},h=new Map,g=new Map,x=new Map,y=new Map;for(let u of l){let p=y.get(u.face);p||(p=[],y.set(u.face,p)),p.push(u)}let P="",v=0,E=new Set,H=u=>{let p=h.get(u.sourceIndex);return p||(p=n.createElement("b"),h.set(u.sourceIndex,p),nl(p,f(u.face,u.baseColor),yl(u,a))),p},k=u=>{let p=g.get(u);return p||(p=n.createElement("span"),p.className=`polycss-voxel-face polycss-voxel-face-${u}`,p.dataset.polycssVoxelFace=u,p.__polycssVoxelFaceHost=!0,g.set(u,p)),p},N=()=>{for(let u of Array.from(t.childNodes))if(!u.__polycssVoxelFaceHost)return u;return null},R=(u,p)=>{let C=p.map(M=>M.sourceIndex).join(",");if(x.get(u)===C)return;let A=k(u),w=n.createDocumentFragment();for(let M of p)w.appendChild(H(M));A.replaceChildren(w),x.set(u,C)},K=()=>{for(let u of Mo)c.has(u)&&R(u,y.get(u)??[])},z=u=>new Set(u.split("|").filter(Boolean)),O=u=>{let p=z(u);return Mo.filter(C=>p.has(C)&&c.has(C))},$=u=>{let p=0;for(let C of u)p+=y.get(C)?.length??0;return p},U=u=>{let p=new Set,C=[],A=new Map;for(let w of u){p.has(w.face)||(p.add(w.face),C.push(w.face));let M=A.get(w.face);M||(M=[],A.set(w.face,M)),M.push(w)}return{orderedFaces:C,itemsByFace:A}},ie=(u,p)=>{let C=new Set(u);for(let A of E){if(C.has(A))continue;let w=g.get(A);w?.parentNode===t&&t.removeChild(w)}if(p){let A=n.createDocumentFragment();for(let w of u)A.appendChild(k(w));t.insertBefore(A,N()),E=C;return}for(let A=0;A<u.length;A+=1){let w=u[A],M=k(w);if(M.parentNode===t)continue;let se=null;for(let he=A+1;he<u.length;he+=1){let _=g.get(u[he]);if(_?.parentNode===t){se=_;break}}t.insertBefore(M,se??N())}E=C},xe=(u,p,C)=>{if(!C){let he=O(u);ie(he,!1),v=$(he);return}let A=new Set(u.split("|").filter(Boolean)),w=Sl(l,A,p),{orderedFaces:M,itemsByFace:se}=U(w);for(let he of M)R(he,se.get(he)??[]);ie(M,!0),v=w.length};return K(),{get brushCount(){return v},render(u){P=Er(u),xe(P,u,!0)},syncCamera(u){let p=Er(u);p!==P&&(P=p,xe(p,u,!1))},dispose(){for(let u of g.values())u.remove();t.classList.remove("polycss-voxel-mesh"),t.style.removeProperty("--polycss-voxel-primitive"),h.clear(),g.clear(),x.clear(),v=0,E=new Set,P=""}}}var Or="polycss-styles";function Fr(e){let n=e??(typeof document<"u"?document:void 0);if(!n||n.getElementById(Or))return;let t=n.createElement("style");t.id=Or,t.textContent=Cl,n.head.appendChild(t)}var Cl=`
1
+ import{CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as mi,VOXEL_CAMERA_CULL_NORMAL_LIMIT as hl,cameraCullNormalKey as gl,cameraCullVisibleSignature as yl,computeSceneBbox as bl,computeLightVisibility as vl,findOverlappingPolygonDuplicates as ci,inverseRotateVec3 as Lo,isAxisAlignedSurfaceNormal as xl,isVoxelCameraCullableNormalGroups as Pl,normalFacesCamera as Sl,optimizeMeshPolygons as Cl,parseHexColor as El,polygonCssSurfaceNormal as di}from"@layoutit/polycss-core";import{packTextureAtlasPlansWithScaleCore as Xi}from"@layoutit/polycss-core";function Zi(e){if(!e)return!1;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return t?t("(pointer: coarse)").matches||t("(hover: none)").matches:!1}function Ot(e,n,t){return Xi(e,n,Zi(t))}import{buildTextureEdgeRepairSets as Js,buildSeamBleedPolygonEdges as ea,buildSeamBleedPolygonSet as ta}from"@layoutit/polycss-core";import{TEXTURE_TRIANGLE_BLEED as Qi,TEXTURE_EDGE_REPAIR_ALPHA_MIN as qi,TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN as Ki,TEXTURE_EDGE_REPAIR_RADIUS as No}from"@layoutit/polycss-core";import{expandClipPoints as Ji}from"@layoutit/polycss-core";import{BASIS_EPS as es}from"@layoutit/polycss-core";var mt=new Map;function ts(e){let n=mt.get(e);return n||(n=new Promise((t,o)=>{let r=new Image;r.decoding="async",r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=()=>o(new Error(`texture load failed: ${e}`)),r.src=e}),mt.set(e,n),n.then(()=>{mt.get(e)===n&&mt.delete(e)},()=>{mt.get(e)===n&&mt.delete(e)})),n}function Re(e,n,t=1,o=0,r=0,i=1,s=0,c=0){e.setTransform(t*n,o*n,r*n,i*n,s*n,c*n)}function Jn(e){let n=e/255;return n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function eo(e){let n=e<=.0031308?e*12.92:1.055*Math.pow(e,.4166666666666667)-.055;return Math.max(0,Math.min(255,Math.round(n*255)))}function ns(e,n,t,o,r,i,s){let c=Math.round(n*s),l=Math.round(t*s),p=Math.max(1,Math.round(o*s)),g=Math.max(1,Math.round(r*s)),x=e.getImageData(c,l,p,g),f=x.data,b=i.r,y=i.g,P=i.b;for(let v=0;v<f.length;v+=4)f[v+3]!==0&&(f[v]=eo(Jn(f[v])*b),f[v+1]=eo(Jn(f[v+1])*y),f[v+2]=eo(Jn(f[v+2])*P));e.putImageData(x,c,l)}function os(e,n,t,o,r,i,s){let c=n.naturalWidth||n.width||1,l=n.naturalHeight||n.height||1,p=Math.max(r/c,i/l),g=c*p,x=l*p;Re(e,s),e.drawImage(n,t+(r-g)/2,o+(i-x)/2,g,x)}function ft(e,n){return Math.max(0,Math.min(n,e))}function Go(e,n,t,o,r,i,s,c){let l=n.naturalWidth||n.width||1,p=n.naturalHeight||n.height||1,g=ft(Math.min(t.minU,t.maxU)*l,l),x=ft(Math.max(t.minU,t.maxU)*l,l),f=ft(Math.min(t.minV,t.maxV)*p,p),b=ft(Math.max(t.minV,t.maxV)*p,p),y=Math.floor(g),P=Math.floor(f),v=Math.ceil(x)-y,C=Math.ceil(b)-P;v<1&&(y=Math.floor(ft((t.minU+t.maxU)/2*l,l-1)),v=1),C<1&&(P=Math.floor(ft((t.minV+t.maxV)/2*p,p-1)),C=1),y=Math.max(0,Math.min(l-1,y)),P=Math.max(0,Math.min(p-1,P)),v=Math.max(1,Math.min(l-y,v)),C=Math.max(1,Math.min(p-P,C)),Re(e,c),e.drawImage(n,y,P,v,C,o,r,i,s)}function Yo(e){return e==="repeat"||e==="mirrored-repeat"}function $o(e,n){return Yo(e)?Math.floor(n):0}function Uo(e,n){return Yo(e)?Math.ceil(n)-1:0}function jo(e,n){return e==="mirrored-repeat"&&Math.abs(n%2)===1}function Wo(e,n,t,o,r,i,s){let c=r?$o(i,r.minU):0,l=r?Uo(i,r.maxU):0,p=r?$o(s,r.minV):0,g=r?Uo(s,r.maxV):0;for(let x=c;x<=l;x++)for(let f=p;f<=g;f++){let b=jo(i,x),y=jo(s,f);if(!b&&!y){e.drawImage(n,x*t,f*o);continue}e.save(),e.translate((b?x+1:x)*t,(y?f+1:f)*o),e.scale(b?-1:1,y?-1:1),e.drawImage(n,0,0),e.restore()}}function to(e,n,t,o){for(let r=0;r<o.length;r+=2){let i=n+o[r],s=t+o[r+1];r===0?e.moveTo(i,s):e.lineTo(i,s)}e.closePath()}function qt(e,n,t,o,r,i){for(let s=0;s<o.length;s+=2){let c=n+o[s]+r,l=t+o[s+1]+i;s===0?e.moveTo(c,l):e.lineTo(c,l)}e.closePath()}function rs(e,n,t,o){Re(e,o),e.beginPath(),to(e,n.x,n.y,n.screenPts),e.clip(),Re(e,o),e.fillStyle=t==="dynamic"?n.polygon.color??"#cccccc":n.shadedColor,e.fillRect(n.x,n.y,n.canvasW,n.canvasH)}function Kt(e,n,t,o,r){n.polygon.textureAlphaMode==="opaque"&&(Re(e,t),e.fillStyle=n.polygon.color??"#cccccc",e.fillRect(n.x+o,n.y+r,n.canvasW,n.canvasH))}function is(e,n,t,o,r=0,i=0){if(n.textureTriangles?.length){let s=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1;for(let l of n.textureTriangles){let p=Ji(l.screenPts,Qi*(n.bleedRatio??1));e.save(),Re(e,o),e.beginPath(),qt(e,n.x,n.y,p,r,i),e.clip(),Kt(e,n,o,r,i),l.uvAffine?(Re(e,o,l.uvAffine.a/s,l.uvAffine.c/s,l.uvAffine.b/c,l.uvAffine.d/c,n.x+l.uvAffine.e+r,n.y+l.uvAffine.f+i),Wo(e,t,s,c,l.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t)):l.uvSampleRect&&Go(e,t,l.uvSampleRect,n.x+r,n.y+i,n.canvasW,n.canvasH,o),e.restore()}}else if(n.uvAffine){let s=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1,l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),Re(e,o),e.beginPath(),qt(e,n.x,n.y,n.screenPts,r,i),e.clip(),Kt(e,n,o,r,i)),Re(e,o,n.uvAffine.a/s,n.uvAffine.c/s,n.uvAffine.b/c,n.uvAffine.d/c,n.x+n.uvAffine.e+r,n.y+n.uvAffine.f+i),Wo(e,t,s,c,n.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t),l&&e.restore()}else if(n.uvSampleRect){let s=n.polygon.textureAlphaMode==="opaque";s&&(e.save(),Re(e,o),e.beginPath(),qt(e,n.x,n.y,n.screenPts,r,i),e.clip(),Kt(e,n,o,r,i)),Go(e,t,n.uvSampleRect,n.x+r,n.y+i,n.canvasW,n.canvasH,o),s&&e.restore()}else{let s=n.polygon.textureAlphaMode==="opaque";s&&(e.save(),Re(e,o),e.beginPath(),qt(e,n.x,n.y,n.screenPts,r,i),e.clip(),Kt(e,n,o,r,i)),os(e,t,n.x+r,n.y+i,n.canvasW,n.canvasH,o),s&&e.restore()}}function ss(e,n,t,o,r,i){let s=r-t,c=i-o,l=s*s+c*c;if(l<=es)return Math.hypot(e-t,n-o);let p=Math.max(0,Math.min(1,((e-t)*s+(n-o)*c)/l));return Math.hypot(e-(t+s*p),n-(o+c*p))}function as(e,n,t,o){let r=1/0,i=t.length/2;for(let s of o){if(s<0||s>=i)continue;let c=s*2,l=(s+1)%i*2;r=Math.min(r,ss(e,n,t[c],t[c+1],t[l],t[l+1]))}return r}function ls(e,n,t,o,r,i){let s=Math.max(0,o-i),c=Math.min(n-1,o+i),l=Math.max(0,r-i),p=Math.min(t-1,r+i),g=null,x=1/0;for(let f=l;f<=p;f++)for(let b=s;b<=c;b++){if(b===o&&f===r)continue;let y=b-o,P=f-r,v=y*y+P*P;if(v>i*i||v>=x)continue;let C=(f*n+b)*4;e[C+3]<Ki||(g=C,x=v)}return g}function cs(e,n,t){if(!n.textureEdgeRepair||!n.texture||!n.textureEdgeRepairEdges||n.textureEdgeRepairEdges.size===0)return;let o=e.canvas;if(!o)return;let r=Math.max(0,Math.floor(n.x*t)),i=Math.max(0,Math.floor(n.y*t)),s=Math.max(1,Math.min(o.width-r,Math.ceil(n.canvasW*t))),c=Math.max(1,Math.min(o.height-i,Math.ceil(n.canvasH*t)));if(s<=0||c<=0)return;let l;try{l=e.getImageData(r,i,s,c)}catch{return}let p=l.data,g=new Uint8ClampedArray(p),x=Math.max(No,No/t),f=Math.max(2,Math.ceil(x*t)+1),b=!1;for(let y=0;y<c;y++)for(let P=0;P<s;P++){let v=(y*s+P)*4,C=p[v+3];if(C<qi||C===255)continue;let F=(r+P+.5)/t-n.x,k=(i+y+.5)/t-n.y;if(as(F,k,n.screenPts,n.textureEdgeRepairEdges)>x)continue;let z=ls(g,s,c,P,y,f);z!==null&&(p[v]=g[z],p[v+1]=g[z+1],p[v+2]=g[z+2],p[v+3]=255,b=!0)}b&&e.putImageData(l,r,i)}function ds(e){if(typeof e.toBlob=="function")return new Promise(n=>{e.toBlob(t=>{n(t?URL.createObjectURL(t):null)},"image/png")});try{return Promise.resolve(e.toDataURL("image/png"))}catch{return Promise.resolve(null)}}async function us(e,n,t,o){let r=t.createElement("canvas");r.width=Math.max(1,Math.ceil(e.width*o)),r.height=Math.max(1,Math.ceil(e.height*o));let i=e.entries.some(g=>g.textureEdgeRepair&&g.texture&&g.textureEdgeRepairEdges&&g.textureEdgeRepairEdges.size>0),s=r.getContext("2d",i?{willReadFrequently:!0}:void 0);if(!s)return{width:e.width,height:e.height,url:null};let c=Array.from(new Set(e.entries.flatMap(g=>g.texture?[g.texture]:[]))),l=new Map;await Promise.all(c.map(async g=>{l.set(g,await ts(g))}));for(let g of e.entries){let x=g.texture?l.get(g.texture):null;if(!g.texture){s.save(),rs(s,g,n,o),s.restore();continue}x&&(s.save(),Re(s,o),s.beginPath(),to(s,g.x,g.y,g.screenPts),s.clip(),is(s,g,x,o),s.restore()),g.texture&&n==="baked"&&(s.save(),Re(s,o),s.beginPath(),to(s,g.x,g.y,g.screenPts),s.clip(),ns(s,g.x,g.y,g.canvasW,g.canvasH,g.textureTint,o),s.restore()),cs(s,g,o)}let p=await ds(r);return r.width=1,r.height=1,{width:e.width,height:e.height,url:p}}async function Ht(e,n,t,o,r){let i=[];for(let s of e){if(r())break;i.push(await us(s,n,t,o))}return i}import{isFullRectSolid as We,isSolidTrianglePlan as et,isProjectiveQuadPlan as Ye,fullRectBounds as bd,safariCssProjectiveUnsupported as Xo,incrementCount as vd,dominantCountKey as xd,filterAtlasPlans as Pd,getSolidPaintDefaultsForPlansCore as ms}from"@layoutit/polycss-core";import{parseHex as fs,rgbKey as hs}from"@layoutit/polycss-core";import{computeTextureAtlasPlan as Td,buildBasisHints as Ad}from"@layoutit/polycss-core";import{resolveProjectiveQuadGuards as ps}from"@layoutit/polycss-core";function ht(e,n){let o=e?.defaultView?.__polycssProjectiveQuadGuards,r=n&&o?{...n,...o}:o??n;return ps(r)}function It(e){if(!!!(e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0))?.supports?.("border-shape","polygon(0 0, 100% 0, 0 100%) circle(0)"))return!1;let r=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return r?r("(pointer: fine)").matches&&r("(hover: hover)").matches:!0}function Zo(e){if(Qo(e))return!0;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Xo(t):!0}function Ft(e){let n=e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0);return!!n?.supports?.("corner-top-left-shape","bevel")&&!!n.supports("corner-top-right-shape","bevel")&&!!n.supports("corner-bottom-right-shape","bevel")&&!!n.supports("corner-bottom-left-shape","bevel")}function Qo(e){let n=e.defaultView?.CSS??(typeof CSS<"u"?CSS:void 0);return!!n?.supports?.("corner-top-left-shape","bevel")&&!!n.supports("corner-top-right-shape","bevel")}function gs(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return/\bFirefox\//.test(t)}function Xe(e,n){return n?.disable?.includes("u")?null:Qo(e)?"corner-bevel":Zo(e)?gs(e)?"border-large":"border":null}function Vt(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Xo(t):!0}function Jt(e,n,t,o,r){let i=new Set(o?.disable??[]);return ms(e,n,i,{solidTriangleSupported:Zo(t),projectiveQuadSupported:Vt(t),cornerShapeSupported:Ft(t),borderShapeSupported:It(t)},fs,hs,r)}import{ASYNC_RENDER_BUDGET_MS as Gs,DEFAULT_SEAM_BLEED as gr,DEFAULT_TILE as $s,PROJECTIVE_QUAD_DENOM_EPS as Us,PROJECTIVE_QUAD_MAX_WEIGHT_RATIO as js,PROJECTIVE_QUAD_BLEED as hr,resolveBleedRatio as bo}from"@layoutit/polycss-core";import{buildBasisHints as vo,buildSeamBleedPolygonEdges as Ws,computeTextureAtlasPlan as $t}from"@layoutit/polycss-core";import{cornerShapeGeometryForPlan as Gt}from"@layoutit/polycss-core";import{formatCssLength as en,formatMatrix3dValues as bs,formatSolidQuadMatrix as vs}from"@layoutit/polycss-core";import{shadePolygon as xs}from"@layoutit/polycss-core";import{parseHex as qo,rgbKey as Ko}from"@layoutit/polycss-core";function xe(e,n,t){let o=e.getAttribute("style")??"",r=`${n}:${t}`,i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`(^|;)\\s*${i}\\s*:[^;]*`,"i"),c=s.test(o)?o.replace(s,(l,p)=>`${p}${r}`):`${o}${o.trim()&&!o.trim().endsWith(";")?";":""}${r}`;c!==o&&e.setAttribute("style",c)}function tt(e,n){let t=e.getAttribute("style")??"";if(!t||!t.toLowerCase().includes(n.toLowerCase()))return;let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(`^\\s*${o}\\s*:`,"i"),i=t.split(";").map(s=>s.trim()).filter(s=>s&&!r.test(s)).join(";");i?e.setAttribute("style",i):e.removeAttribute("style")}function Bt(e,n,t,o=!1){if(n==="dynamic"){let r=qo(e.polygon.color??"#cccccc"),i=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return Ko(r)!==t?.dynamicColorKey&&(i+=`;--psr:${(r.r/255).toFixed(4)};--psg:${(r.g/255).toFixed(4)};--psb:${(r.b/255).toFixed(4)}`),i}return e.shadedColor?`;color:${e.shadedColor}`:""}function ys(e,n){xe(e,"--pnx",n.normal[0].toFixed(4)),xe(e,"--pny",n.normal[1].toFixed(4)),xe(e,"--pnz",n.normal[2].toFixed(4))}function gt(e,n,t,o){if(t==="dynamic"){tt(e,"color"),tt(e,"background"),ys(e,n);let r=qo(n.polygon.color??"#cccccc");Ko(r)===o?.dynamicColorKey?(tt(e,"--psr"),tt(e,"--psg"),tt(e,"--psb")):(xe(e,"--psr",(r.r/255).toFixed(4)),xe(e,"--psg",(r.g/255).toFixed(4)),xe(e,"--psb",(r.b/255).toFixed(4)))}else n.shadedColor!==o?.paintColor?(tt(e,"background"),xe(e,"color",n.shadedColor)):(tt(e,"background"),tt(e,"color"))}import{formatBorderShapeElementStyle as Jo,formatCornerShapeElementStyle as er}from"@layoutit/polycss-core";import{atlasCanonicalSizeForEntry as nt}from"@layoutit/polycss-core";import{computeProjectiveQuadMatrix as Ps,stableBasisFromPlan as Ss}from"@layoutit/polycss-core";import{DEFAULT_LIGHT_DIR as Cs,DEFAULT_LIGHT_COLOR as Es,DEFAULT_LIGHT_INTENSITY as Ts,DEFAULT_AMBIENT_COLOR as As,DEFAULT_AMBIENT_INTENSITY as Ms}from"@layoutit/polycss-core";var tr="polycss-corner-shape-solid",no=new WeakMap,oo=new WeakMap;function ye(e,n,t){let o=no.get(e),r=oo.get(e),i=typeof t=="number";if(!n.data&&!i&&(!o||o.length===0)){e.__polycssHasDataAttrs=!1;return}let s=new Map;if(n.data)for(let[l,p]of Object.entries(n.data))s.set(l,String(p));if(i&&s.set("poly-index",String(t)),o)for(let l of o)s.has(l)||e.removeAttribute(`data-${l}`);for(let[l,p]of s)r?.get(l)!==p&&e.setAttribute(`data-${l}`,p);let c=Array.from(s.keys());c.length>0?no.set(e,c):no.delete(e),s.size>0?oo.set(e,s):oo.delete(e),e.__polycssHasDataAttrs=c.length>0}function yt(e){return e.__polycssHasDataAttrs===!0}function ro(e,n,t,o,r=t==="dynamic"){if(!n.url)return;let i=`url(${n.url})`,s=o.canvasW||1,c=o.canvasH||1,l=nt(o),p=`${en(-o.x/s*l)} ${en(-o.y/c*l)}`,g=`${en(n.width/s*l)} ${en(n.height/c*l)}`,x=`transform:matrix3d(${o.atlasMatrix});--polycss-atlas-size:${l}px`,f=`${x};--polycss-atlas-position:${p};--polycss-atlas-image-size:${g}`;if(t==="dynamic"){let b=r?`;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`:"";e.setAttribute("style",f+`;--polycss-atlas-url:${i}`+b)}else e.setAttribute("style",x+`;background-image:${i};background-position:${p};background-size:${g};background-repeat:no-repeat;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`)}function nr(e,n,t,o){if(n.texture){if(!t.texture||n.texture!==t.texture)return!1}else if(t.texture)return!1;let r=or(n,t);return r?(e.style.visibility="",xe(e,"transform",`matrix3d(${r.matrix})`),o==="dynamic"&&(xe(e,"--pnx",r.normal[0].toFixed(4)),xe(e,"--pny",r.normal[1].toFixed(4)),xe(e,"--pnz",r.normal[2].toFixed(4))),ye(e,t,n.index),!0):(e.style.visibility="hidden",ye(e,t,n.index),!0)}function io(e,n,t,o,r){if(o!=="baked")return{...e,polygon:n,normal:t};let i=r.directionalLight,s=r.ambientLight,c=i?.direction??Cs,l=i?.color??Es,p=Math.max(0,i?.intensity??Ts),g=s?.color??As,x=Math.max(0,s?.intensity??Ms),f=Math.hypot(c[0],c[1],c[2])||1,b=c[0]/f,y=c[1]/f,P=c[2]/f,C=r.lightOccludedPolyIndices?.has(e.index)??!1?0:p*Math.max(0,t[0]*b+t[1]*y+t[2]*P);return{...e,polygon:n,normal:t,shadedColor:xs(n.color??"#cccccc",C,l,g,x)}}function or(e,n){let t=rr(e,n);if(!t)return null;let{normal:o,xAxis:r,yAxis:i,tx:s,ty:c,tz:l}=t;return{normal:o,matrix:bs([r[0]*e.canvasW/nt(e),r[1]*e.canvasW/nt(e),r[2]*e.canvasW/nt(e),0,i[0]*e.canvasH/nt(e),i[1]*e.canvasH/nt(e),i[2]*e.canvasH/nt(e),0,o[0],o[1],o[2],0,s,c,l,1])}}var rr=Ss;function ws(e,n,t){if(e.screenPts.length!==8||n.vertices.length!==4)return null;let o=rr(e,n);if(!o)return null;let r=Ps(e.screenPts,o.xAxis,o.yAxis,o.normal,o.tx,o.ty,o.tz,t);return r?{matrix:r,normal:o.normal}:null}function so(e,n,t,o,r=!1){let i=t.createElement("b");return i.setAttribute("style",`transform:matrix3d(${vs(e)})`+Bt(e,n,o,r)),ye(i,e.polygon,e.index),i}function ao(e,n,t,o,r=!1){let i=t.createElement("i");return i.setAttribute("style",Jo(e)+Bt(e,n,o,r)),ye(i,e.polygon,e.index),i}function lo(e,n,t,o,r,i=!1){let s=o.createElement("u");return s.className=tr,s.setAttribute("style",er(e,n)+Bt(e,t,r,i)),ye(s,e.polygon,e.index),s}function co(e,n,t,o,r=!1){let i=t.createElement("b");return i.setAttribute("style",`transform:matrix3d(${e.projectiveMatrix})`+Bt(e,n,o,r)),ye(i,e.polygon,e.index),i}function ir(e,n,t,o,r,i,s){let c=n.projectiveMatrix?ws(n,t,i):or(n,t);if(!c)return!1;let l=io(n,t,c.normal,o,r);return e.style.visibility="",e.style.transform=`matrix3d(${c.matrix})`,gt(e,l,o,s),ye(e,l.polygon,l.index),!0}function sr(e,n,t,o){e.style.visibility="",e.setAttribute("style",Jo(n)),gt(e,n,t,o),ye(e,n.polygon,n.index)}function ar(e,n,t,o,r){e.style.visibility="",e.className=tr,e.setAttribute("style",er(n,t)),gt(e,n,o,r),xe(e,"background","currentColor"),ye(e,n.polygon,n.index)}function uo(e,n,t,o=!1){let r=t.createElement("s"),i=nt(e),s=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return r.setAttribute("style",`transform:matrix3d(${e.atlasMatrix});--polycss-atlas-size:${i}px;opacity:0`+s),ye(r,e.polygon,e.index),r}import{computeSolidTriangleColorPlan as Ys}from"@layoutit/polycss-core";import{computeSolidTrianglePlanFromCssPoints as Ls,computeSolidTrianglePlan as _s}from"@layoutit/polycss-core";function at(e,n,t,o={}){let r=o.primitive!=null?void 0:(()=>{let i=t.doc??(typeof document<"u"?document:null);return i?Xe(i,t.strategies)??"border":"border"})();return _s(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??r})}function po(e,n,t,o,r,i,s,c,l,p,g,x,f){let b=o.primitive!=null?void 0:(()=>{let y=t.doc??(typeof document<"u"?document:null);return y?Xe(y,t.strategies)??"border":"border"})();return Ls(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??b},r,i,s,c,l,p,g,x,f)}import{buildSeamBleedPolygonEdges as Rs,DEFAULT_SEAM_BLEED as ks,DEFAULT_TILE as $d,resolveBleedRatio as Ds}from"@layoutit/polycss-core";import{rgbEqual as Os,stepRgbToward as Hs,rgbToCss as Is,colorErrorScore as Fs}from"@layoutit/polycss-core";import{computeSolidTriangleColorPlan as Vs}from"@layoutit/polycss-core";import{stableTriangleMatrixDecimals as lr}from"@layoutit/polycss-core";var Bs="0 48px 96px 48px";function cr(e,n){return Rs(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function dr(e,n,t){let o=Ds(t.seamBleed),r=ks*o,i={...t,bleedRatio:o};return n&&r>0?{...i,seamBleed:n.has(e)?r:void 0,seamEdges:n.get(e)}:i}function mo(e){return{updatesDisabled:e.stableTriangleColorFreezeFrames===0,freezeFrames:Math.max(1,Math.floor(e.stableTriangleColorFreezeFrames??1)),colorFrame:Math.max(0,Math.floor(e.stableTriangleColorFrame??0)),maxStep:Math.max(0,Math.floor(e.stableTriangleColorMaxStep??0))}}function ur(e,n){return!n.updatesDisabled&&(n.freezeFrames<=1||(n.colorFrame+e)%n.freezeFrames===0)}function bt(e,n,t,o,r,i){return t?i.updatesDisabled||o==="plan-only"||o==="transform-only"?!1:r==="adaptive"||e.__polycssSolidTriangleColor===void 0?!0:ur(n,i):!0}function fo(e,n){let t=e;t.__polycssSolidTrianglePrimitive!==n&&(n==="corner-bevel"?(e.style.width="",e.style.height="",e.style.backgroundColor="",e.style.borderWidth="",e.style.borderTopLeftRadius="",e.style.borderTopRightRadius="",e.style.removeProperty("corner-top-left-shape"),e.style.removeProperty("corner-top-right-shape")):(e.style.width="",e.style.height="",e.style.backgroundColor="",e.style.borderTopLeftRadius="",e.style.borderTopRightRadius="",e.style.removeProperty("corner-top-left-shape"),e.style.removeProperty("corner-top-right-shape"),e.style.borderWidth=n==="border-large"?Bs:""),t.__polycssSolidTrianglePrimitive=n)}function ho(e){let n=e;n.__polycssSolidTriangleHidden&&(e.style.visibility="",n.__polycssSolidTriangleHidden=!1)}function zt(e){let n=e;n.__polycssSolidTriangleHidden||(e.style.visibility="hidden",n.__polycssSolidTriangleHidden=!0)}function tn(e,n){e.setAttribute("style",n.styleText),fo(e,n.primitive);let t=e;t.__polycssSolidTriangleBasis=n.basis,t.__polycssSolidTriangleHidden=!1,n.colorComputed&&(t.__polycssSolidTriangleColor=n.bakedColor??"",t.__polycssSolidTriangleColorRgb=n.bakedRgb,t.__polycssSolidTriangleColorAlpha=n.bakedAlpha),t.__polycssSolidTriangleColorFrame=void 0,(n.polygon.data||yt(e))&&ye(e,n.polygon)}function pr(e,n,t,o){if(!n.colorComputed){(n.polygon.data||yt(e))&&ye(e,n.polygon);return}let r=e,i=n.bakedColor??"",s=n.bakedRgb,c=n.bakedAlpha??1,l=r.__polycssSolidTriangleColor,p=r.__polycssSolidTriangleColorRgb,g=r.__polycssSolidTriangleColorAlpha??1,x=o??ur(n.index,t);if(!t.updatesDisabled&&l!==i&&(l===void 0||x)){let f=i,b=s;if(t.maxStep>0&&p&&s&&g===c){let y=Hs(p,s,t.maxStep);b=y,f=Is(y,c)}(f!==l||!Os(b,p))&&(e.style.color=f),r.__polycssSolidTriangleColor=f,r.__polycssSolidTriangleColorRgb=b,r.__polycssSolidTriangleColorAlpha=c,r.__polycssSolidTriangleColorFrame=t.colorFrame}(n.polygon.data||yt(e))&&ye(e,n.polygon)}function nn(e,n,t,o){let r=e;fo(e,n.primitive),r.__polycssSolidTriangleBasis!==n.basis&&(r.__polycssSolidTriangleBasis=n.basis),ho(e),e.style.transform=n.transformText,(n.colorComputed||n.polygon.data||yt(e))&&pr(e,n,t,o)}function go(e,n,t,o){ho(e),pr(e,n,t,o)}function on(e,n){let t=e;fo(e,n.primitive),t.__polycssSolidTriangleBasis!==n.basis&&(t.__polycssSolidTriangleBasis=n.basis),ho(e),e.style.transform=n.transformText,(n.polygon.data||yt(e))&&ye(e,n.polygon)}function zs(e,n){let t=n.stableTriangleColorBudget;if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t<=1?Math.max(1,Math.ceil(e*t)):Math.max(1,Math.floor(t));let o=Math.max(1,Math.floor(n.stableTriangleColorFreezeFrames??1));return Math.max(1,Math.ceil(e/o))}function mr(e,n,t){if(t.stableTriangleColorPolicy!=="adaptive")return null;if(t.stableTriangleColorFreezeFrames===0)return new Set;let o=Math.max(0,Math.floor(t.stableTriangleColorFrame??0)),r=Math.max(1,Math.floor(t.stableTriangleColorFreezeFrames??1));if(r<=1&&!Number.isFinite(t.stableTriangleColorBudget))return null;let i=zs(e.length,t),s=Math.max(1,Math.floor(t.stableTriangleColorMaxAge??Math.max(2,r*2))),c=[];for(let l=0;l<e.length;l++){let p=e[l],g=n[l];if(p.kind!=="triangle"||!g)continue;let x=p.element,f=x.__polycssSolidTriangleColor,b=g.bakedColor??"";if(f===b)continue;let y=x.__polycssSolidTriangleColorFrame??0,P=Math.max(0,o-y),v=Fs(f,b);c.push({index:l,score:(P>=s?1e6:0)+v*1e4+P})}return c.length===0?new Set:(c.sort((l,p)=>p.score-l.score),new Set(c.slice(0,i).map(l=>l.index)))}function rn(e,n){let t=n.createElement("u");return tn(t,e),ye(t,e.polygon,e.index),t}function Ns(e,n,t){let o=t.createElement("u");return zt(o),ye(o,e,n),o}function fr(e,n,t,o,r,i){let s=t,c=s.stableTriangleDebug,l=o&&r==="color-only";if(s.stableTriangleColorPolicy==="adaptive"||e.length!==n.length)return!1;let p=lr(s.stableTriangleMatrixDecimals),g=t.doc??(typeof document<"u"?document:null),x=g?Xe(g,t.strategies)??"border":"border";for(let b=0;b<e.length;b++){let y=e[b];if(y.kind!=="triangle"||y.polygonIndex!==b||!n[b])return!1}let f=cr(n,t);for(let b=0;b<e.length;b++){let y=e[b].element,P=n[b];if(l){if(bt(y,b,o,c,s.stableTriangleColorPolicy,i)){let C=Vs(P,b,t);if(!C)continue;go(y,C,i)}continue}let v=at(P,b,dr(b,f,t),{basis:y.__polycssSolidTriangleBasis,matrixDecimals:p,primitive:x,includeColor:r!=="plan-only"&&r!=="transform-only"&&bt(y,b,o,c,s.stableTriangleColorPolicy,i)});if(!v){zt(y);continue}o&&r==="plan-only"||(o&&r==="transform-only"?on(y,v):o?nn(y,v,i):tn(y,v))}return!0}function Nt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=Xe(t,n.strategies);if(!o||e.some(c=>c.texture||c.vertices.length!==3))return null;let r=lr(n.stableTriangleMatrixDecimals),i=[],s=cr(e,n);for(let c=0;c<e.length;c+=1){let l=e[c],p=at(l,c,dr(c,s,n),{matrixDecimals:r,primitive:o}),g=p?rn(p,t):Ns(l,c,t);i.push({polygonIndex:c,element:g,kind:"triangle",dispose:()=>{}})}return{rendered:i,dispose(){}}}import{stableTriangleMatrixDecimals as yr}from"@layoutit/polycss-core";function br(){return new Promise(e=>setTimeout(e,0))}async function yo(e){return performance.now()-e<Gs?e:(await br(),performance.now())}function vr(e,n){let t=bo(n.seamBleed),o=gr*t,r={...n,bleedRatio:t};return e.seamBleedEdges?.size&&o>0?{...r,seamBleed:o,seamEdges:e.seamBleedEdges}:{...r,seamBleed:void 0,seamEdges:void 0}}function xr(e,n){return Ws(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function Pr(e,n,t){let o=bo(t.seamBleed),r=gr*o,i={...t,bleedRatio:o};return n&&r>0?{...i,seamBleed:n.has(e)?r:void 0,seamEdges:n.get(e)}:i}function vt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{};let o=vo(e,n),r=ht(t),i=e.map((s,c)=>$t(s,c,n,r,o[c]));return Jt(i,n.textureLighting??"baked",t,n.strategies)}function xt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=n.textureLighting??"baked",r=n,i=o==="dynamic"&&r.skipDynamicNormalVars===!0,s=new Set(n.strategies?.disable??[]),c=!s.has("b"),l=c&&Vt(t),p=Xe(t,n.strategies),g=p!==null,x=!s.has("i")&&Ft(t),f=!s.has("i")&&It(t),b=vo(e,n),y=ht(t),P=xr(e,n),v=e.map((u,d)=>$t(u,d,Pr(d,P,n),y,b[d]));if(typeof window<"u"){let u=window,d=v[1];u.__vanillaPlan1={matrix:d?.matrix,canvasW:d?.canvasW,canvasH:d?.canvasH,vertexCount:e[1]?.vertices.length}}let C=n.solidPaintDefaults??(r.computeSolidPaintDefaults?Jt(v,o,t,n.strategies):void 0),F=C?{...n,solidPaintDefaults:C}:n,k=v.map(u=>u&&g&&et(u)?at(u.polygon,u.index,vr(u,F),{primitive:p??void 0}):null),z=v.map(u=>u&&x&&!et(u)&&!(c&&We(u))&&!(l&&Ye(u))?Gt(u):null),O=v.map((u,d)=>u&&(u.texture||!(c&&We(u))&&!k[d]&&!(l&&Ye(u))&&!z[d]&&!f?u:null)),{packed:Z,atlasScale:q}=Ot(O,n.textureQuality,t),D=new Map,H=[],V=!1,G=[];for(let u=0;u<e.length;u++){let d=v[u],T=k[u],w=z[u];if(!d)continue;let R=Z.entries[u];if(R){let L=uo(R,o,t,i);D.set(u,L),H.push({polygonIndex:u,element:L,kind:"atlas",plan:R,dispose:()=>{}})}else if(!d.texture&&c&&We(d)){let L=so(d,o,t,C,i);H.push({polygonIndex:u,element:L,kind:"solid",plan:d,dispose:()=>{}})}else if(!d.texture&&T){let L=rn(T,t);H.push({polygonIndex:u,element:L,kind:"triangle",plan:d,dispose:()=>{}})}else if(!d.texture&&l&&Ye(d)){let L=co(d,o,t,C,i);H.push({polygonIndex:u,element:L,kind:"solid",plan:d,dispose:()=>{}})}else if(!d.texture&&w){let L=lo(d,w,o,t,C,i);H.push({polygonIndex:u,element:L,kind:"corner",plan:d,dispose:()=>{}})}else if(!d.texture&&f){let L=ao(d,o,t,C,i);H.push({polygonIndex:u,element:L,kind:"border",plan:d,dispose:()=>{}})}}H.sort((u,d)=>u.polygonIndex-d.polygonIndex);let A=Ht(Z.pages,o,t,q,()=>V).then(u=>{if(V){for(let d of u)d.url?.startsWith("blob:")&&URL.revokeObjectURL(d.url);return}G=u.flatMap(d=>d.url?.startsWith("blob:")?[d.url]:[]);for(let d=0;d<Z.pages.length;d++){let T=Z.pages[d],w=u[d];if(w)for(let R of T.entries){let L=D.get(R.index);!L||!w.url||ro(L,w,o,R,!0)}}}).catch(()=>{if(!V)for(let u of D.values())xe(u,"opacity","0.5"),xe(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:H,solidPaintDefaults:C??{},pagesReady:A,dispose(){V=!0;for(let u of G)URL.revokeObjectURL(u);G=[]}}}async function sn(e,n={},t=()=>!1){let o=n.doc??(typeof document<"u"?document:null);if(!o||t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let r=n.textureLighting??"baked",s=r==="dynamic"&&n.skipDynamicNormalVars===!0,c=new Set(n.strategies?.disable??[]),l=!c.has("b"),p=l&&Vt(o),g=Xe(o,n.strategies),x=g!==null,f=!c.has("i")&&Ft(o),b=!c.has("i")&&It(o);if(await br(),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let y=vo(e,n),P=ht(o),v=xr(e,n),C=performance.now(),F=new Array(e.length);for(let u=0;u<e.length;u++)if(F[u]=$t(e[u],u,Pr(u,v,n),P,y[u]),C=await yo(C),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let k=n.solidPaintDefaults??Jt(F,r,o,n.strategies),z=new Array(F.length),O=new Array(F.length),Z=new Array(F.length);for(let u=0;u<F.length;u++){let d=F[u],T=d&&x&&et(d)?at(d.polygon,d.index,vr(d,{...n,solidPaintDefaults:k}),{primitive:g??void 0}):null;z[u]=T;let w=d&&f&&!et(d)&&!(l&&We(d))&&!(p&&Ye(d))?Gt(d):null;if(O[u]=w,Z[u]=d&&(d.texture||!(l&&We(d))&&!T&&!(p&&Ye(d))&&!w&&!b?d:null),C=await yo(C),t())return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}let{packed:q,atlasScale:D}=Ot(Z,n.textureQuality,o),H=new Map,V=[],G=!1,A=[];for(let u=0;u<e.length;u++){let d=F[u],T=z[u],w=O[u];if(!d)continue;let R=q.entries[u];if(R){let L=uo(R,r,o,s);H.set(u,L),V.push({polygonIndex:u,element:L,kind:"atlas",plan:R,dispose:()=>{}})}else if(!d.texture&&l&&We(d)){let L=so(d,r,o,k,s);V.push({polygonIndex:u,element:L,kind:"solid",plan:d,dispose:()=>{}})}else if(!d.texture&&T){let L=rn(T,o);V.push({polygonIndex:u,element:L,kind:"triangle",plan:d,dispose:()=>{}})}else if(!d.texture&&p&&Ye(d)){let L=co(d,r,o,k,s);V.push({polygonIndex:u,element:L,kind:"solid",plan:d,dispose:()=>{}})}else if(!d.texture&&w){let L=lo(d,w,r,o,k,s);V.push({polygonIndex:u,element:L,kind:"corner",plan:d,dispose:()=>{}})}else if(!d.texture&&b){let L=ao(d,r,o,k,s);V.push({polygonIndex:u,element:L,kind:"border",plan:d,dispose:()=>{}})}if(C=await yo(C),t()){for(let L of V)L.dispose();return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}}V.sort((u,d)=>u.polygonIndex-d.polygonIndex);let h=Ht(q.pages,r,o,D,()=>G||t()).then(u=>{if(G||t()){for(let d of u)d.url?.startsWith("blob:")&&URL.revokeObjectURL(d.url);return}A=u.flatMap(d=>d.url?.startsWith("blob:")?[d.url]:[]);for(let d=0;d<q.pages.length;d++){let T=q.pages[d],w=u[d];if(w)for(let R of T.entries){let L=H.get(R.index);!L||!w.url||ro(L,w,r,R,!0)}}}).catch(()=>{if(!(G||t()))for(let u of H.values())xe(u,"opacity","0.5"),xe(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:V,solidPaintDefaults:k,pagesReady:h,dispose(){G=!0;for(let u of A)URL.revokeObjectURL(u);A=[]}}}function an(e,n,t,o={}){let r=o.textureLighting??"baked",i=o,s=i.optimizeStableTriangleStyle===!0&&r==="baked";if(!s||i.stableTriangleColorPolicy==="adaptive"||e.length!==t.polygonCount||n.length!==t.polygonCount||t.vertices.length<t.polygonCount*9)return!1;let c=i.stableTriangleDebug,l=i.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full");if(l==="color-only")return!1;let p=yr(i.stableTriangleMatrixDecimals),g=mo(i),x=o.tileSize??$s,f=o.layerElevation??x,b=o.doc??(typeof document<"u"?document:null),y=b?Xe(b,o.strategies)??"border":"border";for(let v=0;v<e.length;v++){let C=e[v],F=n[v];if(C.kind!=="triangle"||C.polygonIndex!==v||!F||F.vertices.length!==3||F.texture||F.material?.texture)return!1}let P=t.vertices;for(let v=0;v<e.length;v++){let C=e[v].element,F=n[v],k=v*9,z=P[k+1]*x,O=P[k]*x,Z=P[k+2]*f,q=P[k+4]*x,D=P[k+3]*x,H=P[k+5]*f,V=P[k+7]*x,G=P[k+6]*x,A=P[k+8]*f,h=po(F,v,o,{basis:C.__polycssSolidTriangleBasis,matrixDecimals:p,primitive:y,color:t.colors?.[v],includeColor:l!=="plan-only"&&l!=="transform-only"&&bt(C,v,s,c,i.stableTriangleColorPolicy,g)},z,O,Z,q,D,H,V,G,A);if(!h){zt(C);continue}l!=="plan-only"&&(l==="transform-only"?on(C,h):nn(C,h,g))}return!0}function ln(e,n,t={}){if(e.length!==n.length)return!1;let o=t,r=t.doc??(typeof document<"u"?document:null),i=t.textureLighting??"baked",s=new Set(t.strategies?.disable??[]),c=!s.has("b"),l=!!r&&c&&Vt(r),p=!!r&&!s.has("i")&&Ft(r),g=!!r&&!s.has("i")&&It(r),x=bo(o.seamBleed),f=r?ht(r,{bleed:hr*x}):{denomEps:Us,maxWeightRatio:js,bleed:hr*x,disableGuards:!1},b=o.optimizeStableTriangleStyle===!0&&i==="baked",y=o.stableTriangleDebug,P=o.stableTriangleUpdateMode??(y==="plan-only"||y==="transform-only"?y:"full"),v=b&&P==="color-only",C=mo(o),F=yr(o.stableTriangleMatrixDecimals),k=r?Xe(r,t.strategies)??"border":"border";if(fr(e,n,t,b,P,C))return!0;let z=[],O=[],Z=[];for(let D=0;D<e.length;D++){let H=e[D];if(H.polygonIndex!==D)return!1;let V=n[D];if(!V||v&&H.kind!=="triangle")return!1;if(H.kind==="atlas"){if(!H.plan||!nr(H.element,H.plan,V,i))return!1;continue}if(H.kind==="triangle"){let G=H.element;if(v){let h=o.stableTriangleColorPolicy==="adaptive"||bt(G,D,b,y,o.stableTriangleColorPolicy,C);O[D]=h?Ys(V,D,t):null;continue}let A=at(V,D,t,{basis:G.__polycssSolidTriangleBasis,matrixDecimals:F,primitive:k,includeColor:P!=="plan-only"&&P!=="transform-only"&&bt(G,D,b,y,o.stableTriangleColorPolicy,C)});if(!A){z[D]=null;continue}z[D]=A;continue}if(H.kind==="solid"){if(!H.plan||V.texture||V.vertices.length!==H.plan.polygon.vertices.length)return!1;Z[D]=H.plan;continue}if(H.kind==="border"){let G=$t(V,D,t,f);if(!G||G.texture||!g||c&&We(G)||l&&Ye(G)||p&&Gt(G))return!1;Z[D]=G;continue}if(H.kind==="corner"){let G=$t(V,D,t,f);if(!G||G.texture||!p||et(G)||c&&We(G)||l&&Ye(G)||!Gt(G))return!1;Z[D]=G;continue}return!1}let q=b&&P!=="plan-only"&&P!=="transform-only"?mr(e,v?O:z,o):null;for(let D=0;D<e.length;D++){let H=e[D];if(H.kind==="triangle"){if(v){let G=O[D];G&&go(H.element,G,C,q?.has(D));continue}let V=z[D];if(!V){zt(H.element);continue}if(b&&P==="plan-only")continue;b&&P==="transform-only"?on(H.element,V):b?nn(H.element,V,C,q?.has(D)):tn(H.element,V)}else if(H.kind==="solid"){let V=Z[D];if(!V||!ir(H.element,V,n[D],i,t,f,o.solidPaintDefaults))return!1}else if(H.kind==="border"){let V=Z[D];if(!V)return!1;sr(H.element,V,i,o.solidPaintDefaults)}else if(H.kind==="corner"){let V=Z[D],G=V?Gt(V):null;if(!V||!G)return!1;ar(H.element,V,G,i,o.solidPaintDefaults)}}return!0}import{computeTextureAtlasPlanPublic as na}from"@layoutit/polycss-core";import{formatMatrix3d as oa,formatCssLengthPx as ra,formatSolidQuadEntryMatrix as ia}from"@layoutit/polycss-core";import{formatBorderShapeEntryMatrix as sa,cssBorderShapeForPlan as aa}from"@layoutit/polycss-core";import{BASE_TILE as Pe,computeProjectiveQuadMatrix as la,normalFacesCamera as ca,parsePureColor as Mr,PROJECTIVE_QUAD_BLEED as da,resolveProjectiveQuadGuards as ua,rotateVec3 as pa,rotateVec3InWrapperCssFrame as ma,shadePolygon as fa,SOLID_QUAD_CANONICAL_SIZE as ha}from"@layoutit/polycss-core";var ga=[.4,-.7,.59],ya="#ffffff",ba=1,va="#ffffff",xa=.4,wr=1,Pa=8,Sa=da,Ke=1e-6,Ca=ua({bleed:0}),Lr={t:[0,0,1],b:[0,0,-1],fl:[0,1,0],br:[0,-1,0],fr:[1,0,0],bl:[-1,0,0]},So=["t","b","bl","br","fr","fl"],Ea=new Map([["0,0,1","t"],["0,0,-1","b"],["0,1,0","fl"],["0,-1,0","br"],["1,0,0","fr"],["-1,0,0","bl"]]);function Sr(e){let n=[];for(let t of So)ca(Lr[t],e)&&n.push(t);return n.join("|")}function Ta(e,n,t){let o=e.__polycssVoxelBrushState??(e.__polycssVoxelBrushState={});o.color!==n&&(e.style.color=n,o.color=n),o.transform!==t&&(e.style.transform=t,o.transform=t)}function Aa(e){let n=e.vertices;if(n.length<3)return null;let t=n[0],o=0,r=0,i=0;for(let c=1;c+1<n.length;c+=1){let l=n[c],p=n[c+1],g=l[1]-t[1],x=l[0]-t[0],f=l[2]-t[2],b=p[1]-t[1],y=p[0]-t[0],P=p[2]-t[2];o-=x*P-f*y,r-=f*b-g*P,i-=g*y-x*b}let s=Math.hypot(o,r,i);return s<=1e-9?null:[Math.round(o/s),Math.round(r/s),Math.round(i/s)]}function Ma(e){if(e.texture||e.material||e.uvs||e.textureTriangles||e.vertices.length!==4)return null;let n=Aa(e),t=n?Ea.get(n.join(",")):void 0;if(!t)return null;let o=1/0,r=1/0,i=1/0,s=-1/0,c=-1/0,l=-1/0;for(let x of e.vertices)o=Math.min(o,x[0]),r=Math.min(r,x[1]),i=Math.min(i,x[2]),s=Math.max(s,x[0]),c=Math.max(c,x[1]),l=Math.max(l,x[2]);let p=1e-6,g=Oa(e.color);return Math.abs(l-i)<=p?{axis:"z",face:t,left:r*Pe,top:o*Pe,width:Math.max(0,(c-r)*Pe),height:Math.max(0,(s-o)*Pe),z:i*Pe,baseColor:g,bleed:xo()}:Math.abs(s-o)<=p?{axis:"x",face:t,left:r*Pe,top:i*Pe,width:Math.max(0,(c-r)*Pe),height:Math.max(0,(l-i)*Pe),z:-o*Pe,baseColor:g,bleed:xo()}:Math.abs(c-r)<=p?{axis:"y",face:t,left:i*Pe,top:o*Pe,width:Math.max(0,(l-i)*Pe),height:Math.max(0,(s-o)*Pe),z:-r*Pe,baseColor:g,bleed:xo()}:null}function xo(){return{left:0,right:0,top:0,bottom:0}}function wa(e){let n=o=>String(Number(o.toFixed(6))),t=`${e.item.baseColor}|${e.variableAxis}`;for(let o=0;o<3;o+=1)o!==e.variableAxis&&(t+=`|${o}:${n(e.fixed[o])}`);return t}function Cr(e){return[e[1]*Pe,e[0]*Pe,e[2]*Pe]}function Er(e,n){return e.axis==="x"?[n[0],n[2]]:e.axis==="y"?[n[2],n[1]]:[n[0],n[1]]}function La(e,n,t){let o=e.left,r=e.left+e.width,i=e.top,s=e.top+e.height;if(Math.abs(n[0]-t[0])<=Ke){if(Math.abs(n[0]-o)<=Ke)return"left";if(Math.abs(n[0]-r)<=Ke)return"right"}if(Math.abs(n[1]-t[1])<=Ke){if(Math.abs(n[1]-i)<=Ke)return"top";if(Math.abs(n[1]-s)<=Ke)return"bottom"}return null}function _a(e,n){let t=null;for(let o=0;o<3;o+=1)if(!(Math.abs(e[o]-n[o])<=Ke)){if(t!==null)return null;t=o}return t}function Ra(e,n,t){let o=n.vertices,r=Cr(o[t]),i=Cr(o[(t+1)%o.length]),s=La(e,Er(e,r),Er(e,i));if(!s)return null;let c=_a(r,i);if(c===null)return null;let l=Math.min(r[c],i[c]),p=Math.max(r[c],i[c]);return p-l>Ke?{item:e,side:s,variableAxis:c,fixed:r,start:l,end:p}:null}function Tr(e){e.item.bleed[e.side]=Math.max(e.item.bleed[e.side],Sa)}function ka(e,n){let t=new Map;for(let o of n){let r=e[o.sourceIndex];if(r)for(let i=0;i<r.vertices.length;i+=1){let s=Ra(o,r,i);if(!s)continue;let c=wa(s),l=t.get(c);l?l.push(s):t.set(c,[s])}}for(let o of t.values()){if(o.length<2)continue;o.sort((i,s)=>i.start-s.start||i.end-s.end);let r=[];for(let i of o){r=r.filter(s=>s.end>i.start+Ke);for(let s of r)s.item.sourceIndex!==i.item.sourceIndex&&(Tr(s),Tr(i));r.push(i)}}}function Da(e){let n=Mr(e);return n?{r:n.rgb[0],g:n.rgb[1],b:n.rgb[2],alpha:n.alpha}:{r:255,g:255,b:255,alpha:1}}function Oa(e){if(!e)return"#cccccc";let n=Mr(e);if(!n)return e;let t={r:n.rgb[0],g:n.rgb[1],b:n.rgb[2],alpha:n.alpha};if(t.alpha<1){let o=Math.round(Math.max(0,t.alpha)*1e3)/1e3;return`rgba(${Po(t.r)}, ${Po(t.g)}, ${Po(t.b)}, ${o})`}return Ha(t)}function Ha({r:e,g:n,b:t}){let o=r=>Math.round(Math.max(0,Math.min(255,r))).toString(16).padStart(2,"0");return`#${o(e)}${o(n)}${o(t)}`}function Po(e){return Math.round(Math.max(0,Math.min(255,e)))}function Ia(e,n,t,o){let r=t?.direction??ga,i=Math.hypot(r[0],r[1],r[2])||1,s=r[0]/i,c=r[1]/i,l=r[2]/i,p=Math.max(0,t?.intensity??ba)*Math.max(0,e[0]*s+e[1]*c+e[2]*l),g=Math.max(0,o?.intensity??xa),x=t?.color??ya,f=o?.color??va,b=fa(n,p,x,f,g),y=Da(n);if(y.alpha>=1)return b;let P=parseInt(b.slice(1,3),16),v=parseInt(b.slice(3,5),16),C=parseInt(b.slice(5,7),16);return`rgba(${P}, ${v}, ${C}, ${y.alpha})`}function Fa(e){if(!e?.length)return[];let n=[];for(let t=0;t<e.length;t+=1){let o=e[t],r=Ma(o);if(!r||r.width<=0||r.height<=0)return[];n.push({...r,sourceIndex:t})}return ka(e,n),n}function Va(e){return e.axis==="x"?{xAxis:[1,0,0],yAxis:[0,0,1],normal:[0,-1,0],tx:0,ty:-e.z,tz:0}:e.axis==="y"?{xAxis:[0,0,1],yAxis:[0,1,0],normal:[-1,0,0],tx:-e.z,ty:0,tz:0}:{xAxis:[1,0,0],yAxis:[0,1,0],normal:[0,0,1],tx:0,ty:0,tz:e.z}}function Ba(e){let n=e.left,t=e.top,o=e.left+e.width,r=e.top+e.height;return[n,t,o,t,o,r,n,r]}function za(e){return new Map([[0,e.bleed.top],[1,e.bleed.right],[2,e.bleed.bottom],[3,e.bleed.left]])}function Na(e,n){let t=e.split(",").map(Number);if(t.length!==16||t.some(r=>!Number.isFinite(r)))return null;let o=ha/n;for(let r=0;r<8;r+=1)t[r]*=o;return`matrix3d(${t.map(r=>Number(r.toFixed(6))).join(",")})`}function Ar(e,n){let t=e.left-e.bleed.left,o=e.top-e.bleed.top,r=e.width+e.bleed.left+e.bleed.right,i=e.height+e.bleed.top+e.bleed.bottom,s=e.z,c=r/n,l=i/n;return`matrix3d(${(e.axis==="x"?[c,0,0,0,0,0,l,0,0,-1,0,0,t,-s,o,1]:e.axis==="y"?[0,0,c,0,0,l,0,0,-1,0,0,0,-s,o,t,1]:[c,0,0,0,0,l,0,0,0,0,1,0,t,o,s,1]).map(g=>Number(g.toFixed(6))).join(",")})`}function Ga(e,n){let{xAxis:t,yAxis:o,normal:r,tx:i,ty:s,tz:c}=Va(e),l=la(Ba(e),t,o,r,i,s,c,Ca,za(e));return l?Na(l,n)??Ar(e,n):Ar(e,n)}function $a(e){let n=e.defaultView?.matchMedia;return n?n("(pointer: coarse)").matches||n("(hover: none)").matches:!1}function Ua(e){return $a(e)?Pa:wr}function ja(e){return e.axis==="x"?[e.left+e.width/2,-e.z,e.top+e.height/2]:e.axis==="y"?[-e.z,e.top+e.height/2,e.left+e.width/2]:[e.left+e.width/2,e.top+e.height/2,e.z]}function Wa(e,n){let t=ja(e),o=n.meshRotation;o&&(t=ma(t,o));let[r,i]=pa(t,n.rotX,0,n.rotY);return{x:r,y:i}}function Ya(e,n,t){let o=e.filter(f=>n.has(f.face)).map(f=>({item:f,...Wa(f,t)}));if(o.length===0)return[];let r=1/0,i=-1/0,s=1/0,c=-1/0;for(let f of o)r=Math.min(r,f.x),i=Math.max(i,f.x),s=Math.min(s,f.y),c=Math.max(c,f.y);let l=4,p=Math.max(1e-6,i-r),g=Math.max(1e-6,c-s),x=new Map;for(let f of o){let b=Math.min(l-1,Math.max(0,Math.floor((f.x-r)/p*l))),y=Math.min(l-1,Math.max(0,Math.floor((f.y-s)/g*l))),P=`${b}:${y}`,v=x.get(P);v||(v={tx:b,ty:y,sourceIndex:f.item.sourceIndex,items:[]},x.set(P,v)),v.items.push(f.item),v.sourceIndex=Math.min(v.sourceIndex,f.item.sourceIndex)}return Array.from(x.values()).sort((f,b)=>f.ty-b.ty||f.tx-b.tx||f.sourceIndex-b.sourceIndex).flatMap(f=>f.items)}function _r(e){let{doc:n,wrapper:t,polygons:o,directionalLight:r,ambientLight:i}=e,s=Fa(o);if(s.length===0)return null;let c=new Set(s.map(h=>h.face));t.classList.add("polycss-voxel-mesh");let l=Ua(n);l!==wr&&t.style.setProperty("--polycss-voxel-primitive",`${l}px`);let p=new Map,g=(h,u)=>{let d=`${h}|${u}`,T=p.get(d);if(T)return T;let w=Ia(Lr[h],u,r,i);return p.set(d,w),w},x=new Map,f=new Map,b=new Map,y=new Map;for(let h of s){let u=y.get(h.face);u||(u=[],y.set(h.face,u)),u.push(h)}let P="",v=0,C=new Set,F=h=>{let u=x.get(h.sourceIndex);return u||(u=n.createElement("b"),x.set(h.sourceIndex,u),Ta(u,g(h.face,h.baseColor),Ga(h,l))),u},k=h=>{let u=f.get(h);return u||(u=n.createElement("span"),u.className=`polycss-voxel-face polycss-voxel-face-${h}`,u.dataset.polycssVoxelFace=h,u.__polycssVoxelFaceHost=!0,f.set(h,u)),u},z=()=>{for(let h of Array.from(t.childNodes))if(!h.__polycssVoxelFaceHost)return h;return null},O=(h,u)=>{let d=u.map(R=>R.sourceIndex).join(",");if(b.get(h)===d)return;let T=k(h),w=n.createDocumentFragment();for(let R of u)w.appendChild(F(R));T.replaceChildren(w),b.set(h,d)},Z=()=>{for(let h of So)c.has(h)&&O(h,y.get(h)??[])},q=h=>new Set(h.split("|").filter(Boolean)),D=h=>{let u=q(h);return So.filter(d=>u.has(d)&&c.has(d))},H=h=>{let u=0;for(let d of h)u+=y.get(d)?.length??0;return u},V=h=>{let u=new Set,d=[],T=new Map;for(let w of h){u.has(w.face)||(u.add(w.face),d.push(w.face));let R=T.get(w.face);R||(R=[],T.set(w.face,R)),R.push(w)}return{orderedFaces:d,itemsByFace:T}},G=(h,u)=>{let d=new Set(h);for(let T of C){if(d.has(T))continue;let w=f.get(T);w?.parentNode===t&&t.removeChild(w)}if(u){let T=n.createDocumentFragment();for(let w of h)T.appendChild(k(w));t.insertBefore(T,z()),C=d;return}for(let T=0;T<h.length;T+=1){let w=h[T],R=k(w);if(R.parentNode===t)continue;let L=null;for(let te=T+1;te<h.length;te+=1){let _=f.get(h[te]);if(_?.parentNode===t){L=_;break}}t.insertBefore(R,L??z())}C=d},A=(h,u,d)=>{if(!d){let te=D(h);G(te,!1),v=H(te);return}let T=new Set(h.split("|").filter(Boolean)),w=Ya(s,T,u),{orderedFaces:R,itemsByFace:L}=V(w);for(let te of R)O(te,L.get(te)??[]);G(R,!0),v=w.length};return Z(),{get brushCount(){return v},render(h){P=Sr(h),A(P,h,!0)},syncCamera(h){let u=Sr(h);u!==P&&(P=u,A(u,h,!1))},dispose(){for(let h of f.values())h.remove();t.classList.remove("polycss-voxel-mesh"),t.style.removeProperty("--polycss-voxel-primitive"),x.clear(),f.clear(),b.clear(),v=0,C=new Set,P=""}}}var Rr="polycss-styles";function kr(e){let n=e??(typeof document<"u"?document:void 0);if(!n||n.getElementById(Rr))return;let t=n.createElement("style");t.id=Rr,t.textContent=Xa,n.head.appendChild(t)}var Xa=`
2
2
  /* \u2500\u2500 Scene container \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
3
3
 
4
4
  .polycss-scene,
@@ -51,12 +51,32 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
51
51
  transform-style: preserve-3d !important;
52
52
  }
53
53
 
54
+ /* \u2500\u2500 Shadow root wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
55
+
56
+ /* Single 0\xD70 preserve-3d container that owns every shadow SVG (ground +
57
+ per-face receiver). Children composite via their own absolute matrix3d
58
+ transforms exactly as if mounted on .polycss-scene directly. The wrapper
59
+ exists so the DOM has one obvious "shadows live here" node and so
60
+ future toggles (clip-region, hide-all-shadows) flip a single ancestor. */
61
+ .polycss-shadows {
62
+ position: absolute;
63
+ top: 0;
64
+ left: 0;
65
+ width: 0;
66
+ height: 0;
67
+ transform-style: preserve-3d;
68
+ pointer-events: none;
69
+ }
70
+
54
71
  /* \u2500\u2500 Mesh wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
55
72
 
56
73
  .polycss-mesh {
57
74
  position: absolute;
58
75
  transform-style: preserve-3d;
59
- transform-origin: var(--origin);
76
+ /* Pivot at wrapper local (0,0,0) for three.js mesh.position/rotation/scale
77
+ parity. Geometry is positioned by the parser (bbox-min-at-origin by
78
+ default, or pre-centered via parseGltf/parseObj { center: true }). */
79
+ transform-origin: 0 0 0;
60
80
  }
61
81
 
62
82
  /* \u2500\u2500 Polygon leaf element \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
@@ -138,30 +158,39 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
138
158
  border-width: 0 16px 32px 16px;
139
159
  }
140
160
 
141
- .polycss-scene u.polycss-large-border-triangle {
142
- border-width: 0 48px 96px 48px;
143
- }
144
-
145
- .polycss-scene u.polycss-corner-triangle {
146
- width: 32px;
147
- height: 32px;
148
- background: currentColor;
149
- border: 0;
150
- border-top-left-radius: 50% 100%;
151
- border-top-right-radius: 50% 100%;
152
- corner-top-left-shape: bevel;
153
- corner-top-right-shape: bevel;
161
+ @supports (corner-top-left-shape: bevel) and (corner-top-right-shape: bevel) {
162
+ .polycss-scene > u,
163
+ .polycss-mesh > u,
164
+ .polycss-bucket > u {
165
+ border-width: 0;
166
+ width: 32px;
167
+ height: 32px;
168
+ background-color: currentColor;
169
+ border-top-left-radius: 50% 100%;
170
+ border-top-right-radius: 50% 100%;
171
+ corner-top-left-shape: bevel;
172
+ corner-top-right-shape: bevel;
173
+ }
174
+
175
+ .polycss-scene > u.polycss-corner-shape-solid,
176
+ .polycss-mesh > u.polycss-corner-shape-solid,
177
+ .polycss-bucket > u.polycss-corner-shape-solid {
178
+ width: 16px;
179
+ height: 16px;
180
+ box-sizing: border-box;
181
+ border: 0;
182
+ background: currentColor;
183
+ border-radius: 0;
184
+ corner-top-left-shape: initial;
185
+ corner-top-right-shape: initial;
186
+ corner-bottom-right-shape: initial;
187
+ corner-bottom-left-shape: initial;
188
+ }
154
189
  }
155
190
 
156
- /* <q> \u2014 dedicated shadow leaf. Same border-shape rendering trick as <i>
157
- (border-color: currentColor fills the polygon outline) but with its
158
- own tag so we don't have to thread :not(.polycss-shadow) exclusions
159
- through every dynamic-mode color rule. backface-visibility must be
160
- visible because the projection matrix is near-rank-deficient and the
161
- resulting plane's normal can read as back-facing under some camera
162
- angles; the leaf is intentionally always painted. Strip the UA's
163
- default ::before/::after open-/close-quote so the element is just a
164
- styled box. */
191
+ /* Reserved internal <q> shadow element rules. Current shadow emission uses SVG
192
+ surfaces; these rules keep any retained <q> markup styled as a plain
193
+ border-shape leaf instead of inheriting UA quote styling. */
165
194
  .polycss-scene q {
166
195
  position: absolute;
167
196
  display: block;
@@ -344,13 +373,34 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
344
373
  leaves, so there's nothing inside a leaf that needs to participate
345
374
  in 3D compositing across the contain boundary. */
346
375
  contain: strict;
376
+ /*
377
+ * Three.js MeshLambertMaterial parity for textured surfaces:
378
+ *
379
+ * target = sRGB_encode(albedo_linear \xD7 irradiance_linear / \u03C0)
380
+ *
381
+ * background-blend-mode: multiply produces (bitmap \xD7 tint) in sRGB
382
+ * \u2014 approximately sRGB(albedo_linear \xD7 tint_linear) when bitmap \u2248
383
+ * sRGB(albedo_linear). So we want tint = sRGB_encode(irradiance /\u03C0).
384
+ *
385
+ * Each light/ambient colour channel is sRGB-to-linearised
386
+ * via pow((c + 0.055) / 1.055, 2.4) before the dot product so the
387
+ * irradiance accumulates in linear space; final encode is
388
+ * 1.055 \xD7 pow(c, 1/2.4) - 0.055. min(1, \u2026) clamps inside the encode
389
+ * domain. Matches the solid <b>/<i>/<u> pipeline below.
390
+ */
347
391
  background-color: rgb(
348
- calc(255 * (var(--par) * var(--pai)
349
- + var(--plr) * var(--pli) * var(--plam)))
350
- calc(255 * (var(--pag) * var(--pai)
351
- + var(--plg) * var(--pli) * var(--plam)))
352
- calc(255 * (var(--pab) * var(--pai)
353
- + var(--plb) * var(--pli) * var(--plam)))
392
+ calc(255 * max(0, 1.055 * pow(min(1, (
393
+ pow((var(--par) + 0.055) / 1.055, 2.4) * var(--pai) +
394
+ pow((var(--plr) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
395
+ ) / 3.14159265), 0.4167) - 0.055))
396
+ calc(255 * max(0, 1.055 * pow(min(1, (
397
+ pow((var(--pag) + 0.055) / 1.055, 2.4) * var(--pai) +
398
+ pow((var(--plg) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
399
+ ) / 3.14159265), 0.4167) - 0.055))
400
+ calc(255 * max(0, 1.055 * pow(min(1, (
401
+ pow((var(--pab) + 0.055) / 1.055, 2.4) * var(--pai) +
402
+ pow((var(--plb) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
403
+ ) / 3.14159265), 0.4167) - 0.055))
354
404
  );
355
405
  background-blend-mode: multiply;
356
406
  background-image: var(--polycss-atlas-url);
@@ -371,21 +421,55 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
371
421
  .polycss-scene[data-polycss-lighting="dynamic"] b,
372
422
  .polycss-scene[data-polycss-lighting="dynamic"] i,
373
423
  .polycss-scene[data-polycss-lighting="dynamic"] u {
424
+ /*
425
+ * Three.js MeshLambertMaterial parity (default useLegacyLights=false,
426
+ * physically-correct pipeline):
427
+ *
428
+ * lit_linear = albedo_linear \xD7 (lightColor_linear \xD7 intensity \xD7 lambert
429
+ * + ambient_linear \xD7 ambientIntensity) / \u03C0
430
+ * output = 255 \xD7 sRGB_encode(min(1, lit_linear))
431
+ *
432
+ * sRGB\u2192linear: pow((c + 0.055) / 1.055, 2.4) for c > 0.04045
433
+ * 12.92 \xD7 c otherwise (skipped \u2014 tiny)
434
+ * linear\u2192sRGB: 1.055 \xD7 pow(c, 1/2.4) - 0.055 for c > 0.0031308
435
+ * 12.92 \xD7 c otherwise (skipped \u2014 tiny)
436
+ *
437
+ * The naive pow(c, 2.4) shortcut undershoots by ~2x for small c
438
+ * (dark channels of a saturated colour) \u2014 the +0.055/1.055 offset
439
+ * is load-bearing for the G/B drift on saturated fixtures.
440
+ *
441
+ * Verified against per-pixel screenshots in bench/three-parity.html
442
+ * (cube #dc2626 top face): drift <3 per channel across i=0.5..3,
443
+ * ambient=0..0.3, lambert=0..1.
444
+ */
374
445
  color: rgb(
375
- calc(255 * var(--psr) * (var(--par) * var(--pai)
376
- + var(--plr) * var(--pli) * var(--plam)))
377
- calc(255 * var(--psg) * (var(--pag) * var(--pai)
378
- + var(--plg) * var(--pli) * var(--plam)))
379
- calc(255 * var(--psb) * (var(--pab) * var(--pai)
380
- + var(--plb) * var(--pli) * var(--plam)))
446
+ calc(255 * max(0, 1.055 * pow(min(1,
447
+ pow((var(--psr) + 0.055) / 1.055, 2.4) * (
448
+ pow((var(--par) + 0.055) / 1.055, 2.4) * var(--pai) +
449
+ pow((var(--plr) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
450
+ ) / 3.14159265
451
+ ), 0.4167) - 0.055))
452
+ calc(255 * max(0, 1.055 * pow(min(1,
453
+ pow((var(--psg) + 0.055) / 1.055, 2.4) * (
454
+ pow((var(--pag) + 0.055) / 1.055, 2.4) * var(--pai) +
455
+ pow((var(--plg) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
456
+ ) / 3.14159265
457
+ ), 0.4167) - 0.055))
458
+ calc(255 * max(0, 1.055 * pow(min(1,
459
+ pow((var(--psb) + 0.055) / 1.055, 2.4) * (
460
+ pow((var(--pab) + 0.055) / 1.055, 2.4) * var(--pai) +
461
+ pow((var(--plb) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
462
+ ) / 3.14159265
463
+ ), 0.4167) - 0.055))
381
464
  );
382
465
  }
383
466
 
384
- /* \u2500\u2500 Cast shadow projection (dynamic-mode CSS path) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
467
+ /* \u2500\u2500 Retained <q> shadow projection (dynamic-mode CSS path) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
385
468
 
386
469
  /*
387
- * Shadow projection matrix. Projects any 3D point P onto the horizontal
388
- * ground plane (cssZ \u2248 G) along the CSS-space light direction (--clx/y/z).
470
+ * Projection matrix for retained internal <q> shadow leaves. Projects any
471
+ * 3D point P onto the horizontal ground plane (cssZ \u2248 G) along the CSS-space
472
+ * light direction (--clx/y/z).
389
473
  *
390
474
  * In PolyCSS's world convention world Z is up (red-green plane is the
391
475
  * floor in the axes helper). After the world\u2192CSS swap (Y\u2194X), world Z stays
@@ -398,7 +482,7 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
398
482
  * has a valid layout box. The fix: collapse along z by a near-zero
399
483
  * scale (Z_SQUASH = 0.01) instead of exactly zero \u2014 output.z is then
400
484
  * approximately G with ~1% drift from the input, full-rank and renderable.
401
- * The shadow still looks flat to the eye (the drift is sub-pixel for
485
+ * The result still looks flat to the eye (the drift is sub-pixel for
402
486
  * any realistic scene size).
403
487
  *
404
488
  * out.cssX = P.cssX - (--clx/--clz) * (P.cssZ - G)
@@ -426,19 +510,10 @@ import{BASE_TILE as El,CAMERA_BACKFACE_CULL_EPS as wo,DEFAULT_SEAM_BLEED as Gr,V
426
510
  );
427
511
  }
428
512
 
429
- /* <q> shadow leaf \u2014 Lambert-gated opacity. Polygons facing the light cast
430
- full shadow; polygons facing away cast zero shadow (their projection
431
- would stack inside the silhouette and produce ugly overdraw). The
432
- * 10 multiplier sharpens the cutoff so small positive Lambert values
433
- jump quickly to 1, giving a near-binary visibility decision with a
434
- smooth edge transition. Pure CSS calc \u2014 no JS at light-change time.
435
-
436
- Scoped to dynamic mode: baked-mode shadow leaves are dropped from the
437
- DOM up-front by isBakedShadowCaster() and don't carry --pnx/--pny/--pnz,
438
- so an unscoped gate would silently zero them via the @property
439
- initial values. The base layout / positioning / pseudo-element-strip
440
- rules for <q> live in the polygon-leaf section above. */
513
+ /* Retained <q> opacity gate. Polygons facing the light cast full shadow;
514
+ polygons facing away cast zero shadow. The * 10 multiplier sharpens the
515
+ cutoff so small positive Lambert values jump quickly to 1. */
441
516
  .polycss-scene[data-polycss-lighting="dynamic"] q {
442
517
  opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1);
443
518
  }
444
- `;var Il=750;function zr(e){return!Object.prototype.hasOwnProperty.call(e,"seamBleed")||e.seamBleed!==void 0?e:{...e,seamBleed:Gr}}var Vl=1,We=El,zl=Symbol.for("polycss.animation.triangleFrameTarget"),Bl={key:"non-cullable",normal:[1,1,0]};function Br(){return[Bl]}function Nl(e,n){let t=e?.disable??[],o=n?.disable??[];if(t.length!==o.length)return!1;for(let r of t)if(!o.includes(r))return!1;return!0}function Ul(e,n){return e===n?!0:!e||!n?!1:e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}function $l(e,n){return e===n?!0:(e?.color??"#000000")===(n?.color??"#000000")&&(e?.opacity??.25)===(n?.opacity??.25)&&(e?.lift??.05)===(n?.lift??.05)&&(e?.maxExtend??2e3)===(n?.maxExtend??2e3)}function Nr(e){let n=[];return e.position&&n.push(`translate3d(${e.position[0]}px, ${e.position[1]}px, ${e.position[2]}px)`),e.scale!==void 0&&(typeof e.scale=="number"?e.scale!==1&&n.push(`scale3d(${e.scale}, ${e.scale}, ${e.scale})`):n.push(`scale3d(${e.scale[0]}, ${e.scale[1]}, ${e.scale[2]})`)),e.rotation&&(e.rotation[0]&&n.push(`rotateX(${e.rotation[0]}deg)`),e.rotation[1]&&n.push(`rotateY(${e.rotation[1]}deg)`),e.rotation[2]&&n.push(`rotateZ(${e.rotation[2]}deg)`)),n.length>0?n.join(" "):void 0}function Ur(e,n=[0,0,0],t=1){let o=e.state,r=o.rotX,i=o.rotY,l=(o.zoom??Vl)*t,c=(o.distance??0)*t,a=o.target??[0,0,0],m=a[0]+n[0],f=a[1]+n[1],h=a[2]+n[2],g=f*We,x=m*We,y=h*We;return`${c!==0?`translateZ(${-c}px) `:""}scale(${l}) rotateX(${r}deg) rotate(${i}deg) translate3d(${-g}px, ${-x}px, ${-y}px)`}function Gl(e){let n=e.trim();if(!n||n==="normal")return 1;let t=n.endsWith("%")?Number(n.slice(0,-1))/100:Number(n);return Number.isFinite(t)&&t>0?t:1}function Yl(e){let n=e.ownerDocument?.defaultView;if(!n)return 1;let t=1;for(let o=e;o;o=o.parentElement)t*=Gl(n.getComputedStyle(o).getPropertyValue("zoom"));return Number.isFinite(t)&&t>0?t:1}function $r(e,n){return n===1?e:e*n}function jl(e,n){Math.abs(n-1)<1e-6?e.style.removeProperty("zoom"):e.style.setProperty("zoom",String(1/n))}var Xl=.1;function Wl(e){if(e.vertices.length<3)return null;let n=e.vertices[0],t=0,o=0,r=0;for(let h=1;h+1<e.vertices.length;h++){let g=e.vertices[h],x=e.vertices[h+1],y=g[1]-n[1],P=g[0]-n[0],v=g[2]-n[2],E=x[1]-n[1],H=x[0]-n[0],k=x[2]-n[2];t-=P*k-v*H,o-=v*E-y*k,r-=y*H-P*E}let i=Math.hypot(t,o,r);if(i<1e-9)return null;t/=i,o/=i,r/=i;let l=1/Xl,c=Math.round(t*l)/l,a=Math.round(o*l)/l,m=Math.round(r*l)/l,f=Math.hypot(c,a,m);return f<1e-9?null:{key:c+","+a+","+m,vec:[c/f,a/f,m/f]}}function Yr(e,n){if(!e||typeof e.appendChild!="function")throw new Error("createPolyScene: host must be an HTMLElement");if(!n?.camera)throw new Error("createPolyScene: a camera handle is required. Use createPolyCamera({...}) or createPolyPerspectiveCamera({...}) and pass as { camera }.");let t=n.camera;e.ownerDocument&&Fr(e.ownerDocument),e.ownerDocument?.defaultView&&e.ownerDocument.defaultView.getComputedStyle(e).position==="static"&&(e.style.position="relative");let{camera:o,...r}=n,i=zr({seamBleed:Gr,...r}),l=Yl(e),c=[0,0,0],a=e.ownerDocument??document,m=a.createElement("div");m.className="polycss-camera",z(m,i),e.appendChild(m);let f=a.createElement("div");f.className="polycss-scene",f.setAttribute("aria-hidden","true"),O(f,i),m.appendChild(f);let h=new Set,g=null,x=[];function y(){for(let s of x)s.parentNode&&s.parentNode.removeChild(s);x.length=0,k()}let P=new Map,v=new Map;function E(s){for(let d of s)d.svg&&d.svg.parentNode&&d.svg.parentNode.removeChild(d.svg),d.svg=null,d.path=null}function H(s){if(s){let d=P.get(s);d&&E(d),P.delete(s),v.delete(s)}else{for(let d of P.values())E(d);P.clear(),v.clear()}}function k(){for(let s of P.values())for(let d of s)d.svg&&d.visible&&(d.svg.style.display="none",d.visible=!1)}let N=new Map,R=new Map;function K(s){s?(N.delete(s),R.delete(s)):(N.clear(),R.clear())}function z(s,d){let S=t.perspectiveStyle;if(S==="none")s.style.perspective=`${$r(1e6,l)}px`;else{let T=parseFloat(S);Number.isFinite(T)&&(s.style.perspective=`${$r(T,l)}px`)}}function O(s,d){jl(s,l),s.style.transform=Ur(t,c,l),U(s,d)}function $(s){s.style.transform=Ur(t,c,l)}function U(s,d){let S=d.textureLighting==="dynamic";s.dataset.polycssLighting=d.textureLighting??"baked";let T=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--clx","--cly","--clz"];if(!S){for(let Pe of T)s.style.removeProperty(Pe);return}let I=d.directionalLight?.direction??[.4,-.7,.59],V=Math.hypot(I[0],I[1],I[2])||1,F=I[0]/V,q=I[1]/V,Y=I[2]/V,B=_o(d.directionalLight?.color??"#ffffff")?.rgb??[255,255,255],ee=_o(d.ambientLight?.color??"#ffffff")?.rgb??[255,255,255],j=d.directionalLight?.intensity??1,b=d.ambientLight?.intensity??.4,J=Pe=>(Pe/255).toFixed(4);s.style.setProperty("--plx",F.toFixed(4)),s.style.setProperty("--ply",q.toFixed(4)),s.style.setProperty("--plz",Y.toFixed(4)),s.style.setProperty("--plr",J(B[0])),s.style.setProperty("--plg",J(B[1])),s.style.setProperty("--plb",J(B[2])),s.style.setProperty("--pli",j.toFixed(4)),s.style.setProperty("--par",J(ee[0])),s.style.setProperty("--pag",J(ee[1])),s.style.setProperty("--pab",J(ee[2])),s.style.setProperty("--pai",b.toFixed(4));let Ce=Y,Te=Math.sign(Ce||1)*Math.max(Math.abs(Ce),.01);s.style.setProperty("--clx",F.toFixed(4)),s.style.setProperty("--cly",q.toFixed(4)),s.style.setProperty("--clz",Te.toFixed(4))}function ie(s){s.voxelRenderer?.dispose(),s.voxelRenderer=void 0,C(s.rendered,s.disposeAtlas),s.disposeAtlas=void 0,s.rendered.length=0,s.renderedByPolygonIndex=[],s.cameraCullGroups=[],s.cameraCullSignature="",p(s);for(let d of Array.from(s.wrapper.children))d instanceof HTMLElement&&d.classList.contains("polycss-bucket")&&d.remove();s.hasBuckets=!1}function xe(s){for(let d of Array.from(s.wrapper.childNodes)){if(!(d instanceof HTMLElement))return d;if(d.classList.contains("polycss-bucket")||d.classList.contains("polycss-shadow"))continue;let S=d.tagName.toLowerCase();if(!(S==="b"||S==="i"||S==="s"||S==="u"||S==="q"))return d}return null}function u(s,d,S){S?.parentNode===s.wrapper?s.wrapper.insertBefore(d,S):s.wrapper.appendChild(d)}function p(s){for(let d of s.shadowRendered)d.parentNode&&d.parentNode.removeChild(d);s.shadowRendered.length=0,y()}function C(s,d){d?.();for(let S of s){try{S.dispose()}catch{}S.element.parentNode&&S.element.parentNode.removeChild(S.element)}}function A(s,d,S){s.rendered=d,s.renderedByPolygonIndex=[];for(let T of d)s.renderedByPolygonIndex[T.polygonIndex]=T;s.disposeAtlas=S}function w(s,d){let S=s.renderedByPolygonIndex[d];return S?.polygonIndex===d?S:void 0}function M(s){for(let d of Array.from(s.wrapper.children))d instanceof HTMLElement&&d.classList.contains("polycss-bucket")&&d.remove();s.hasBuckets=!1;for(let d of s.rendered)d.element.parentNode&&d.element.parentNode.removeChild(d.element)}function se(s,d){let S=s.polygons[d.polygonIndex];return s.stableDom&&S?Vr(S):d.plan?.normal??(S?Vr(S):null)}function he(s){if(!Ee(s))return s.rendered;let d=_(s);return s.rendered.filter(S=>ne(s,S,wo,d))}function _(s){return{rotX:t.state.rotX,rotY:t.state.rotY,meshRotation:s.handle.transform.rotation}}function ne(s,d,S=wo,T=_(s)){let I=se(s,d);return I===null||kl(I,T,S)}function oe(s){if(s.excludeFromAutoCenter){s.cameraCullGroups=[];return}let d=new Map;for(let S of s.rendered){let T=se(s,S);if(!T)continue;if(!Rl(T)){s.cameraCullGroups=Br();return}let I=Al(T);if(!d.has(I)&&(d.set(I,T),d.size>Tl)){s.cameraCullGroups=Br();return}}s.cameraCullGroups=Array.from(d,([S,T])=>({key:S,normal:T}))}function Se(s){return Ee(s)?Ml(s.cameraCullGroups,_(s)):"all"}function Ee(s){return!s.excludeFromAutoCenter&&Dl(s.cameraCullGroups)}function De(s){s.cameraCullSignature=Ee(s)?Se(s):"all"}function Ve(s,d){let S=new Array(s.rendered.length),T=!1,I=_(s);for(let j=0;j<s.rendered.length;j+=1){let b=s.rendered[j],J=ne(s,b,d,I);S[j]=J}let V=null,F=null,q=()=>{if(!(!V||!F)){if(V===F)V.remove();else{let j=a.createRange();j.setStartBefore(V),j.setEndAfter(F),j.deleteContents(),j.detach()}V=null,F=null,T=!0}};for(let j=0;j<s.rendered.length;j+=1){let b=s.rendered[j];!S[j]&&b.element.parentNode===s.wrapper?(F&&F.nextSibling===b.element||(q(),V=b.element),F=b.element):q()}q();let Y=j=>{for(let b=j;b<s.rendered.length;b+=1){let J=s.rendered[b].element;if(J.parentNode===s.wrapper)return J}return xe(s)},B=-1,ee=j=>{if(B<0)return;let b=a.createDocumentFragment();for(let J=B;J<j;J+=1){let Ce=s.rendered[J];Ue(s,Ce),b.appendChild(Ce.element)}u(s,b,Y(j)),B=-1,T=!0};for(let j=0;j<s.rendered.length;j+=1){let b=s.rendered[j];S[j]&&b.element.parentNode!==s.wrapper?B<0&&(B=j):ee(j)}return ee(s.rendered.length),T}function _e(s,d=!1){if(s.voxelRenderer){d?s.voxelRenderer.render(_(s)):s.voxelRenderer.syncCamera(_(s)),s.cameraCullSignature="voxel-direct";return}if(!Ee(s)){let I=s.cameraCullSignature!=="all";s.cameraCullSignature="all",I&&ke(s);return}if(s.hasBuckets){ze(s,d);return}let S=Se(s);if(!d&&S===s.cameraCullSignature)return;let T=Ve(s,wo);s.cameraCullSignature=S,T&&ae(s)}function ze(s,d=!1){let S=Ee(s)?Se(s):"all";!d&&S===s.cameraCullSignature||ke(s)}function Je(s,d){return se(s,d)}function Ue(s,d){if(i.textureLighting!=="dynamic")return;let S=Je(s,d);S&&(d.element.style.setProperty("--pnx",S[0].toFixed(4)),d.element.style.setProperty("--pny",S[1].toFixed(4)),d.element.style.setProperty("--pnz",S[2].toFixed(4)))}function Xe(s){M(s),s.hasBuckets=!1;let d=s.skipBucketNormalCleanupOnce;s.skipBucketNormalCleanupOnce=!1;let S=a.createDocumentFragment(),T=i.textureLighting==="dynamic"&&!s.stableDom,I=new Map,V=[];for(let F of he(s)){let q=s.polygons[F.polygonIndex],Y=T&&q?Wl(q):null;if(!Y){V.push(F);continue}let B=Y.key+"|"+(q.color??""),ee=I.get(B);ee||(ee={vec:Y.vec,items:[]},I.set(B,ee)),ee.items.push(F)}for(let F of V)Ue(s,F),S.appendChild(F.element);for(let F of I.values()){if(F.items.length<2){for(let Y of F.items)Ue(s,Y),S.appendChild(Y.element);continue}let q=a.createElement("div");q.className="polycss-bucket",s.hasBuckets=!0,q.style.setProperty("--pnx",String(F.vec[0])),q.style.setProperty("--pny",String(F.vec[1])),q.style.setProperty("--pnz",String(F.vec[2]));for(let Y of F.items)q.appendChild(Y.element),(!d||Y.kind==="triangle")&&(Y.element.style.removeProperty("--pnx"),Y.element.style.removeProperty("--pny"),Y.element.style.removeProperty("--pnz"));S.appendChild(q)}u(s,S,xe(s)),De(s)}function Ht(){return new Promise(s=>setTimeout(s,0))}async function It(s,d){if(i.textureLighting==="dynamic"&&!s.stableDom)return Xe(s),!d();M(s);let T=a.createDocumentFragment(),I=xe(s),V=0;for(let F of he(s)){if(d())return!1;Ue(s,F),T.appendChild(F.element),V++,V%Il===0&&(u(s,T,I),T=a.createDocumentFragment(),await Ht())}return T.childNodes.length>0&&u(s,T,I),De(s),!d()}function lt(s,d){let S=i.textureLighting==="dynamic",T=i.directionalLight?.direction,I=d&&(d[0]!==0||d[1]!==0||d[2]!==0);if(!S||!I||!T){if(s.lightOverrideSignature==="clear")return;s.wrapper.style.removeProperty("--plx"),s.wrapper.style.removeProperty("--ply"),s.wrapper.style.removeProperty("--plz"),s.lightOverrideSignature="clear";return}let V=Ir(T,d),F=Math.hypot(V[0],V[1],V[2])||1,q=(V[0]/F).toFixed(4),Y=(V[1]/F).toFixed(4),B=(V[2]/F).toFixed(4),ee=`${q}|${Y}|${B}`;s.lightOverrideSignature!==ee&&(s.wrapper.style.setProperty("--plx",q),s.wrapper.style.setProperty("--ply",Y),s.wrapper.style.setProperty("--plz",B),s.lightOverrideSignature=ee)}function ht(s,d){d.paintColor?s.style.setProperty("--polycss-paint",d.paintColor):s.style.getPropertyValue("--polycss-paint")&&s.style.removeProperty("--polycss-paint"),d.dynamicColor?(s.style.setProperty("--psr",(d.dynamicColor.r/255).toFixed(4)),s.style.setProperty("--psg",(d.dynamicColor.g/255).toFixed(4)),s.style.setProperty("--psb",(d.dynamicColor.b/255).toFixed(4))):(s.style.getPropertyValue("--psr")||s.style.getPropertyValue("--psg")||s.style.getPropertyValue("--psb"))&&(s.style.removeProperty("--psr"),s.style.removeProperty("--psg"),s.style.removeProperty("--psb"))}function eo(s,d){let S=Fl(d??"#cccccc");s.style.setProperty("--psr",(S.r/255).toFixed(4)),s.style.setProperty("--psg",(S.g/255).toFixed(4)),s.style.setProperty("--psb",(S.b/255).toFixed(4))}function to(s,d){if(!s.plan||s.kind==="atlas"||s.plan.texture)return!1;let S=i.textureLighting??"baked",T={directionalLight:i.directionalLight,ambientLight:i.ambientLight,textureLighting:S,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies},I=mo(s.plan,d,s.plan.normal,S,T);return Tt(s.element,I,S),!0}function no(s,d,S){let T=s.polygons[d];if(!T)return!1;let I=w(s,d);if(!I)return!1;let V=i.textureLighting??"baked";return V==="dynamic"?(eo(I.element,S),!0):V==="baked"?to(I,T):!1}function G(s,d){let S=s.polygons[d];if(!S)return!1;let T=w(s,d);return T?(Fe(T.element,S),!0):!1}function ge(s,d,S){return!(S.length===0||!S.every(T=>T==="color"||T==="data")||S.includes("color")&&!no(s,d,s.polygons[d]?.color)||S.includes("data")&&!G(s,d))}function ae(s){we()}function we(){y();let s=[];for(let B of h)!B.disposed&&B.castShadow&&s.push(B);if(s.length===0)return;let d=i.shadow?.color??"#000000",S=i.shadow?.opacity??.25,T=_o(d)?.rgb??[0,0,0],I=T[0],V=T[1],F=T[2],q=i.directionalLight?.direction??[.4,-.7,.59],Y=new Map;for(let B of s)Y.set(B,_l(B.polygons,{normalTolerance:.1,distanceTolerance:.5,overlapFraction:.4,preserveDoubleSidedBackfaces:!1}));g!==null&&Vt(s,Y,q,g,I,V,F,S);for(let B of h)B.disposed||!B.receiveShadow||yt(s,Y,B,q,I,V,F,S)}function Vt(s,d,S,T,I,V,F,q){let Y=[],B=1/0,ee=1/0,j=-1/0,b=-1/0,J=1/0,Ce=1/0,Te=-1/0,Pe=-1/0;for(let ue of s){let de=ue.handle.transform.position??[0,0,0],fe=d.get(ue);for(let et of ue.rendered){if(fe.has(et.polygonIndex)||!et.plan)continue;let Bt=ue.polygons[et.polygonIndex];if(!Bt)continue;let ut=[];for(let dt of Bt.vertices){let Ae=[dt[1]*We+de[0],dt[0]*We+de[1],dt[2]*We+de[2]];Ae[0]<J&&(J=Ae[0]),Ae[1]<Ce&&(Ce=Ae[1]),Ae[0]>Te&&(Te=Ae[0]),Ae[1]>Pe&&(Pe=Ae[1]);let Le=Hl(Ae,S,T);ut.push(Le),Le[0]<B&&(B=Le[0]),Le[1]<ee&&(ee=Le[1]),Le[0]>j&&(j=Le[0]),Le[1]>b&&(b=Le[1])}let Be=ut.length>3?Hr(ut):ut;Be.length>=3&&Y.push(Be)}}if(Y.length===0)return;let me=i.shadow?.maxExtend??2e3,W=Math.max(B,J-me),ce=Math.max(ee,Ce-me),te=Math.min(j,Te+me),L=Math.min(b,Pe+me),D=te-W,Z=L-ce;if(!(D>0)||!(Z>0))return;let re="";for(let ue of Y){let de=Lo(ue);re+=`M${(de[0][0]-W).toFixed(3)},${(de[0][1]-ce).toFixed(3)}`;for(let fe=1;fe<de.length;fe++)re+=`L${(de[fe][0]-W).toFixed(3)},${(de[fe][1]-ce).toFixed(3)}`;re+="Z"}let pe="http://www.w3.org/2000/svg",X=a.createElementNS(pe,"svg");X.setAttribute("class","polycss-shadow polycss-shadow-svg"),X.setAttribute("width",String(D)),X.setAttribute("height",String(Z)),X.setAttribute("viewBox",`0 0 ${D} ${Z}`),X.setAttribute("style",`position:absolute;top:0;left:0;display:block;overflow:hidden;transform-origin:0 0;pointer-events:none;will-change:transform;transform:translate3d(${W.toFixed(3)}px,${ce.toFixed(3)}px,${T.toFixed(3)}px)`);let Q=a.createElementNS(pe,"path");Q.setAttribute("d",re);let ye=`rgb(${I},${V},${F})`;Q.setAttribute("fill",ye),Q.setAttribute("fill-rule","nonzero"),Q.setAttribute("stroke",ye),Q.setAttribute("stroke-width","2"),Q.setAttribute("stroke-linejoin","round"),Q.setAttribute("opacity",q.toFixed(4)),X.appendChild(Q),x.push(X);let be=f.firstChild;be?f.insertBefore(X,be):f.appendChild(X)}function zt(s,d,S){let T=[];for(let Y of s.polygons){if(Y.vertices.length<3)continue;let B=S(Y.vertices[0],d),ee=S(Y.vertices[1],d),j=S(Y.vertices[2],d),b=[ee[0]-B[0],ee[1]-B[1],ee[2]-B[2]],J=[j[0]-B[0],j[1]-B[1],j[2]-B[2]],Ce=J[1]*b[2]-J[2]*b[1],Te=J[2]*b[0]-J[0]*b[2],Pe=J[0]*b[1]-J[1]*b[0],me=Math.hypot(Ce,Te,Pe);if(me<1e-9)continue;let W=[Ce/me,Te/me,Pe/me],ce=Math.hypot(b[0],b[1],b[2]);if(ce<1e-9)continue;let te=[b[0]/ce,b[1]/ce,b[2]/ce],L=[W[1]*te[2]-W[2]*te[1],W[2]*te[0]-W[0]*te[2],W[0]*te[1]-W[1]*te[0]],D=W[0]*B[0]+W[1]*B[1]+W[2]*B[2];T.push({face:Y,O:B,n:W,u:te,v:L,offset:D})}let I=.001,V=.5,F=[];for(let Y of T){let B=!1;for(let ee of F){let j=ee.rep;if(!(1-(Y.n[0]*j.n[0]+Y.n[1]*j.n[1]+Y.n[2]*j.n[2])>I)&&!(Math.abs(Y.offset-j.offset)>V)){ee.faces.push(Y),B=!0;break}}B||F.push({rep:Y,faces:[Y]})}let q=[];for(let Y of F){let{O:B,n:ee,u:j,v:b}=Y.rep,J=[];for(let Te of Y.faces)for(let Pe of Te.face.vertices){let me=S(Pe,d),W=me[0]-B[0],ce=me[1]-B[1],te=me[2]-B[2];J.push([W*j[0]+ce*j[1]+te*j[2],W*b[0]+ce*b[1]+te*b[2]])}if(J.length<3)continue;let Ce=Hr(J);Ce.length<3||q.push({O:B,n:ee,u:j,v:b,outlineUv:Lo(Ce)})}return q}function yt(s,d,S,T,I,V,F,q){let Y=Math.hypot(T[0],T[1],T[2])||1,B=T[0]/Y,ee=T[1]/Y,j=T[2]/Y,b="http://www.w3.org/2000/svg",J=S.handle.transform.position??[0,0,0],Ce=(W,ce)=>[W[1]*We+ce[0],W[0]*We+ce[1],W[2]*We+ce[2]],Te=`${S.polygons.length}|${J.join(",")}`,Pe=P.get(S);(Pe===void 0||v.get(S)!==Te)&&(Pe=zt(S,J,Ce).map(ce=>{let{O:te,n:L,u:D,v:Z,outlineUv:re}=ce,pe=1/0,X=1/0,Q=-1/0,ye=-1/0;for(let Be of re)Be[0]<pe&&(pe=Be[0]),Be[1]<X&&(X=Be[1]),Be[0]>Q&&(Q=Be[0]),Be[1]>ye&&(ye=Be[1]);let be=Q-pe,ue=ye-X,de=5,fe=te[0]+pe*D[0]+X*Z[0]+de*L[0],et=te[1]+pe*D[1]+X*Z[1]+de*L[1],Re=te[2]+pe*D[2]+X*Z[2]+de*L[2],ut=`matrix3d(${[D[0],D[1],D[2],0,Z[0],Z[1],Z[2],0,L[0],L[1],L[2],0,fe,et,Re,1].map(Be=>Be.toFixed(4)).join(",")})`;return{O:te,n:L,u:D,v:Z,outlineUv:re,minU:pe,minV:X,width:be,height:ue,matrixCss:ut,svg:null,path:null,visible:!1}}),P.set(S,Pe),v.set(S,Te));let me=[];for(let W of s){if(W===S)continue;let ce=W.handle.transform.position??[0,0,0],te=`${W.polygons.length}|${ce.join(",")}`,L=N.get(W);if(L===void 0||R.get(W)!==te){let D=d.get(W);L=[];for(let Z of W.rendered){if(D.has(Z.polygonIndex)||!Z.plan)continue;let pe=W.polygons[Z.polygonIndex];if(!pe)continue;let X=pe.vertices.map(Re=>Ce(Re,ce)),Q=1/0,ye=1/0,be=1/0,ue=-1/0,de=-1/0,fe=-1/0;for(let Re of X)Re[0]<Q&&(Q=Re[0]),Re[0]>ue&&(ue=Re[0]),Re[1]<ye&&(ye=Re[1]),Re[1]>de&&(de=Re[1]),Re[2]<be&&(be=Re[2]),Re[2]>fe&&(fe=Re[2]);let et=[[Q,ye,be],[ue,ye,be],[Q,de,be],[ue,de,be],[Q,ye,fe],[ue,ye,fe],[Q,de,fe],[ue,de,fe]];L.push({wv:X,bboxCorners:et})}N.set(W,L),R.set(W,te)}for(let D of L)me.push(D)}for(let W of Pe){let{O:ce,n:te,u:L,v:D,outlineUv:Z,minU:re,minV:pe,width:X,height:Q,matrixCss:ye}=W,be=B*te[0]+ee*te[1]+j*te[2];if(be<=1e-6)continue;let ue=ve=>(ve[0]-ce[0])*te[0]+(ve[1]-ce[1])*te[1]+(ve[2]-ce[2])*te[2],de=(ve,qe,bt,vt)=>{let tt=bt/(bt-vt);return[ve[0]+tt*(qe[0]-ve[0]),ve[1]+tt*(qe[1]-ve[1]),ve[2]+tt*(qe[2]-ve[2])]},fe=ve=>{let qe=ve[0]-ce[0],bt=ve[1]-ce[1],vt=ve[2]-ce[2],tt=(qe*te[0]+bt*te[1]+vt*te[2])/be,Nt=ve[0]-tt*B,Ut=ve[1]-tt*ee,Pt=ve[2]-tt*j,nt=Nt-ce[0],mt=Ut-ce[1],Ge=Pt-ce[2];return[nt*L[0]+mt*L[1]+Ge*L[2],nt*D[0]+mt*D[1]+Ge*D[2]]},et=[],Re=re,Bt=pe,ut=W.minU+X,Be=W.minV+Q;for(let ve of me){let qe=ve.bboxCorners,bt=!1,vt=1/0,tt=1/0,Nt=-1/0,Ut=-1/0;for(let nt=0;nt<8;nt++){let mt=qe[nt];ue(mt)>=0&&(bt=!0);let Ge=fe(mt);Ge[0]<vt&&(vt=Ge[0]),Ge[0]>Nt&&(Nt=Ge[0]),Ge[1]<tt&&(tt=Ge[1]),Ge[1]>Ut&&(Ut=Ge[1])}if(!bt||Nt<Re||vt>ut||Ut<Bt||tt>Be)continue;let Pt=ve.wv;for(let nt=1;nt<Pt.length-1;nt++){let mt=Pt[0],Ge=Pt[nt],Bo=Pt[nt+1],vi=ue(mt),xi=ue(Ge),Pi=ue(Bo),an=[],No=[[mt,vi],[Ge,xi],[Bo,Pi]];for(let cn=0;cn<3;cn++){let[$o,so]=No[cn],[Ei,Go]=No[(cn+1)%3];so>=0&&an.push($o),so>=0!=Go>=0&&an.push(de($o,Ei,so,Go))}if(an.length<3)continue;let Si=an.map(fe),Ci=Lo(Si),Uo=wl(Ci,Z);Uo.length<3||et.push(Uo)}}if(et.length===0||!(X>0)||!(Q>0))continue;let dt="";for(let ve of et){dt+=`M${(ve[0][0]-re).toFixed(1)},${(ve[0][1]-pe).toFixed(1)}`;for(let qe=1;qe<ve.length;qe++)dt+=`L${(ve[qe][0]-re).toFixed(1)},${(ve[qe][1]-pe).toFixed(1)}`;dt+="Z"}let Ae=W.svg,Le=W.path;!Ae||!Le?(Ae=a.createElementNS(b,"svg"),Ae.setAttribute("class","polycss-shadow polycss-shadow-svg polycss-shadow-receiver"),Ae.setAttribute("width",String(X)),Ae.setAttribute("height",String(Q)),Ae.setAttribute("viewBox",`0 0 ${X} ${Q}`),Ae.setAttribute("style",`position:absolute;top:0;left:0;display:block;overflow:hidden;transform-origin:0 0;pointer-events:none;will-change:transform;transform:${ye}`),Le=a.createElementNS(b,"path"),Le.setAttribute("fill-rule","nonzero"),Ae.appendChild(Le),f.insertBefore(Ae,f.firstChild),W.svg=Ae,W.path=Le):W.visible||(Ae.style.display="block"),W.visible=!0,Le.setAttribute("d",dt);let Vo=`rgb(${I},${V},${F})`;Le.getAttribute("fill")!==Vo&&Le.setAttribute("fill",Vo);let zo=q.toFixed(4);Le.getAttribute("opacity")!==zo&&Le.setAttribute("opacity",zo)}}function ke(s){if(s.voxelRenderer){s.voxelRenderer.render(_(s)),s.cameraCullSignature="voxel-direct";return}p(s),Xe(s),ae(s)}function Qe(s){return!!s.voxelSource&&i.textureLighting!=="dynamic"&&!s.stableDom&&!s.castShadow}function Ie(s,d){ie(s);let S=i.directionalLight,T=d?{...S,direction:d}:S;if(Qe(s)){let F=kr({doc:a,wrapper:s.wrapper,polygons:s.parseResult.polygons,directionalLight:T,ambientLight:i.ambientLight});if(F){s.voxelRenderer=F,F.render(_(s)),s.cameraCullSignature="voxel-direct";return}}let I={doc:a,directionalLight:T,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies},V=s.stableDom?(()=>{let F=wt(s.polygons,I);return ht(s.wrapper,F),Qt(s.polygons,{...I,solidPaintDefaults:F})??Jt(s.polygons,{...I,solidPaintDefaults:F})})():Jt(s.polygons,{...I,computeSolidPaintDefaults:!0,skipDynamicNormalVars:i.textureLighting==="dynamic"});s.stableDom||ht(s.wrapper,V.solidPaintDefaults??{}),A(s,V.rendered,V.dispose),s.skipBucketNormalCleanupOnce=i.textureLighting==="dynamic"&&!s.stableDom,oe(s),Xe(s),ae(s)}function $e(){let s=1/0,d=!1;for(let V of h)if(!V.disposed&&V.receiveShadow){d=!0;break}for(let V of h){if(V.disposed||!(d?V.receiveShadow:V.castShadow))continue;let q=V.handle.transform.position?.[2]??0;for(let Y of V.polygons)for(let B of Y.vertices){let ee=B[2]+q;ee<s&&(s=ee)}}if(!Number.isFinite(s)){let V=g!==null;g=null,V&&y();return}let S=i.shadow?.lift??.05,T=(s+S)*We,I=g;g=T,I!==T&&we()}async function oo(s,d){ie(s);let S={doc:a,directionalLight:i.directionalLight,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies},T=s.stableDom?Qt(s.polygons,S):null;if(T){let F=wt(s.polygons,S);return ht(s.wrapper,F),A(s,T.rendered,T.dispose),oe(s),Xe(s),ae(s),!d()}let I=await bn(s.polygons,{...S,skipDynamicNormalVars:i.textureLighting==="dynamic"},d);if(d())return I.dispose(),!1;ht(s.wrapper,I.solidPaintDefaults),A(s,I.rendered,I.dispose),s.skipBucketNormalCleanupOnce=i.textureLighting==="dynamic"&&!s.stableDom,oe(s);let V=await It(s,d);return V&&ae(s),V}function at(){let s=c,d=[0,0,0];if(i.autoCenter){let S=[];for(let T of h)!T.disposed&&!T.excludeFromAutoCenter&&S.push(...T.polygons);if(S.length>0){let T=Ll(S);d=[(T.min[0]+T.max[0])/2,(T.min[1]+T.max[1])/2,(T.min[2]+T.max[2])/2]}}s[0]===d[0]&&s[1]===d[1]&&s[2]===d[2]||(c=d,O(f,i))}function ro(s,d={}){let T=(f.ownerDocument??document).createElement("div");T.className="polycss-mesh",d.id&&T.setAttribute("data-poly-mesh-id",d.id);let I={...d},V=d.merge!==!1,F=!!d.stableDom,q=0,Y=Nr(I);Y&&(T.style.transform=Y);let B=(L,D)=>s.voxelSource||!D?L:Ol(L,{meshResolution:d.meshResolution}),ee=B(s.polygons,V);function j(L){if(L.length===0){T.style.removeProperty("--origin");return}let D=1/0,Z=1/0,re=1/0,pe=-1/0,X=-1/0,Q=-1/0;for(let de of L)for(let fe of de.vertices)fe[0]<D&&(D=fe[0]),fe[0]>pe&&(pe=fe[0]),fe[1]<Z&&(Z=fe[1]),fe[1]>X&&(X=fe[1]),fe[2]<re&&(re=fe[2]),fe[2]>Q&&(Q=fe[2]);if(!Number.isFinite(D)){T.style.removeProperty("--origin");return}let ye=(Z+X)/2*We,be=(D+pe)/2*We,ue=(re+Q)/2*We;T.style.setProperty("--origin",`${ye}px ${be}px ${ue}px`)}j(ee),f.appendChild(T);let b={handle:void 0,wrapper:T,parseResult:s,rendered:[],renderedByPolygonIndex:[],shadowRendered:[],polygons:ee,voxelSource:s.voxelSource,disposed:!1,stableDom:F,hasBuckets:!1,skipBucketNormalCleanupOnce:!1,excludeFromAutoCenter:!!d.excludeFromAutoCenter,castShadow:!!d.castShadow,receiveShadow:!!d.receiveShadow,cameraCullGroups:[],cameraCullSignature:"",lightOverrideSignature:"clear",stableTriangleColorFrame:0,bakedRotation:d.rotation?[...d.rotation]:[0,0,0]},J=null,Ce=0,Te=-1,Pe=null;function me(){J=null,Pe=null,Te=-1}function W(){let L=J;if(!L||L.polygonCount!==b.polygons.length)return b.polygons;if(Pe&&Te===Ce)return Pe;let D=L.vertices,Z=new Array(L.polygonCount);for(let re=0;re<L.polygonCount;re++){let pe=b.polygons[re],X=re*9;Z[re]={...pe,color:L.colors?.[re]??pe.color,vertices:[[D[X],D[X+1],D[X+2]],[D[X+3],D[X+4],D[X+5]],[D[X+6],D[X+7],D[X+8]]]}}return Pe=Z,Te=Ce,Z}function ce(L,D){let Z=L?.stableTriangleUpdateMode==="color-only";b.stableTriangleColorFrame++;let re=b.stableDom&&!D;if(re||j(b.polygons),b.stableDom&&!b.hasBuckets){let pe={doc:a,directionalLight:i.directionalLight,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed},X=b.rendered.length===b.polygons.length&&b.rendered.every(ue=>ue.kind==="triangle"),Q=b.stableDom&&!D,ye=X||Q?{}:wt(b.polygons,pe);X||ht(b.wrapper,ye);let be={...pe,solidPaintDefaults:ye,optimizeStableTriangleStyle:!0,stableTriangleDebug:L?.stableTriangleDebug,stableTriangleUpdateMode:L?.stableTriangleUpdateMode,stableTriangleColorPolicy:L?.stableTriangleColorPolicy,stableTriangleColorSteps:L?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:L?.stableTriangleColorFreezeFrames,stableTriangleColorBudget:L?.stableTriangleColorBudget,stableTriangleColorMaxAge:L?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:L?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:L?.stableTriangleMatrixDecimals,stableTriangleColorFrame:b.stableTriangleColorFrame};if(xn(b.rendered,b.polygons,be))return Z||(oe(b),_e(b,!0),D&&at()),!0}return re&&j(b.polygons),!1}let te={get polygons(){return W()},set polygons(L){me(),b.polygons=L},element:T,id:d.id,get transform(){return I},remove(){q++,T.parentNode&&T.parentNode.removeChild(T),ie(b),h.delete(b),H(b),K(b),at(),$e()},setPolygons(L,D){q++,V=D?.merge??V,F=D?.stableDom??F,b.stableDom=F,b.voxelSource=void 0,b.polygons=B(L,V),K(b),H(b),me(),te.polygons=b.polygons;let Z=D?.recomputeAutoCenter??!0;ce(D,Z)||(Ie(b),Z&&at())},[zl](L,D){let Z=D?.merge??V,re=D?.stableDom??F;if(!L.solidTriangles||!re||Z||d.meshResolution!==void 0||b.hasBuckets||L.polygonCount!==b.polygons.length||L.vertices.length<L.polygonCount*9||b.rendered.length!==L.polygonCount)return!1;for(let Q=0;Q<b.rendered.length;Q++){let ye=b.rendered[Q],be=b.polygons[Q];if(ye?.kind!=="triangle"||ye.polygonIndex!==Q||!be||be.vertices.length!==3||be.texture||be.material?.texture)return!1}let pe=D?.recomputeAutoCenter??!0;if(!pe){let Q=b.stableTriangleColorFrame+1,ye={doc:a,directionalLight:i.directionalLight,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,solidPaintDefaults:{},optimizeStableTriangleStyle:!0,stableTriangleDebug:D?.stableTriangleDebug,stableTriangleUpdateMode:D?.stableTriangleUpdateMode,stableTriangleColorPolicy:D?.stableTriangleColorPolicy,stableTriangleColorSteps:D?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:D?.stableTriangleColorFreezeFrames??0,stableTriangleColorBudget:D?.stableTriangleColorBudget,stableTriangleColorMaxAge:D?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:D?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:D?.stableTriangleMatrixDecimals,stableTriangleColorFrame:Q};if(vn(b.rendered,b.polygons,L,ye))return q++,V=Z,F=re,b.stableDom=F,b.voxelSource=void 0,b.stableTriangleColorFrame=Q,J=L,Ce++,Pe=null,Te=-1,Ee(b)?(oe(b),_e(b,!0)):De(b),!0}q++,V=Z,F=re,b.stableDom=F,b.voxelSource=void 0;let X=L.vertices;for(let Q=0;Q<L.polygonCount;Q++){let ye=b.polygons[Q],be=L.colors?.[Q];be&&(ye.color=be);let ue=ye.vertices,de=Q*9;ue[0][0]=X[de],ue[0][1]=X[de+1],ue[0][2]=X[de+2],ue[1][0]=X[de+3],ue[1][1]=X[de+4],ue[1][2]=X[de+5],ue[2][0]=X[de+6],ue[2][1]=X[de+7],ue[2][2]=X[de+8]}return me(),te.polygons=b.polygons,ce(D,pe)},updatePolygon(L,D){let Z=typeof L=="number"?L:b.polygons.indexOf(L);if(Z<0&&typeof L!="number"&&J&&(Z=W().indexOf(L)),Z<0||Z>=b.polygons.length)return;me(),b.voxelSource=void 0,Object.assign(b.polygons[Z],D);let re=Object.keys(D);ge(b,Z,re)||Ie(b)},async setPolygonsChunked(L,D){let Z=++q;V=D?.merge??V,F=D?.stableDom??F,b.stableDom=F,b.voxelSource=void 0,b.polygons=B(L,V),me(),te.polygons=b.polygons,j(b.polygons);let re=D?.recomputeAutoCenter??!0;if(!await oo(b,()=>b.disposed||Z!==q)){ie(b);return}re&&at()},setTransform(L){let D=b.castShadow,Z=b.receiveShadow;L.castShadow!==void 0&&(b.castShadow=!!L.castShadow),L.receiveShadow!==void 0&&(b.receiveShadow=!!L.receiveShadow),I={...I,...L};let re=Nr(I);T.style.transform=re??"",lt(b,I.rotation),L.rotation!==void 0&&_e(b,!0),b.castShadow!==D&&(ae(b),$e()),b.receiveShadow!==Z&&we(),L.position!==void 0&&($e(),we())},dispose(){if(!b.disposed){b.disposed=!0,q++,T.parentNode&&T.parentNode.removeChild(T),ie(b);try{s.dispose()}catch{}h.delete(b),at(),$e()}},rebakeAtlas(){b.bakedRotation=I.rotation?[...I.rotation]:[0,0,0];let L=i.directionalLight?.direction??[.4,-.7,.59],D=Ir(L,b.bakedRotation);Ie(b,D)},getPosition(){return I.position},getRotation(){return I.rotation},getScale(){return I.scale},getPolygons(){return te.polygons}};return b.handle=te,h.add(b),Ie(b),lt(b,I.rotation),at(),$e(),b.receiveShadow&&we(),te}function io(s){let d=!!i.autoCenter,S=i.strategies,T=i.seamBleed,I=i.textureLighting,V=i.directionalLight?.direction,F=i.shadow,q=zr(s);i={...i,...q},O(f,i);let Y=!!i.autoCenter;for(let me of h)lt(me,me.handle.transform.rotation);let B=s.strategies!==void 0&&!Nl(s.strategies,S),ee=Object.prototype.hasOwnProperty.call(s,"seamBleed")&&q.seamBleed!==T;if(B||ee)for(let me of h)Ie(me);d!==Y&&at();let j=s.textureLighting!==void 0&&I!==i.textureLighting,b=i.directionalLight?.direction,J=s.directionalLight!==void 0&&!Ul(V,b),Ce=i.shadow,Te=s.shadow!==void 0&&!$l(F,Ce),Pe=J||Te;if(j){for(let me of h)!B&&!ee&&(me.voxelSource||me.voxelRenderer)&&Ie(me);$e(),we()}else Pe&&we();Te&&s.shadow?.lift!==F?.lift&&$e()}function sn(){return i}function ln(){$(f);for(let s of h)_e(s)}function hi(){let s=[];for(let d of h)s.push(d.handle);return s}function yi(s){let d=s;for(;d;){if(d instanceof HTMLElement&&d.classList.contains("polycss-mesh")){for(let S of h)if(S.wrapper===d)return S.handle;return null}d=d.parentElement}return null}function bi(){let s=Array.from(h);for(let d of s)try{d.handle.dispose()}catch{}m.parentNode&&m.parentNode.removeChild(m)}return{add:ro,setOptions:io,destroy:bi,host:e,camera:t,cameraEl:m,applyCamera:ln,getOptions:sn,meshes:hi,findMeshByElement:yi}}import{createIsometricCamera as jr}from"@layoutit/polycss-core";var Zl=8e3;function en(e={}){let n={};e.zoom!==void 0&&(n.zoom=e.zoom),e.target!==void 0&&(n.target=e.target),e.rotX!==void 0&&(n.rotX=e.rotX),e.rotY!==void 0&&(n.rotY=e.rotY),e.distance!==void 0&&(n.distance=e.distance);let t=jr(n),o=`${e.perspective??Zl}px`;return{get state(){return t.state},update(r){t.update(r)},getStyle(r){return t.getStyle(r)},type:"perspective",perspectiveStyle:o}}function tn(e={}){let n={};e.zoom!==void 0&&(n.zoom=e.zoom),e.target!==void 0&&(n.target=e.target),e.rotX!==void 0&&(n.rotX=e.rotX),e.rotY!==void 0&&(n.rotY=e.rotY),e.distance!==void 0&&(n.distance=e.distance);let t=jr(n);return{get state(){return t.state},update(o){t.update(o)},getStyle(o){return t.getStyle(o)},type:"orthographic",perspectiveStyle:"none"}}var Ql=typeof HTMLElement<"u"?HTMLElement:class{},ql=["perspective","rot-x","rot-y","zoom","directional-direction","directional-color","directional-intensity","ambient-color","ambient-intensity","texture-lighting","texture-quality","auto-center"];function Ke(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function Kl(e){return e==="false"?!1:Ke(e)}function Ro(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Jl(e){if(e==="baked"||e==="dynamic")return e}function ea(e){return e==="auto"?"auto":Ke(e)}function ta(e){return typeof e.getCamera=="function"}var je=class extends Ql{constructor(){super(...arguments);this._scene=null;this._implicitCamera=null}static get observedAttributes(){return[...ql]}getScene(){return this._scene}_findAncestorCamera(){let t=this.parentElement;for(;t;){if(ta(t)){let o=t.getCamera();if(o)return o}t=t.parentElement}return null}_buildImplicitCamera(){let t=Kl(this.getAttribute("perspective")),o=Ke(this.getAttribute("rot-x")),r=Ke(this.getAttribute("rot-y")),i=Ke(this.getAttribute("zoom")),l=Ke(this.getAttribute("distance")),c=Ro(this.getAttribute("target")),a={...o!==void 0?{rotX:o}:{},...r!==void 0?{rotY:r}:{},...i!==void 0?{zoom:i}:{},...l!==void 0?{distance:l}:{},...c!==void 0?{target:c}:{}};return t===!1?tn(a):t!==void 0?en({...a,perspective:t}):tn(a)}_readNonCameraOptions(){let t=this._readDirectionalLight(),o=this._readAmbientLight(),r={};r.textureLighting=Jl(this.getAttribute("texture-lighting"))??"baked";let i=ea(this.getAttribute("texture-quality"));return i!==void 0&&(r.textureQuality=i),r.autoCenter=this.hasAttribute("auto-center"),t&&(r.directionalLight=t),o&&(r.ambientLight=o),r}_readDirectionalLight(){let t=Ro(this.getAttribute("directional-direction")),o=this.getAttribute("directional-color")||void 0,r=Ke(this.getAttribute("directional-intensity"));if(!t&&!o&&r===void 0)return;let i={direction:t??[.4,-.7,.59]};return o&&(i.color=o),r!==void 0&&(i.intensity=r),i}_readAmbientLight(){let t=this.getAttribute("ambient-color")||void 0,o=Ke(this.getAttribute("ambient-intensity"));if(!t&&o===void 0)return;let r={};return t&&(r.color=t),o!==void 0&&(r.intensity=o),r}connectedCallback(){if(this._scene)return;let t=this._findAncestorCamera(),o;t?(o=t,this._implicitCamera=null):(this._implicitCamera=this._buildImplicitCamera(),o=this._implicitCamera),this._scene=Yr(this,{camera:o,...this._readNonCameraOptions()}),this.dispatchEvent(new CustomEvent("polycss:scene-ready",{bubbles:!1}))}disconnectedCallback(){this._scene&&(this._scene.destroy(),this._scene=null),this._implicitCamera=null}attributeChangedCallback(t,o,r){if(o!==r&&this._scene){if(this._implicitCamera&&["rot-x","rot-y","zoom","distance","target"].includes(t)){let l=Ke(this.getAttribute("rot-x")),c=Ke(this.getAttribute("rot-y")),a=Ke(this.getAttribute("zoom")),m=Ke(this.getAttribute("distance")),f=Ro(this.getAttribute("target"));l!==void 0&&this._implicitCamera.update({rotX:l}),c!==void 0&&this._implicitCamera.update({rotY:c}),a!==void 0&&this._implicitCamera.update({zoom:a}),m!==void 0&&this._implicitCamera.update({distance:m}),f!==void 0&&this._implicitCamera.update({target:f}),this._scene.applyCamera();return}this._scene.setOptions(this._readNonCameraOptions())}}};import{computeSceneBbox as na,loadMesh as oa}from"@layoutit/polycss-core";var ra=typeof HTMLElement<"u"?HTMLElement:class{},ia=["src","mtl","mesh-resolution","position","scale","rotation","auto-center"];function nn(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Xr(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return nn(e)}}function sa(e){return e.closest("poly-scene")??null}function la(e){if(e.length===0)return e;let n=na(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,r=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&r===0)return e;let i=l=>[l[0]-t,l[1]-o,l[2]-r];return e.map(l=>({...l,vertices:l.vertices.map(i),...l.textureTriangles?.length?{textureTriangles:l.textureTriangles.map(c=>({...c,vertices:c.vertices.map(i)}))}:null}))}var _t=class extends ra{constructor(){super(...arguments);this._handle=null;this._parseResult=null;this._loadToken=0}static get observedAttributes(){return[...ia]}getMeshHandle(){return this._handle}connectedCallback(){this._maybeLoad()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){if(o!==r){if(t==="src"||t==="mtl"||t==="mesh-resolution"){this._tearDown(),this._maybeLoad();return}this._handle&&this._handle.setTransform({position:nn(this.getAttribute("position")),scale:Xr(this.getAttribute("scale")),rotation:nn(this.getAttribute("rotation"))})}}_tearDown(){if(this._loadToken+=1,this._handle){try{this._handle.dispose()}catch{}this._handle=null}this._parseResult=null}async _maybeLoad(){let t=this.getAttribute("src");if(!t)return;let o=sa(this);if(!o)return;let r=++this._loadToken,i=this.getAttribute("mtl")||void 0,c=this.getAttribute("mesh-resolution")==="lossless"?"lossless":void 0,a;try{let h=i||c!==void 0?{...i?{mtlUrl:i}:{},...c!==void 0?{meshResolution:c}:{}}:void 0;a=await oa(t,h)}catch(h){this.dispatchEvent(new CustomEvent("polycss:error",{detail:h,bubbles:!0}));return}if(r!==this._loadToken){try{a.dispose()}catch{}return}let m=o.getScene();if(!m){try{a.dispose()}catch{}return}this.hasAttribute("auto-center")&&(a={...a,polygons:la(a.polygons)}),this._parseResult=a,this._handle=m.add(a,{position:nn(this.getAttribute("position")),scale:Xr(this.getAttribute("scale")),rotation:nn(this.getAttribute("rotation"))}),this.dispatchEvent(new CustomEvent("polycss:loaded",{detail:{polygons:this._handle.polygons},bubbles:!0}))}};var aa=typeof HTMLElement<"u"?HTMLElement:class{},ca=["vertices","color","texture","uvs","position","scale","rotation"];function Wr(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Do(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function ua(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Do(e)}}function da(e){return e.closest("poly-scene")??null}var Pn=class extends aa{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...ca]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){o!==r&&(this._tearDown(),this.isConnected&&this._mount())}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=da(this);if(!t)return;let o=t.getScene();if(!o)return;let r=Wr(this.getAttribute("vertices"));if(!r||!Array.isArray(r)||r.length<3)return;let i=this.getAttribute("color")||void 0,l=this.getAttribute("texture")||void 0,c=Wr(this.getAttribute("uvs"))??void 0,a={};for(let h of Array.from(this.attributes))h.name.startsWith("data-")&&(a[h.name.slice(5)]=h.value);let f={polygons:[{vertices:r,...i!==void 0?{color:i}:{},...l!==void 0?{texture:l}:{},...c!==void 0?{uvs:c}:{},...Object.keys(a).length>0?{data:a}:{}}],objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(f,{position:Do(this.getAttribute("position")),scale:ua(this.getAttribute("scale")),rotation:Do(this.getAttribute("rotation"))})}};import{axesHelperPolygons as ma}from"@layoutit/polycss-core";var pa=typeof HTMLElement<"u"?HTMLElement:class{},fa=["size","thickness","negative","x-color","y-color","z-color"];function ga(e){return e.closest("poly-scene")??null}function Zr(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}var Sn=class extends pa{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...fa]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){o!==r&&this._handle&&this._remount()}_polygons(){return ma({size:Zr(this.getAttribute("size")),thickness:Zr(this.getAttribute("thickness")),negative:this.hasAttribute("negative"),xColor:this.getAttribute("x-color")??void 0,yColor:this.getAttribute("y-color")??void 0,zColor:this.getAttribute("z-color")??void 0})}_mount(){let t=ga(this);if(!t)return;let o=t.getScene();if(!o)return;let r={polygons:this._polygons(),objectUrls:[],dispose:()=>{},warnings:[]};this._handle=o.add(r,{excludeFromAutoCenter:!0,merge:!1})}_remount(){this._tearDown(),this._mount()}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}};import{octahedronPolygons as ha}from"@layoutit/polycss-core";var ya=typeof HTMLElement<"u"?HTMLElement:class{},ba=["direction","target","distance","size","color"],ko=50,va=5,xa=.35,Pa="#ffd54a";function Sa(e){return e.closest("poly-scene")??null}function Qr(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function qr(e,n){if(e==null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}var Cn=class extends ya{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...ba]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){if(o!==r&&this._handle){if(t==="size"||t==="color"){this._remount();return}this._handle.setTransform({position:this._meshPosition()})}}_meshPosition(){let t=Qr(this.getAttribute("direction"));if(!t)return;let o=Qr(this.getAttribute("target"))??[0,0,0],r=qr(this.getAttribute("distance"),va),i=t[0],l=t[1],c=t[2],a=Math.hypot(i,l,c)||1,m=o[0]+l/a*r,f=o[1]+i/a*r,h=o[2]+c/a*r;return[f*ko,m*ko,h*ko]}_mount(){let t=Sa(this);if(!t)return;let o=t.getScene();if(!o)return;let r=qr(this.getAttribute("size"),xa),i=this.getAttribute("color")??Pa,l={polygons:ha({center:[0,0,0],size:r,color:i}),objectUrls:[],dispose:()=>{},warnings:[]};this._handle=o.add(l,{position:this._meshPosition(),excludeFromAutoCenter:!0,merge:!1})}_remount(){this._tearDown(),this._mount()}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}};import{BASE_TILE as Ca}from"@layoutit/polycss-core";var En={drag:!0,wheel:!0,dolly:!1,invert:!1,minZoom:.1,maxZoom:10,minDistance:0,maxDistance:1/0,animate:!1};function Rt(e,n){let t;return n.animate===!1?t=!1:n.animate?t={speed:n.animate.speed??.3,axis:n.animate.axis??"y",pauseOnInteraction:n.animate.pauseOnInteraction??!0}:t=e.animate,{drag:n.drag??e.drag,wheel:n.wheel??e.wheel,dolly:n.dolly??e.dolly,invert:n.invert??e.invert,minZoom:n.minZoom??e.minZoom,maxZoom:n.maxZoom??e.maxZoom,minDistance:n.minDistance??e.minDistance,maxDistance:n.maxDistance??e.maxDistance,animate:t}}function on(e){return e===!0?-1:e===!1?1:e}function Dt(){let e=[],n=[],t=[];function o(l){return l==="change"?e:l==="start"?n:t}function r(l){if(e.length===0)return;let c={type:"change",camera:l()},a=e.slice();for(let m of a)try{m(c)}catch(f){console.error("[polycss] controls 'change' listener threw:",f)}}function i(l,c){let a=l==="start"?n:t;if(a.length===0)return;let m={type:l,camera:c()},f=a.slice();for(let h of f)try{h(m)}catch(g){console.error(`[polycss] controls '${l}' listener threw:`,g)}}return{changeListeners:e,startListeners:n,endListeners:t,listenerArray:o,emitChange:r,emitInteraction:i}}function kt(e){return()=>{let n=e.camera.state,t=n.target??[0,0,0];return{rotX:n.rotX??0,rotY:n.rotY??0,zoom:n.zoom??1,target:[t[0],t[1],t[2]],distance:n.distance??0}}}function Tn(e,n,t,o,r,i){let l=!1,c=null;return{onWheel:f=>{let h=n();if(!h.wheel||t())return;f.preventDefault();let g=f.deltaMode===1?16:f.deltaMode===2?100:1,x=f.deltaY*g;f.ctrlKey?x*=10:x*=3;let y=e.camera.state;if(h.dolly){let P=y.distance??0,v=Math.max(h.minDistance,Math.min(h.maxDistance,P+x*.05));e.camera.update({distance:v})}else{let P=Math.exp(-x*513e-6),v=y.zoom??1,E=Math.max(h.minZoom,Math.min(h.maxZoom,v*P));e.camera.update({zoom:E})}e.applyCamera(),l||(l=!0,i("start",o)),r(o),c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,l=!1,i("end",o)},150)},teardown:()=>{c!==null&&(clearTimeout(c),c=null),l=!1}}}function An(e,n,t,o,r,i,l){let c=null,a=0,m=x=>{if(c===null||o())return;let y=t();if(!y.animate){c=null;return}if(r())a=x;else{let P=Math.min(50,a?x-a:16.67);a=x;let v=y.animate.speed*(P/16.67),E=n.camera.state;if(y.animate.axis==="x"){let H=(((E.rotX??65)+v)%360+360)%360;n.camera.update({rotX:H})}else{let H=(((E.rotY??45)+v)%360+360)%360;n.camera.update({rotY:H})}n.applyCamera(),l(i)}c=e.requestAnimationFrame(m)};return{start:()=>{c!==null||!t().animate||o()||(a=0,c=e.requestAnimationFrame(m))},stop:()=>{c!==null&&(e.cancelAnimationFrame(c),c=null)},isRunning:()=>c!==null}}function Kr(e,n={}){let t=Rt(En,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,i=null,l={x:0,y:0},c=!1,a=!1,m=Dt(),f=kt(e),{changeListeners:h,startListeners:g,endListeners:x,listenerArray:y,emitChange:P,emitInteraction:v}=m,E=An(r,e,()=>t,()=>a,()=>c,f,P),H=C=>{if(!(!t.drag||a)&&i===null&&C.isPrimary!==!1){C.preventDefault(),i=C.pointerId,l={x:C.clientX,y:C.clientY},o.style.cursor="grabbing";try{C.target.setPointerCapture(C.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),v("start",f)}},k=C=>{if(i===null||C.pointerId!==i||!t.drag||a)return;C.preventDefault();let A=C.clientX-l.x,w=C.clientY-l.y;l={x:C.clientX,y:C.clientY};let M=on(t.invert),se=A/4*M,he=w/4*M,_=e.camera.state;if(C.shiftKey){let ne=_.rotX??65,oe=_.rotY??45,Se=Math.max(.01,_.zoom??1),Ee=Math.cos(ne*Math.PI/180),De=Ee>=0?Math.max(.1,Ee):Math.min(-.1,Ee),Ve=Math.cos(oe*Math.PI/180),_e=Math.sin(oe*Math.PI/180),ze=Se*Ca,Je=(A*_e-w*Ve/De)/ze,Ue=-(A*Ve+w*_e/De)/ze,Xe=_.target??[0,0,0];e.camera.update({target:[Xe[0]+Je,Xe[1]+Ue,Xe[2]]})}else{let ne=Math.max(0,Math.min(100,(_.rotX??65)-he)),oe=(((_.rotY??45)-se)%360+360)%360;e.camera.update({rotX:ne,rotY:oe})}e.applyCamera(),P(f)},N=C=>{if(i===C.pointerId){i=null,o.style.cursor=t.drag&&!a?"grab":"";try{C.target.releasePointerCapture(C.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),v("end",f)}},R=Tn(e,()=>t,()=>a,f,P,v);function K(){o.addEventListener("pointerdown",H),o.addEventListener("pointermove",k),o.addEventListener("pointerup",N),o.addEventListener("pointercancel",N),o.addEventListener("wheel",R.onWheel,{passive:!1}),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function z(){o.removeEventListener("pointerdown",H),o.removeEventListener("pointermove",k),o.removeEventListener("pointerup",N),o.removeEventListener("pointercancel",N),o.removeEventListener("wheel",R.onWheel),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",R.teardown()}K(),E.start();function O(C){let A=!!t.animate;t=Rt(t,C),!a&&i===null&&(o.style.cursor=t.drag?"grab":"");let w=!!t.animate;A&&!w?E.stop():!A&&w&&E.start()}function $(){a&&(a=!1,K(),E.start())}function U(){a||(a=!0,z(),E.stop(),i=null,c=!1,R.teardown())}function ie(){U(),h.length=0,g.length=0,x.length=0}function xe(C,A){let w=y(C);w.includes(A)||w.push(A)}function u(C,A){let w=y(C),M=w.indexOf(A);M>=0&&w.splice(M,1)}function p(C,A){return y(C).includes(A)}return{update:O,resume:$,pause:U,destroy:ie,addEventListener:xe,removeEventListener:u,hasEventListener:p}}function le(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function Mn(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Ne(e){if(e!==null)return!(e==="false"||e==="0")}function wn(e){if(e===null)return;if(e==="true")return!0;if(e==="false")return!1;let n=parseFloat(e);return Number.isFinite(n)?n:!0}function Ln(e){if(e==="x"||e==="y")return e}var Ea=typeof HTMLElement<"u"?HTMLElement:class{},Ta=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],_n=class extends Ea{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Ta]}_readAnimate(){let t=le(this.getAttribute("animate-speed")),o=Ln(this.getAttribute("animate-axis")),r=this.getAttribute("animate-pause-on-interaction");if(this.hasAttribute("animate-speed")||this.hasAttribute("animate-axis")||this.hasAttribute("animate-pause-on-interaction"))return{...t!==void 0?{speed:t}:{},...o!==void 0?{axis:o}:{},...r!==null?{pauseOnInteraction:Ne(r)}:{}}}_readOptions(){let t={},o=Ne(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Ne(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let i=le(this.getAttribute("min-distance"));i!==void 0&&(t.minDistance=i);let l=le(this.getAttribute("max-distance"));l!==void 0&&(t.maxDistance=l);let c=wn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let a=le(this.getAttribute("zoom-min")),m=le(this.getAttribute("zoom-max"));return a!==void 0&&(t.minZoom=a),m!==void 0&&(t.maxZoom=m),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof je)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=Kr(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};import{BASE_TILE as Aa}from"@layoutit/polycss-core";function Jr(e,n={}){let t=Rt(En,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,i=null,l={x:0,y:0},c=!1,a=!1,m=!1,f={x:0,y:0},h=Dt(),g=kt(e),{changeListeners:x,startListeners:y,endListeners:P,listenerArray:v,emitChange:E,emitInteraction:H}=h,k=An(r,e,()=>t,()=>a,()=>c,g,E),N=_=>{if(!(!t.drag||a)&&i===null&&_.isPrimary!==!1){_.preventDefault(),i=_.pointerId,l={x:_.clientX,y:_.clientY},o.style.cursor="grabbing";try{_.target.setPointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),H("start",g)}},R=_=>{if(i===null||_.pointerId!==i||!t.drag||a)return;_.preventDefault();let ne=_.clientX-l.x,oe=_.clientY-l.y;l={x:_.clientX,y:_.clientY};let Se=e.camera.state;if(_.shiftKey){let Ee=on(t.invert),De=ne/4*Ee,Ve=oe/4*Ee,_e=Math.max(0,Math.min(100,(Se.rotX??65)-Ve)),ze=(((Se.rotY??45)-De)%360+360)%360;e.camera.update({rotX:_e,rotY:ze})}else{let Ee=Se.rotX??65,De=Se.rotY??45,Ve=Math.max(.01,Se.zoom??1),_e=Math.cos(Ee*Math.PI/180),ze=_e>=0?Math.max(.1,_e):Math.min(-.1,_e),Je=Math.cos(De*Math.PI/180),Ue=Math.sin(De*Math.PI/180),Xe=Ve*Aa,Ht=(ne*Ue-oe*Je/ze)/Xe,It=-(ne*Je+oe*Ue/ze)/Xe,lt=Se.target??[0,0,0];e.camera.update({target:[lt[0]+Ht,lt[1]+It,lt[2]]})}e.applyCamera(),E(g)},K=_=>{if(i===_.pointerId){i=null,o.style.cursor=t.drag&&!a?"grab":"";try{_.target.releasePointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),H("end",g)}},z=_=>{_.preventDefault()},O=_=>{_.button===2&&(m=!0,f={x:_.clientX,y:_.clientY},t.animate&&t.animate.pauseOnInteraction&&(c=!0),H("start",g))},$=_=>{if(!m||!t.drag)return;let ne=_.clientX-f.x,oe=_.clientY-f.y;f={x:_.clientX,y:_.clientY};let Se=on(t.invert),Ee=ne/4*Se,De=oe/4*Se,Ve=e.camera.state,_e=Math.max(0,Math.min(100,(Ve.rotX??65)-De)),ze=(((Ve.rotY??45)-Ee)%360+360)%360;e.camera.update({rotX:_e,rotY:ze}),e.applyCamera(),E(g)},U=_=>{_.button===2&&m&&(m=!1,H("end",g))},ie=Tn(e,()=>t,()=>a,g,E,H);function xe(){o.addEventListener("pointerdown",N),o.addEventListener("pointermove",R),o.addEventListener("pointerup",K),o.addEventListener("pointercancel",K),o.addEventListener("wheel",ie.onWheel,{passive:!1}),o.addEventListener("contextmenu",z),o.addEventListener("mousedown",O),o.addEventListener("mousemove",$),o.addEventListener("mouseup",U),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function u(){o.removeEventListener("pointerdown",N),o.removeEventListener("pointermove",R),o.removeEventListener("pointerup",K),o.removeEventListener("pointercancel",K),o.removeEventListener("wheel",ie.onWheel),o.removeEventListener("contextmenu",z),o.removeEventListener("mousedown",O),o.removeEventListener("mousemove",$),o.removeEventListener("mouseup",U),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",ie.teardown()}xe(),k.start();function p(_){let ne=!!t.animate;t=Rt(t,_),!a&&i===null&&(o.style.cursor=t.drag?"grab":"");let oe=!!t.animate;ne&&!oe?k.stop():!ne&&oe&&k.start()}function C(){a&&(a=!1,xe(),k.start())}function A(){a||(a=!0,u(),k.stop(),i=null,c=!1,m=!1,ie.teardown())}function w(){A(),x.length=0,y.length=0,P.length=0}function M(_,ne){let oe=v(_);oe.includes(ne)||oe.push(ne)}function se(_,ne){let oe=v(_),Se=oe.indexOf(ne);Se>=0&&oe.splice(Se,1)}function he(_,ne){return v(_).includes(ne)}return{update:p,resume:C,pause:A,destroy:w,addEventListener:M,removeEventListener:se,hasEventListener:he}}var Ma=typeof HTMLElement<"u"?HTMLElement:class{},wa=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],Rn=class extends Ma{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...wa]}_readAnimate(){let t=le(this.getAttribute("animate-speed")),o=Ln(this.getAttribute("animate-axis")),r=this.getAttribute("animate-pause-on-interaction");if(this.hasAttribute("animate-speed")||this.hasAttribute("animate-axis")||this.hasAttribute("animate-pause-on-interaction"))return{...t!==void 0?{speed:t}:{},...o!==void 0?{axis:o}:{},...r!==null?{pauseOnInteraction:Ne(r)}:{}}}_readOptions(){let t={},o=Ne(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Ne(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let i=le(this.getAttribute("min-distance"));i!==void 0&&(t.minDistance=i);let l=le(this.getAttribute("max-distance"));l!==void 0&&(t.maxDistance=l);let c=wn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let a=le(this.getAttribute("zoom-min")),m=le(this.getAttribute("zoom-max"));return a!==void 0&&(t.minZoom=a),m!==void 0&&(t.maxZoom=m),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof je)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=Jr(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};import{BASE_TILE as La}from"@layoutit/polycss-core";var _a={enabled:!0,lookEnabled:!0,moveEnabled:!0,jumpEnabled:!0,crouchEnabled:!0,lookSensitivity:.15,invertY:!1,moveSpeed:5,jumpVelocity:7,gravity:18,eyeHeight:1.7,crouchHeight:1,groundZ:0,minPitch:5,maxPitch:175};function ei(e,n){return{enabled:n.enabled??e.enabled,lookEnabled:n.lookEnabled??e.lookEnabled,moveEnabled:n.moveEnabled??e.moveEnabled,jumpEnabled:n.jumpEnabled??e.jumpEnabled,crouchEnabled:n.crouchEnabled??e.crouchEnabled,lookSensitivity:n.lookSensitivity??e.lookSensitivity,invertY:n.invertY??e.invertY,moveSpeed:n.moveSpeed??e.moveSpeed,jumpVelocity:n.jumpVelocity??e.jumpVelocity,gravity:n.gravity??e.gravity,eyeHeight:n.eyeHeight??e.eyeHeight,crouchHeight:n.crouchHeight??e.crouchHeight,groundZ:n.groundZ??e.groundZ,minPitch:n.minPitch??e.minPitch,maxPitch:n.maxPitch??e.maxPitch}}var ti=new Set(["KeyW","ArrowUp"]),ni=new Set(["KeyS","ArrowDown"]),oi=new Set(["KeyA","ArrowLeft"]),ri=new Set(["KeyD","ArrowRight"]),ii=new Set(["Space"]),Oo=new Set(["ControlLeft","ControlRight"]);function si(e,n={}){let t=ei(_a,n),o=e.host,r=e.cameraEl,i=o.ownerDocument??document,l=i.defaultView??globalThis,c=Dt(),a=kt(e),{changeListeners:m,startListeners:f,endListeners:h,listenerArray:g,emitChange:x,emitInteraction:y}=c,P=new Set,v=!1,E=!1,H=0,k=0,N=!1,R=[0,0,t.groundZ+t.eyeHeight];function K(G,ge){let ae=G*Math.PI/180,we=ge*Math.PI/180;return[-Math.sin(ae)*Math.cos(we),-Math.sin(ae)*Math.sin(we),-Math.cos(ae)]}function z(){let G=e.camera.perspectiveStyle,ge=G==="none"?0:parseFloat(G);return(Number.isFinite(ge)&&ge>0?ge:2e3)/La}function O(){let G=e.camera.state,ge=K(G.rotX??90,G.rotY??0),ae=z();return[R[0]+ge[0]*ae,R[1]+ge[1]*ae,R[2]+ge[2]*ae]}function $(){let G=O();e.camera.update({target:G}),e.applyCamera()}function U(){let G=e.camera.state.target??[0,0,0];R=[G[0],G[1],t.groundZ+t.eyeHeight],$()}let ie=()=>{if(!(!t.enabled||!t.lookEnabled||E||v))try{o.requestPointerLock()}catch{}},xe=()=>{let G=i.pointerLockElement===o;G!==v&&(v=G,v?(N=!0,y("start",a)):N&&(N=!1,y("end",a)))},u=G=>{if(!v||!t.enabled||!t.lookEnabled||E)return;let ge=G.movementX??0,ae=G.movementY??0;if(ge===0&&ae===0)return;let we=e.camera.state,Vt=t.lookSensitivity,zt=t.invertY?-1:1,yt=(((we.rotY??0)-ge*Vt)%360+360)%360,ke=(we.rotX??90)-ae*Vt*zt;ke<t.minPitch?ke=t.minPitch:ke>t.maxPitch&&(ke=t.maxPitch);let Qe=K(ke,yt),Ie=z(),$e=[R[0]+Qe[0]*Ie,R[1]+Qe[1]*Ie,R[2]+Qe[2]*Ie];e.camera.update({rotX:ke,rotY:yt,target:$e}),e.applyCamera(),x(a)},p=G=>ti.has(G)||ni.has(G)||oi.has(G)||ri.has(G)||ii.has(G)||Oo.has(G),C=G=>{if(!(!t.enabled||E)&&p(G.code)&&!(!v&&!t.moveEnabled)){if(ii.has(G.code)){if(!t.jumpEnabled)return;G.preventDefault(),!P.has(G.code)&&H===0&&k===0&&(H=t.jumpVelocity),P.add(G.code);return}Oo.has(G.code)&&!t.crouchEnabled||!t.moveEnabled&&!Oo.has(G.code)||(G.preventDefault(),P.add(G.code))}},A=G=>{p(G.code)&&P.delete(G.code)},w=()=>{P.clear()},M=null,se=0,he=.05,_=G=>{if(M===null||E)return;let ge=Math.min(he,se?(G-se)/1e3:.0167);if(se=G,t.enabled){let ae=!1,we=e.camera.state;if(t.moveEnabled){let ke=0,Qe=0;for(let Ie of P)ti.has(Ie)?ke+=1:ni.has(Ie)?ke-=1:ri.has(Ie)?Qe+=1:oi.has(Ie)&&(Qe-=1);if(ke!==0||Qe!==0){let $e=(we.rotY??0)*Math.PI/180,oo=-Math.cos($e),at=-Math.sin($e),ro=-Math.sin($e),io=Math.cos($e),sn=Math.hypot(ke,Qe)||1,ln=t.moveSpeed*ge;R[0]+=(oo*ke+ro*Qe)/sn*ln,R[1]+=(at*ke+io*Qe)/sn*ln,ae=!0}}let zt=t.crouchEnabled&&(P.has("ControlLeft")||P.has("ControlRight"))?t.crouchHeight:t.eyeHeight;t.jumpEnabled&&(H!==0||k>0)?(H-=t.gravity*ge,k+=H*ge,k<=0&&(k=0,H=0)):t.jumpEnabled||(k=0,H=0);let yt=t.groundZ+zt+k;if(Math.abs(R[2]-yt)>1e-4&&(R[2]=yt,ae=!0),ae){let ke=O();e.camera.update({target:ke}),e.applyCamera(),x(a)}}M=l.requestAnimationFrame(_)};function ne(){M!==null||E||(se=0,M=l.requestAnimationFrame(_))}function oe(){M!==null&&(l.cancelAnimationFrame(M),M=null)}function Se(){let ge=r.ownerDocument?.defaultView?.getComputedStyle(r).perspective??"",ae=parseFloat(ge),we=Number.isFinite(ae)&&ae>0?ae:2e3;r.style.setProperty("--polycss-fpv-perspective",`${we}px`),r.classList.add("polycss-fpv-host")}function Ee(){r.classList.remove("polycss-fpv-host"),r.style.removeProperty("--polycss-fpv-perspective")}function De(){o.addEventListener("click",ie),i.addEventListener("pointerlockchange",xe),i.addEventListener("mousemove",u),l.addEventListener("keydown",C),l.addEventListener("keyup",A),l.addEventListener("blur",w),o.style.cursor=t.lookEnabled?"crosshair":"",Se()}function Ve(){if(o.removeEventListener("click",ie),i.removeEventListener("pointerlockchange",xe),i.removeEventListener("mousemove",u),l.removeEventListener("keydown",C),l.removeEventListener("keyup",A),l.removeEventListener("blur",w),o.style.cursor="",P.clear(),v)try{i.exitPointerLock()}catch{}Ee()}U(),De(),ne();function _e(G){let ge=t.eyeHeight,ae=t.groundZ;t=ei(t,G),E||(o.style.cursor=t.lookEnabled?"crosshair":""),(t.eyeHeight!==ge||t.groundZ!==ae)&&(R[2]=t.groundZ+t.eyeHeight,$(),x(a))}function ze(){E&&(E=!1,De(),ne())}function Je(){E||(E=!0,Ve(),oe(),N&&(N=!1,y("end",a)))}function Ue(){Je(),m.length=0,f.length=0,h.length=0}function Xe(){if(!(!t.enabled||!t.lookEnabled||E))try{o.requestPointerLock()}catch{}}function Ht(){if(v)try{i.exitPointerLock()}catch{}}function It(){return v}function lt(G,ge){let ae=g(G);ae.includes(ge)||ae.push(ge)}function ht(G,ge){let ae=g(G),we=ae.indexOf(ge);we>=0&&ae.splice(we,1)}function eo(G,ge){return g(G).includes(ge)}function to(){return[R[0],R[1],R[2]]}function no(G){R[0]=G[0],R[1]=G[1],R[2]=G[2],$(),x(a)}return{update:_e,resume:ze,pause:Je,destroy:Ue,lock:Xe,unlock:Ht,isLocked:It,getOrigin:to,setOrigin:no,addEventListener:lt,removeEventListener:ht,hasEventListener:eo}}var Ra=typeof HTMLElement<"u"?HTMLElement:class{},Da=["enabled","look-enabled","move-enabled","jump-enabled","crouch-enabled","look-sensitivity","invert-y","move-speed","jump-velocity","gravity","eye-height","crouch-height","ground-z","min-pitch","max-pitch"],Dn=class extends Ra{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Da]}_readOptions(){let t={},o=Ne(this.getAttribute("enabled"));o!==void 0&&(t.enabled=o);let r=Ne(this.getAttribute("look-enabled"));r!==void 0&&(t.lookEnabled=r);let i=Ne(this.getAttribute("move-enabled"));i!==void 0&&(t.moveEnabled=i);let l=Ne(this.getAttribute("jump-enabled"));l!==void 0&&(t.jumpEnabled=l);let c=Ne(this.getAttribute("crouch-enabled"));c!==void 0&&(t.crouchEnabled=c);let a=le(this.getAttribute("look-sensitivity"));if(a!==void 0&&(t.lookSensitivity=a),this.hasAttribute("invert-y")){let E=Ne(this.getAttribute("invert-y"));E!==void 0&&(t.invertY=E)}let m=le(this.getAttribute("move-speed"));m!==void 0&&(t.moveSpeed=m);let f=le(this.getAttribute("jump-velocity"));f!==void 0&&(t.jumpVelocity=f);let h=le(this.getAttribute("gravity"));h!==void 0&&(t.gravity=h);let g=le(this.getAttribute("eye-height"));g!==void 0&&(t.eyeHeight=g);let x=le(this.getAttribute("crouch-height"));x!==void 0&&(t.crouchHeight=x);let y=le(this.getAttribute("ground-z"));y!==void 0&&(t.groundZ=y);let P=le(this.getAttribute("min-pitch"));P!==void 0&&(t.minPitch=P);let v=le(this.getAttribute("max-pitch"));return v!==void 0&&(t.maxPitch=v),t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof je)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=si(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};var ka=typeof HTMLElement<"u"?HTMLElement:class{},Oa=["perspective","zoom","rot-x","rot-y","target","distance"],kn=class extends ka{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...Oa]}getCamera(){return this._camera}_readOptions(){return{perspective:le(this.getAttribute("perspective")),zoom:le(this.getAttribute("zoom")),rotX:le(this.getAttribute("rot-x")),rotY:le(this.getAttribute("rot-y")),target:Mn(this.getAttribute("target")),distance:le(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=en(t),this._wrapper=this.ownerDocument.createElement("div"),this._wrapper.className="polycss-camera",this._wrapper.style.perspective=this._camera.perspectiveStyle;this.firstChild;)this._wrapper.appendChild(this.firstChild);this.appendChild(this._wrapper),this.dispatchEvent(new CustomEvent("polycss:camera-ready",{bubbles:!1}))}_teardown(){if(this._wrapper){for(;this._wrapper.firstChild;)this.insertBefore(this._wrapper.firstChild,this._wrapper);this._wrapper.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null}this._camera=null}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,r){if(o===r||!this._camera||!this._wrapper)return;let i=this._readOptions();this._camera=en(i),this._wrapper.style.perspective=this._camera.perspectiveStyle}};var Fa=typeof HTMLElement<"u"?HTMLElement:class{},Ha=["zoom","rot-x","rot-y","target","distance"],Ot=class extends Fa{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...Ha]}getCamera(){return this._camera}_readOptions(){return{zoom:le(this.getAttribute("zoom")),rotX:le(this.getAttribute("rot-x")),rotY:le(this.getAttribute("rot-y")),target:Mn(this.getAttribute("target")),distance:le(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=tn(t),this._wrapper=this.ownerDocument.createElement("div"),this._wrapper.className="polycss-camera",this._wrapper.style.perspective=this._camera.perspectiveStyle;this.firstChild;)this._wrapper.appendChild(this.firstChild);this.appendChild(this._wrapper),this.dispatchEvent(new CustomEvent("polycss:camera-ready",{bubbles:!1}))}_teardown(){if(this._wrapper){for(;this._wrapper.firstChild;)this.insertBefore(this._wrapper.firstChild,this._wrapper);this._wrapper.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null}this._camera=null}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,r){if(o===r||!this._camera)return;let i=this._readOptions();i.zoom!==void 0&&this._camera.update({zoom:i.zoom}),i.rotX!==void 0&&this._camera.update({rotX:i.rotX}),i.rotY!==void 0&&this._camera.update({rotY:i.rotY}),i.target!==void 0&&this._camera.update({target:i.target}),i.distance!==void 0&&this._camera.update({distance:i.distance})}};var On=class extends Ot{};import{arrowPolygons as Ia,eulerXYZFromQuat as Va,planePolygons as za,quatFromAxisAngle as Ba,quatFromEulerXYZ as Na,quatMultiply as Ua,ringQuadPolygons as $a}from"@layoutit/polycss-core";var Hn="#ff3653",In="#8adb00",Vn="#2c8fff",Ft=50,li=60,Ga=.6,Ya=.0125,ja=.15,Xa=.04,Wa=1,ai=.02,Fo=1.04,Za=.1,Qa=.25,mi=1e-4,qa=.6,Ka=.8,Ja=1,rn={0:1,1:0,2:2},ci=[{cssAxis:0,sign:1,key:"x",color:Hn},{cssAxis:0,sign:-1,key:"-x",color:Hn},{cssAxis:1,sign:1,key:"y",color:In},{cssAxis:1,sign:-1,key:"-y",color:In},{cssAxis:2,sign:1,key:"z",color:Vn},{cssAxis:2,sign:-1,key:"-z",color:Vn}],ui=[{cssAxis:0,key:"x",color:Hn},{cssAxis:1,key:"y",color:In},{cssAxis:2,key:"z",color:Vn}],di=[{perpAxis:2,axisA:0,axisB:1,key:"xy",color:Vn},{perpAxis:1,axisA:0,axisB:2,key:"xz",color:In},{perpAxis:0,axisA:1,axisB:2,key:"yz",color:Hn}];function Ho(e,n,t,o){let r=t*Math.PI/180,i=o*Math.PI/180,l=[0,0,0];l[e]=n;let c=l[0]*Math.cos(i)-l[1]*Math.sin(i),a=l[0]*Math.sin(i)+l[1]*Math.cos(i),m=l[2];return a*Math.sin(r)+m*Math.cos(r)<0}function ec(e,n){let t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return e;let o=parseInt(t[1],16),r=parseInt(t[2],16),i=parseInt(t[3],16);return`rgba(${o}, ${r}, ${i}, ${n})`}function zn(e,n){return!n||n<=0?e:Math.round(e/n)*n}function tc(e){if(e.length===0)return[0,0,0];let n=1/0,t=1/0,o=1/0,r=-1/0,i=-1/0,l=-1/0;for(let c of e)for(let a of c.vertices)a[0]<n&&(n=a[0]),a[0]>r&&(r=a[0]),a[1]<t&&(t=a[1]),a[1]>i&&(i=a[1]),a[2]<o&&(o=a[2]),a[2]>l&&(l=a[2]);return Number.isFinite(n)?[(t+i)/2*Ft,(n+r)/2*Ft,(o+l)/2*Ft]:[0,0,0]}function Io(e){if(e.length===0)return li;let n=1/0,t=1/0,o=1/0,r=-1/0,i=-1/0,l=-1/0;for(let a of e)for(let m of a.vertices)m[0]<n&&(n=m[0]),m[0]>r&&(r=m[0]),m[1]<t&&(t=m[1]),m[1]>i&&(i=m[1]),m[2]<o&&(o=m[2]),m[2]>l&&(l=m[2]);return Number.isFinite(n)?Math.max(r-n,i-t,l-o)*Ft*Ga:li}function Fn(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let r of o){let i=r.getBoundingClientRect();if(!(i.width<=0||i.height<=0)&&n>=i.left&&n<=i.right&&t>=i.top&&t<=i.bottom)return!0}return!1}function nc(e){let{cssAxis:n,sign:t,shaftLengthCss:o,wrapper:r,target:i,startClientX:l,startClientY:c,translationSnap:a,onAxisDelta:m,onMouseDown:f,onMouseUp:h,onDraggingChanged:g}=e,x=o,y=[0,0,0];y[n]=t;let P=r.ownerDocument.createElement("div");P.style.position="absolute",P.style.left="0",P.style.top="0",P.style.width="0",P.style.height="0",P.style.transform=`translate3d(${y[0]*x}px, ${y[1]*x}px, ${y[2]*x}px)`,r.appendChild(P);let v=r.getBoundingClientRect(),E=P.getBoundingClientRect();r.removeChild(P);let H=(E.left-v.left)/x,k=(E.top-v.top)/x,N=H*H+k*k;if(N<mi)return;f?.(),g?.(!0);let R=z=>{let O=z.clientX-l,$=z.clientY-c,U=(O*H+$*k)/N;U=zn(U,a),m(U,y)},K=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",K),window.removeEventListener("pointercancel",K);let z=O=>{O.stopPropagation(),O.stopImmediatePropagation()};window.addEventListener("click",z,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",z,!0),0),h?.(),g?.(!1)};window.addEventListener("pointermove",R),window.addEventListener("pointerup",K),window.addEventListener("pointercancel",K)}function oc(e){let{axisA:n,axisB:t,probeDistanceCss:o,wrapper:r,startClientX:i,startClientY:l,translationSnap:c,onPlaneDelta:a,onMouseDown:m,onMouseUp:f,onDraggingChanged:h}=e,g=[0,0,0];g[n]=1;let x=[0,0,0];x[t]=1;function y(N){let R=r.ownerDocument.createElement("div");R.style.position="absolute",R.style.left="0",R.style.top="0",R.style.width="0",R.style.height="0",R.style.transform=`translate3d(${N[0]*o}px, ${N[1]*o}px, ${N[2]*o}px)`,r.appendChild(R);let K=r.getBoundingClientRect(),z=R.getBoundingClientRect();return r.removeChild(R),{x:(z.left-K.left)/o,y:(z.top-K.top)/o}}let P=y(g),v=y(x),E=P.x*v.y-v.x*P.y;if(Math.abs(E)<mi)return;m?.(),h?.(!0);let H=N=>{let R=N.clientX-i,K=N.clientY-l,z=(v.y*R-v.x*K)/E,O=(-P.y*R+P.x*K)/E;z=zn(z,c),O=zn(O,c),a(z,O,g,x)},k=()=>{window.removeEventListener("pointermove",H),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k);let N=R=>{R.stopPropagation(),R.stopImmediatePropagation()};window.addEventListener("click",N,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",N,!0),0),f?.(),h?.(!1)};window.addEventListener("pointermove",H),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k)}function rc(e){let{cssAxis:n,wrapper:t,target:o,startClientX:r,startClientY:i,rotationSnap:l,onAngleDelta:c,onMouseDown:a,onMouseUp:m,onDraggingChanged:f}=e,h=t.getBoundingClientRect(),g=h.left,x=h.top,y=Math.atan2(i-x,r-g),P=0;a?.(),f?.(!0);let v=H=>{let k=Math.atan2(H.clientY-x,H.clientX-g),N=k-y;N>Math.PI?N-=2*Math.PI:N<-Math.PI&&(N+=2*Math.PI),P+=N,y=k;let R=P*180/Math.PI;R=zn(R,l),c(R)},E=()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",E),window.removeEventListener("pointercancel",E);let H=k=>{k.stopPropagation(),k.stopImmediatePropagation()};window.addEventListener("click",H,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",H,!0),0),m?.(),f?.(!1)};window.addEventListener("pointermove",v),window.addEventListener("pointerup",E),window.addEventListener("pointercancel",E)}function pi(e,n={}){let t=null,o=n.mode??"translate",r=n.size??1,i={...n},l=new Map,c=null,a=null,m=[0,0,0];function f(){if(!t)return[0,0,0];let u=t.transform.position??[0,0,0];return[u[0]+m[0],u[1]+m[1],u[2]+m[2]]}function h(u){return a===u?Ja:c===u?Ka:qa}function g(){for(let[u,p]of l){let C=x(p.spec,h(u));p.handle.setPolygons(C,{recomputeAutoCenter:!1})}}function x(u,p){let A=Io(t?.polygons??[])*r,w=A/Ft,M=ec(u.color,p);if(u.kind==="arrow"){let _=e.camera.state,ne=Ho(u.cssAxis,u.sign,_.rotX??65,_.rotY??45);return Ia({axis:rn[u.cssAxis],sign:u.sign,shaftLength:w,shaftHalfThickness:w*Ya,headLength:w*ja,headHalfThickness:w*Xa,color:M,shaft:!ne})}if(u.kind==="plane"){let _=e.camera.state,ne=_.rotX??65,oe=_.rotY??45,Se=rn[u.perpAxis],Ee=(Se+1)%3,De=(Se+2)%3,Ve=rn[Ee],_e=rn[De],ze=Ho(Ve,1,ne,oe)?-1:1,Je=Ho(_e,1,ne,oe)?-1:1,Ue=w*Qa;return za({axis:Se,size:w*Za,offset:[ze*Ue,Je*Ue],color:M})}let he=A*Wa/Ft*Fo;return $a({axis:rn[u.cssAxis],outerRadius:he,color:M})}function y(u){return u.kind==="arrow"?"polycss-transform-arrow":u.kind==="plane"?"polycss-transform-plane":"polycss-transform-ring"}function P(){if(o==="translate"){let u=ci.map(C=>({kind:"arrow",key:C.key,cssAxis:C.cssAxis,sign:C.sign,color:C.color})),p=di.map(C=>({kind:"plane",key:C.key,perpAxis:C.perpAxis,axisA:C.axisA,axisB:C.axisB,color:C.color}));return[...u,...p]}return o==="rotate"?ui.map(u=>({kind:"ring",key:u.key,cssAxis:u.cssAxis,color:u.color})):[]}function v(){if(E(),!t)return;let u={x:i.showX!==!1,y:i.showY!==!1,z:i.showZ!==!1};function p(A){if(A.kind==="arrow"){let se=A.key.replace("-","")[0];return u[se]}if(A.kind==="ring")return u[A.key];let w=["x","y","z"][A.axisA],M=["x","y","z"][A.axisB];return u[w]&&u[M]}let C=f();for(let A of P()){if(!p(A))continue;let w=x(A,h(A.key)),M=e.add({polygons:w,objectUrls:[],warnings:[],dispose:()=>{}},{excludeFromAutoCenter:!0,id:`__poly-gizmo-${A.key}`,position:C}),se=y(A);if(M.element.classList.add("polycss-transform-gizmo",se,`${se}--${A.key}`),A.kind==="ring"){let he=(1-ai)/Fo,_=(1+ai)/Fo;M.element.style.setProperty("--ring-inner-ratio",`${he}`),M.element.style.setProperty("--ring-outer-ratio",`${_}`)}l.set(A.key,{handle:M,spec:A})}}function E(){for(let{handle:u}of l.values())u.remove();l.clear(),c=null,a=null}function H(){if(!t)return;let u=f();for(let{handle:p}of l.values())p.setTransform({position:u})}function k(){t&&(l.size===0?v():H())}function N(u){if(t=u,!u){m=[0,0,0],E();return}m=tc(u.polygons),E(),v()}function R(){N(null)}function K(u){u!==o&&(o=u,t&&(E(),v()))}function z(u,p,C){if(!t||!O)return;let A=[O[0]+p*C[0],O[1]+p*C[1],O[2]+p*C[2]];t.setTransform({position:A}),H(),i.onObjectChange?.({object:t,position:A}),i.onChange?.()}let O=null,$=null,U=u=>{if(!t||i.enabled===!1)return;let p={x:i.showX!==!1,y:i.showY!==!1,z:i.showZ!==!1};if(o==="translate"){for(let C of di){let A=["x","y","z"][C.axisA],w=["x","y","z"][C.axisB];if(!p[A]||!p[w])continue;let M=l.get(C.key);if(M&&Fn(M.handle.element,u.clientX,u.clientY)){u.preventDefault(),u.stopPropagation(),a=C.key,g(),O=(t.transform.position??[0,0,0]).slice(),oc({axisA:C.axisA,axisB:C.axisB,probeDistanceCss:Io(t.polygons)*r,wrapper:M.handle.element,target:t,startClientX:u.clientX,startClientY:u.clientY,translationSnap:i.translationSnap??null,onPlaneDelta:(se,he,_,ne)=>{if(!t||!O)return;let oe=[O[0]+se*_[0]+he*ne[0],O[1]+se*_[1]+he*ne[1],O[2]+se*_[2]+he*ne[2]];t.setTransform({position:oe}),H(),i.onObjectChange?.({object:t,position:oe}),i.onChange?.()},onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:se=>{se||(a=null,O=null,g()),i.onDraggingChanged?.(se)}});return}}for(let C of ci){let A=C.key.replace("-","")[0];if(!p[A])continue;let w=l.get(C.key);if(w&&Fn(w.handle.element,u.clientX,u.clientY)){u.preventDefault(),u.stopPropagation(),a=C.key,g(),O=(t.transform.position??[0,0,0]).slice(),nc({cssAxis:C.cssAxis,sign:C.sign,shaftLengthCss:Io(t.polygons)*r,wrapper:w.handle.element,target:t,startClientX:u.clientX,startClientY:u.clientY,translationSnap:i.translationSnap??null,onAxisDelta:(M,se)=>z(C,M,se),onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:M=>{M||(a=null,O=null,g()),i.onDraggingChanged?.(M)}});return}}}else if(o==="rotate")for(let C of ui){if(!p[C.key])continue;let A=l.get(C.key);if(A&&Fn(A.handle.element,u.clientX,u.clientY)){u.preventDefault(),u.stopPropagation(),a=C.key,g(),$=(t.transform.rotation??[0,0,0]).slice(),rc({cssAxis:C.cssAxis,wrapper:A.handle.element,target:t,startClientX:u.clientX,startClientY:u.clientY,rotationSnap:i.rotationSnap??null,onAngleDelta:w=>{if(!t||!$)return;let M=C.cssAxis===0?-1:1,se=[0,0,0];se[C.cssAxis]=1;let he=w*M*Math.PI/180,_=Na($),ne=Ba(se,he),oe=Va(Ua(ne,_));t.setTransform({rotation:oe}),i.onObjectChange?.({object:t,rotation:oe}),i.onChange?.()},onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:w=>{w||(a=null,$=null,g(),t?.rebakeAtlas()),i.onDraggingChanged?.(w)}});return}}};e.host.addEventListener("pointerdown",U,{capture:!0});let ie=u=>{if(!t||a||i.enabled===!1)return;let p=null;for(let[C,A]of l)if(Fn(A.handle.element,u.clientX,u.clientY)){p=C;break}p!==c&&(c=p,g())};e.host.addEventListener("pointermove",ie);function xe(){e.host.removeEventListener("pointerdown",U,{capture:!0}),e.host.removeEventListener("pointermove",ie),E()}return{attach:N,detach:R,setMode:K,update:k,destroy:xe}}var ic=typeof HTMLElement<"u"?HTMLElement:class{},sc=["mode","target","size","enabled"];function fi(e){if(e==="translate"||e==="rotate")return e}var Bn=class extends ic{constructor(){super(...arguments);this._tc=null}static get observedAttributes(){return[...sc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof je)return t;t=t.parentNode}return null}_findTargetMesh(){let t=this.getAttribute("target");if(!t)return null;let o=this._findScene();if(!o)return null;let r=null;try{r=o.querySelector(`#${t}`)??o.querySelector(t)}catch{r=o.querySelector(`[id="${t}"]`)}return r instanceof _t?r:null}_readOptions(){let t={},o=fi(this.getAttribute("mode"));o!==void 0&&(t.mode=o);let r=le(this.getAttribute("size"));r!==void 0&&(t.size=r);let i=this.getAttribute("enabled");return i!==null&&(t.enabled=i!=="false"&&i!=="0"),t.onObjectChange=l=>{this.dispatchEvent(new CustomEvent("polycss:object-change",{bubbles:!0,detail:{position:l.position,rotation:l.rotation}}))},t}_attach(){if(this._tc)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._tc=pi(o,this._readOptions());let r=this._findTargetMesh();if(r){let i=r.getMeshHandle();i&&this._tc.attach(i)}}connectedCallback(){this._attach()}disconnectedCallback(){this._tc&&(this._tc.destroy(),this._tc=null)}attributeChangedCallback(t,o,r){if(o!==r&&this._tc){if(t==="mode"){let i=fi(r);i&&this._tc.setMode(i)}else if(t==="target"){let i=this._findTargetMesh();this._tc.attach(i?i.getMeshHandle()??null:null)}}}};function lc(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let r of o){let i=r.getBoundingClientRect();if(!(i.width<=0||i.height<=0)&&n>=i.left&&n<=i.right&&t>=i.top&&t<=i.bottom)return!0}return!1}function gi(e,n={}){let t=[],o=new Set;n.onChange&&o.add(n.onChange);function r(){t=n.filter?n.filter(t):t;for(let P of o)try{P(t)}catch(v){console.error("[polycss/createSelect] onChange threw:",v)}}function i(y){t=y,r()}function l(y){n.multiple?t.includes(y)||(t=[...t,y]):t=[y],r()}function c(y){t.includes(y)&&(t=t.filter(P=>P!==y),r())}function a(y){t.includes(y)?t=t.filter(P=>P!==y):n.multiple?t=[...t,y]:t=[y],r()}function m(){t.length!==0&&(t=[],r())}function f(y){return t.includes(y)}function h(y,P){for(let v of e.meshes())if(!v.element.classList.contains("polycss-transform-gizmo")&&lc(v.element,y,P))return v;return null}let g=y=>{let P=y.target;if(P?.closest(".polycss-transform-gizmo"))return;let v=e.findMeshByElement(P)??h(y.clientX,y.clientY);if(!v){n.onPointerMissed&&n.onPointerMissed(y),n.clearOnMiss!==!1&&m();return}n.multiple&&(y.shiftKey||y.metaKey||y.ctrlKey)?a(v):t.length===1&&t[0]===v?m():i([v])};e.host.addEventListener("click",g);function x(){e.host.removeEventListener("click",g),o.clear()}return{get selected(){return t},set:i,add:l,remove:c,toggle:a,clear:m,has:f,destroy:x}}var ac=typeof HTMLElement<"u"?HTMLElement:class{},cc=["multiple","clear-on-miss"],Nn=class extends ac{constructor(){super(...arguments);this._selection=null}static get observedAttributes(){return[...cc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof je)return t;t=t.parentNode}return null}_readOptions(){return{multiple:this.hasAttribute("multiple"),clearOnMiss:!this.hasAttribute("clear-on-miss")||this.getAttribute("clear-on-miss")!=="false",onChange:t=>{this.dispatchEvent(new CustomEvent("polycss:select",{bubbles:!0,detail:{selected:t}}))}}}_attach(){if(this._selection)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._selection=gi(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._selection&&(this._selection.destroy(),this._selection=null)}attributeChangedCallback(t,o,r){o!==r&&(this._selection&&(this._selection.destroy(),this._selection=null),this._attach())}};import{boxPolygons as uc,planePolygons as dc,ringPolygons as mc,octahedronPolygons as pc,spherePolygons as fc,tetrahedronPolygons as gc,icosahedronPolygons as hc,dodecahedronPolygons as yc,cylinderPolygons as bc,conePolygons as vc,torusPolygons as xc,computeSceneBbox as Pc}from"@layoutit/polycss-core";var Sc=typeof HTMLElement<"u"?HTMLElement:class{};function Cc(e){return e.closest("poly-scene")??null}function Me(e,n,t){let o=e.getAttribute(n);if(!o)return t;let r=parseFloat(o);return Number.isFinite(r)?r:t}function st(e,n,t){return e.getAttribute(n)??t}function Un(e,n){let t=e.getAttribute(n);if(!t)return;let o=t.split(",").map(r=>parseFloat(r.trim()));if(!(o.length!==3||o.some(r=>!Number.isFinite(r))))return[o[0],o[1],o[2]]}function Ec(e){if(e.length===0)return e;let n=Pc(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,r=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&r===0)return e;let i=l=>[l[0]-t,l[1]-o,l[2]-r];return e.map(l=>({...l,vertices:l.vertices.map(i)}))}var Ze=class extends Sc{constructor(){super(...arguments);this._handle=null}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=Cc(this);if(!t)return;let o=t.getScene?.();if(!o)return;let r=this.buildPolygons();this.hasAttribute("auto-center")&&(r=Ec(r));let i={polygons:r,objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(i,{position:Un(this,"position"),scale:(()=>{let l=this.getAttribute("scale");if(!l)return;if(l.includes(","))return Un(this,"scale");let c=parseFloat(l);return Number.isFinite(c)?c:void 0})(),rotation:Un(this,"rotation"),merge:!1})}},$n=class extends Ze{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("size"),t=n?parseFloat(n):void 0;return uc({size:t!==void 0&&Number.isFinite(t)?t:void 0,color:st(this,"color")})}},Gn=class extends Ze{static get observedAttributes(){return["axis","size","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=Me(this,"axis",2);return dc({axis:n===0||n===1||n===2?n:2,size:Me(this,"size",.4),color:st(this,"color")})}},Yn=class extends Ze{static get observedAttributes(){return["axis","radius","segments","half-thickness","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=Me(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("half-thickness");return mc({axis:t,radius:Me(this,"radius",50),segments:Me(this,"segments",32),halfThickness:o?parseFloat(o):void 0,color:st(this,"color")})}},jn=class extends Ze{static get observedAttributes(){return["size","color","center","auto-center","position","scale","rotation"]}buildPolygons(){return pc({center:Un(this,"center")??[0,0,0],size:Me(this,"size",50),color:st(this,"color")})}},Xn=class extends Ze{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return gc({size:Me(this,"size",100),color:st(this,"color")})}},Wn=class extends Ze{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return hc({size:Me(this,"size",100),color:st(this,"color")})}},Zn=class extends Ze{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return yc({size:Me(this,"size",100),color:st(this,"color")})}},Qn=class extends Ze{static get observedAttributes(){return["radius","subdivisions","color","auto-center","position","scale","rotation"]}buildPolygons(){return fc({radius:Me(this,"radius",50),subdivisions:Me(this,"subdivisions",1),color:st(this,"color")})}},qn=class extends Ze{static get observedAttributes(){return["radius","radius-top","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("radius-top");return bc({radius:Me(this,"radius",50),radiusTop:n?parseFloat(n):void 0,height:Me(this,"height",100),radialSegments:Me(this,"radial-segments",12),color:st(this,"color")})}},Kn=class extends Ze{static get observedAttributes(){return["radius","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return vc({radius:Me(this,"radius",50),height:Me(this,"height",100),radialSegments:Me(this,"radial-segments",12),color:st(this,"color")})}},Jn=class extends Ze{static get observedAttributes(){return["radius","tube","radial-segments","tubular-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return xc({radius:Me(this,"radius",50),tube:Me(this,"tube",15),radialSegments:Me(this,"radial-segments",12),tubularSegments:Me(this,"tubular-segments",16),color:st(this,"color")})}};typeof customElements<"u"&&(customElements.get("poly-scene")||customElements.define("poly-scene",je),customElements.get("poly-mesh")||customElements.define("poly-mesh",_t),customElements.get("poly-polygon")||customElements.define("poly-polygon",Pn),customElements.get("poly-axes-helper")||customElements.define("poly-axes-helper",Sn),customElements.get("poly-directional-light-helper")||customElements.define("poly-directional-light-helper",Cn),customElements.get("poly-orbit-controls")||customElements.define("poly-orbit-controls",_n),customElements.get("poly-map-controls")||customElements.define("poly-map-controls",Rn),customElements.get("poly-first-person-controls")||customElements.define("poly-first-person-controls",Dn),customElements.get("poly-perspective-camera")||customElements.define("poly-perspective-camera",kn),customElements.get("poly-orthographic-camera")||customElements.define("poly-orthographic-camera",Ot),customElements.get("poly-camera")||customElements.define("poly-camera",On),customElements.get("poly-transform-controls")||customElements.define("poly-transform-controls",Bn),customElements.get("poly-select")||customElements.define("poly-select",Nn),customElements.get("poly-box")||customElements.define("poly-box",$n),customElements.get("poly-plane")||customElements.define("poly-plane",Gn),customElements.get("poly-ring")||customElements.define("poly-ring",Yn),customElements.get("poly-octahedron")||customElements.define("poly-octahedron",jn),customElements.get("poly-tetrahedron")||customElements.define("poly-tetrahedron",Xn),customElements.get("poly-sphere")||customElements.define("poly-sphere",Qn),customElements.get("poly-icosahedron")||customElements.define("poly-icosahedron",Wn),customElements.get("poly-dodecahedron")||customElements.define("poly-dodecahedron",Zn),customElements.get("poly-cylinder")||customElements.define("poly-cylinder",qn),customElements.get("poly-cone")||customElements.define("poly-cone",Kn),customElements.get("poly-torus")||customElements.define("poly-torus",Jn));export{Sn as PolyAxesHelperElement,$n as PolyBoxElement,On as PolyCameraElement,Kn as PolyConeElement,qn as PolyCylinderElement,Cn as PolyDirectionalLightHelperElement,Zn as PolyDodecahedronElement,Dn as PolyFirstPersonControlsElement,Wn as PolyIcosahedronElement,Rn as PolyMapControlsElement,_t as PolyMeshElement,jn as PolyOctahedronElement,_n as PolyOrbitControlsElement,Ot as PolyOrthographicCameraElement,kn as PolyPerspectiveCameraElement,Gn as PolyPlaneElement,Pn as PolyPolygonElement,Yn as PolyRingElement,je as PolySceneElement,Nn as PolySelectElement,Qn as PolySphereElement,Xn as PolyTetrahedronElement,Jn as PolyTorusElement,Bn as PolyTransformControlsElement};
519
+ `;import{BASE_TILE as Za}from"@layoutit/polycss-core";var Qa=1,Ve=Za,qa=.1;function Ka(e){return[e[1]*Ve,e[0]*Ve,e[2]*Ve]}function Pt(e){return[e[1],e[0],e[2]]}function ot(e){return e?.direction?{...e,direction:Pt(e.direction)}:e}function cn(e){let n=typeof e.scale=="number"?e.scale:e.scale?.[0]??1,t=typeof e.scale=="number"?e.scale:e.scale?.[1]??1,o=typeof e.scale=="number"?e.scale:e.scale?.[2]??1,r=n!==1||t!==1||o!==1,i=!!e.rotation&&(!!e.rotation[0]||!!e.rotation[1]||!!e.rotation[2]),s=e.position?Ka(e.position):[0,0,0],c=[];return(s[0]!==0||s[1]!==0||s[2]!==0)&&c.push(`translate3d(${s[0]}px, ${s[1]}px, ${s[2]}px)`),i&&(e.rotation[0]&&c.push(`rotateY(${-e.rotation[0]}deg)`),e.rotation[1]&&c.push(`rotateX(${-e.rotation[1]}deg)`),e.rotation[2]&&c.push(`rotateZ(${-e.rotation[2]}deg)`)),r&&c.push(`scale3d(${n}, ${t}, ${o})`),c.length>0?c.join(" "):void 0}function Co(e,n=[0,0,0],t=1){let o=e.state,r=o.rotX,i=o.rotY,c=(o.zoom??Qa)/Ve*t,l=(o.distance??0)*t,p=o.target??[0,0,0],g=p[0]+n[0],x=p[1]+n[1],f=p[2]+n[2],b=x*Ve,y=g*Ve,P=f*Ve;return`${l!==0?`translateZ(${-l}px) `:""}scale(${c}) rotateX(${r}deg) rotate(${i}deg) translate3d(${-b}px, ${-y}px, ${-P}px)`}function Ja(e){let n=e.trim();if(!n||n==="normal")return 1;let t=n.endsWith("%")?Number(n.slice(0,-1))/100:Number(n);return Number.isFinite(t)&&t>0?t:1}function Dr(e){let n=e.ownerDocument?.defaultView;if(!n)return 1;let t=1;for(let o=e;o;o=o.parentElement)t*=Ja(n.getComputedStyle(o).getPropertyValue("zoom"));return Number.isFinite(t)&&t>0?t:1}function Or(e,n){Math.abs(n-1)<1e-6?e.style.removeProperty("zoom"):e.style.setProperty("zoom",String(1/n))}function Hr(e){if(e.vertices.length<3)return null;let n=e.vertices[0],t=0,o=0,r=0;for(let x=1;x+1<e.vertices.length;x++){let f=e.vertices[x],b=e.vertices[x+1],y=f[1]-n[1],P=f[0]-n[0],v=f[2]-n[2],C=b[1]-n[1],F=b[0]-n[0],k=b[2]-n[2];t-=P*k-v*F,o-=v*C-y*k,r-=y*F-P*C}let i=Math.hypot(t,o,r);if(i<1e-9)return null;t/=i,o/=i,r/=i;let s=1/qa,c=Math.round(t*s)/s,l=Math.round(o*s)/s,p=Math.round(r*s)/s,g=Math.hypot(c,l,p);return g<1e-9?null:{key:c+","+l+","+p,vec:[c/g,l/g,p/g]}}function Ir(e,n){let t=e?.disable??[],o=n?.disable??[];if(t.length!==o.length)return!1;for(let r of t)if(!o.includes(r))return!1;return!0}function Fr(e,n){return e===n?!0:!e||!n?!1:e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}function Vr(e,n){return e===n?!0:(e?.color??"#000000")===(n?.color??"#000000")&&(e?.opacity??.25)===(n?.opacity??.25)&&(e?.lift??.05)===(n?.lift??.05)&&(e?.maxExtend??2e3)===(n?.maxExtend??2e3)}import{parseHex as Nr,parseHexColor as Br,parsePureColor as el}from"@layoutit/polycss-core";var tl=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--clx","--cly","--clz"],St="--polycss-light-preview-active",zr=`var(${St}, 0)`,nl="max(0, calc(var(--pnx, 0) * var(--plx, 0) + var(--pny, 0) * var(--ply, 0) + var(--pnz, 1) * var(--plz, 1)))",Eo=(e,n,t)=>`calc(255 * max(0, 1.055 * pow(min(1, pow((var(${e}, 1) + 0.055) / 1.055, 2.4) * (pow((var(${n}, 1) + 0.055) / 1.055, 2.4) * var(--pai, 0.4) + pow((var(${t}, 1) + 0.055) / 1.055, 2.4) * var(--pli, 1) * var(--plam, 0)) / 3.14159265), 0.4167) - 0.055))`,ol=Eo("--psr","--par","--plr"),rl=Eo("--psg","--pag","--plg"),il=Eo("--psb","--pab","--plb");function de(e,n,t){return e.style.getPropertyValue(n)===t?!1:(e.style.setProperty(n,t),!0)}function lt(e){for(let n of tl)e.style.getPropertyValue(n)&&e.style.removeProperty(n)}function dn(e,n){let t=n.directionalLight?.direction??[.4,-.7,.59],o=Pt(t),r=Math.hypot(o[0],o[1],o[2])||1,i=o[0]/r,s=o[1]/r,c=o[2]/r,l=Br(n.directionalLight?.color??"#ffffff")?.rgb??[255,255,255],p=Br(n.ambientLight?.color??"#ffffff")?.rgb??[255,255,255],g=n.directionalLight?.intensity??1,x=n.ambientLight?.intensity??.4,f=P=>(P/255).toFixed(4);de(e,"--plx",i.toFixed(2)),de(e,"--ply",s.toFixed(2)),de(e,"--plz",c.toFixed(2)),de(e,"--plr",f(l[0])),de(e,"--plg",f(l[1])),de(e,"--plb",f(l[2])),de(e,"--pli",g.toFixed(4)),de(e,"--par",f(p[0])),de(e,"--pag",f(p[1])),de(e,"--pab",f(p[2])),de(e,"--pai",x.toFixed(4));let b=c,y=Math.sign(b||1)*Math.max(Math.abs(b),.01);de(e,"--clx",i.toFixed(2)),de(e,"--cly",s.toFixed(2)),de(e,"--clz",y.toFixed(2))}function Gr(e,n){let t=n.textureLighting==="dynamic";if(e.dataset.polycssLighting=n.textureLighting??"baked",!t){lt(e);return}dn(e,n)}function ct(e,n){n.paintColor?e.style.setProperty("--polycss-paint",n.paintColor):e.style.getPropertyValue("--polycss-paint")&&e.style.removeProperty("--polycss-paint"),n.dynamicColor?(e.style.setProperty("--psr",(n.dynamicColor.r/255).toFixed(4)),e.style.setProperty("--psg",(n.dynamicColor.g/255).toFixed(4)),e.style.setProperty("--psb",(n.dynamicColor.b/255).toFixed(4))):(e.style.getPropertyValue("--psr")||e.style.getPropertyValue("--psg")||e.style.getPropertyValue("--psb"))&&(e.style.removeProperty("--psr"),e.style.removeProperty("--psg"),e.style.removeProperty("--psb"))}function $r(e,n){let t=Nr(n??"#cccccc");e.style.setProperty("--psr",(t.r/255).toFixed(4)),e.style.setProperty("--psg",(t.g/255).toFixed(4)),e.style.setProperty("--psb",(t.b/255).toFixed(4))}function To(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=t.textureLighting??"baked",r={directionalLight:ot(t.directionalLight),ambientLight:t.ambientLight,textureLighting:o,textureQuality:t.textureQuality,seamBleed:t.seamBleed,strategies:t.strategies},i=io(e.plan,n,e.plan.normal,o,r);return gt(e.element,i,o),o==="baked"&&al(e.element),!0}function sl(e){let n=el(e)??{rgb:[255,255,255],alpha:1},[t,o,r]=n.rgb,i=(c,l)=>`calc(${c} * (1 - ${zr}) + var(${l}, ${c}) * ${zr})`,s=n.alpha<1?` / ${n.alpha}`:"";return`rgb(${i(t,"--polycss-preview-r")} ${i(o,"--polycss-preview-g")} ${i(r,"--polycss-preview-b")}${s})`}function Ur(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=e.element,r=e.plan.normal,i=Nr(n.color??"#cccccc"),s=!1;return s=de(o,"--pnx",r[0].toFixed(4))||s,s=de(o,"--pny",r[1].toFixed(4))||s,s=de(o,"--pnz",r[2].toFixed(4))||s,s=de(o,"--psr",(i.r/255).toFixed(4))||s,s=de(o,"--psg",(i.g/255).toFixed(4))||s,s=de(o,"--psb",(i.b/255).toFixed(4))||s,s=de(o,"--plam",nl)||s,s=de(o,"--polycss-preview-r",ol)||s,s=de(o,"--polycss-preview-g",rl)||s,s=de(o,"--polycss-preview-b",il)||s,s=de(o,"--polycss-paint",sl(t))||s,o.style.getPropertyValue("color")&&(o.style.removeProperty("color"),s=!0),s}function al(e){e.style.removeProperty("--pnx"),e.style.removeProperty("--pny"),e.style.removeProperty("--pnz"),e.style.removeProperty("--psr"),e.style.removeProperty("--psg"),e.style.removeProperty("--psb"),e.style.removeProperty("--plam"),e.style.removeProperty("--polycss-preview-r"),e.style.removeProperty("--polycss-preview-g"),e.style.removeProperty("--polycss-preview-b"),e.style.removeProperty("--polycss-paint")}var ll="http://www.w3.org/2000/svg",un=class{constructor(){this.groundSvg=null;this.groundVisible=!1;this.currentGroundCssZ=null;this.shadowRoot=null}};function jr(e,n,t){let o=e.shadowRoot;if(o||(o=n.createElement("div"),o.setAttribute("class","polycss-shadows"),o.style.position="absolute",o.style.top="0",o.style.left="0",o.style.width="0",o.style.height="0",o.style.transformStyle="preserve-3d",o.style.pointerEvents="none",e.shadowRoot=o),o.parentNode!==t){let r=t.firstChild;r?t.insertBefore(o,r):t.appendChild(o)}return o}function Wr(e){e.groundSvg?.parentNode&&e.groundSvg.parentNode.removeChild(e.groundSvg),e.groundSvg=null,e.groundVisible=!1}function Yr(e){e.groundSvg&&e.groundVisible&&(e.groundSvg.style.display="none",e.groundVisible=!1)}function Xr(e,n,t,o){let r=[],i=e.firstChild;for(let s=0;s<t;s++){let c=i;c&&c.tagName==="path"?i=c.nextSibling:(c=n.createElementNS(ll,"path"),c.setAttribute("fill-rule","nonzero"),o&&(c.setAttribute("stroke-width","0.5"),c.setAttribute("stroke-linejoin","round")),e.insertBefore(c,i)),r.push(c)}for(;i;){let s=i.nextSibling;e.removeChild(i),i=s}return r}function Zr(e){return{host:e.host,doc:e.doc,cameraEl:e.cameraEl,sceneEl:e.sceneEl,camera:e.camera,layoutScale:e.layoutScale,options:{current:e.options},meshes:new Set,meshAutoCounter:{next:0},autoCenter:{offset:[0,0,0]},bboxCenterCssCache:{value:null},shadowSvgState:new un,receiverShadowCache:new Map,receiverShadowCacheKey:new Map,casterItemsCache:new Map,casterItemsCacheKey:new Map}}import{buildSharedEdgeMap as cl,computeReceiverShadowFaces as dl,meshScaleVec3 as ti,prepareCasterEdgeOwners as ul,prepareCasterPolyItems as pl,prepareReceiverFacePlanes as ml}from"@layoutit/polycss-core";function Qr(e){for(let n of e)n.svg&&n.svg.parentNode&&n.svg.parentNode.removeChild(n.svg),n.svg=null}function qr(e,n){if(n){let t=e.receiverShadowCache.get(n);t&&Qr(t),e.receiverShadowCache.delete(n),e.receiverShadowCacheKey.delete(n)}else{for(let t of e.receiverShadowCache.values())Qr(t);e.receiverShadowCache.clear(),e.receiverShadowCacheKey.clear()}}function Kr(e,n){n?(e.casterItemsCache.delete(n),e.casterItemsCacheKey.delete(n)):(e.casterItemsCache.clear(),e.casterItemsCacheKey.clear())}function Jr(e){Wr(e.shadowSvgState),ei(e)}function Ao(e){return e.handle.id??e.autoMeshId}var fl="http://www.w3.org/2000/svg",pn=new WeakMap,ni=new WeakMap,oi=new WeakMap,ri=new WeakMap,ii=new WeakMap;function si(e){let n=pn.get(e);return n||(n=new Map,pn.set(e,n)),n}function Mo(e){let n=pn.get(e);if(n){for(let t of n.values())t.svg&&t.svg.parentNode&&t.svg.parentNode.removeChild(t.svg);n.clear(),pn.delete(e)}}function ei(e){for(let n of e.meshes)Mo(n)}function ai(e,n,t,o,r,i,s,c,l,p){let g=e.options.current,{receiverShadowCache:x,receiverShadowCacheKey:f,casterItemsCache:b,casterItemsCacheKey:y}=e,P=o.handle.transform.position??[0,0,0],v=o.handle.transform.rotation??[0,0,0],C=o.polygons.some(A=>A.texture!==void 0),F=ti(o.handle.transform.scale),k=o.bboxCenterCss,z=g.shadow?.lift??.001,O=`${o.polygons.length}|${r.size}|${P.join(",")}|${v.join(",")}|${F.join(",")}|${k?k.join(","):"n"}|${z}`,Z=x.get(o);if(Z===void 0||f.get(o)!==O){Z=ml(o.polygons,P,o.handle.transform.scale,r,z,v),x.set(o,Z),f.set(o,O);let A=si(o);for(let h of A.values())h.svg&&h.svg.parentNode&&h.svg.parentNode.removeChild(h.svg);A.clear()}let q=[];for(let A of n){let h=A.handle.transform.position??[0,0,0],u=A.handle.transform.rotation??[0,0,0],d=ti(A.handle.transform.scale),T=A.bboxCenterCss,w=`${A.polygons.length}|${h.join(",")}|${u.join(",")}|${d.join(",")}|${T?T.join(","):"n"}`,R=b.get(A);if(R===void 0||y.get(A)!==w){let _=t.get(A),j=new Set;for(let Q of A.rendered)Q.plan&&!_.has(Q.polygonIndex)&&j.add(Q.polygonIndex);R=pl(A.polygons,h,A.handle.transform.scale,Q=>j.has(Q),u),b.set(A,R),y.set(A,w)}let L;if(A===o){let _=ni.get(A);(_===void 0||oi.get(A)!==A.polygons)&&(_=cl(A.polygons),ni.set(A,_),oi.set(A,A.polygons)),L=_}let te;if(A!==o&&A.polygons.length>=40){let _=ri.get(A);(_===void 0||ii.get(A)!==w)&&(_=ul(A.polygons,h,A.handle.transform.scale,u),ri.set(A,_),ii.set(A,w)),te=_}q.push({id:A,items:R,selfShadowEdgeMap:L,edgeOwners:te,casterPolygonCount:A.polygons.length})}let D={rotX:e.camera.state.rotX,rotY:e.camera.state.rotY,meshRotation:o.handle.transform.rotation},H=dl({receiverPlanes:Z,receiverPolygons:o.polygons,receiverHasTexture:C,casters:q,lightDir:i,cameraRot:D,ambientLight:g.ambientLight,directionalLight:g.directionalLight,shadow:{color:g.shadow?.color,opacity:p,maxExtend:g.shadow?.maxExtend}}),V=si(o),G=new Set;for(let A of H){G.add(A.faceIndex);let h=V.get(A.faceIndex);h||(h={svg:null,visible:!1,width:-1,height:-1,matrixCss:""},V.set(A.faceIndex,h));let u=h.svg;u?(h.visible||(u.style.display="block"),(h.width!==A.width||h.height!==A.height)&&(u.setAttribute("width",String(A.width)),u.setAttribute("height",String(A.height)),u.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),h.width=A.width,h.height=A.height),h.matrixCss!==A.matrixCss&&(u.style.transform=A.matrixCss,h.matrixCss=A.matrixCss)):(u=e.doc.createElementNS(fl,"svg"),u.setAttribute("class","polycss-shadow polycss-shadow-svg polycss-shadow-receiver"),g.debugShadowAttrs&&(u.setAttribute("data-poly-shadow-type","receiver"),u.setAttribute("data-poly-shadow-receiver",Ao(o)),u.setAttribute("data-poly-shadow-receiver-face",String(A.faceIndex)),u.setAttribute("data-poly-shadow-receiver-polys",JSON.stringify(A.memberPolyIndices))),u.setAttribute("width",String(A.width)),u.setAttribute("height",String(A.height)),u.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),u.setAttribute("style",`position:absolute;top:0;left:0;display:block;overflow:hidden;transform-origin:0 0;pointer-events:none;will-change:transform;transform:${A.matrixCss}`),jr(e.shadowSvgState,e.doc,e.sceneEl).appendChild(u),h.svg=u,h.width=A.width,h.height=A.height,h.matrixCss=A.matrixCss),h.visible=!0;let d=Xr(u,e.doc,A.paths.length,!0),T=A.opacity.toFixed(4),w=[],R=!!g.debugShadowAttrs;for(let L=0;L<A.paths.length;L++){let te=A.paths[L],_=R?Ao(te.casterId):"";R&&w.push(_);let j=d[L];if(j.setAttribute("d",te.d),j.getAttribute("fill")!==A.fill&&j.setAttribute("fill",A.fill),j.getAttribute("stroke")!==A.fill&&j.setAttribute("stroke",A.fill),j.getAttribute("opacity")!==T&&j.setAttribute("opacity",T),R){j.getAttribute("data-poly-shadow-caster")!==_&&j.setAttribute("data-poly-shadow-caster",_);let Q=JSON.stringify(te.casterPolygonIndices);j.getAttribute("data-poly-shadow-caster-polys")!==Q&&j.setAttribute("data-poly-shadow-caster-polys",Q)}}if(R){let L=w.join(" ");u.getAttribute("data-poly-shadow-casters")!==L&&u.setAttribute("data-poly-shadow-casters",L)}}for(let[A,h]of V)G.has(A)||h.svg&&h.visible&&(h.svg.style.display="none",h.visible=!1)}var li=Symbol.for("polycss.animation.triangleFrameTarget");var Tl=750;function ui(e){return!Object.prototype.hasOwnProperty.call(e,"seamBleed")||e.seamBleed!==void 0?e:{...e,seamBleed:mi}}var Al={key:"non-cullable",normal:[1,1,0]};function pi(){return[Al]}function fi(e,n){if(!e||typeof e.appendChild!="function")throw new Error("createPolyScene: host must be an HTMLElement");if(!n?.camera)throw new Error("createPolyScene: a camera handle is required. Use createPolyCamera({...}) or createPolyPerspectiveCamera({...}) and pass as { camera }.");let t=n.camera;e.ownerDocument&&kr(e.ownerDocument),e.ownerDocument?.defaultView&&e.ownerDocument.defaultView.getComputedStyle(e).position==="static"&&(e.style.position="relative");let{camera:o,...r}=n,i=ui({seamBleed:mi,...r}),s=Dr(e),c=[0,0,0],l=e.ownerDocument??document,p=l.createElement("div");p.className="polycss-camera",Z(p,i),e.appendChild(p);let g=l.createElement("div");g.className="polycss-scene",g.setAttribute("aria-hidden","true"),q(g,i),p.appendChild(g);let x=Zr({host:e,doc:l,cameraEl:p,sceneEl:g,camera:t,layoutScale:s,options:i}),f=x.meshes,b=new WeakMap,y=x.shadowSvgState,P=()=>Yr(y),v=()=>Jr(x),C=null;function F(a){if(!a)return null;let m=Math.hypot(a[0],a[1],a[2]);if(!Number.isFinite(m)||m<=0)return null;let S=Math.round(a[0]/m*100)/100,E=Math.round(a[1]/m*100)/100,W=Math.round(a[2]/m*100)/100;return`${S}|${E}|${W}`}function k(){C=null}let z=a=>qr(x,a),O=a=>Kr(x,a);function Z(a,m){let S=t.perspectiveStyle;if(S==="none")a.style.perspective="1000000px";else{let E=parseFloat(S);Number.isFinite(E)&&(a.style.perspective=`${E}px`)}}function q(a,m){Or(a,s),a.style.transform=Co(t,c,s),Gr(a,m)}function D(a){a.style.transform=Co(t,c,s)}function H(a){a.voxelRenderer?.dispose(),a.voxelRenderer=void 0,h(a.rendered,a.disposeAtlas),a.disposeAtlas=void 0,a.rendered.length=0,a.renderedByPolygonIndex=[],a.cameraCullGroups=[],a.cameraCullSignature="",a.solidLightingPreviewPrepared=!1,a.solidLightingPreviewActive=!1,A(a);for(let m of Array.from(a.wrapper.children))m instanceof HTMLElement&&m.classList.contains("polycss-bucket")&&m.remove();a.hasBuckets=!1}function V(a){for(let m of Array.from(a.wrapper.childNodes)){if(!(m instanceof HTMLElement))return m;if(m.classList.contains("polycss-bucket")||m.classList.contains("polycss-shadow"))continue;let S=m.tagName.toLowerCase();if(!(S==="b"||S==="i"||S==="s"||S==="u"||S==="q"))return m}return null}function G(a,m,S){S?.parentNode===a.wrapper?a.wrapper.insertBefore(m,S):a.wrapper.appendChild(m)}function A(a){for(let m of a.shadowRendered)m.parentNode&&m.parentNode.removeChild(m);a.shadowRendered.length=0,v()}function h(a,m){m?.();for(let S of a){try{S.dispose()}catch{}S.element.parentNode&&S.element.parentNode.removeChild(S.element)}}function u(a,m,S){a.rendered=m,a.renderedByPolygonIndex=[];for(let E of m)a.renderedByPolygonIndex[E.polygonIndex]=E;a.disposeAtlas=S,a.solidLightingPreviewPrepared=!1}function d(a,m){let S=a.renderedByPolygonIndex[m];return S?.polygonIndex===m?S:void 0}function T(a){for(let m of Array.from(a.wrapper.children))m instanceof HTMLElement&&m.classList.contains("polycss-bucket")&&m.remove();a.hasBuckets=!1;for(let m of a.rendered)m.element.parentNode&&m.element.parentNode.removeChild(m.element)}function w(a,m){let S=a.polygons[m.polygonIndex];return a.stableDom&&S?di(S):m.plan?.normal??(S?di(S):null)}function R(a){if(!Q(a))return a.rendered;let m=L(a);return a.rendered.filter(S=>te(a,S,wo,m))}function L(a){return{rotX:t.state.rotX,rotY:t.state.rotY,meshRotation:a.handle.transform.rotation}}function te(a,m,S=wo,E=L(a)){let W=w(a,m);return W===null||Sl(W,E,S)}function _(a){if(a.excludeFromAutoCenter){a.cameraCullGroups=[];return}let m=new Map;for(let S of a.rendered){let E=w(a,S);if(!E)continue;if(!xl(E)){a.cameraCullGroups=pi();return}let W=gl(E);if(!m.has(W)&&(m.set(W,E),m.size>hl)){a.cameraCullGroups=pi();return}}a.cameraCullGroups=Array.from(m,([S,E])=>({key:S,normal:E}))}function j(a){return Q(a)?yl(a.cameraCullGroups,L(a)):"all"}function Q(a){return!a.excludeFromAutoCenter&&Pl(a.cameraCullGroups)}function re(a){a.cameraCullSignature=Q(a)?j(a):"all"}function fe(a,m){let S=new Array(a.rendered.length),E=!1,W=L(a);for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K],J=te(a,oe,m,W);S[K]=J}let B=null,I=null,U=()=>{if(!(!B||!I)){if(B===I)B.remove();else{let K=l.createRange();K.setStartBefore(B),K.setEndAfter(I),K.deleteContents(),K.detach()}B=null,I=null,E=!0}};for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K];!S[K]&&oe.element.parentNode===a.wrapper?(I&&I.nextSibling===oe.element||(U(),B=oe.element),I=oe.element):U()}U();let Y=K=>{for(let oe=K;oe<a.rendered.length;oe+=1){let J=a.rendered[oe].element;if(J.parentNode===a.wrapper)return J}return V(a)},ae=-1,ne=K=>{if(ae<0)return;let oe=l.createDocumentFragment();for(let J=ae;J<K;J+=1){let He=a.rendered[J];be(a,He),oe.appendChild(He.element)}G(a,oe,Y(K)),ae=-1,E=!0};for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K];S[K]&&oe.element.parentNode!==a.wrapper?ae<0&&(ae=K):ne(K)}return ne(a.rendered.length),E}function ue(a,m=!1){if(a.voxelRenderer){m?a.voxelRenderer.render(L(a)):a.voxelRenderer.syncCamera(L(a)),a.cameraCullSignature="voxel-direct";return}if(!Q(a)){let W=a.cameraCullSignature!=="all";a.cameraCullSignature="all",W&&ve(a);return}if(a.hasBuckets){pe(a,m);return}let S=j(a);if(!m&&S===a.cameraCullSignature)return;let E=fe(a,wo);a.cameraCullSignature=S,E&&Ne(a)}function pe(a,m=!1){let S=Q(a)?j(a):"all";!m&&S===a.cameraCullSignature||ve(a)}function Ce(a,m){return w(a,m)}function be(a,m){if(i.textureLighting!=="dynamic")return;let S=Ce(a,m);S&&(m.element.style.setProperty("--pnx",S[0].toFixed(4)),m.element.style.setProperty("--pny",S[1].toFixed(4)),m.element.style.setProperty("--pnz",S[2].toFixed(4)))}function Ae(a){T(a),a.hasBuckets=!1;let m=a.skipBucketNormalCleanupOnce;a.skipBucketNormalCleanupOnce=!1;let S=l.createDocumentFragment(),E=i.textureLighting==="dynamic"&&!a.stableDom,W=new Map,B=[];for(let I of R(a)){let U=a.polygons[I.polygonIndex],Y=E&&U?Hr(U):null;if(!Y){B.push(I);continue}let ae=Y.key+"|"+(U.color??""),ne=W.get(ae);ne||(ne={vec:Y.vec,items:[]},W.set(ae,ne)),ne.items.push(I)}for(let I of B)be(a,I),S.appendChild(I.element);for(let I of W.values()){if(I.items.length<2){for(let Y of I.items)be(a,Y),S.appendChild(Y.element);continue}let U=l.createElement("div");U.className="polycss-bucket",a.hasBuckets=!0,U.style.setProperty("--pnx",String(I.vec[0])),U.style.setProperty("--pny",String(I.vec[1])),U.style.setProperty("--pnz",String(I.vec[2]));for(let Y of I.items)U.appendChild(Y.element),(!m||Y.kind==="triangle")&&(Y.element.style.removeProperty("--pnx"),Y.element.style.removeProperty("--pny"),Y.element.style.removeProperty("--pnz"));S.appendChild(U)}G(a,S,V(a)),re(a)}function ze(){return new Promise(a=>setTimeout(a,0))}async function Qe(a,m){if(i.textureLighting==="dynamic"&&!a.stableDom)return Ae(a),!m();T(a);let E=l.createDocumentFragment(),W=V(a),B=0;for(let I of R(a)){if(m())return!1;be(a,I),E.appendChild(I.element),B++,B%Tl===0&&(G(a,E,W),E=l.createDocumentFragment(),await ze())}return E.childNodes.length>0&&G(a,E,W),re(a),!m()}function rt(a,m){let S=i.textureLighting==="dynamic",E=i.directionalLight?.direction,W=m&&(m[0]!==0||m[1]!==0||m[2]!==0);if(!S||!W||!E){if(a.lightOverrideSignature==="clear")return;a.wrapper.style.removeProperty("--plx"),a.wrapper.style.removeProperty("--ply"),a.wrapper.style.removeProperty("--plz"),a.lightOverrideSignature="clear";return}let B=Lo(E,m),I=Pt(B),U=Math.hypot(I[0],I[1],I[2])||1,Y=(I[0]/U).toFixed(2),ae=(I[1]/U).toFixed(2),ne=(I[2]/U).toFixed(2),K=`${Y}|${ae}|${ne}`;a.lightOverrideSignature!==K&&(a.wrapper.style.setProperty("--plx",Y),a.wrapper.style.setProperty("--ply",ae),a.wrapper.style.setProperty("--plz",ne),a.lightOverrideSignature=K)}function ut(a){let m=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let E=a.polygons[S.polygonIndex];E&&(m=To(S,E,i)||m)}return a.solidLightingPreviewPrepared=!1,a.solidLightingPreviewActive=!1,m}function it(a){if((i.textureLighting??"baked")!=="baked")return!1;let m=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let E=a.polygons[S.polygonIndex];E&&(Ur(S,E,S.plan.shadedColor),m=!0)}return a.solidLightingPreviewPrepared=m,m}function jn(a){return(i.textureLighting??"baked")!=="baked"||!a.solidLightingPreviewPrepared&&!it(a)?!1:(a.solidLightingPreviewActive=!0,!0)}function Wn(a){return a.kind==="atlas"||!!a.plan?.texture}function Yn(){if((i.textureLighting??"baked")!=="baked")return!1;let a=!1;for(let m of f)a=ut(m)||a,m.rendered.some(Wn)&&(Rt(m),a=!0);g.style.removeProperty(St);for(let m of f)lt(m.wrapper),m.solidLightingPreviewActive=!1;return lt(g),a}function Xn(){g.style.removeProperty(St);for(let a of f)a.solidLightingPreviewActive&&(ut(a),lt(a.wrapper));(i.textureLighting??"baked")!=="dynamic"&&(lt(g),k(),Ee())}function $(a,m){let S=a.handle.transform.rotation,E=m.directionalLight?.direction??i.directionalLight?.direction;if(!(S&&(S[0]!==0||S[1]!==0||S[2]!==0))||!E){lt(a.wrapper);return}let B=Lo(E,S);dn(a.wrapper,{...i,...m,directionalLight:{...i.directionalLight,...m.directionalLight,direction:B}})}function ie(a){if((i.textureLighting??"baked")!=="baked")return!1;dn(g,{...i,...a}),!a.skipShadows&&a.directionalLight?.direction&&Ee(a.directionalLight.direction);let m=!1;for(let S of f)$(S,a),m=jn(S)||m;return m?de(g,St,"1"):g.style.removeProperty(St),m}function se(a,m,S){let E=a.polygons[m];if(!E)return!1;let W=d(a,m);if(!W)return!1;let B=i.textureLighting??"baked";return B==="dynamic"?($r(W.element,S),!0):B==="baked"?To(W,E,i):!1}function Me(a,m){let S=a.polygons[m];if(!S)return!1;let E=d(a,m);return E?(ye(E.element,S,m),!0):!1}function _t(a,m,S){return!(S.length===0||!S.every(E=>E==="color"||E==="data")||S.includes("color")&&!se(a,m,a.polygons[m]?.color)||S.includes("data")&&!Me(a,m))}function Ne(a){k(),Ee()}function Ee(a){let m=[];for(let J of f)!J.disposed&&J.castShadow&&m.push(J);if(m.length===0){v(),C=null;return}let S=i.shadow?.color??"#000000",E=i.shadow?.opacity??.25,W=El(S)?.rgb??[0,0,0],B=W[0],I=W[1],U=W[2],Y=a??i.directionalLight?.direction??[.4,-.7,.59],ae=Pt(Y),ne=F(ae);if(ne!==null&&ne===C)return;let K=new Map;for(let J of m)K.set(J,ci(J.polygons,{normalTolerance:.1,distanceTolerance:.5,overlapFraction:.95,preserveDoubleSidedBackfaces:!1}));let oe=new Map;for(let J of f)J.disposed||!J.receiveShadow||oe.set(J,new Set);P();for(let J of f)J.disposed||!J.receiveShadow||ai(x,m,K,J,oe.get(J)??new Set,ae,B,I,U,E);C=ne}function ve(a){if(a.voxelRenderer){a.voxelRenderer.render(L(a)),a.cameraCullSignature="voxel-direct";return}A(a),Ae(a),Ne(a)}function De(a,m){if(!m||!a.polygons||a.polygons.length<2)return;let S=Math.hypot(m[0],m[1],m[2]);if(!Number.isFinite(S)||S<=0)return;let E=m[0]/S,W=m[1]/S,B=m[2]/S,I=K=>Math.round(K*1e3)/1e3,U=`${I(E)},${I(W)},${I(B)}`,Y=a.lightOcclusionCache;if(Y&&Y.polygons===a.polygons&&Y.lightDirKey===U)return Y.occluded;let ae=Y&&Y.polygons===a.polygons?Y.dedupDropped:ci(a.polygons,{normalTolerance:.1,distanceTolerance:.12,overlapFraction:.98,preserveDoubleSidedBackfaces:!1}),ne=vl(a.polygons,[E,W,B],ae);return a.lightOcclusionCache={polygons:a.polygons,lightDirKey:U,occluded:ne,dedupDropped:ae},ne}function Oe(a){return!!a.voxelSource&&i.textureLighting!=="dynamic"&&!a.stableDom&&!a.castShadow}function Se(a,m){H(a);let S=i.directionalLight,E=m?{...S,direction:m}:S,W=ot(E),B=void 0;if(Oe(a)){let Y=_r({doc:l,wrapper:a.wrapper,polygons:a.parseResult.polygons,directionalLight:W,ambientLight:i.ambientLight});if(Y){a.voxelRenderer=Y,Y.render(L(a)),a.cameraCullSignature="voxel-direct";return}}let I={doc:l,directionalLight:W,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies,lightOccludedPolyIndices:B},U=a.stableDom?(()=>{let Y=vt(a.polygons,I);return ct(a.wrapper,Y),Nt(a.polygons,{...I,solidPaintDefaults:Y})??xt(a.polygons,{...I,solidPaintDefaults:Y})})():xt(a.polygons,{...I,computeSolidPaintDefaults:!0,skipDynamicNormalVars:i.textureLighting==="dynamic"});a.stableDom||ct(a.wrapper,U.solidPaintDefaults??{}),u(a,U.rendered,U.dispose),a.skipBucketNormalCleanupOnce=i.textureLighting==="dynamic"&&!a.stableDom,_(a),Ae(a),Ne(a)}function Rt(a,m){if(a.rendered.length===0||a.voxelRenderer||a.stableDom||Oe(a)){Se(a,m);return}if(a.rendered[0]?.element.parentNode===null){Se(a,m);return}let S=i.directionalLight,E=m?{...S,direction:m}:S,W=ot(E),B={doc:l,directionalLight:W,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies,computeSolidPaintDefaults:!0,skipDynamicNormalVars:i.textureLighting==="dynamic"},I=xt(a.polygons,B),U=()=>{a.rebakeInFlight=!1;let ne=a.rebakeQueuedLightDir;ne!==null&&(a.rebakeQueuedLightDir=null,Rt(a,ne))},Y=()=>{if(a.disposed){I.dispose(),U();return}if(I.rendered.length!==a.rendered.length){I.dispose(),Se(a,m),U();return}for(let oe of I.rendered){let J=a.renderedByPolygonIndex[oe.polygonIndex];if(!J)continue;let He=oe.element.getAttribute("style");He!==null&&J.element.setAttribute("style",He)}let ne=I.solidPaintDefaults;ne&&ct(a.wrapper,ne);let K=a.disposeAtlas;a.disposeAtlas=I.dispose,K&&(typeof requestAnimationFrame=="function"?J=>{requestAnimationFrame(J)}:J=>{setTimeout(J,0)})(K),Ne(a),U()},ae=I.pagesReady;ae&&typeof ae.then=="function"?ae.then(()=>Qn(I.rendered)).then(qn).then(Y,()=>{I.dispose(),a.disposed||Se(a,m),U()}):Y()}function Zn(a,m){if(a.rebakeInFlight){a.rebakeQueuedLightDir=m;return}a.rebakeInFlight=!0,Rt(a,m)}function Qn(a){let m=new Set;for(let S of a){let E=S.element.getAttribute("style")??"",W=/url\((blob:[^)]+)\)/g,B;for(;(B=W.exec(E))!==null;)m.add(B[1])}return Array.from(m)}function qn(a){return a.length===0||typeof Image>"u"?Promise.resolve():Promise.all(a.map(m=>{let S=new Image;S.src=m;let E=S.decode?.();return E?E.catch(()=>{}):Promise.resolve()})).then(()=>{})}function qe(){let a=1/0,m=!1;for(let B of f)if(!B.disposed&&B.receiveShadow){m=!0;break}for(let B of f){if(B.disposed||!(m?B.receiveShadow:B.castShadow))continue;let U=B.handle.transform.position?.[2]??0;for(let Y of B.polygons)for(let ae of Y.vertices){let ne=ae[2]+U;ne<a&&(a=ne)}}if(!Number.isFinite(a)){let B=y.currentGroundCssZ!==null;y.currentGroundCssZ=null,B&&(v(),k());return}let S=i.shadow?.lift??.05,E=(a+S)*Ve,W=y.currentGroundCssZ;y.currentGroundCssZ=E,W!==E&&(k(),Ee())}async function Zt(a,m){H(a);let S=ot(i.directionalLight),E={doc:l,directionalLight:S,ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,strategies:i.strategies,lightOccludedPolyIndices:void 0},W=a.stableDom?Nt(a.polygons,E):null;if(W){let U=vt(a.polygons,E);return ct(a.wrapper,U),u(a,W.rendered,W.dispose),_(a),Ae(a),Ne(a),!m()}let B=await sn(a.polygons,{...E,skipDynamicNormalVars:i.textureLighting==="dynamic"},m);if(m())return B.dispose(),!1;ct(a.wrapper,B.solidPaintDefaults),u(a,B.rendered,B.dispose),a.skipBucketNormalCleanupOnce=i.textureLighting==="dynamic"&&!a.stableDom,_(a);let I=await Qe(a,m);return I&&Ne(a),I}function st(){let a=c,m=[0,0,0];if(i.autoCenter){let S=[];for(let E of f)!E.disposed&&!E.excludeFromAutoCenter&&S.push(...E.polygons);if(S.length>0){let E=bl(S);m=[(E.min[0]+E.max[0])/2,(E.min[1]+E.max[1])/2,(E.min[2]+E.max[2])/2]}}a[0]===m[0]&&a[1]===m[1]&&a[2]===m[2]||(c=m,x.autoCenter.offset=m,q(g,i))}function Ni(a,m={}){let E=(g.ownerDocument??document).createElement("div");E.className="polycss-mesh",m.id&&E.setAttribute("data-poly-mesh-id",m.id);let W=`polycss-mesh-${x.meshAutoCounter.next++}`;E.setAttribute("data-poly-mesh-index",W);let B={...m},I=m.merge!==!1,U=!!m.stableDom,Y=0,ae=cn(B);ae&&(E.style.transform=ae);let ne=(N,X)=>a.voxelSource?N:X?Cl(N,{meshResolution:m.meshResolution}):(U||m.excludeFromAutoCenter,N),K=ne(a.polygons,I),oe=null;function J(){let N=cn(B);E.style.transform=N??""}function He(N){if(N.length===0){oe=null,Ge&&(Ge.bboxCenterCss=null),J();return}let X=1/0,le=1/0,me=1/0,Le=-1/0,ce=-1/0,ge=-1/0;for(let je of N)for(let Fe of je.vertices)Fe[0]<X&&(X=Fe[0]),Fe[0]>Le&&(Le=Fe[0]),Fe[1]<le&&(le=Fe[1]),Fe[1]>ce&&(ce=Fe[1]),Fe[2]<me&&(me=Fe[2]),Fe[2]>ge&&(ge=Fe[2]);if(!Number.isFinite(X)){oe=null,Ge&&(Ge.bboxCenterCss=null),J();return}let Ie=(le+ce)/2*Ve,Ue=(X+Le)/2*Ve,_e=(me+ge)/2*Ve;oe=[Ie,Ue,_e],Ge&&(Ge.bboxCenterCss=oe),J()}let Ge=null;He(K),g.appendChild(E);let M={handle:void 0,wrapper:E,parseResult:a,rendered:[],renderedByPolygonIndex:[],shadowRendered:[],polygons:K,voxelSource:a.voxelSource,disposed:!1,stableDom:U,hasBuckets:!1,skipBucketNormalCleanupOnce:!1,excludeFromAutoCenter:!!m.excludeFromAutoCenter,castShadow:!!m.castShadow,bboxCenterCss:oe,receiveShadow:!!m.receiveShadow,cameraCullGroups:[],cameraCullSignature:"",lightOverrideSignature:"clear",stableTriangleColorFrame:0,solidLightingPreviewPrepared:!1,solidLightingPreviewActive:!1,bakedRotation:m.rotation?[...m.rotation]:[0,0,0],autoMeshId:W,rebakeInFlight:!1,rebakeQueuedLightDir:null},$e=null,Kn=0,Qt=-1,kt=null;function Dt(){$e=null,kt=null,Qt=-1}function Bo(){let N=$e;if(!N||N.polygonCount!==M.polygons.length)return M.polygons;if(kt&&Qt===Kn)return kt;let X=N.vertices,le=new Array(N.polygonCount);for(let me=0;me<N.polygonCount;me++){let Le=M.polygons[me],ce=me*9;le[me]={...Le,color:N.colors?.[me]??Le.color,vertices:[[X[ce],X[ce+1],X[ce+2]],[X[ce+3],X[ce+4],X[ce+5]],[X[ce+6],X[ce+7],X[ce+8]]]}}return kt=le,Qt=Kn,le}function zo(N,X){let le=N?.stableTriangleUpdateMode==="color-only";M.stableTriangleColorFrame++;let me=M.stableDom&&!X;if(me||He(M.polygons),M.stableDom&&!M.hasBuckets){let Le={doc:l,directionalLight:ot(i.directionalLight),ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed},ce=M.rendered.length===M.polygons.length&&M.rendered.every(_e=>_e.kind==="triangle"),ge=M.stableDom&&!X,Ie=ce||ge?{}:vt(M.polygons,Le);ce||ct(M.wrapper,Ie);let Ue={...Le,solidPaintDefaults:Ie,optimizeStableTriangleStyle:!0,stableTriangleDebug:N?.stableTriangleDebug,stableTriangleUpdateMode:N?.stableTriangleUpdateMode,stableTriangleColorPolicy:N?.stableTriangleColorPolicy,stableTriangleColorSteps:N?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:N?.stableTriangleColorFreezeFrames,stableTriangleColorBudget:N?.stableTriangleColorBudget,stableTriangleColorMaxAge:N?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:N?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:N?.stableTriangleMatrixDecimals,stableTriangleColorFrame:M.stableTriangleColorFrame};if(ln(M.rendered,M.polygons,Ue))return le||(_(M),ue(M,!0),X&&st()),!0}return me&&He(M.polygons),!1}let pt={get polygons(){return Bo()},set polygons(N){Dt(),M.polygons=N},element:E,id:m.id,get transform(){return B},remove(){Y++,E.parentNode&&E.parentNode.removeChild(E),H(M),f.delete(M),b.delete(E),z(M),O(M),st(),qe()},setPolygons(N,X){Y++,I=X?.merge??I,U=X?.stableDom??U,M.stableDom=U,M.voxelSource=void 0,M.polygons=ne(N,I),O(M),z(M),Dt(),pt.polygons=M.polygons;let le=X?.recomputeAutoCenter??!0;zo(X,le)||(Se(M),le&&st())},[li](N,X){let le=X?.merge??I,me=X?.stableDom??U;if(!N.solidTriangles||!me||le||m.meshResolution!==void 0||M.hasBuckets||N.polygonCount!==M.polygons.length||N.vertices.length<N.polygonCount*9||M.rendered.length!==N.polygonCount)return!1;for(let ge=0;ge<M.rendered.length;ge++){let Ie=M.rendered[ge],Ue=M.polygons[ge];if(Ie?.kind!=="triangle"||Ie.polygonIndex!==ge||!Ue||Ue.vertices.length!==3||Ue.texture||Ue.material?.texture)return!1}let Le=X?.recomputeAutoCenter??!0;if(!Le){let ge=M.stableTriangleColorFrame+1,Ie={doc:l,directionalLight:ot(i.directionalLight),ambientLight:i.ambientLight,textureLighting:i.textureLighting,textureQuality:i.textureQuality,seamBleed:i.seamBleed,solidPaintDefaults:{},optimizeStableTriangleStyle:!0,stableTriangleDebug:X?.stableTriangleDebug,stableTriangleUpdateMode:X?.stableTriangleUpdateMode,stableTriangleColorPolicy:X?.stableTriangleColorPolicy,stableTriangleColorSteps:X?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:X?.stableTriangleColorFreezeFrames??0,stableTriangleColorBudget:X?.stableTriangleColorBudget,stableTriangleColorMaxAge:X?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:X?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:X?.stableTriangleMatrixDecimals,stableTriangleColorFrame:ge};if(an(M.rendered,M.polygons,N,Ie))return Y++,I=le,U=me,M.stableDom=U,M.voxelSource=void 0,M.stableTriangleColorFrame=ge,$e=N,Kn++,kt=null,Qt=-1,Q(M)?(_(M),ue(M,!0)):re(M),!0}Y++,I=le,U=me,M.stableDom=U,M.voxelSource=void 0;let ce=N.vertices;for(let ge=0;ge<N.polygonCount;ge++){let Ie=M.polygons[ge],Ue=N.colors?.[ge];Ue&&(Ie.color=Ue);let _e=Ie.vertices,je=ge*9;_e[0][0]=ce[je],_e[0][1]=ce[je+1],_e[0][2]=ce[je+2],_e[1][0]=ce[je+3],_e[1][1]=ce[je+4],_e[1][2]=ce[je+5],_e[2][0]=ce[je+6],_e[2][1]=ce[je+7],_e[2][2]=ce[je+8]}return Dt(),pt.polygons=M.polygons,zo(X,Le)},updatePolygon(N,X){let le=typeof N=="number"?N:M.polygons.indexOf(N);if(le<0&&typeof N!="number"&&$e&&(le=Bo().indexOf(N)),le<0||le>=M.polygons.length)return;Dt(),M.voxelSource=void 0,Object.assign(M.polygons[le],X);let me=Object.keys(X);_t(M,le,me)||Se(M)},async setPolygonsChunked(N,X){let le=++Y;I=X?.merge??I,U=X?.stableDom??U,M.stableDom=U,M.voxelSource=void 0,M.polygons=ne(N,I),Dt(),pt.polygons=M.polygons,He(M.polygons);let me=X?.recomputeAutoCenter??!0;if(!await Zt(M,()=>M.disposed||le!==Y)){H(M);return}me&&st()},setTransform(N){let X=M.castShadow,le=M.receiveShadow;N.castShadow!==void 0&&(M.castShadow=!!N.castShadow),N.receiveShadow!==void 0&&(M.receiveShadow=!!N.receiveShadow),B={...B,...N};let me=cn(B);E.style.transform=me??"",rt(M,B.rotation),N.rotation!==void 0&&ue(M,!0),M.castShadow!==X&&(M.voxelSource&&Se(M),Ne(M),qe()),M.receiveShadow!==le&&(M.receiveShadow||Mo(M),k(),Ee()),(N.position!==void 0||N.scale!==void 0)&&(M.castShadow||M.receiveShadow)&&(qe(),k(),Ee())},dispose(){if(!M.disposed){M.disposed=!0,Y++,E.parentNode&&E.parentNode.removeChild(E),H(M);try{a.dispose()}catch{}f.delete(M),b.delete(E),st(),qe()}},rebakeAtlas(){M.bakedRotation=B.rotation?[...B.rotation]:[0,0,0];let N=i.directionalLight?.direction??[.4,-.7,.59],X=Lo(N,M.bakedRotation);Zn(M,X)},getPosition(){return B.position},getRotation(){return B.rotation},getScale(){return B.scale},getPolygons(){return pt.polygons}};return M.handle=pt,Ge=M,b.set(E,M),f.add(M),Se(M),rt(M,B.rotation),st(),qe(),M.receiveShadow&&(k(),Ee()),pt}function Gi(a){let m=!!i.autoCenter,S=i.strategies,E=i.seamBleed,W=i.textureLighting,B=i.directionalLight?.direction,I=i.shadow,U=ui(a);i={...i,...U},x.options.current=i,q(g,i);let Y=!!i.autoCenter;for(let $e of f)rt($e,$e.handle.transform.rotation);let ae=a.strategies!==void 0&&!Ir(a.strategies,S),ne=Object.prototype.hasOwnProperty.call(a,"seamBleed")&&U.seamBleed!==E;if(ae||ne)for(let $e of f)Se($e);m!==Y&&st();let K=a.textureLighting!==void 0&&W!==i.textureLighting,oe=i.directionalLight?.direction,J=a.directionalLight!==void 0&&!Fr(B,oe),He=i.shadow,Ge=a.shadow!==void 0&&!Vr(I,He),M=J||Ge;if(K){if(!ae&&!ne)for(let $e of f)Se($e);qe(),k(),Ee()}else M&&(Ge&&k(),Ee());Ge&&a.shadow?.lift!==I?.lift&&qe()}function $i(){return i}function Ui(){D(g);for(let a of f)ue(a)}function ji(){let a=[];for(let m of f)a.push(m.handle);return a}function Wi(a){let m=a;for(;m;){if(m instanceof HTMLElement){let S=b.get(m);if(S&&!S.disposed)return S.handle;if(m.classList.contains("polycss-mesh"))return null}m=m.parentElement}return null}function Yi(){let a=Array.from(f);for(let m of a)try{m.handle.dispose()}catch{}p.parentNode&&p.parentNode.removeChild(p)}return{add:Ni,setOptions:Gi,destroy:Yi,host:e,camera:t,cameraEl:p,applyCamera:Ui,getOptions:$i,meshes:ji,findMeshByElement:Wi,previewBakedSolidLighting:ie,commitBakedSolidLighting:Yn,clearBakedSolidLightingPreview:Xn}}import{createIsometricCamera as hi}from"@layoutit/polycss-core";var Ml=32e3;function Ut(e={}){let n={};e.zoom!==void 0&&(n.zoom=e.zoom),e.target!==void 0&&(n.target=e.target),e.rotX!==void 0&&(n.rotX=e.rotX),e.rotY!==void 0&&(n.rotY=e.rotY),e.distance!==void 0&&(n.distance=e.distance);let t=hi(n),o=`${e.perspective??Ml}px`;return{get state(){return t.state},update(r){t.update(r)},getStyle(r){return t.getStyle(r)},type:"perspective",perspectiveStyle:o}}function jt(e={}){let n={};e.zoom!==void 0&&(n.zoom=e.zoom),e.target!==void 0&&(n.target=e.target),e.rotX!==void 0&&(n.rotX=e.rotX),e.rotY!==void 0&&(n.rotY=e.rotY),e.distance!==void 0&&(n.distance=e.distance);let t=hi(n);return{get state(){return t.state},update(o){t.update(o)},getStyle(o){return t.getStyle(o)},type:"orthographic",perspectiveStyle:"none"}}var wl=typeof HTMLElement<"u"?HTMLElement:class{},Ll=["perspective","rot-x","rot-y","zoom","directional-direction","directional-color","directional-intensity","ambient-color","ambient-intensity","texture-lighting","texture-quality","auto-center"];function Be(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function _l(e){return e==="false"?!1:Be(e)}function _o(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Rl(e){if(e==="baked"||e==="dynamic")return e}function kl(e){return e==="auto"?"auto":Be(e)}function Dl(e){return typeof e.getCamera=="function"}var we=class extends wl{constructor(){super(...arguments);this._scene=null;this._implicitCamera=null}static get observedAttributes(){return[...Ll]}getScene(){return this._scene}_findAncestorCamera(){let t=this.parentElement;for(;t;){if(Dl(t)){let o=t.getCamera();if(o)return o}t=t.parentElement}return null}_buildImplicitCamera(){let t=_l(this.getAttribute("perspective")),o=Be(this.getAttribute("rot-x")),r=Be(this.getAttribute("rot-y")),i=Be(this.getAttribute("zoom")),s=Be(this.getAttribute("distance")),c=_o(this.getAttribute("target")),l={...o!==void 0?{rotX:o}:{},...r!==void 0?{rotY:r}:{},...i!==void 0?{zoom:i}:{},...s!==void 0?{distance:s}:{},...c!==void 0?{target:c}:{}};return t===!1?jt(l):t!==void 0?Ut({...l,perspective:t}):jt(l)}_readNonCameraOptions(){let t=this._readDirectionalLight(),o=this._readAmbientLight(),r={};r.textureLighting=Rl(this.getAttribute("texture-lighting"))??"baked";let i=kl(this.getAttribute("texture-quality"));return i!==void 0&&(r.textureQuality=i),r.autoCenter=this.hasAttribute("auto-center"),t&&(r.directionalLight=t),o&&(r.ambientLight=o),r}_readDirectionalLight(){let t=_o(this.getAttribute("directional-direction")),o=this.getAttribute("directional-color")||void 0,r=Be(this.getAttribute("directional-intensity"));if(!t&&!o&&r===void 0)return;let i={direction:t??[.4,-.7,.59]};return o&&(i.color=o),r!==void 0&&(i.intensity=r),i}_readAmbientLight(){let t=this.getAttribute("ambient-color")||void 0,o=Be(this.getAttribute("ambient-intensity"));if(!t&&o===void 0)return;let r={};return t&&(r.color=t),o!==void 0&&(r.intensity=o),r}connectedCallback(){if(this._scene)return;let t=this._findAncestorCamera(),o;t?(o=t,this._implicitCamera=null):(this._implicitCamera=this._buildImplicitCamera(),o=this._implicitCamera),this._scene=fi(this,{camera:o,...this._readNonCameraOptions()}),this.dispatchEvent(new CustomEvent("polycss:scene-ready",{bubbles:!1}))}disconnectedCallback(){this._scene&&(this._scene.destroy(),this._scene=null),this._implicitCamera=null}attributeChangedCallback(t,o,r){if(o!==r&&this._scene){if(this._implicitCamera&&["rot-x","rot-y","zoom","distance","target"].includes(t)){let s=Be(this.getAttribute("rot-x")),c=Be(this.getAttribute("rot-y")),l=Be(this.getAttribute("zoom")),p=Be(this.getAttribute("distance")),g=_o(this.getAttribute("target"));s!==void 0&&this._implicitCamera.update({rotX:s}),c!==void 0&&this._implicitCamera.update({rotY:c}),l!==void 0&&this._implicitCamera.update({zoom:l}),p!==void 0&&this._implicitCamera.update({distance:p}),g!==void 0&&this._implicitCamera.update({target:g}),this._scene.applyCamera();return}this._scene.setOptions(this._readNonCameraOptions())}}};import{computeSceneBbox as Ol,loadMesh as Hl}from"@layoutit/polycss-core";var Il=typeof HTMLElement<"u"?HTMLElement:class{},Fl=["src","mtl","mesh-resolution","position","scale","rotation","auto-center","cast-shadow","receive-shadow","target-size","default-color","palette","include-objects","exclude-objects"];function Wt(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function gi(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Wt(e)}}function Ro(e){if(!e)return;let n=e.split(",").map(t=>t.trim()).filter(t=>t.length>0);return n.length>0?n:void 0}function Vl(e){let n=e.getAttribute("target-size"),t=e.getAttribute("default-color"),o=Ro(e.getAttribute("palette")),r=Ro(e.getAttribute("include-objects")),i=Ro(e.getAttribute("exclude-objects")),s=n!==null?parseFloat(n):NaN,c={};return Number.isFinite(s)&&(c.targetSize=s),t&&(c.defaultColor=t),o&&(c.palette=o),r&&(c.includeObjects=r),i&&(c.excludeObjects=i),Object.keys(c).length>0?c:void 0}function Bl(e){return e.closest("poly-scene")??null}function zl(e){if(e.length===0)return e;let n=Ol(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,r=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&r===0)return e;let i=s=>[s[0]-t,s[1]-o,s[2]-r];return e.map(s=>({...s,vertices:s.vertices.map(i),...s.textureTriangles?.length?{textureTriangles:s.textureTriangles.map(c=>({...c,vertices:c.vertices.map(i)}))}:null}))}var Ct=class extends Il{constructor(){super(...arguments);this._handle=null;this._parseResult=null;this._loadToken=0}static get observedAttributes(){return[...Fl]}getMeshHandle(){return this._handle}connectedCallback(){this._maybeLoad()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){if(o!==r){if(t==="src"||t==="mtl"||t==="mesh-resolution"||t==="target-size"||t==="default-color"||t==="palette"||t==="include-objects"||t==="exclude-objects"){this._tearDown(),this._maybeLoad();return}this._handle&&this._handle.setTransform({position:Wt(this.getAttribute("position")),scale:gi(this.getAttribute("scale")),rotation:Wt(this.getAttribute("rotation")),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow")})}}_tearDown(){if(this._loadToken+=1,this._handle){try{this._handle.dispose()}catch{}this._handle=null}this._parseResult=null}async _maybeLoad(){let t=this.getAttribute("src");if(!t)return;let o=Bl(this);if(!o)return;let r=++this._loadToken,i=this.getAttribute("mtl")||void 0,c=this.getAttribute("mesh-resolution")==="lossless"?"lossless":void 0,l=Vl(this),p;try{let f=i||c!==void 0||l?{...i?{mtlUrl:i}:{},...c!==void 0?{meshResolution:c}:{},...l?{objOptions:l}:{}}:void 0;p=await Hl(t,f)}catch(f){this.dispatchEvent(new CustomEvent("polycss:error",{detail:f,bubbles:!0}));return}if(r!==this._loadToken){try{p.dispose()}catch{}return}let g=o.getScene();if(!g){try{p.dispose()}catch{}return}this.hasAttribute("auto-center")&&(p={...p,polygons:zl(p.polygons)}),this._parseResult=p,this._handle=g.add(p,{position:Wt(this.getAttribute("position")),scale:gi(this.getAttribute("scale")),rotation:Wt(this.getAttribute("rotation")),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow")}),this.dispatchEvent(new CustomEvent("polycss:loaded",{detail:{polygons:this._handle.polygons},bubbles:!0}))}};import{BASE_TILE as Yt}from"@layoutit/polycss-core";var Nl=typeof HTMLElement<"u"?HTMLElement:class{},Gl=["src","width","height","position","rotation","scale","allow","loading","referrerpolicy","sandbox","title"];function ko(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function $l(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return ko(e)}}function yi(e,n){if(e===null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}function Ul(e){let n=e.closest("poly-scene");return n?n.querySelector(".polycss-scene"):null}function jl(e,n,t,o,r){let i=typeof t=="number"?t:t?.[0]??1,s=typeof t=="number"?t:t?.[1]??1,c=typeof t=="number"?t:t?.[2]??1,l=i!==1||s!==1||c!==1,p=!!n&&(!!n[0]||!!n[1]||!!n[2]),g=(e?.[1]??0)*Yt,x=(e?.[0]??0)*Yt,f=(e?.[2]??0)*Yt,b=[];return b.push(`translate3d(${g}px, ${x}px, ${f}px)`),p&&(n[0]&&b.push(`rotateY(${-n[0]}deg)`),n[1]&&b.push(`rotateX(${-n[1]}deg)`),n[2]&&b.push(`rotateZ(${-n[2]}deg)`)),l&&b.push(`scale3d(${i}, ${s}, ${c})`),b.push(`translate(${-o/2}px, ${-r/2}px)`),b.join(" ")}var mn=class extends Nl{constructor(){super(...arguments);this._wrapper=null;this._iframe=null}static get observedAttributes(){return[...Gl]}getIframeElement(){return this._iframe}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,r){if(o!==r&&!(!this._wrapper||!this._iframe)){if(t==="src"){this._iframe.src=this.getAttribute("src")??"";return}if(t==="allow"||t==="loading"||t==="referrerpolicy"||t==="sandbox"||t==="title"){let i=this.getAttribute(t);i===null?this._iframe.removeAttribute(t):this._iframe.setAttribute(t,i);return}this._applyGeometry()}}_mount(){let t=Ul(this);if(!t)return;let o=this.ownerDocument;if(!o)return;let r=o.createElement("div");r.className="polycss-iframe",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.transformOrigin="0 0",r.style.transformStyle="preserve-3d";let i=o.createElement("iframe");i.style.display="block",i.style.border="0",i.style.background="#000";let s=this.getAttribute("src");s&&(i.src=s);let c=this.getAttribute("allow");c&&i.setAttribute("allow",c);for(let l of["loading","referrerpolicy","sandbox","title"]){let p=this.getAttribute(l);p!==null&&i.setAttribute(l,p)}r.appendChild(i),t.appendChild(r),this._wrapper=r,this._iframe=i,this._applyGeometry()}_applyGeometry(){if(!this._wrapper||!this._iframe)return;let t=yi(this.getAttribute("width"),16),o=yi(this.getAttribute("height"),9),r=t*Yt,i=o*Yt;this._iframe.style.width=`${r}px`,this._iframe.style.height=`${i}px`;let s=ko(this.getAttribute("position")),c=ko(this.getAttribute("rotation")),l=$l(this.getAttribute("scale"));this._wrapper.style.transform=jl(s,c,l,r,i)}_teardown(){this._wrapper?.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null,this._iframe=null}};var Wl=typeof HTMLElement<"u"?HTMLElement:class{},Yl=["vertices","color","texture","uvs","position","scale","rotation"];function bi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Do(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Xl(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Do(e)}}function Zl(e){return e.closest("poly-scene")??null}var fn=class extends Wl{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...Yl]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){o!==r&&(this._tearDown(),this.isConnected&&this._mount())}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=Zl(this);if(!t)return;let o=t.getScene();if(!o)return;let r=bi(this.getAttribute("vertices"));if(!r||!Array.isArray(r)||r.length<3)return;let i=this.getAttribute("color")||void 0,s=this.getAttribute("texture")||void 0,c=bi(this.getAttribute("uvs"))??void 0,l={};for(let x of Array.from(this.attributes))x.name.startsWith("data-")&&(l[x.name.slice(5)]=x.value);let g={polygons:[{vertices:r,...i!==void 0?{color:i}:{},...s!==void 0?{texture:s}:{},...c!==void 0?{uvs:c}:{},...Object.keys(l).length>0?{data:l}:{}}],objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(g,{position:Do(this.getAttribute("position")),scale:Xl(this.getAttribute("scale")),rotation:Do(this.getAttribute("rotation"))})}};import{axesHelperPolygons as Ql}from"@layoutit/polycss-core";var ql=typeof HTMLElement<"u"?HTMLElement:class{},Kl=["size","thickness","negative","x-color","y-color","z-color"];function Jl(e){return e.closest("poly-scene")??null}function vi(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}var hn=class extends ql{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...Kl]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){o!==r&&this._handle&&this._remount()}_polygons(){return Ql({size:vi(this.getAttribute("size")),thickness:vi(this.getAttribute("thickness")),negative:this.hasAttribute("negative"),xColor:this.getAttribute("x-color")??void 0,yColor:this.getAttribute("y-color")??void 0,zColor:this.getAttribute("z-color")??void 0})}_mount(){let t=Jl(this);if(!t)return;let o=t.getScene();if(!o)return;let r={polygons:this._polygons(),objectUrls:[],dispose:()=>{},warnings:[]};this._handle=o.add(r,{excludeFromAutoCenter:!0,merge:!1})}_remount(){this._tearDown(),this._mount()}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}};import{octahedronPolygons as ec}from"@layoutit/polycss-core";var tc=typeof HTMLElement<"u"?HTMLElement:class{},nc=["direction","target","distance","size","color"],oc=5,rc=.35,ic="#ffd54a";function sc(e){return e.closest("poly-scene")??null}function xi(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Pi(e,n){if(e==null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}var gn=class extends tc{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...nc]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){if(o!==r&&this._handle){if(t==="size"||t==="color"){this._remount();return}this._handle.setTransform({position:this._meshPosition()})}}_meshPosition(){let t=xi(this.getAttribute("direction"));if(!t)return;let o=xi(this.getAttribute("target"))??[0,0,0],r=Pi(this.getAttribute("distance"),oc),[i,s,c]=t,l=Math.hypot(i,s,c)||1;return[o[0]+i/l*r,o[1]+s/l*r,o[2]+c/l*r]}_mount(){let t=sc(this);if(!t)return;let o=t.getScene();if(!o)return;let r=Pi(this.getAttribute("size"),rc),i=this.getAttribute("color")??ic,s={polygons:ec({center:[0,0,0],size:r,color:i}),objectUrls:[],dispose:()=>{},warnings:[]};this._handle=o.add(s,{position:this._meshPosition(),excludeFromAutoCenter:!0,merge:!1})}_remount(){this._tearDown(),this._mount()}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}};import{BASE_TILE as ac}from"@layoutit/polycss-core";var yn={drag:!0,wheel:!0,dolly:!1,invert:!1,minZoom:.1,maxZoom:10,minDistance:0,maxDistance:1/0,animate:!1};function Et(e,n){let t;return n.animate===!1?t=!1:n.animate?t={speed:n.animate.speed??.3,axis:n.animate.axis??"y",pauseOnInteraction:n.animate.pauseOnInteraction??!0}:t=e.animate,{drag:n.drag??e.drag,wheel:n.wheel??e.wheel,dolly:n.dolly??e.dolly,invert:n.invert??e.invert,minZoom:n.minZoom??e.minZoom,maxZoom:n.maxZoom??e.maxZoom,minDistance:n.minDistance??e.minDistance,maxDistance:n.maxDistance??e.maxDistance,animate:t}}function Xt(e){return e===!0?-1:e===!1?1:e}function Tt(){let e=[],n=[],t=[];function o(s){return s==="change"?e:s==="start"?n:t}function r(s){if(e.length===0)return;let c={type:"change",camera:s()},l=e.slice();for(let p of l)try{p(c)}catch(g){console.error("[polycss] controls 'change' listener threw:",g)}}function i(s,c){let l=s==="start"?n:t;if(l.length===0)return;let p={type:s,camera:c()},g=l.slice();for(let x of g)try{x(p)}catch(f){console.error(`[polycss] controls '${s}' listener threw:`,f)}}return{changeListeners:e,startListeners:n,endListeners:t,listenerArray:o,emitChange:r,emitInteraction:i}}function At(e){return()=>{let n=e.camera.state,t=n.target??[0,0,0];return{rotX:n.rotX??0,rotY:n.rotY??0,zoom:n.zoom??1,target:[t[0],t[1],t[2]],distance:n.distance??0}}}function bn(e,n,t,o,r,i){let s=!1,c=null;return{onWheel:g=>{let x=n();if(!x.wheel||t())return;g.preventDefault();let f=g.deltaMode===1?16:g.deltaMode===2?100:1,b=g.deltaY*f;g.ctrlKey?b*=10:b*=3;let y=e.camera.state;if(x.dolly){let P=y.distance??0,v=Math.max(x.minDistance,Math.min(x.maxDistance,P+b*.05));e.camera.update({distance:v})}else{let P=Math.exp(-b*513e-6),v=y.zoom??1,C=Math.max(x.minZoom,Math.min(x.maxZoom,v*P));e.camera.update({zoom:C})}e.applyCamera(),s||(s=!0,i("start",o)),r(o),c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,s=!1,i("end",o)},150)},teardown:()=>{c!==null&&(clearTimeout(c),c=null),s=!1}}}function vn(e,n,t,o,r,i,s){let c=null,l=0,p=b=>{if(c===null||o())return;let y=t();if(!y.animate){c=null;return}if(r())l=b;else{let P=Math.min(50,l?b-l:16.67);l=b;let v=y.animate.speed*(P/16.67),C=n.camera.state;if(y.animate.axis==="x"){let F=(((C.rotX??65)+v)%360+360)%360;n.camera.update({rotX:F})}else{let F=(((C.rotY??45)+v)%360+360)%360;n.camera.update({rotY:F})}n.applyCamera(),s(i)}c=e.requestAnimationFrame(p)};return{start:()=>{c!==null||!t().animate||o()||(l=0,c=e.requestAnimationFrame(p))},stop:()=>{c!==null&&(e.cancelAnimationFrame(c),c=null)},isRunning:()=>c!==null}}function Si(e,n={}){let t=Et(yn,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,i=null,s={x:0,y:0},c=!1,l=!1,p=Tt(),g=At(e),{changeListeners:x,startListeners:f,endListeners:b,listenerArray:y,emitChange:P,emitInteraction:v}=p,C=vn(r,e,()=>t,()=>l,()=>c,g,P),F=d=>{if(!(!t.drag||l)&&i===null&&d.isPrimary!==!1){d.preventDefault(),i=d.pointerId,s={x:d.clientX,y:d.clientY},o.style.cursor="grabbing";try{d.target.setPointerCapture(d.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),v("start",g)}},k=d=>{if(i===null||d.pointerId!==i||!t.drag||l)return;d.preventDefault();let T=d.clientX-s.x,w=d.clientY-s.y;s={x:d.clientX,y:d.clientY};let R=Xt(t.invert),L=T/4*R,te=w/4*R,_=e.camera.state;if(d.shiftKey){let j=_.rotX??65,Q=_.rotY??45,re=Math.max(.01,_.zoom??1),fe=Math.cos(j*Math.PI/180),ue=fe>=0?Math.max(.1,fe):Math.min(-.1,fe),pe=Math.cos(Q*Math.PI/180),Ce=Math.sin(Q*Math.PI/180),be=re*ac,Ae=(T*Ce-w*pe/ue)/be,ze=-(T*pe+w*Ce/ue)/be,Qe=_.target??[0,0,0];e.camera.update({target:[Qe[0]+Ae,Qe[1]+ze,Qe[2]]})}else{let j=Math.max(0,Math.min(89,(_.rotX??65)-te)),Q=(((_.rotY??45)-L)%360+360)%360;e.camera.update({rotX:j,rotY:Q})}e.applyCamera(),P(g)},z=d=>{if(i===d.pointerId){i=null,o.style.cursor=t.drag&&!l?"grab":"";try{d.target.releasePointerCapture(d.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),v("end",g)}},O=bn(e,()=>t,()=>l,g,P,v);function Z(){o.addEventListener("pointerdown",F),o.addEventListener("pointermove",k),o.addEventListener("pointerup",z),o.addEventListener("pointercancel",z),o.addEventListener("wheel",O.onWheel,{passive:!1}),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function q(){o.removeEventListener("pointerdown",F),o.removeEventListener("pointermove",k),o.removeEventListener("pointerup",z),o.removeEventListener("pointercancel",z),o.removeEventListener("wheel",O.onWheel),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",O.teardown()}Z(),C.start();function D(d){let T=!!t.animate;t=Et(t,d),!l&&i===null&&(o.style.cursor=t.drag?"grab":"");let w=!!t.animate;T&&!w?C.stop():!T&&w&&C.start()}function H(){l&&(l=!1,Z(),C.start())}function V(){l||(l=!0,q(),C.stop(),i=null,c=!1,O.teardown())}function G(){V(),x.length=0,f.length=0,b.length=0}function A(d,T){let w=y(d);w.includes(T)||w.push(T)}function h(d,T){let w=y(d),R=w.indexOf(T);R>=0&&w.splice(R,1)}function u(d,T){return y(d).includes(T)}return{update:D,resume:H,pause:V,destroy:G,addEventListener:A,removeEventListener:h,hasEventListener:u}}function ee(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function xn(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Te(e){if(e!==null)return!(e==="false"||e==="0")}function Pn(e){if(e===null)return;if(e==="true")return!0;if(e==="false")return!1;let n=parseFloat(e);return Number.isFinite(n)?n:!0}function Sn(e){if(e==="x"||e==="y")return e}var lc=typeof HTMLElement<"u"?HTMLElement:class{},cc=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],Cn=class extends lc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...cc]}getControls(){return this._controls}_readAnimate(){let t=ee(this.getAttribute("animate-speed")),o=Sn(this.getAttribute("animate-axis")),r=this.getAttribute("animate-pause-on-interaction");if(this.hasAttribute("animate-speed")||this.hasAttribute("animate-axis")||this.hasAttribute("animate-pause-on-interaction"))return{...t!==void 0?{speed:t}:{},...o!==void 0?{axis:o}:{},...r!==null?{pauseOnInteraction:Te(r)}:{}}}_readOptions(){let t={},o=Te(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Te(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let i=ee(this.getAttribute("min-distance"));i!==void 0&&(t.minDistance=i);let s=ee(this.getAttribute("max-distance"));s!==void 0&&(t.maxDistance=s);let c=Pn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=ee(this.getAttribute("zoom-min")),p=ee(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),p!==void 0&&(t.maxZoom=p),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof we)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=Si(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};import{BASE_TILE as dc}from"@layoutit/polycss-core";function Ci(e,n={}){let t=Et(yn,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,i=null,s={x:0,y:0},c=!1,l=!1,p=!1,g={x:0,y:0},x=Tt(),f=At(e),{changeListeners:b,startListeners:y,endListeners:P,listenerArray:v,emitChange:C,emitInteraction:F}=x,k=vn(r,e,()=>t,()=>l,()=>c,f,C),z=_=>{if(!(!t.drag||l)&&i===null&&_.isPrimary!==!1){_.preventDefault(),i=_.pointerId,s={x:_.clientX,y:_.clientY},o.style.cursor="grabbing";try{_.target.setPointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),F("start",f)}},O=_=>{if(i===null||_.pointerId!==i||!t.drag||l)return;_.preventDefault();let j=_.clientX-s.x,Q=_.clientY-s.y;s={x:_.clientX,y:_.clientY};let re=e.camera.state;if(_.shiftKey){let fe=Xt(t.invert),ue=j/4*fe,pe=Q/4*fe,Ce=(re.rotX??65)-pe,be=(((re.rotY??45)-ue)%360+360)%360;e.camera.update({rotX:Ce,rotY:be})}else{let fe=re.rotX??65,ue=re.rotY??45,pe=Math.max(.01,re.zoom??1),Ce=Math.cos(fe*Math.PI/180),be=Ce>=0?Math.max(.1,Ce):Math.min(-.1,Ce),Ae=Math.cos(ue*Math.PI/180),ze=Math.sin(ue*Math.PI/180),Qe=pe*dc,rt=(j*ze-Q*Ae/be)/Qe,ut=-(j*Ae+Q*ze/be)/Qe,it=re.target??[0,0,0];e.camera.update({target:[it[0]+rt,it[1]+ut,it[2]]})}e.applyCamera(),C(f)},Z=_=>{if(i===_.pointerId){i=null,o.style.cursor=t.drag&&!l?"grab":"";try{_.target.releasePointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),F("end",f)}},q=_=>{_.preventDefault()},D=_=>{_.button===2&&(p=!0,g={x:_.clientX,y:_.clientY},t.animate&&t.animate.pauseOnInteraction&&(c=!0),F("start",f))},H=_=>{if(!p||!t.drag)return;let j=_.clientX-g.x,Q=_.clientY-g.y;g={x:_.clientX,y:_.clientY};let re=Xt(t.invert),fe=j/4*re,ue=Q/4*re,pe=e.camera.state,Ce=(pe.rotX??65)-ue,be=(((pe.rotY??45)-fe)%360+360)%360;e.camera.update({rotX:Ce,rotY:be}),e.applyCamera(),C(f)},V=_=>{_.button===2&&p&&(p=!1,F("end",f))},G=bn(e,()=>t,()=>l,f,C,F);function A(){o.addEventListener("pointerdown",z),o.addEventListener("pointermove",O),o.addEventListener("pointerup",Z),o.addEventListener("pointercancel",Z),o.addEventListener("wheel",G.onWheel,{passive:!1}),o.addEventListener("contextmenu",q),o.addEventListener("mousedown",D),o.addEventListener("mousemove",H),o.addEventListener("mouseup",V),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function h(){o.removeEventListener("pointerdown",z),o.removeEventListener("pointermove",O),o.removeEventListener("pointerup",Z),o.removeEventListener("pointercancel",Z),o.removeEventListener("wheel",G.onWheel),o.removeEventListener("contextmenu",q),o.removeEventListener("mousedown",D),o.removeEventListener("mousemove",H),o.removeEventListener("mouseup",V),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",G.teardown()}A(),k.start();function u(_){let j=!!t.animate;t=Et(t,_),!l&&i===null&&(o.style.cursor=t.drag?"grab":"");let Q=!!t.animate;j&&!Q?k.stop():!j&&Q&&k.start()}function d(){l&&(l=!1,A(),k.start())}function T(){l||(l=!0,h(),k.stop(),i=null,c=!1,p=!1,G.teardown())}function w(){T(),b.length=0,y.length=0,P.length=0}function R(_,j){let Q=v(_);Q.includes(j)||Q.push(j)}function L(_,j){let Q=v(_),re=Q.indexOf(j);re>=0&&Q.splice(re,1)}function te(_,j){return v(_).includes(j)}return{update:u,resume:d,pause:T,destroy:w,addEventListener:R,removeEventListener:L,hasEventListener:te}}var uc=typeof HTMLElement<"u"?HTMLElement:class{},pc=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],En=class extends uc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...pc]}_readAnimate(){let t=ee(this.getAttribute("animate-speed")),o=Sn(this.getAttribute("animate-axis")),r=this.getAttribute("animate-pause-on-interaction");if(this.hasAttribute("animate-speed")||this.hasAttribute("animate-axis")||this.hasAttribute("animate-pause-on-interaction"))return{...t!==void 0?{speed:t}:{},...o!==void 0?{axis:o}:{},...r!==null?{pauseOnInteraction:Te(r)}:{}}}_readOptions(){let t={},o=Te(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Te(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let i=ee(this.getAttribute("min-distance"));i!==void 0&&(t.minDistance=i);let s=ee(this.getAttribute("max-distance"));s!==void 0&&(t.maxDistance=s);let c=Pn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=ee(this.getAttribute("zoom-min")),p=ee(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),p!==void 0&&(t.maxZoom=p),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof we)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=Ci(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};import{BASE_TILE as mc}from"@layoutit/polycss-core";var fc={enabled:!0,lookEnabled:!0,moveEnabled:!0,jumpEnabled:!0,crouchEnabled:!0,lookSensitivity:.15,invertY:!1,moveSpeed:5,jumpVelocity:7,gravity:18,eyeHeight:1.7,crouchHeight:1,groundZ:0,minPitch:5,maxPitch:175};function Ei(e,n){return{enabled:n.enabled??e.enabled,lookEnabled:n.lookEnabled??e.lookEnabled,moveEnabled:n.moveEnabled??e.moveEnabled,jumpEnabled:n.jumpEnabled??e.jumpEnabled,crouchEnabled:n.crouchEnabled??e.crouchEnabled,lookSensitivity:n.lookSensitivity??e.lookSensitivity,invertY:n.invertY??e.invertY,moveSpeed:n.moveSpeed??e.moveSpeed,jumpVelocity:n.jumpVelocity??e.jumpVelocity,gravity:n.gravity??e.gravity,eyeHeight:n.eyeHeight??e.eyeHeight,crouchHeight:n.crouchHeight??e.crouchHeight,groundZ:n.groundZ??e.groundZ,minPitch:n.minPitch??e.minPitch,maxPitch:n.maxPitch??e.maxPitch}}var Ti=new Set(["KeyW","ArrowUp"]),Ai=new Set(["KeyS","ArrowDown"]),Mi=new Set(["KeyA","ArrowLeft"]),wi=new Set(["KeyD","ArrowRight"]),Li=new Set(["Space"]),Oo=new Set(["ControlLeft","ControlRight"]);function _i(e,n={}){let t=Ei(fc,n),o=e.host,r=e.cameraEl,i=o.ownerDocument??document,s=i.defaultView??globalThis,c=Tt(),l=At(e),{changeListeners:p,startListeners:g,endListeners:x,listenerArray:f,emitChange:b,emitInteraction:y}=c,P=new Set,v=!1,C=!1,F=0,k=0,z=!1,O=[0,0,t.groundZ+t.eyeHeight];function Z($,ie){let se=$*Math.PI/180,Me=ie*Math.PI/180;return[-Math.sin(se)*Math.cos(Me),-Math.sin(se)*Math.sin(Me),-Math.cos(se)]}function q(){let $=e.camera.perspectiveStyle,ie=$==="none"?0:parseFloat($);return(Number.isFinite(ie)&&ie>0?ie:2e3)/mc}function D(){let $=e.camera.state,ie=Z($.rotX??90,$.rotY??0),se=q();return[O[0]+ie[0]*se,O[1]+ie[1]*se,O[2]+ie[2]*se]}function H(){let $=D();e.camera.update({target:$}),e.applyCamera()}function V(){let $=e.camera.state.target??[0,0,0];O=[$[0],$[1],t.groundZ+t.eyeHeight],H()}let G=()=>{if(!(!t.enabled||!t.lookEnabled||C||v))try{o.requestPointerLock()}catch{}},A=()=>{let $=i.pointerLockElement===o;$!==v&&(v=$,v?(z=!0,y("start",l)):z&&(z=!1,y("end",l)))},h=$=>{if(!v||!t.enabled||!t.lookEnabled||C)return;let ie=$.movementX??0,se=$.movementY??0;if(ie===0&&se===0)return;let Me=e.camera.state,_t=t.lookSensitivity,Ne=t.invertY?-1:1,Ee=(((Me.rotY??0)-ie*_t)%360+360)%360,ve=(Me.rotX??90)-se*_t*Ne;ve<t.minPitch?ve=t.minPitch:ve>t.maxPitch&&(ve=t.maxPitch);let De=Z(ve,Ee),Oe=q(),Se=[O[0]+De[0]*Oe,O[1]+De[1]*Oe,O[2]+De[2]*Oe];e.camera.update({rotX:ve,rotY:Ee,target:Se}),e.applyCamera(),b(l)},u=$=>Ti.has($)||Ai.has($)||Mi.has($)||wi.has($)||Li.has($)||Oo.has($),d=$=>{if(!(!t.enabled||C)&&u($.code)&&!(!v&&!t.moveEnabled)){if(Li.has($.code)){if(!t.jumpEnabled)return;$.preventDefault(),!P.has($.code)&&F===0&&k===0&&(F=t.jumpVelocity),P.add($.code);return}Oo.has($.code)&&!t.crouchEnabled||!t.moveEnabled&&!Oo.has($.code)||($.preventDefault(),P.add($.code))}},T=$=>{u($.code)&&P.delete($.code)},w=()=>{P.clear()},R=null,L=0,te=.05,_=$=>{if(R===null||C)return;let ie=Math.min(te,L?($-L)/1e3:.0167);if(L=$,t.enabled){let se=!1,Me=e.camera.state;if(t.moveEnabled){let ve=0,De=0;for(let Oe of P)Ti.has(Oe)?ve+=1:Ai.has(Oe)?ve-=1:wi.has(Oe)?De+=1:Mi.has(Oe)&&(De-=1);if(ve!==0||De!==0){let Se=(Me.rotY??0)*Math.PI/180,Rt=-Math.cos(Se),Zn=-Math.sin(Se),Qn=-Math.sin(Se),qn=Math.cos(Se),qe=Math.hypot(ve,De)||1,Zt=t.moveSpeed*ie;O[0]+=(Rt*ve+Qn*De)/qe*Zt,O[1]+=(Zn*ve+qn*De)/qe*Zt,se=!0}}let Ne=t.crouchEnabled&&(P.has("ControlLeft")||P.has("ControlRight"))?t.crouchHeight:t.eyeHeight;t.jumpEnabled&&(F!==0||k>0)?(F-=t.gravity*ie,k+=F*ie,k<=0&&(k=0,F=0)):t.jumpEnabled||(k=0,F=0);let Ee=t.groundZ+Ne+k;if(Math.abs(O[2]-Ee)>1e-4&&(O[2]=Ee,se=!0),se){let ve=D();e.camera.update({target:ve}),e.applyCamera(),b(l)}}R=s.requestAnimationFrame(_)};function j(){R!==null||C||(L=0,R=s.requestAnimationFrame(_))}function Q(){R!==null&&(s.cancelAnimationFrame(R),R=null)}function re(){let ie=r.ownerDocument?.defaultView?.getComputedStyle(r).perspective??"",se=parseFloat(ie),Me=Number.isFinite(se)&&se>0?se:2e3;r.style.setProperty("--polycss-fpv-perspective",`${Me}px`),r.classList.add("polycss-fpv-host")}function fe(){r.classList.remove("polycss-fpv-host"),r.style.removeProperty("--polycss-fpv-perspective")}function ue(){o.addEventListener("click",G),i.addEventListener("pointerlockchange",A),i.addEventListener("mousemove",h),s.addEventListener("keydown",d),s.addEventListener("keyup",T),s.addEventListener("blur",w),o.style.cursor=t.lookEnabled?"crosshair":"",re()}function pe(){if(o.removeEventListener("click",G),i.removeEventListener("pointerlockchange",A),i.removeEventListener("mousemove",h),s.removeEventListener("keydown",d),s.removeEventListener("keyup",T),s.removeEventListener("blur",w),o.style.cursor="",P.clear(),v)try{i.exitPointerLock()}catch{}fe()}V(),ue(),j();function Ce($){let ie=t.eyeHeight,se=t.groundZ;t=Ei(t,$),C||(o.style.cursor=t.lookEnabled?"crosshair":""),(t.eyeHeight!==ie||t.groundZ!==se)&&(O[2]=t.groundZ+t.eyeHeight,H(),b(l))}function be(){C&&(C=!1,ue(),j())}function Ae(){C||(C=!0,pe(),Q(),z&&(z=!1,y("end",l)))}function ze(){Ae(),p.length=0,g.length=0,x.length=0}function Qe(){if(!(!t.enabled||!t.lookEnabled||C))try{o.requestPointerLock()}catch{}}function rt(){if(v)try{i.exitPointerLock()}catch{}}function ut(){return v}function it($,ie){let se=f($);se.includes(ie)||se.push(ie)}function jn($,ie){let se=f($),Me=se.indexOf(ie);Me>=0&&se.splice(Me,1)}function Wn($,ie){return f($).includes(ie)}function Yn(){return[O[0],O[1],O[2]]}function Xn($){O[0]=$[0],O[1]=$[1],O[2]=$[2],H(),b(l)}return{update:Ce,resume:be,pause:Ae,destroy:ze,lock:Qe,unlock:rt,isLocked:ut,getOrigin:Yn,setOrigin:Xn,addEventListener:it,removeEventListener:jn,hasEventListener:Wn}}var hc=typeof HTMLElement<"u"?HTMLElement:class{},gc=["enabled","look-enabled","move-enabled","jump-enabled","crouch-enabled","look-sensitivity","invert-y","move-speed","jump-velocity","gravity","eye-height","crouch-height","ground-z","min-pitch","max-pitch"],Tn=class extends hc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...gc]}_readOptions(){let t={},o=Te(this.getAttribute("enabled"));o!==void 0&&(t.enabled=o);let r=Te(this.getAttribute("look-enabled"));r!==void 0&&(t.lookEnabled=r);let i=Te(this.getAttribute("move-enabled"));i!==void 0&&(t.moveEnabled=i);let s=Te(this.getAttribute("jump-enabled"));s!==void 0&&(t.jumpEnabled=s);let c=Te(this.getAttribute("crouch-enabled"));c!==void 0&&(t.crouchEnabled=c);let l=ee(this.getAttribute("look-sensitivity"));if(l!==void 0&&(t.lookSensitivity=l),this.hasAttribute("invert-y")){let C=Te(this.getAttribute("invert-y"));C!==void 0&&(t.invertY=C)}let p=ee(this.getAttribute("move-speed"));p!==void 0&&(t.moveSpeed=p);let g=ee(this.getAttribute("jump-velocity"));g!==void 0&&(t.jumpVelocity=g);let x=ee(this.getAttribute("gravity"));x!==void 0&&(t.gravity=x);let f=ee(this.getAttribute("eye-height"));f!==void 0&&(t.eyeHeight=f);let b=ee(this.getAttribute("crouch-height"));b!==void 0&&(t.crouchHeight=b);let y=ee(this.getAttribute("ground-z"));y!==void 0&&(t.groundZ=y);let P=ee(this.getAttribute("min-pitch"));P!==void 0&&(t.minPitch=P);let v=ee(this.getAttribute("max-pitch"));return v!==void 0&&(t.maxPitch=v),t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof we)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._controls=_i(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,r){o!==r&&this._controls&&this._controls.update(this._readOptions())}};var yc=typeof HTMLElement<"u"?HTMLElement:class{},bc=["perspective","zoom","rot-x","rot-y","target","distance"],An=class extends yc{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...bc]}getCamera(){return this._camera}_readOptions(){return{perspective:ee(this.getAttribute("perspective")),zoom:ee(this.getAttribute("zoom")),rotX:ee(this.getAttribute("rot-x")),rotY:ee(this.getAttribute("rot-y")),target:xn(this.getAttribute("target")),distance:ee(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=Ut(t),this._wrapper=this.ownerDocument.createElement("div"),this._wrapper.className="polycss-camera",this._wrapper.style.perspective=this._camera.perspectiveStyle;this.firstChild;)this._wrapper.appendChild(this.firstChild);this.appendChild(this._wrapper),this.dispatchEvent(new CustomEvent("polycss:camera-ready",{bubbles:!1}))}_teardown(){if(this._wrapper){for(;this._wrapper.firstChild;)this.insertBefore(this._wrapper.firstChild,this._wrapper);this._wrapper.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null}this._camera=null}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,r){if(o===r||!this._camera||!this._wrapper)return;let i=this._readOptions();if(t==="perspective"){this._camera=Ut(i),this._wrapper.style.perspective=this._camera.perspectiveStyle;return}this._camera.update({rotX:i.rotX,rotY:i.rotY,zoom:i.zoom,target:i.target,distance:i.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var vc=typeof HTMLElement<"u"?HTMLElement:class{},xc=["zoom","rot-x","rot-y","target","distance"],Mt=class extends vc{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...xc]}getCamera(){return this._camera}_readOptions(){return{zoom:ee(this.getAttribute("zoom")),rotX:ee(this.getAttribute("rot-x")),rotY:ee(this.getAttribute("rot-y")),target:xn(this.getAttribute("target")),distance:ee(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=jt(t),this._wrapper=this.ownerDocument.createElement("div"),this._wrapper.className="polycss-camera",this._wrapper.style.perspective=this._camera.perspectiveStyle;this.firstChild;)this._wrapper.appendChild(this.firstChild);this.appendChild(this._wrapper),this.dispatchEvent(new CustomEvent("polycss:camera-ready",{bubbles:!1}))}_teardown(){if(this._wrapper){for(;this._wrapper.firstChild;)this.insertBefore(this._wrapper.firstChild,this._wrapper);this._wrapper.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null}this._camera=null}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,r){if(o===r||!this._camera)return;let i=this._readOptions();i.zoom!==void 0&&this._camera.update({zoom:i.zoom}),i.rotX!==void 0&&this._camera.update({rotX:i.rotX}),i.rotY!==void 0&&this._camera.update({rotY:i.rotY}),i.target!==void 0&&this._camera.update({target:i.target}),i.distance!==void 0&&this._camera.update({distance:i.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var Mn=class extends Mt{};import{arrowPolygons as Pc,eulerXYZFromQuat as Sc,planePolygons as Cc,quatFromAxisAngle as Ec,quatFromEulerXYZ as Tc,quatMultiply as Ac,ringQuadPolygons as Mc,rotateVec3 as Ho}from"@layoutit/polycss-core";function wt(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let r of o){let i=r.getBoundingClientRect();if(!(i.width<=0||i.height<=0)&&n>=i.left&&n<=i.right&&t>=i.top&&t<=i.bottom)return!0}return!1}function Ri(e,n,t,o){for(let r of e)if(!(o&&!o(r))&&wt(r.element,n,t))return r;return null}var wn="#ff3653",Ln="#8adb00",_n="#2c8fff",Lt=50,ki=60,wc=.6,Lc=.0125,_c=.15,Rc=.04,kc=1,Di=.02,Io=1.04,Dc=.1,Oc=.25,Fi=1e-4,Hc=.6,Ic=.8,Fc=1,Je={0:1,1:0,2:2},Oi=[{cssAxis:0,sign:1,key:"x",color:wn},{cssAxis:0,sign:-1,key:"-x",color:wn},{cssAxis:1,sign:1,key:"y",color:Ln},{cssAxis:1,sign:-1,key:"-y",color:Ln},{cssAxis:2,sign:1,key:"z",color:_n},{cssAxis:2,sign:-1,key:"-z",color:_n}],Hi=[{cssAxis:0,key:"x",color:wn},{cssAxis:1,key:"y",color:Ln},{cssAxis:2,key:"z",color:_n}],Ii=[{perpAxis:2,axisA:0,axisB:1,key:"xy",color:_n},{perpAxis:1,axisA:0,axisB:2,key:"xz",color:Ln},{perpAxis:0,axisA:1,axisB:2,key:"yz",color:wn}];function Fo(e,n,t,o){let r=t*Math.PI/180,i=o*Math.PI/180,s=[0,0,0];s[e]=n;let c=s[0]*Math.cos(i)-s[1]*Math.sin(i),l=s[0]*Math.sin(i)+s[1]*Math.cos(i),p=s[2];return l*Math.sin(r)+p*Math.cos(r)<0}function Vc(e,n){let t=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(e);if(!t)return e;let o=parseInt(t[1],16),r=parseInt(t[2],16),i=parseInt(t[3],16);return`rgba(${o}, ${r}, ${i}, ${n})`}function Rn(e,n){return!n||n<=0?e:Math.round(e/n)*n}function Bc(e){if(e.length===0)return[0,0,0];let n=1/0,t=1/0,o=1/0,r=-1/0,i=-1/0,s=-1/0;for(let c of e)for(let l of c.vertices)l[0]<n&&(n=l[0]),l[0]>r&&(r=l[0]),l[1]<t&&(t=l[1]),l[1]>i&&(i=l[1]),l[2]<o&&(o=l[2]),l[2]>s&&(s=l[2]);return Number.isFinite(n)?[(n+r)/2,(t+i)/2,(o+s)/2]:[0,0,0]}function Vo(e){if(e.length===0)return ki;let n=1/0,t=1/0,o=1/0,r=-1/0,i=-1/0,s=-1/0;for(let l of e)for(let p of l.vertices)p[0]<n&&(n=p[0]),p[0]>r&&(r=p[0]),p[1]<t&&(t=p[1]),p[1]>i&&(i=p[1]),p[2]<o&&(o=p[2]),p[2]>s&&(s=p[2]);return Number.isFinite(n)?Math.max(r-n,i-t,s-o)*Lt*wc:ki}function zc(e){let{cssAxis:n,sign:t,shaftLengthCss:o,wrapper:r,target:i,startClientX:s,startClientY:c,translationSnap:l,onAxisDelta:p,onMouseDown:g,onMouseUp:x,onDraggingChanged:f}=e,b=o,y=[0,0,0];y[n]=t;let P=r.ownerDocument.createElement("div");P.style.position="absolute",P.style.left="0",P.style.top="0",P.style.width="0",P.style.height="0",P.style.transform=`translate3d(${y[0]*b}px, ${y[1]*b}px, ${y[2]*b}px)`,r.appendChild(P);let v=r.getBoundingClientRect(),C=P.getBoundingClientRect();r.removeChild(P);let F=(C.left-v.left)/b,k=(C.top-v.top)/b,z=F*F+k*k;if(z<Fi)return;g?.(),f?.(!0);let O=q=>{let D=q.clientX-s,H=q.clientY-c,V=(D*F+H*k)/z;V=Rn(V,l),p(V,y)},Z=()=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",Z),window.removeEventListener("pointercancel",Z);let q=D=>{D.stopPropagation(),D.stopImmediatePropagation()};window.addEventListener("click",q,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",q,!0),0),x?.(),f?.(!1)};window.addEventListener("pointermove",O),window.addEventListener("pointerup",Z),window.addEventListener("pointercancel",Z)}function Nc(e){let{axisA:n,axisB:t,probeDistanceCss:o,wrapper:r,startClientX:i,startClientY:s,translationSnap:c,onPlaneDelta:l,onMouseDown:p,onMouseUp:g,onDraggingChanged:x}=e,f=[0,0,0];f[n]=1;let b=[0,0,0];b[t]=1;function y(z){let O=r.ownerDocument.createElement("div");O.style.position="absolute",O.style.left="0",O.style.top="0",O.style.width="0",O.style.height="0",O.style.transform=`translate3d(${z[0]*o}px, ${z[1]*o}px, ${z[2]*o}px)`,r.appendChild(O);let Z=r.getBoundingClientRect(),q=O.getBoundingClientRect();return r.removeChild(O),{x:(q.left-Z.left)/o,y:(q.top-Z.top)/o}}let P=y(f),v=y(b),C=P.x*v.y-v.x*P.y;if(Math.abs(C)<Fi)return;p?.(),x?.(!0);let F=z=>{let O=z.clientX-i,Z=z.clientY-s,q=(v.y*O-v.x*Z)/C,D=(-P.y*O+P.x*Z)/C;q=Rn(q,c),D=Rn(D,c),l(q,D,f,b)},k=()=>{window.removeEventListener("pointermove",F),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k);let z=O=>{O.stopPropagation(),O.stopImmediatePropagation()};window.addEventListener("click",z,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",z,!0),0),g?.(),x?.(!1)};window.addEventListener("pointermove",F),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k)}function Gc(e){let{cssAxis:n,wrapper:t,target:o,startClientX:r,startClientY:i,rotationSnap:s,onAngleDelta:c,onMouseDown:l,onMouseUp:p,onDraggingChanged:g}=e,x=t.getBoundingClientRect(),f=x.left,b=x.top,y=Math.atan2(i-b,r-f),P=0;l?.(),g?.(!0);let v=F=>{let k=Math.atan2(F.clientY-b,F.clientX-f),z=k-y;z>Math.PI?z-=2*Math.PI:z<-Math.PI&&(z+=2*Math.PI),P+=z,y=k;let O=P*180/Math.PI;O=Rn(O,s),c(O)},C=()=>{window.removeEventListener("pointermove",v),window.removeEventListener("pointerup",C),window.removeEventListener("pointercancel",C);let F=k=>{k.stopPropagation(),k.stopImmediatePropagation()};window.addEventListener("click",F,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",F,!0),0),p?.(),g?.(!1)};window.addEventListener("pointermove",v),window.addEventListener("pointerup",C),window.addEventListener("pointercancel",C)}function Vi(e,n={}){let t=null,o=n.mode??"translate",r=n.size??1,i={...n},s=new Map,c=null,l=null,p=[0,0,0];function g(){if(!t)return[0,0,0];let h=t.transform.position??[0,0,0],u=t.transform.rotation??[0,0,0],d=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,T=Ho(p,u[0],u[1],u[2]);return[h[0]+d*T[0],h[1]+d*T[1],h[2]+d*T[2]]}function x(h){return l===h?Fc:c===h?Ic:Hc}function f(){for(let[h,u]of s){let d=b(u.spec,x(h));u.handle.setPolygons(d,{recomputeAutoCenter:!1})}}function b(h,u){let T=Vo(t?.polygons??[])*r,w=T/Lt,R=Vc(h.color,u);if(h.kind==="arrow"){let _=e.camera.state,j=Fo(h.cssAxis,h.sign,_.rotX??65,_.rotY??45);return Pc({axis:Je[h.cssAxis],sign:h.sign,shaftLength:w,shaftHalfThickness:w*Lc,headLength:w*_c,headHalfThickness:w*Rc,color:R,shaft:!j})}if(h.kind==="plane"){let _=e.camera.state,j=_.rotX??65,Q=_.rotY??45,re=Je[h.perpAxis],fe=(re+1)%3,ue=(re+2)%3,pe=Je[fe],Ce=Je[ue],be=Fo(pe,1,j,Q)?-1:1,Ae=Fo(Ce,1,j,Q)?-1:1,ze=w*Oc;return Cc({axis:re,size:w*Dc,offset:[be*ze,Ae*ze],color:R})}let te=T*kc/Lt*Io;return Mc({axis:Je[h.cssAxis],outerRadius:te,color:R})}function y(h){return h.kind==="arrow"?"polycss-transform-arrow":h.kind==="plane"?"polycss-transform-plane":"polycss-transform-ring"}function P(){if(o==="translate"){let h=Oi.map(d=>({kind:"arrow",key:d.key,cssAxis:d.cssAxis,sign:d.sign,color:d.color})),u=Ii.map(d=>({kind:"plane",key:d.key,perpAxis:d.perpAxis,axisA:d.axisA,axisB:d.axisB,color:d.color}));return[...h,...u]}return o==="rotate"?Hi.map(h=>({kind:"ring",key:h.key,cssAxis:h.cssAxis,color:h.color})):[]}function v(){if(C(),!t)return;let h={x:i.showX!==!1,y:i.showY!==!1,z:i.showZ!==!1};function u(T){if(T.kind==="arrow"){let L=T.key.replace("-","")[0];return h[L]}if(T.kind==="ring")return h[T.key];let w=["x","y","z"][T.axisA],R=["x","y","z"][T.axisB];return h[w]&&h[R]}let d=g();for(let T of P()){if(!u(T))continue;let w=b(T,x(T.key)),R=e.add({polygons:w,objectUrls:[],warnings:[],dispose:()=>{}},{excludeFromAutoCenter:!0,id:`__poly-gizmo-${T.key}`,position:d}),L=y(T);if(R.element.classList.add("polycss-transform-gizmo",L,`${L}--${T.key}`),T.kind==="ring"){let te=(1-Di)/Io,_=(1+Di)/Io;R.element.style.setProperty("--ring-inner-ratio",`${te}`),R.element.style.setProperty("--ring-outer-ratio",`${_}`)}s.set(T.key,{handle:R,spec:T})}}function C(){for(let{handle:h}of s.values())h.remove();s.clear(),c=null,l=null}function F(){if(!t)return;let h=g();for(let{handle:u}of s.values())u.setTransform({position:h})}function k(){t&&(s.size===0?v():F())}function z(h){if(t=h,!h){p=[0,0,0],C();return}p=Bc(h.polygons),C(),v()}function O(){z(null)}function Z(h){h!==o&&(o=h,t&&(C(),v()))}function q(h,u,d){if(!t||!D)return;let T=d[h.cssAxis],w=Je[h.cssAxis],R=u*T/Lt,L=D.slice();L[w]=D[w]+R,t.setTransform({position:L}),F(),i.onObjectChange?.({object:t,position:L}),i.onChange?.()}let D=null,H=null,V=h=>{if(!t||i.enabled===!1)return;let u={x:i.showX!==!1,y:i.showY!==!1,z:i.showZ!==!1};if(o==="translate"){for(let d of Ii){let T=["x","y","z"][d.axisA],w=["x","y","z"][d.axisB];if(!u[T]||!u[w])continue;let R=s.get(d.key);if(R&&wt(R.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=d.key,f(),D=(t.transform.position??[0,0,0]).slice(),Nc({axisA:d.axisA,axisB:d.axisB,probeDistanceCss:Vo(t.polygons)*r,wrapper:R.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,translationSnap:i.translationSnap??null,onPlaneDelta:(L,te,_,j)=>{if(!t||!D)return;let Q=_[d.axisA],re=j[d.axisB],fe=Je[d.axisA],ue=Je[d.axisB],pe=D.slice();pe[fe]+=L*Q/Lt,pe[ue]+=te*re/Lt,t.setTransform({position:pe}),F(),i.onObjectChange?.({object:t,position:pe}),i.onChange?.()},onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:L=>{L||(l=null,D=null,f()),i.onDraggingChanged?.(L)}});return}}for(let d of Oi){let T=d.key.replace("-","")[0];if(!u[T])continue;let w=s.get(d.key);if(w&&wt(w.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=d.key,f(),D=(t.transform.position??[0,0,0]).slice(),zc({cssAxis:d.cssAxis,sign:d.sign,shaftLengthCss:Vo(t.polygons)*r,wrapper:w.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,translationSnap:i.translationSnap??null,onAxisDelta:(R,L)=>q(d,R,L),onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:R=>{R||(l=null,D=null,f()),i.onDraggingChanged?.(R)}});return}}}else if(o==="rotate")for(let d of Hi){if(!u[d.key])continue;let T=s.get(d.key);if(T&&wt(T.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=d.key,f(),H=(t.transform.rotation??[0,0,0]).slice(),D=(t.transform.position??[0,0,0]).slice(),Gc({cssAxis:d.cssAxis,wrapper:T.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,rotationSnap:i.rotationSnap??null,onAngleDelta:w=>{if(!t||!H||!D)return;let R=Je[d.cssAxis],L=[0,0,0];L[R]=1;let te=-w*Math.PI/180,_=Tc(H),j=Ec(L,te),Q=Sc(Ac(j,_)),re=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,fe=Ho(p,H[0],H[1],H[2]),ue=Ho(p,Q[0],Q[1],Q[2]),pe=[D[0]+re*(fe[0]-ue[0]),D[1]+re*(fe[1]-ue[1]),D[2]+re*(fe[2]-ue[2])];t.setTransform({rotation:Q,position:pe}),F(),i.onObjectChange?.({object:t,rotation:Q,position:pe}),i.onChange?.()},onMouseDown:i.onMouseDown,onMouseUp:i.onMouseUp,onDraggingChanged:w=>{w||(l=null,H=null,D=null,f(),t?.rebakeAtlas()),i.onDraggingChanged?.(w)}});return}}};e.host.addEventListener("pointerdown",V,{capture:!0});let G=h=>{if(!t||l||i.enabled===!1)return;let u=null;for(let[d,T]of s)if(wt(T.handle.element,h.clientX,h.clientY)){u=d;break}u!==c&&(c=u,f())};e.host.addEventListener("pointermove",G);function A(){e.host.removeEventListener("pointerdown",V,{capture:!0}),e.host.removeEventListener("pointermove",G),C()}return{attach:z,detach:O,setMode:Z,update:k,destroy:A}}var $c=typeof HTMLElement<"u"?HTMLElement:class{},Uc=["mode","target","size","enabled"];function Bi(e){if(e==="translate"||e==="rotate")return e}var kn=class extends $c{constructor(){super(...arguments);this._tc=null}static get observedAttributes(){return[...Uc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof we)return t;t=t.parentNode}return null}_findTargetMesh(){let t=this.getAttribute("target");if(!t)return null;let o=this._findScene();if(!o)return null;let r=null;try{r=o.querySelector(`#${t}`)??o.querySelector(t)}catch{r=o.querySelector(`[id="${t}"]`)}return r instanceof Ct?r:null}_readOptions(){let t={},o=Bi(this.getAttribute("mode"));o!==void 0&&(t.mode=o);let r=ee(this.getAttribute("size"));r!==void 0&&(t.size=r);let i=this.getAttribute("enabled");return i!==null&&(t.enabled=i!=="false"&&i!=="0"),t.onObjectChange=s=>{this.dispatchEvent(new CustomEvent("polycss:object-change",{bubbles:!0,detail:{position:s.position,rotation:s.rotation}}))},t}_attach(){if(this._tc)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._tc=Vi(o,this._readOptions());let r=this._findTargetMesh();if(r){let i=r.getMeshHandle();i&&this._tc.attach(i)}}connectedCallback(){this._attach()}disconnectedCallback(){this._tc&&(this._tc.destroy(),this._tc=null)}attributeChangedCallback(t,o,r){if(o!==r&&this._tc){if(t==="mode"){let i=Bi(r);i&&this._tc.setMode(i)}else if(t==="target"){let i=this._findTargetMesh();this._tc.attach(i?i.getMeshHandle()??null:null)}}}};function zi(e,n={}){let t=[],o=new Set;n.onChange&&o.add(n.onChange);function r(){t=n.filter?n.filter(t):t;for(let P of o)try{P(t)}catch(v){console.error("[polycss/createSelect] onChange threw:",v)}}function i(y){t=y,r()}function s(y){n.multiple?t.includes(y)||(t=[...t,y]):t=[y],r()}function c(y){t.includes(y)&&(t=t.filter(P=>P!==y),r())}function l(y){t.includes(y)?t=t.filter(P=>P!==y):n.multiple?t=[...t,y]:t=[y],r()}function p(){t.length!==0&&(t=[],r())}function g(y){return t.includes(y)}function x(y,P){return Ri(e.meshes(),y,P,v=>!v.element.classList.contains("polycss-transform-gizmo"))}let f=y=>{let P=y.target;if(P?.closest(".polycss-transform-gizmo"))return;let v=e.findMeshByElement(P)??x(y.clientX,y.clientY);if(!v){n.onPointerMissed&&n.onPointerMissed(y),n.clearOnMiss!==!1&&p();return}n.multiple&&(y.shiftKey||y.metaKey||y.ctrlKey)?l(v):t.length===1&&t[0]===v?p():i([v])};e.host.addEventListener("click",f);function b(){e.host.removeEventListener("click",f),o.clear()}return{get selected(){return t},set:i,add:s,remove:c,toggle:l,clear:p,has:g,destroy:b}}var jc=typeof HTMLElement<"u"?HTMLElement:class{},Wc=["multiple","clear-on-miss"],Dn=class extends jc{constructor(){super(...arguments);this._selection=null}static get observedAttributes(){return[...Wc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof we)return t;t=t.parentNode}return null}_readOptions(){return{multiple:this.hasAttribute("multiple"),clearOnMiss:!this.hasAttribute("clear-on-miss")||this.getAttribute("clear-on-miss")!=="false",onChange:t=>{this.dispatchEvent(new CustomEvent("polycss:select",{bubbles:!0,detail:{selected:t}}))}}}_attach(){if(this._selection)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._selection=zi(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._selection&&(this._selection.destroy(),this._selection=null)}attributeChangedCallback(t,o,r){o!==r&&(this._selection&&(this._selection.destroy(),this._selection=null),this._attach())}};import{boxPolygons as Yc,planePolygons as Xc,ringPolygons as Zc,octahedronPolygons as Qc,spherePolygons as qc,tetrahedronPolygons as Kc,icosahedronPolygons as Jc,dodecahedronPolygons as ed,cylinderPolygons as td,conePolygons as nd,torusPolygons as od,computeSceneBbox as rd}from"@layoutit/polycss-core";var id=typeof HTMLElement<"u"?HTMLElement:class{};function sd(e){return e.closest("poly-scene")??null}function he(e,n,t){let o=e.getAttribute(n);if(!o)return t;let r=parseFloat(o);return Number.isFinite(r)?r:t}function Ze(e,n,t){return e.getAttribute(n)??t}function dt(e,n){let t=e.getAttribute(n);if(!t)return;let o=t.split(",").map(r=>parseFloat(r.trim()));if(!(o.length!==3||o.some(r=>!Number.isFinite(r))))return[o[0],o[1],o[2]]}function ad(e){if(e.length===0)return e;let n=rd(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,r=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&r===0)return e;let i=s=>[s[0]-t,s[1]-o,s[2]-r];return e.map(s=>({...s,vertices:s.vertices.map(i)}))}var ke=class extends id{constructor(){super(...arguments);this._handle=null}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,r){if(o!==r&&this._handle){if(t==="position"||t==="scale"||t==="rotation"||t==="cast-shadow"||t==="receive-shadow"){this._handle.setTransform({position:dt(this,"position"),scale:(()=>{let i=this.getAttribute("scale");if(!i)return;if(i.includes(","))return dt(this,"scale");let s=parseFloat(i);return Number.isFinite(s)?s:void 0})(),rotation:dt(this,"rotation"),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow")});return}this._tearDown(),this._mount()}}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=sd(this);if(!t)return;let o=t.getScene?.();if(!o)return;let r=this.buildPolygons();this.hasAttribute("auto-center")&&(r=ad(r));let i={polygons:r,objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(i,{position:dt(this,"position"),scale:(()=>{let s=this.getAttribute("scale");if(!s)return;if(s.includes(","))return dt(this,"scale");let c=parseFloat(s);return Number.isFinite(c)?c:void 0})(),rotation:dt(this,"rotation"),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow"),excludeFromAutoCenter:this.hasAttribute("exclude-from-auto-center"),merge:!1})}},On=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("size"),t=n?parseFloat(n):void 0;return Yc({size:t!==void 0&&Number.isFinite(t)?t:void 0,color:Ze(this,"color")})}},Hn=class extends ke{static get observedAttributes(){return["axis","size","offset","color","auto-center","position","scale","rotation","cast-shadow","receive-shadow"]}buildPolygons(){let n=he(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("offset"),r=o===null?0:parseFloat(o);return Xc({axis:t,size:he(this,"size",.4),offset:Number.isFinite(r)?r:0,color:Ze(this,"color")})}},In=class extends ke{static get observedAttributes(){return["axis","radius","segments","half-thickness","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=he(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("half-thickness");return Zc({axis:t,radius:he(this,"radius",50),segments:he(this,"segments",32),halfThickness:o?parseFloat(o):void 0,color:Ze(this,"color")})}},Fn=class extends ke{static get observedAttributes(){return["size","color","center","auto-center","position","scale","rotation"]}buildPolygons(){return Qc({center:dt(this,"center")??[0,0,0],size:he(this,"size",50),color:Ze(this,"color")})}},Vn=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return Kc({size:he(this,"size",100),color:Ze(this,"color")})}},Bn=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return Jc({size:he(this,"size",100),color:Ze(this,"color")})}},zn=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return ed({size:he(this,"size",100),color:Ze(this,"color")})}},Nn=class extends ke{static get observedAttributes(){return["radius","subdivisions","color","auto-center","position","scale","rotation"]}buildPolygons(){return qc({radius:he(this,"radius",50),subdivisions:he(this,"subdivisions",1),color:Ze(this,"color")})}},Gn=class extends ke{static get observedAttributes(){return["radius","radius-top","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("radius-top");return td({radius:he(this,"radius",50),radiusTop:n?parseFloat(n):void 0,height:he(this,"height",100),radialSegments:he(this,"radial-segments",12),color:Ze(this,"color")})}},$n=class extends ke{static get observedAttributes(){return["radius","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return nd({radius:he(this,"radius",50),height:he(this,"height",100),radialSegments:he(this,"radial-segments",12),color:Ze(this,"color")})}},Un=class extends ke{static get observedAttributes(){return["radius","tube","radial-segments","tubular-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return od({radius:he(this,"radius",50),tube:he(this,"tube",15),radialSegments:he(this,"radial-segments",12),tubularSegments:he(this,"tubular-segments",16),color:Ze(this,"color")})}};typeof customElements<"u"&&(customElements.get("poly-scene")||customElements.define("poly-scene",we),customElements.get("poly-mesh")||customElements.define("poly-mesh",Ct),customElements.get("poly-iframe")||customElements.define("poly-iframe",mn),customElements.get("poly-polygon")||customElements.define("poly-polygon",fn),customElements.get("poly-axes-helper")||customElements.define("poly-axes-helper",hn),customElements.get("poly-directional-light-helper")||customElements.define("poly-directional-light-helper",gn),customElements.get("poly-orbit-controls")||customElements.define("poly-orbit-controls",Cn),customElements.get("poly-map-controls")||customElements.define("poly-map-controls",En),customElements.get("poly-first-person-controls")||customElements.define("poly-first-person-controls",Tn),customElements.get("poly-perspective-camera")||customElements.define("poly-perspective-camera",An),customElements.get("poly-orthographic-camera")||customElements.define("poly-orthographic-camera",Mt),customElements.get("poly-camera")||customElements.define("poly-camera",Mn),customElements.get("poly-transform-controls")||customElements.define("poly-transform-controls",kn),customElements.get("poly-select")||customElements.define("poly-select",Dn),customElements.get("poly-box")||customElements.define("poly-box",On),customElements.get("poly-plane")||customElements.define("poly-plane",Hn),customElements.get("poly-ring")||customElements.define("poly-ring",In),customElements.get("poly-octahedron")||customElements.define("poly-octahedron",Fn),customElements.get("poly-tetrahedron")||customElements.define("poly-tetrahedron",Vn),customElements.get("poly-sphere")||customElements.define("poly-sphere",Nn),customElements.get("poly-icosahedron")||customElements.define("poly-icosahedron",Bn),customElements.get("poly-dodecahedron")||customElements.define("poly-dodecahedron",zn),customElements.get("poly-cylinder")||customElements.define("poly-cylinder",Gn),customElements.get("poly-cone")||customElements.define("poly-cone",$n),customElements.get("poly-torus")||customElements.define("poly-torus",Un));export{hn as PolyAxesHelperElement,On as PolyBoxElement,Mn as PolyCameraElement,$n as PolyConeElement,Gn as PolyCylinderElement,gn as PolyDirectionalLightHelperElement,zn as PolyDodecahedronElement,Tn as PolyFirstPersonControlsElement,Bn as PolyIcosahedronElement,mn as PolyIframeElement,En as PolyMapControlsElement,Ct as PolyMeshElement,Fn as PolyOctahedronElement,Cn as PolyOrbitControlsElement,Mt as PolyOrthographicCameraElement,An as PolyPerspectiveCameraElement,Hn as PolyPlaneElement,fn as PolyPolygonElement,In as PolyRingElement,we as PolySceneElement,Dn as PolySelectElement,Nn as PolySphereElement,Vn as PolyTetrahedronElement,Un as PolyTorusElement,kn as PolyTransformControlsElement};