@layoutit/polycss 0.2.5 → 0.2.6

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/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{CAMERA_BACKFACE_CULL_EPS as To,DEFAULT_SEAM_BLEED as zs,VOXEL_CAMERA_CULL_NORMAL_LIMIT as _l,cameraCullNormalKey as Rl,cameraCullVisibleSignature as kl,computeSceneBbox as Ol,computeLightVisibility as Dl,findOverlappingPolygonDuplicates as Hs,inverseRotateVec3 as Eo,isAxisAlignedSurfaceNormal as Il,isVoxelCameraCullableNormalGroups as Hl,normalFacesCamera as Fl,optimizeMeshPolygons as Vl,parseHexColor as Bl,polygonCssSurfaceNormal as Fs}from"@layoutit/polycss-core";import{packTextureAtlasPlansWithScaleCore as bi}from"@layoutit/polycss-core";function vi(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 vt(e,n,t){return bi(e,n,vi(t))}import{buildTextureEdgeRepairSets as Gr,buildSeamBleedPolygonEdges as ba,buildSeamBleedPolygonSet as va}from"@layoutit/polycss-core";import{TEXTURE_TRIANGLE_BLEED as xi,TEXTURE_EDGE_REPAIR_ALPHA_MIN as Pi,TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN as Si,TEXTURE_EDGE_REPAIR_RADIUS as mr}from"@layoutit/polycss-core";import{expandClipPoints as Ci}from"@layoutit/polycss-core";import{BASIS_EPS as Ti}from"@layoutit/polycss-core";var xt=new Map;function Ei(e){let n=xt.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}),xt.set(e,n),n.then(()=>{xt.get(e)===n&&xt.delete(e)},()=>{xt.get(e)===n&&xt.delete(e)})),n}function _e(e,n,t=1,o=0,r=0,s=1,i=0,c=0){e.setTransform(t*n,o*n,r*n,s*n,i*n,c*n)}function Nn(e){let n=e/255;return n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Un(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 Ai(e,n,t,o,r,s,i){let c=Math.round(n*i),l=Math.round(t*i),u=Math.max(1,Math.round(o*i)),d=Math.max(1,Math.round(r*i)),x=e.getImageData(c,l,u,d),h=x.data,b=s.r,v=s.g,P=s.b;for(let y=0;y<h.length;y+=4)h[y+3]!==0&&(h[y]=Un(Nn(h[y])*b),h[y+1]=Un(Nn(h[y+1])*v),h[y+2]=Un(Nn(h[y+2])*P));e.putImageData(x,c,l)}function wi(e,n,t,o,r,s,i){let c=n.naturalWidth||n.width||1,l=n.naturalHeight||n.height||1,u=Math.max(r/c,s/l),d=c*u,x=l*u;_e(e,i),e.drawImage(n,t+(r-d)/2,o+(s-x)/2,d,x)}function Pt(e,n){return Math.max(0,Math.min(n,e))}function fr(e,n,t,o,r,s,i,c){let l=n.naturalWidth||n.width||1,u=n.naturalHeight||n.height||1,d=Pt(Math.min(t.minU,t.maxU)*l,l),x=Pt(Math.max(t.minU,t.maxU)*l,l),h=Pt(Math.min(t.minV,t.maxV)*u,u),b=Pt(Math.max(t.minV,t.maxV)*u,u),v=Math.floor(d),P=Math.floor(h),y=Math.ceil(x)-v,C=Math.ceil(b)-P;y<1&&(v=Math.floor(Pt((t.minU+t.maxU)/2*l,l-1)),y=1),C<1&&(P=Math.floor(Pt((t.minV+t.maxV)/2*u,u-1)),C=1),v=Math.max(0,Math.min(l-1,v)),P=Math.max(0,Math.min(u-1,P)),y=Math.max(1,Math.min(l-v,y)),C=Math.max(1,Math.min(u-P,C)),_e(e,c),e.drawImage(n,v,P,y,C,o,r,s,i)}function vr(e){return e==="repeat"||e==="mirrored-repeat"}function hr(e,n){return vr(e)?Math.floor(n):0}function gr(e,n){return vr(e)?Math.ceil(n)-1:0}function yr(e,n){return e==="mirrored-repeat"&&Math.abs(n%2)===1}function br(e,n,t,o,r,s,i){let c=r?hr(s,r.minU):0,l=r?gr(s,r.maxU):0,u=r?hr(i,r.minV):0,d=r?gr(i,r.maxV):0;for(let x=c;x<=l;x++)for(let h=u;h<=d;h++){let b=yr(s,x),v=yr(i,h);if(!b&&!v){e.drawImage(n,x*t,h*o);continue}e.save(),e.translate((b?x+1:x)*t,(v?h+1:h)*o),e.scale(b?-1:1,v?-1:1),e.drawImage(n,0,0),e.restore()}}function Gn(e,n,t,o){for(let r=0;r<o.length;r+=2){let s=n+o[r],i=t+o[r+1];r===0?e.moveTo(s,i):e.lineTo(s,i)}e.closePath()}function dn(e,n,t,o,r,s){for(let i=0;i<o.length;i+=2){let c=n+o[i]+r,l=t+o[i+1]+s;i===0?e.moveTo(c,l):e.lineTo(c,l)}e.closePath()}function Mi(e,n,t,o){_e(e,o),e.beginPath(),Gn(e,n.x,n.y,n.screenPts),e.clip(),_e(e,o),e.fillStyle=t==="dynamic"?n.polygon.color??"#cccccc":n.shadedColor,e.fillRect(n.x,n.y,n.canvasW,n.canvasH)}function pn(e,n,t,o,r){n.polygon.textureAlphaMode==="opaque"&&(_e(e,t),e.fillStyle=n.polygon.color??"#cccccc",e.fillRect(n.x+o,n.y+r,n.canvasW,n.canvasH))}function Li(e,n,t,o,r=0,s=0){if(n.textureTriangles?.length){let i=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1;for(let l of n.textureTriangles){let u=Ci(l.screenPts,xi*(n.bleedRatio??1));e.save(),_e(e,o),e.beginPath(),dn(e,n.x,n.y,u,r,s),e.clip(),pn(e,n,o,r,s),l.uvAffine?(_e(e,o,l.uvAffine.a/i,l.uvAffine.c/i,l.uvAffine.b/c,l.uvAffine.d/c,n.x+l.uvAffine.e+r,n.y+l.uvAffine.f+s),br(e,t,i,c,l.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t)):l.uvSampleRect&&fr(e,t,l.uvSampleRect,n.x+r,n.y+s,n.canvasW,n.canvasH,o),e.restore()}}else if(n.uvAffine){let i=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1,l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),_e(e,o),e.beginPath(),dn(e,n.x,n.y,n.screenPts,r,s),e.clip(),pn(e,n,o,r,s)),_e(e,o,n.uvAffine.a/i,n.uvAffine.c/i,n.uvAffine.b/c,n.uvAffine.d/c,n.x+n.uvAffine.e+r,n.y+n.uvAffine.f+s),br(e,t,i,c,n.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t),l&&e.restore()}else if(n.uvSampleRect){let i=n.polygon.textureAlphaMode==="opaque";i&&(e.save(),_e(e,o),e.beginPath(),dn(e,n.x,n.y,n.screenPts,r,s),e.clip(),pn(e,n,o,r,s)),fr(e,t,n.uvSampleRect,n.x+r,n.y+s,n.canvasW,n.canvasH,o),i&&e.restore()}else{let i=n.polygon.textureAlphaMode==="opaque";i&&(e.save(),_e(e,o),e.beginPath(),dn(e,n.x,n.y,n.screenPts,r,s),e.clip(),pn(e,n,o,r,s)),wi(e,t,n.x+r,n.y+s,n.canvasW,n.canvasH,o),i&&e.restore()}}function _i(e,n,t,o,r,s){let i=r-t,c=s-o,l=i*i+c*c;if(l<=Ti)return Math.hypot(e-t,n-o);let u=Math.max(0,Math.min(1,((e-t)*i+(n-o)*c)/l));return Math.hypot(e-(t+i*u),n-(o+c*u))}function Ri(e,n,t,o){let r=1/0,s=t.length/2;for(let i of o){if(i<0||i>=s)continue;let c=i*2,l=(i+1)%s*2;r=Math.min(r,_i(e,n,t[c],t[c+1],t[l],t[l+1]))}return r}function ki(e,n,t,o,r,s){let i=Math.max(0,o-s),c=Math.min(n-1,o+s),l=Math.max(0,r-s),u=Math.min(t-1,r+s),d=null,x=1/0;for(let h=l;h<=u;h++)for(let b=i;b<=c;b++){if(b===o&&h===r)continue;let v=b-o,P=h-r,y=v*v+P*P;if(y>s*s||y>=x)continue;let C=(h*n+b)*4;e[C+3]<Si||(d=C,x=y)}return d}function Oi(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)),s=Math.max(0,Math.floor(n.y*t)),i=Math.max(1,Math.min(o.width-r,Math.ceil(n.canvasW*t))),c=Math.max(1,Math.min(o.height-s,Math.ceil(n.canvasH*t)));if(i<=0||c<=0)return;let l;try{l=e.getImageData(r,s,i,c)}catch{return}let u=l.data,d=new Uint8ClampedArray(u),x=Math.max(mr,mr/t),h=Math.max(2,Math.ceil(x*t)+1),b=!1;for(let v=0;v<c;v++)for(let P=0;P<i;P++){let y=(v*i+P)*4,C=u[y+3];if(C<Pi||C===255)continue;let D=(r+P+.5)/t-n.x,k=(s+v+.5)/t-n.y;if(Ri(D,k,n.screenPts,n.textureEdgeRepairEdges)>x)continue;let z=ki(d,i,c,P,v,h);z!==null&&(u[y]=d[z],u[y+1]=d[z+1],u[y+2]=d[z+2],u[y+3]=255,b=!0)}b&&e.putImageData(l,r,s)}function Di(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 Ii(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 s=e.entries.some(d=>d.textureEdgeRepair&&d.texture&&d.textureEdgeRepairEdges&&d.textureEdgeRepairEdges.size>0),i=r.getContext("2d",s?{willReadFrequently:!0}:void 0);if(!i)return{width:e.width,height:e.height,url:null};let c=Array.from(new Set(e.entries.flatMap(d=>d.texture?[d.texture]:[]))),l=new Map;await Promise.all(c.map(async d=>{l.set(d,await Ei(d))}));for(let d of e.entries){let x=d.texture?l.get(d.texture):null;if(!d.texture){i.save(),Mi(i,d,n,o),i.restore();continue}x&&(i.save(),_e(i,o),i.beginPath(),Gn(i,d.x,d.y,d.screenPts),i.clip(),Li(i,d,x,o),i.restore()),d.texture&&n==="baked"&&(i.save(),_e(i,o),i.beginPath(),Gn(i,d.x,d.y,d.screenPts),i.clip(),Ai(i,d.x,d.y,d.canvasW,d.canvasH,d.textureTint,o),i.restore()),Oi(i,d,o)}let u=await Di(r);return r.width=1,r.height=1,{width:e.width,height:e.height,url:u}}async function St(e,n,t,o,r){let s=[];for(let i of e){if(r())break;s.push(await Ii(i,n,t,o))}return s}import{isFullRectSolid as Ve,isSolidTrianglePlan as Ke,isProjectiveQuadPlan as Be,fullRectBounds as Ad,safariCssProjectiveUnsupported as xr,incrementCount as wd,dominantCountKey as Md,filterAtlasPlans as Fi,getSolidPaintDefaultsForPlansCore as Vi}from"@layoutit/polycss-core";import{parseHex as Bi,rgbKey as zi}from"@layoutit/polycss-core";import{computeTextureAtlasPlan as kd,buildBasisHints as Od}from"@layoutit/polycss-core";import{resolveProjectiveQuadGuards as Hi}from"@layoutit/polycss-core";function Ct(e,n){let o=e?.defaultView?.__polycssProjectiveQuadGuards,r=n&&o?{...n,...o}:o??n;return Hi(r)}function Tt(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 $n(e){if(Pr(e))return!0;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!xr(t):!0}function Nt(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 Pr(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 Ni(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return/\bFirefox\//.test(t)}function ze(e,n){return n?.disable?.includes("u")?null:Pr(e)?"corner-bevel":$n(e)?Ni(e)?"border-large":"border":null}function Et(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!xr(t):!0}function Ut(e,n,t,o,r){let s=new Set(o?.disable??[]);return Vi(e,n,s,{solidTriangleSupported:$n(t),projectiveQuadSupported:Et(t),cornerShapeSupported:Nt(t),borderShapeSupported:Tt(t)},Bi,zi,r)}function Wn(e,n,t=new Set,o){let r=o??(typeof document<"u"?document:null);if(!r)return{};let s=t.size>0?{disable:Array.from(t)}:void 0;return Ut(e,n,r,s)}function mn(e){let n=e??(typeof document<"u"?document:null);if(!n){if(!!!(typeof CSS<"u"?CSS:void 0)?.supports?.("border-shape","polygon(0 0, 100% 0, 0 100%) circle(0)"))return!1;let r=typeof matchMedia<"u"?matchMedia:void 0;return r?r("(pointer: fine)").matches&&r("(hover: hover)").matches:!0}return Tt(n)}function fn(e){let n=e??(typeof document<"u"?document:null);if(!n){let t=typeof CSS<"u"?CSS:void 0;if(t?.supports?.("corner-top-left-shape","bevel")&&t.supports("corner-top-right-shape","bevel"))return!0;let o=(typeof navigator<"u"?navigator:globalThis.navigator)?.userAgent??"";if(!o)return!0;let r=/\b(?:Chrome|HeadlessChrome|Chromium|Edg|OPR)\//.test(o);return!/\bVersion\/[\d.]+.*\bSafari\//.test(o)||r}return $n(n)}function jn(e,n,t,o){let r=o??(typeof document<"u"?document:null);return Fi(e,n,t,{solidTriangleSupported:fn(o),projectiveQuadSupported:r?Et(r):!0,borderShapeSupported:mn(o)})}import{ASYNC_RENDER_BUDGET_MS as pa,DEFAULT_SEAM_BLEED as Fr,DEFAULT_TILE as ma,PROJECTIVE_QUAD_DENOM_EPS as fa,PROJECTIVE_QUAD_MAX_WEIGHT_RATIO as ha,PROJECTIVE_QUAD_BLEED as Hr,resolveBleedRatio as mo}from"@layoutit/polycss-core";import{buildBasisHints as fo,buildSeamBleedPolygonEdges as ga,computeTextureAtlasPlan as Xt}from"@layoutit/polycss-core";import{cornerShapeGeometryForPlan as Yt}from"@layoutit/polycss-core";import{formatCssLength as hn,formatMatrix3dValues as Gi,formatSolidQuadMatrix as $i}from"@layoutit/polycss-core";import{shadePolygon as Wi}from"@layoutit/polycss-core";import{parseHex as Sr,rgbKey as Cr}from"@layoutit/polycss-core";function xe(e,n,t){let o=e.getAttribute("style")??"",r=`${n}:${t}`,s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(^|;)\\s*${s}\\s*:[^;]*`,"i"),c=i.test(o)?o.replace(i,(l,u)=>`${u}${r}`):`${o}${o.trim()&&!o.trim().endsWith(";")?";":""}${r}`;c!==o&&e.setAttribute("style",c)}function nt(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"),s=t.split(";").map(i=>i.trim()).filter(i=>i&&!r.test(i)).join(";");s?e.setAttribute("style",s):e.removeAttribute("style")}function Gt(e,n,t,o=!1){if(n==="dynamic"){let r=Sr(e.polygon.color??"#cccccc"),s=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return Cr(r)!==t?.dynamicColorKey&&(s+=`;--psr:${(r.r/255).toFixed(4)};--psg:${(r.g/255).toFixed(4)};--psb:${(r.b/255).toFixed(4)}`),s}return e.shadedColor?`;color:${e.shadedColor}`:""}function Ui(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 At(e,n,t,o){if(t==="dynamic"){nt(e,"color"),nt(e,"background"),Ui(e,n);let r=Sr(n.polygon.color??"#cccccc");Cr(r)===o?.dynamicColorKey?(nt(e,"--psr"),nt(e,"--psg"),nt(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?(nt(e,"background"),xe(e,"color",n.shadedColor)):(nt(e,"background"),nt(e,"color"))}import{formatBorderShapeElementStyle as Tr,formatCornerShapeElementStyle as Er}from"@layoutit/polycss-core";import{atlasCanonicalSizeForEntry as ot}from"@layoutit/polycss-core";import{computeProjectiveQuadMatrix as ji,stableBasisFromPlan as Yi}from"@layoutit/polycss-core";import{DEFAULT_LIGHT_DIR as Xi,DEFAULT_LIGHT_COLOR as Zi,DEFAULT_LIGHT_INTENSITY as qi,DEFAULT_AMBIENT_COLOR as Qi,DEFAULT_AMBIENT_INTENSITY as Ki}from"@layoutit/polycss-core";var Ar="polycss-corner-shape-solid",Yn=new WeakMap,Xn=new WeakMap;function ye(e,n,t){let o=Yn.get(e),r=Xn.get(e),s=typeof t=="number";if(!n.data&&!s&&(!o||o.length===0)){e.__polycssHasDataAttrs=!1;return}let i=new Map;if(n.data)for(let[l,u]of Object.entries(n.data))i.set(l,String(u));if(s&&i.set("poly-index",String(t)),o)for(let l of o)i.has(l)||e.removeAttribute(`data-${l}`);for(let[l,u]of i)r?.get(l)!==u&&e.setAttribute(`data-${l}`,u);let c=Array.from(i.keys());c.length>0?Yn.set(e,c):Yn.delete(e),i.size>0?Xn.set(e,i):Xn.delete(e),e.__polycssHasDataAttrs=c.length>0}function wt(e){return e.__polycssHasDataAttrs===!0}function Zn(e,n,t,o,r=t==="dynamic"){if(!n.url)return;let s=`url(${n.url})`,i=o.canvasW||1,c=o.canvasH||1,l=ot(o),u=`${hn(-o.x/i*l)} ${hn(-o.y/c*l)}`,d=`${hn(n.width/i*l)} ${hn(n.height/c*l)}`,x=`transform:matrix3d(${o.atlasMatrix});--polycss-atlas-size:${l}px`,h=`${x};--polycss-atlas-position:${u};--polycss-atlas-image-size:${d}`;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",h+`;--polycss-atlas-url:${s}`+b)}else e.setAttribute("style",x+`;background-image:${s};background-position:${u};background-size:${d};background-repeat:no-repeat;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`)}function wr(e,n,t,o){if(n.texture){if(!t.texture||n.texture!==t.texture)return!1}else if(t.texture)return!1;let r=Mr(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 qn(e,n,t,o,r){if(o!=="baked")return{...e,polygon:n,normal:t};let s=r.directionalLight,i=r.ambientLight,c=s?.direction??Xi,l=s?.color??Zi,u=Math.max(0,s?.intensity??qi),d=i?.color??Qi,x=Math.max(0,i?.intensity??Ki),h=Math.hypot(c[0],c[1],c[2])||1,b=c[0]/h,v=c[1]/h,P=c[2]/h,C=r.lightOccludedPolyIndices?.has(e.index)??!1?0:u*Math.max(0,t[0]*b+t[1]*v+t[2]*P);return{...e,polygon:n,normal:t,shadedColor:Wi(n.color??"#cccccc",C,l,d,x)}}function Mr(e,n){let t=Lr(e,n);if(!t)return null;let{normal:o,xAxis:r,yAxis:s,tx:i,ty:c,tz:l}=t;return{normal:o,matrix:Gi([r[0]*e.canvasW/ot(e),r[1]*e.canvasW/ot(e),r[2]*e.canvasW/ot(e),0,s[0]*e.canvasH/ot(e),s[1]*e.canvasH/ot(e),s[2]*e.canvasH/ot(e),0,o[0],o[1],o[2],0,i,c,l,1])}}var Lr=Yi;function Ji(e,n,t){if(e.screenPts.length!==8||n.vertices.length!==4)return null;let o=Lr(e,n);if(!o)return null;let r=ji(e.screenPts,o.xAxis,o.yAxis,o.normal,o.tx,o.ty,o.tz,t);return r?{matrix:r,normal:o.normal}:null}function Qn(e,n,t,o,r=!1){let s=t.createElement("b");return s.setAttribute("style",`transform:matrix3d(${$i(e)})`+Gt(e,n,o,r)),ye(s,e.polygon,e.index),s}function Kn(e,n,t,o,r=!1){let s=t.createElement("i");return s.setAttribute("style",Tr(e)+Gt(e,n,o,r)),ye(s,e.polygon,e.index),s}function Jn(e,n,t,o,r,s=!1){let i=o.createElement("u");return i.className=Ar,i.setAttribute("style",Er(e,n)+Gt(e,t,r,s)),ye(i,e.polygon,e.index),i}function eo(e,n,t,o,r=!1){let s=t.createElement("b");return s.setAttribute("style",`transform:matrix3d(${e.projectiveMatrix})`+Gt(e,n,o,r)),ye(s,e.polygon,e.index),s}function _r(e,n,t,o,r,s,i){let c=n.projectiveMatrix?Ji(n,t,s):Mr(n,t);if(!c)return!1;let l=qn(n,t,c.normal,o,r);return e.style.visibility="",e.style.transform=`matrix3d(${c.matrix})`,At(e,l,o,i),ye(e,l.polygon,l.index),!0}function Rr(e,n,t,o){e.style.visibility="",e.setAttribute("style",Tr(n)),At(e,n,t,o),ye(e,n.polygon,n.index)}function kr(e,n,t,o,r){e.style.visibility="",e.className=Ar,e.setAttribute("style",Er(n,t)),At(e,n,o,r),xe(e,"background","currentColor"),ye(e,n.polygon,n.index)}function to(e,n,t,o=!1){let r=t.createElement("s"),s=ot(e),i=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:${s}px;opacity:0`+i),ye(r,e.polygon,e.index),r}import{computeSolidTriangleColorPlan as ya}from"@layoutit/polycss-core";import{computeSolidTrianglePlanFromCssPoints as ea,computeSolidTrianglePlan as ta}from"@layoutit/polycss-core";function rt(e,n,t,o={}){let r=o.primitive!=null?void 0:(()=>{let s=t.doc??(typeof document<"u"?document:null);return s?ze(s,t.strategies)??"border":"border"})();return ta(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??r})}function no(e,n,t,o,r,s,i,c,l,u,d,x,h){let b=o.primitive!=null?void 0:(()=>{let v=t.doc??(typeof document<"u"?document:null);return v?ze(v,t.strategies)??"border":"border"})();return ea(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??b},r,s,i,c,l,u,d,x,h)}import{buildSeamBleedPolygonEdges as na,DEFAULT_SEAM_BLEED as oa,DEFAULT_TILE as qd,resolveBleedRatio as ra}from"@layoutit/polycss-core";import{rgbEqual as sa,stepRgbToward as ia,rgbToCss as aa,colorErrorScore as la}from"@layoutit/polycss-core";import{computeSolidTriangleColorPlan as Or}from"@layoutit/polycss-core";import{stableTriangleMatrixDecimals as oo}from"@layoutit/polycss-core";var ca="0 48px 96px 48px";function ro(e,n){return na(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function so(e,n,t){let o=ra(t.seamBleed),r=oa*o,s={...t,bleedRatio:o};return n&&r>0?{...s,seamBleed:n.has(e)?r:void 0,seamEdges:n.get(e)}:s}function gn(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 Dr(e,n){return!n.updatesDisabled&&(n.freezeFrames<=1||(n.colorFrame+e)%n.freezeFrames===0)}function st(e,n,t,o,r,s){return t?s.updatesDisabled||o==="plan-only"||o==="transform-only"?!1:r==="adaptive"||e.__polycssSolidTriangleColor===void 0?!0:Dr(n,s):!0}function io(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"?ca:""),t.__polycssSolidTrianglePrimitive=n)}function ao(e){let n=e;n.__polycssSolidTriangleHidden&&(e.style.visibility="",n.__polycssSolidTriangleHidden=!1)}function Mt(e){let n=e;n.__polycssSolidTriangleHidden||(e.style.visibility="hidden",n.__polycssSolidTriangleHidden=!0)}function $t(e,n){e.setAttribute("style",n.styleText),io(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||wt(e))&&ye(e,n.polygon)}function Ir(e,n,t,o){if(!n.colorComputed){(n.polygon.data||wt(e))&&ye(e,n.polygon);return}let r=e,s=n.bakedColor??"",i=n.bakedRgb,c=n.bakedAlpha??1,l=r.__polycssSolidTriangleColor,u=r.__polycssSolidTriangleColorRgb,d=r.__polycssSolidTriangleColorAlpha??1,x=o??Dr(n.index,t);if(!t.updatesDisabled&&l!==s&&(l===void 0||x)){let h=s,b=i;if(t.maxStep>0&&u&&i&&d===c){let v=ia(u,i,t.maxStep);b=v,h=aa(v,c)}(h!==l||!sa(b,u))&&(e.style.color=h),r.__polycssSolidTriangleColor=h,r.__polycssSolidTriangleColorRgb=b,r.__polycssSolidTriangleColorAlpha=c,r.__polycssSolidTriangleColorFrame=t.colorFrame}(n.polygon.data||wt(e))&&ye(e,n.polygon)}function Wt(e,n,t,o){let r=e;io(e,n.primitive),r.__polycssSolidTriangleBasis!==n.basis&&(r.__polycssSolidTriangleBasis=n.basis),ao(e),e.style.transform=n.transformText,(n.colorComputed||n.polygon.data||wt(e))&&Ir(e,n,t,o)}function yn(e,n,t,o){ao(e),Ir(e,n,t,o)}function jt(e,n){let t=e;io(e,n.primitive),t.__polycssSolidTriangleBasis!==n.basis&&(t.__polycssSolidTriangleBasis=n.basis),ao(e),e.style.transform=n.transformText,(n.polygon.data||wt(e))&&ye(e,n.polygon)}function ua(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 lo(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 s=ua(e.length,t),i=Math.max(1,Math.floor(t.stableTriangleColorMaxAge??Math.max(2,r*2))),c=[];for(let l=0;l<e.length;l++){let u=e[l],d=n[l];if(u.kind!=="triangle"||!d)continue;let x=u.element,h=x.__polycssSolidTriangleColor,b=d.bakedColor??"";if(h===b)continue;let v=x.__polycssSolidTriangleColorFrame??0,P=Math.max(0,o-v),y=la(h,b);c.push({index:l,score:(P>=i?1e6:0)+y*1e4+P})}return c.length===0?new Set:(c.sort((l,u)=>u.score-l.score),new Set(c.slice(0,s).map(l=>l.index)))}function bn(e,n){let t=n.createElement("u");return $t(t,e),ye(t,e.polygon,e.index),t}function da(e,n,t){let o=t.createElement("u");return Mt(o),ye(o,e,n),o}function co(e,n,t,o,r,s){let i=t,c=i.stableTriangleDebug,l=o&&r==="color-only";if(i.stableTriangleColorPolicy==="adaptive"||e.length!==n.length)return!1;let u=oo(i.stableTriangleMatrixDecimals),d=t.doc??(typeof document<"u"?document:null),x=d?ze(d,t.strategies)??"border":"border";for(let b=0;b<e.length;b++){let v=e[b];if(v.kind!=="triangle"||v.polygonIndex!==b||!n[b])return!1}let h=ro(n,t);for(let b=0;b<e.length;b++){let v=e[b].element,P=n[b];if(l){if(st(v,b,o,c,i.stableTriangleColorPolicy,s)){let C=Or(P,b,t);if(!C)continue;yn(v,C,s)}continue}let y=rt(P,b,so(b,h,t),{basis:v.__polycssSolidTriangleBasis,matrixDecimals:u,primitive:x,includeColor:r!=="plan-only"&&r!=="transform-only"&&st(v,b,o,c,i.stableTriangleColorPolicy,s)});if(!y){Mt(v);continue}o&&r==="plan-only"||(o&&r==="transform-only"?jt(v,y):o?Wt(v,y,s):$t(v,y))}return!0}function Lt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=ze(t,n.strategies);if(!o||e.some(c=>c.texture||c.vertices.length!==3))return null;let r=oo(n.stableTriangleMatrixDecimals),s=[],i=ro(e,n);for(let c=0;c<e.length;c+=1){let l=e[c],u=rt(l,c,so(c,i,n),{matrixDecimals:r,primitive:o}),d=u?bn(u,t):da(l,c,t);s.push({polygonIndex:c,element:d,kind:"triangle",dispose:()=>{}})}return{rendered:s,dispose(){}}}function uo(e,n,t={}){let o=t.doc??(typeof document<"u"?document:null);if(!o)return{rendered:e,dispose:()=>{}};let r=ze(o,t.strategies);if(!r||e.some(y=>y.kind!=="triangle")||n.length!==e.length)return null;for(let y=0;y<e.length;y++)if(e[y].polygonIndex!==y)return null;let s=t.optimizeStableTriangleStyle===!0&&(t.textureLighting??"baked")==="baked",i=t,c=i.stableTriangleDebug,l=i.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full"),u=s&&l==="color-only",d=gn(i),x=oo(i.stableTriangleMatrixDecimals);if(co(e,n,t,s,l,d))return{rendered:e,dispose(){}};let h=new Array(e.length),b=new Array(e.length),v=ro(n,t);for(let y=0;y<e.length;y++){let C=e[y].element;if(u){let D=i.stableTriangleColorPolicy==="adaptive"||st(C,y,s,c,i.stableTriangleColorPolicy,d);b[y]=D?Or(n[y],y,t):null;continue}h[y]=rt(n[y],y,so(y,v,t),{basis:C.__polycssSolidTriangleBasis,matrixDecimals:x,primitive:r,includeColor:l!=="plan-only"&&l!=="transform-only"&&st(C,y,s,c,i.stableTriangleColorPolicy,d)})}let P=s&&l!=="plan-only"&&l!=="transform-only"?lo(e,u?b:h,i):null;for(let y=0;y<e.length;y++){if(u){let D=b[y];D&&yn(e[y].element,D,d,P?.has(y));continue}let C=h[y];if(!C){Mt(e[y].element);continue}s&&l==="plan-only"||(s&&l==="transform-only"?jt(e[y].element,C):s?Wt(e[y].element,C,d,P?.has(y)):$t(e[y].element,C))}return{rendered:e,dispose(){}}}import{stableTriangleMatrixDecimals as Vr}from"@layoutit/polycss-core";function Br(){return new Promise(e=>setTimeout(e,0))}async function po(e){return performance.now()-e<pa?e:(await Br(),performance.now())}function zr(e,n){let t=mo(n.seamBleed),o=Fr*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 Nr(e,n){return ga(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function Ur(e,n,t){let o=mo(t.seamBleed),r=Fr*o,s={...t,bleedRatio:o};return n&&r>0?{...s,seamBleed:n.has(e)?r:void 0,seamEdges:n.get(e)}:s}function ut(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{};let o=fo(e,n),r=Ct(t),s=e.map((i,c)=>Xt(i,c,n,r,o[c]));return Ut(s,n.textureLighting??"baked",t,n.strategies)}function dt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=n.textureLighting??"baked",r=n,s=o==="dynamic"&&r.skipDynamicNormalVars===!0,i=new Set(n.strategies?.disable??[]),c=!i.has("b"),l=c&&Et(t),u=ze(t,n.strategies),d=u!==null,x=!i.has("i")&&Nt(t),h=!i.has("i")&&Tt(t),b=fo(e,n),v=Ct(t),P=Nr(e,n),y=e.map((m,p)=>Xt(m,p,Ur(p,P,n),v,b[p]));if(typeof window<"u"){let m=window,p=y[1];m.__vanillaPlan1={matrix:p?.matrix,canvasW:p?.canvasW,canvasH:p?.canvasH,vertexCount:e[1]?.vertices.length}}let C=n.solidPaintDefaults??(r.computeSolidPaintDefaults?Ut(y,o,t,n.strategies):void 0),D=C?{...n,solidPaintDefaults:C}:n,k=y.map(m=>m&&d&&Ke(m)?rt(m.polygon,m.index,zr(m,D),{primitive:u??void 0}):null),z=y.map(m=>m&&x&&!Ke(m)&&!(c&&Ve(m))&&!(l&&Be(m))?Yt(m):null),I=y.map((m,p)=>m&&(m.texture||!(c&&Ve(m))&&!k[p]&&!(l&&Be(m))&&!z[p]&&!h?m:null)),{packed:Z,atlasScale:Q}=vt(I,n.textureQuality,t),O=new Map,H=[],V=!1,U=[];for(let m=0;m<e.length;m++){let p=y[m],E=k[m],M=z[m];if(!p)continue;let R=Z.entries[m];if(R){let L=to(R,o,t,s);O.set(m,L),H.push({polygonIndex:m,element:L,kind:"atlas",plan:R,dispose:()=>{}})}else if(!p.texture&&c&&Ve(p)){let L=Qn(p,o,t,C,s);H.push({polygonIndex:m,element:L,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&E){let L=bn(E,t);H.push({polygonIndex:m,element:L,kind:"triangle",plan:p,dispose:()=>{}})}else if(!p.texture&&l&&Be(p)){let L=eo(p,o,t,C,s);H.push({polygonIndex:m,element:L,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&M){let L=Jn(p,M,o,t,C,s);H.push({polygonIndex:m,element:L,kind:"corner",plan:p,dispose:()=>{}})}else if(!p.texture&&h){let L=Kn(p,o,t,C,s);H.push({polygonIndex:m,element:L,kind:"border",plan:p,dispose:()=>{}})}}H.sort((m,p)=>m.polygonIndex-p.polygonIndex);let A=St(Z.pages,o,t,Q,()=>V).then(m=>{if(V){for(let p of m)p.url?.startsWith("blob:")&&URL.revokeObjectURL(p.url);return}U=m.flatMap(p=>p.url?.startsWith("blob:")?[p.url]:[]);for(let p=0;p<Z.pages.length;p++){let E=Z.pages[p],M=m[p];if(M)for(let R of E.entries){let L=O.get(R.index);!L||!M.url||Zn(L,M,o,R,!0)}}}).catch(()=>{if(!V)for(let m of O.values())xe(m,"opacity","0.5"),xe(m,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:H,solidPaintDefaults:C??{},pagesReady:A,dispose(){V=!0;for(let m of U)URL.revokeObjectURL(m);U=[]}}}async function Zt(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",i=r==="dynamic"&&n.skipDynamicNormalVars===!0,c=new Set(n.strategies?.disable??[]),l=!c.has("b"),u=l&&Et(o),d=ze(o,n.strategies),x=d!==null,h=!c.has("i")&&Nt(o),b=!c.has("i")&&Tt(o);if(await Br(),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let v=fo(e,n),P=Ct(o),y=Nr(e,n),C=performance.now(),D=new Array(e.length);for(let m=0;m<e.length;m++)if(D[m]=Xt(e[m],m,Ur(m,y,n),P,v[m]),C=await po(C),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let k=n.solidPaintDefaults??Ut(D,r,o,n.strategies),z=new Array(D.length),I=new Array(D.length),Z=new Array(D.length);for(let m=0;m<D.length;m++){let p=D[m],E=p&&x&&Ke(p)?rt(p.polygon,p.index,zr(p,{...n,solidPaintDefaults:k}),{primitive:d??void 0}):null;z[m]=E;let M=p&&h&&!Ke(p)&&!(l&&Ve(p))&&!(u&&Be(p))?Yt(p):null;if(I[m]=M,Z[m]=p&&(p.texture||!(l&&Ve(p))&&!E&&!(u&&Be(p))&&!M&&!b?p:null),C=await po(C),t())return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}let{packed:Q,atlasScale:O}=vt(Z,n.textureQuality,o),H=new Map,V=[],U=!1,A=[];for(let m=0;m<e.length;m++){let p=D[m],E=z[m],M=I[m];if(!p)continue;let R=Q.entries[m];if(R){let L=to(R,r,o,i);H.set(m,L),V.push({polygonIndex:m,element:L,kind:"atlas",plan:R,dispose:()=>{}})}else if(!p.texture&&l&&Ve(p)){let L=Qn(p,r,o,k,i);V.push({polygonIndex:m,element:L,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&E){let L=bn(E,o);V.push({polygonIndex:m,element:L,kind:"triangle",plan:p,dispose:()=>{}})}else if(!p.texture&&u&&Be(p)){let L=eo(p,r,o,k,i);V.push({polygonIndex:m,element:L,kind:"solid",plan:p,dispose:()=>{}})}else if(!p.texture&&M){let L=Jn(p,M,r,o,k,i);V.push({polygonIndex:m,element:L,kind:"corner",plan:p,dispose:()=>{}})}else if(!p.texture&&b){let L=Kn(p,r,o,k,i);V.push({polygonIndex:m,element:L,kind:"border",plan:p,dispose:()=>{}})}if(C=await po(C),t()){for(let L of V)L.dispose();return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}}V.sort((m,p)=>m.polygonIndex-p.polygonIndex);let g=St(Q.pages,r,o,O,()=>U||t()).then(m=>{if(U||t()){for(let p of m)p.url?.startsWith("blob:")&&URL.revokeObjectURL(p.url);return}A=m.flatMap(p=>p.url?.startsWith("blob:")?[p.url]:[]);for(let p=0;p<Q.pages.length;p++){let E=Q.pages[p],M=m[p];if(M)for(let R of E.entries){let L=H.get(R.index);!L||!M.url||Zn(L,M,r,R,!0)}}}).catch(()=>{if(!(U||t()))for(let m of H.values())xe(m,"opacity","0.5"),xe(m,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:V,solidPaintDefaults:k,pagesReady:g,dispose(){U=!0;for(let m of A)URL.revokeObjectURL(m);A=[]}}}function qt(e,n,t,o={}){let r=o.textureLighting??"baked",s=o,i=s.optimizeStableTriangleStyle===!0&&r==="baked";if(!i||s.stableTriangleColorPolicy==="adaptive"||e.length!==t.polygonCount||n.length!==t.polygonCount||t.vertices.length<t.polygonCount*9)return!1;let c=s.stableTriangleDebug,l=s.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full");if(l==="color-only")return!1;let u=Vr(s.stableTriangleMatrixDecimals),d=gn(s),x=o.tileSize??ma,h=o.layerElevation??x,b=o.doc??(typeof document<"u"?document:null),v=b?ze(b,o.strategies)??"border":"border";for(let y=0;y<e.length;y++){let C=e[y],D=n[y];if(C.kind!=="triangle"||C.polygonIndex!==y||!D||D.vertices.length!==3||D.texture||D.material?.texture)return!1}let P=t.vertices;for(let y=0;y<e.length;y++){let C=e[y].element,D=n[y],k=y*9,z=P[k+1]*x,I=P[k]*x,Z=P[k+2]*h,Q=P[k+4]*x,O=P[k+3]*x,H=P[k+5]*h,V=P[k+7]*x,U=P[k+6]*x,A=P[k+8]*h,g=no(D,y,o,{basis:C.__polycssSolidTriangleBasis,matrixDecimals:u,primitive:v,color:t.colors?.[y],includeColor:l!=="plan-only"&&l!=="transform-only"&&st(C,y,i,c,s.stableTriangleColorPolicy,d)},z,I,Z,Q,O,H,V,U,A);if(!g){Mt(C);continue}l!=="plan-only"&&(l==="transform-only"?jt(C,g):Wt(C,g,d))}return!0}function Qt(e,n,t={}){if(e.length!==n.length)return!1;let o=t,r=t.doc??(typeof document<"u"?document:null),s=t.textureLighting??"baked",i=new Set(t.strategies?.disable??[]),c=!i.has("b"),l=!!r&&c&&Et(r),u=!!r&&!i.has("i")&&Nt(r),d=!!r&&!i.has("i")&&Tt(r),x=mo(o.seamBleed),h=r?Ct(r,{bleed:Hr*x}):{denomEps:fa,maxWeightRatio:ha,bleed:Hr*x,disableGuards:!1},b=o.optimizeStableTriangleStyle===!0&&s==="baked",v=o.stableTriangleDebug,P=o.stableTriangleUpdateMode??(v==="plan-only"||v==="transform-only"?v:"full"),y=b&&P==="color-only",C=gn(o),D=Vr(o.stableTriangleMatrixDecimals),k=r?ze(r,t.strategies)??"border":"border";if(co(e,n,t,b,P,C))return!0;let z=[],I=[],Z=[];for(let O=0;O<e.length;O++){let H=e[O];if(H.polygonIndex!==O)return!1;let V=n[O];if(!V||y&&H.kind!=="triangle")return!1;if(H.kind==="atlas"){if(!H.plan||!wr(H.element,H.plan,V,s))return!1;continue}if(H.kind==="triangle"){let U=H.element;if(y){let g=o.stableTriangleColorPolicy==="adaptive"||st(U,O,b,v,o.stableTriangleColorPolicy,C);I[O]=g?ya(V,O,t):null;continue}let A=rt(V,O,t,{basis:U.__polycssSolidTriangleBasis,matrixDecimals:D,primitive:k,includeColor:P!=="plan-only"&&P!=="transform-only"&&st(U,O,b,v,o.stableTriangleColorPolicy,C)});if(!A){z[O]=null;continue}z[O]=A;continue}if(H.kind==="solid"){if(!H.plan||V.texture||V.vertices.length!==H.plan.polygon.vertices.length)return!1;Z[O]=H.plan;continue}if(H.kind==="border"){let U=Xt(V,O,t,h);if(!U||U.texture||!d||c&&Ve(U)||l&&Be(U)||u&&Yt(U))return!1;Z[O]=U;continue}if(H.kind==="corner"){let U=Xt(V,O,t,h);if(!U||U.texture||!u||Ke(U)||c&&Ve(U)||l&&Be(U)||!Yt(U))return!1;Z[O]=U;continue}return!1}let Q=b&&P!=="plan-only"&&P!=="transform-only"?lo(e,y?I:z,o):null;for(let O=0;O<e.length;O++){let H=e[O];if(H.kind==="triangle"){if(y){let U=I[O];U&&yn(H.element,U,C,Q?.has(O));continue}let V=z[O];if(!V){Mt(H.element);continue}if(b&&P==="plan-only")continue;b&&P==="transform-only"?jt(H.element,V):b?Wt(H.element,V,C,Q?.has(O)):$t(H.element,V)}else if(H.kind==="solid"){let V=Z[O];if(!V||!_r(H.element,V,n[O],s,t,h,o.solidPaintDefaults))return!1}else if(H.kind==="border"){let V=Z[O];if(!V)return!1;Rr(H.element,V,s,o.solidPaintDefaults)}else if(H.kind==="corner"){let V=Z[O],U=V?Yt(V):null;if(!V||!U)return!1;kr(H.element,V,U,s,o.solidPaintDefaults)}}return!0}import{computeTextureAtlasPlanPublic as $r}from"@layoutit/polycss-core";import{formatMatrix3d as Wr,formatCssLengthPx as jr,formatSolidQuadEntryMatrix as Yr}from"@layoutit/polycss-core";import{formatBorderShapeEntryMatrix as Xr,cssBorderShapeForPlan as Zr}from"@layoutit/polycss-core";import{BASE_TILE as Pe,computeProjectiveQuadMatrix as xa,normalFacesCamera as Pa,parsePureColor as ts,PROJECTIVE_QUAD_BLEED as Sa,resolveProjectiveQuadGuards as Ca,rotateVec3 as Ta,rotateVec3InWrapperCssFrame as Ea,shadePolygon as Aa,SOLID_QUAD_CANONICAL_SIZE as wa}from"@layoutit/polycss-core";var Ma=[.4,-.7,.59],La="#ffffff",_a=1,Ra="#ffffff",ka=.4,ns=1,Oa=8,Da=Sa,Je=1e-6,Ia=Ca({bleed:0}),os={t:[0,0,1],b:[0,0,-1],fl:[0,1,0],br:[0,-1,0],fr:[1,0,0],bl:[-1,0,0]},yo=["t","b","bl","br","fr","fl"],Ha=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 qr(e){let n=[];for(let t of yo)Pa(os[t],e)&&n.push(t);return n.join("|")}function Fa(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 Va(e){let n=e.vertices;if(n.length<3)return null;let t=n[0],o=0,r=0,s=0;for(let c=1;c+1<n.length;c+=1){let l=n[c],u=n[c+1],d=l[1]-t[1],x=l[0]-t[0],h=l[2]-t[2],b=u[1]-t[1],v=u[0]-t[0],P=u[2]-t[2];o-=x*P-h*v,r-=h*b-d*P,s-=d*v-x*b}let i=Math.hypot(o,r,s);return i<=1e-9?null:[Math.round(o/i),Math.round(r/i),Math.round(s/i)]}function Ba(e){if(e.texture||e.material||e.uvs||e.textureTriangles||e.vertices.length!==4)return null;let n=Va(e),t=n?Ha.get(n.join(",")):void 0;if(!t)return null;let o=1/0,r=1/0,s=1/0,i=-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]),s=Math.min(s,x[2]),i=Math.max(i,x[0]),c=Math.max(c,x[1]),l=Math.max(l,x[2]);let u=1e-6,d=ja(e.color);return Math.abs(l-s)<=u?{axis:"z",face:t,left:r*Pe,top:o*Pe,width:Math.max(0,(c-r)*Pe),height:Math.max(0,(i-o)*Pe),z:s*Pe,baseColor:d,bleed:ho()}:Math.abs(i-o)<=u?{axis:"x",face:t,left:r*Pe,top:s*Pe,width:Math.max(0,(c-r)*Pe),height:Math.max(0,(l-s)*Pe),z:-o*Pe,baseColor:d,bleed:ho()}:Math.abs(c-r)<=u?{axis:"y",face:t,left:s*Pe,top:o*Pe,width:Math.max(0,(l-s)*Pe),height:Math.max(0,(i-o)*Pe),z:-r*Pe,baseColor:d,bleed:ho()}:null}function ho(){return{left:0,right:0,top:0,bottom:0}}function za(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 Qr(e){return[e[1]*Pe,e[0]*Pe,e[2]*Pe]}function Kr(e,n){return e.axis==="x"?[n[0],n[2]]:e.axis==="y"?[n[2],n[1]]:[n[0],n[1]]}function Na(e,n,t){let o=e.left,r=e.left+e.width,s=e.top,i=e.top+e.height;if(Math.abs(n[0]-t[0])<=Je){if(Math.abs(n[0]-o)<=Je)return"left";if(Math.abs(n[0]-r)<=Je)return"right"}if(Math.abs(n[1]-t[1])<=Je){if(Math.abs(n[1]-s)<=Je)return"top";if(Math.abs(n[1]-i)<=Je)return"bottom"}return null}function Ua(e,n){let t=null;for(let o=0;o<3;o+=1)if(!(Math.abs(e[o]-n[o])<=Je)){if(t!==null)return null;t=o}return t}function Ga(e,n,t){let o=n.vertices,r=Qr(o[t]),s=Qr(o[(t+1)%o.length]),i=Na(e,Kr(e,r),Kr(e,s));if(!i)return null;let c=Ua(r,s);if(c===null)return null;let l=Math.min(r[c],s[c]),u=Math.max(r[c],s[c]);return u-l>Je?{item:e,side:i,variableAxis:c,fixed:r,start:l,end:u}:null}function Jr(e){e.item.bleed[e.side]=Math.max(e.item.bleed[e.side],Da)}function $a(e,n){let t=new Map;for(let o of n){let r=e[o.sourceIndex];if(r)for(let s=0;s<r.vertices.length;s+=1){let i=Ga(o,r,s);if(!i)continue;let c=za(i),l=t.get(c);l?l.push(i):t.set(c,[i])}}for(let o of t.values()){if(o.length<2)continue;o.sort((s,i)=>s.start-i.start||s.end-i.end);let r=[];for(let s of o){r=r.filter(i=>i.end>s.start+Je);for(let i of r)i.item.sourceIndex!==s.item.sourceIndex&&(Jr(i),Jr(s));r.push(s)}}}function Wa(e){let n=ts(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 ja(e){if(!e)return"#cccccc";let n=ts(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(${go(t.r)}, ${go(t.g)}, ${go(t.b)}, ${o})`}return Ya(t)}function Ya({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 go(e){return Math.round(Math.max(0,Math.min(255,e)))}function Xa(e,n,t,o){let r=t?.direction??Ma,s=Math.hypot(r[0],r[1],r[2])||1,i=r[0]/s,c=r[1]/s,l=r[2]/s,u=Math.max(0,t?.intensity??_a)*Math.max(0,e[0]*i+e[1]*c+e[2]*l),d=Math.max(0,o?.intensity??ka),x=t?.color??La,h=o?.color??Ra,b=Aa(n,u,x,h,d),v=Wa(n);if(v.alpha>=1)return b;let P=parseInt(b.slice(1,3),16),y=parseInt(b.slice(3,5),16),C=parseInt(b.slice(5,7),16);return`rgba(${P}, ${y}, ${C}, ${v.alpha})`}function Za(e){if(!e?.length)return[];let n=[];for(let t=0;t<e.length;t+=1){let o=e[t],r=Ba(o);if(!r||r.width<=0||r.height<=0)return[];n.push({...r,sourceIndex:t})}return $a(e,n),n}function qa(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 Qa(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 Ka(e){return new Map([[0,e.bleed.top],[1,e.bleed.right],[2,e.bleed.bottom],[3,e.bleed.left]])}function Ja(e,n){let t=e.split(",").map(Number);if(t.length!==16||t.some(r=>!Number.isFinite(r)))return null;let o=wa/n;for(let r=0;r<8;r+=1)t[r]*=o;return`matrix3d(${t.map(r=>Number(r.toFixed(6))).join(",")})`}function es(e,n){let t=e.left-e.bleed.left,o=e.top-e.bleed.top,r=e.width+e.bleed.left+e.bleed.right,s=e.height+e.bleed.top+e.bleed.bottom,i=e.z,c=r/n,l=s/n;return`matrix3d(${(e.axis==="x"?[c,0,0,0,0,0,l,0,0,-1,0,0,t,-i,o,1]:e.axis==="y"?[0,0,c,0,0,l,0,0,-1,0,0,0,-i,o,t,1]:[c,0,0,0,0,l,0,0,0,0,1,0,t,o,i,1]).map(d=>Number(d.toFixed(6))).join(",")})`}function el(e,n){let{xAxis:t,yAxis:o,normal:r,tx:s,ty:i,tz:c}=qa(e),l=xa(Qa(e),t,o,r,s,i,c,Ia,Ka(e));return l?Ja(l,n)??es(e,n):es(e,n)}function tl(e){let n=e.defaultView?.matchMedia;return n?n("(pointer: coarse)").matches||n("(hover: none)").matches:!1}function nl(e){return tl(e)?Oa:ns}function ol(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 rl(e,n){let t=ol(e),o=n.meshRotation;o&&(t=Ea(t,o));let[r,s]=Ta(t,n.rotX,0,n.rotY);return{x:r,y:s}}function sl(e,n,t){let o=e.filter(h=>n.has(h.face)).map(h=>({item:h,...rl(h,t)}));if(o.length===0)return[];let r=1/0,s=-1/0,i=1/0,c=-1/0;for(let h of o)r=Math.min(r,h.x),s=Math.max(s,h.x),i=Math.min(i,h.y),c=Math.max(c,h.y);let l=4,u=Math.max(1e-6,s-r),d=Math.max(1e-6,c-i),x=new Map;for(let h of o){let b=Math.min(l-1,Math.max(0,Math.floor((h.x-r)/u*l))),v=Math.min(l-1,Math.max(0,Math.floor((h.y-i)/d*l))),P=`${b}:${v}`,y=x.get(P);y||(y={tx:b,ty:v,sourceIndex:h.item.sourceIndex,items:[]},x.set(P,y)),y.items.push(h.item),y.sourceIndex=Math.min(y.sourceIndex,h.item.sourceIndex)}return Array.from(x.values()).sort((h,b)=>h.ty-b.ty||h.tx-b.tx||h.sourceIndex-b.sourceIndex).flatMap(h=>h.items)}function rs(e){let{doc:n,wrapper:t,polygons:o,directionalLight:r,ambientLight:s}=e,i=Za(o);if(i.length===0)return null;let c=new Set(i.map(g=>g.face));t.classList.add("polycss-voxel-mesh");let l=nl(n);l!==ns&&t.style.setProperty("--polycss-voxel-primitive",`${l}px`);let u=new Map,d=(g,m)=>{let p=`${g}|${m}`,E=u.get(p);if(E)return E;let M=Xa(os[g],m,r,s);return u.set(p,M),M},x=new Map,h=new Map,b=new Map,v=new Map;for(let g of i){let m=v.get(g.face);m||(m=[],v.set(g.face,m)),m.push(g)}let P="",y=0,C=new Set,D=g=>{let m=x.get(g.sourceIndex);return m||(m=n.createElement("b"),x.set(g.sourceIndex,m),Fa(m,d(g.face,g.baseColor),el(g,l))),m},k=g=>{let m=h.get(g);return m||(m=n.createElement("span"),m.className=`polycss-voxel-face polycss-voxel-face-${g}`,m.dataset.polycssVoxelFace=g,m.__polycssVoxelFaceHost=!0,h.set(g,m)),m},z=()=>{for(let g of Array.from(t.childNodes))if(!g.__polycssVoxelFaceHost)return g;return null},I=(g,m)=>{let p=m.map(R=>R.sourceIndex).join(",");if(b.get(g)===p)return;let E=k(g),M=n.createDocumentFragment();for(let R of m)M.appendChild(D(R));E.replaceChildren(M),b.set(g,p)},Z=()=>{for(let g of yo)c.has(g)&&I(g,v.get(g)??[])},Q=g=>new Set(g.split("|").filter(Boolean)),O=g=>{let m=Q(g);return yo.filter(p=>m.has(p)&&c.has(p))},H=g=>{let m=0;for(let p of g)m+=v.get(p)?.length??0;return m},V=g=>{let m=new Set,p=[],E=new Map;for(let M of g){m.has(M.face)||(m.add(M.face),p.push(M.face));let R=E.get(M.face);R||(R=[],E.set(M.face,R)),R.push(M)}return{orderedFaces:p,itemsByFace:E}},U=(g,m)=>{let p=new Set(g);for(let E of C){if(p.has(E))continue;let M=h.get(E);M?.parentNode===t&&t.removeChild(M)}if(m){let E=n.createDocumentFragment();for(let M of g)E.appendChild(k(M));t.insertBefore(E,z()),C=p;return}for(let E=0;E<g.length;E+=1){let M=g[E],R=k(M);if(R.parentNode===t)continue;let L=null;for(let te=E+1;te<g.length;te+=1){let _=h.get(g[te]);if(_?.parentNode===t){L=_;break}}t.insertBefore(R,L??z())}C=p},A=(g,m,p)=>{if(!p){let te=O(g);U(te,!1),y=H(te);return}let E=new Set(g.split("|").filter(Boolean)),M=sl(i,E,m),{orderedFaces:R,itemsByFace:L}=V(M);for(let te of R)I(te,L.get(te)??[]);U(R,!0),y=M.length};return Z(),{get brushCount(){return y},render(g){P=qr(g),A(P,g,!0)},syncCamera(g){let m=qr(g);m!==P&&(P=m,A(m,g,!1))},dispose(){for(let g of h.values())g.remove();t.classList.remove("polycss-voxel-mesh"),t.style.removeProperty("--polycss-voxel-primitive"),x.clear(),h.clear(),b.clear(),y=0,C=new Set,P=""}}}var ss="polycss-styles";function bo(e){let n=e??(typeof document<"u"?document:void 0);if(!n||n.getElementById(ss))return;let t=n.createElement("style");t.id=ss,t.textContent=il,n.head.appendChild(t)}var il=`
1
+ import{CAMERA_BACKFACE_CULL_EPS as Ho,DEFAULT_SEAM_BLEED as ni,VOXEL_CAMERA_CULL_NORMAL_LIMIT as Ql,cameraCullNormalKey as Kl,cameraCullVisibleSignature as Jl,computeSceneBbox as ec,computeLightVisibility as tc,capturePolyCameraSnapshot as nc,findOverlappingPolygonDuplicates as Ks,inverseRotateVec3 as Fo,isAxisAlignedSurfaceNormal as oc,isVoxelCameraCullableNormalGroups as rc,normalFacesCamera as sc,optimizeMeshPolygons as ic,parseHexColor as ac,polygonCssSurfaceNormal as Js}from"@layoutit/polycss-core";import{packTextureAtlasPlansWithScaleCore as Bi}from"@layoutit/polycss-core";function Vi(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 Et(e,n,t,o){return Bi(e,n,Vi(t),o)}import{buildTextureEdgeRepairSets as ss,buildSeamBleedPolygonEdges as Va,buildSeamBleedPolygonSet as Na}from"@layoutit/polycss-core";import{TEXTURE_TRIANGLE_BLEED as Ni,TEXTURE_EDGE_REPAIR_ALPHA_MIN as ji,TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN as $i,TEXTURE_EDGE_REPAIR_RADIUS as wr}from"@layoutit/polycss-core";import{expandClipPoints as Ui}from"@layoutit/polycss-core";import{BASIS_EPS as Wi}from"@layoutit/polycss-core";var At=new Map;function Gi(e){let n=At.get(e);return n||(n=new Promise((t,o)=>{let s=new Image;s.decoding="async",s.crossOrigin="anonymous",s.onload=()=>t(s),s.onerror=()=>o(new Error(`texture load failed: ${e}`)),s.src=e}),At.set(e,n),n.then(()=>{At.get(e)===n&&At.delete(e)},()=>{At.get(e)===n&&At.delete(e)})),n}function _e(e,n,t=1,o=0,s=0,r=1,i=0,c=0){e.setTransform(t*n,o*n,s*n,r*n,i*n,c*n)}function Qn(e){let n=e/255;return n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Kn(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 Yi(e,n,t,o,s,r,i){let c=Math.round(n*i),l=Math.round(t*i),u=Math.max(1,Math.round(o*i)),d=Math.max(1,Math.round(s*i)),P=e.getImageData(c,l,u,d),f=P.data,b=r.r,x=r.g,v=r.b;for(let y=0;y<f.length;y+=4)f[y+3]!==0&&(f[y]=Kn(Qn(f[y])*b),f[y+1]=Kn(Qn(f[y+1])*x),f[y+2]=Kn(Qn(f[y+2])*v));e.putImageData(P,c,l)}function Xi(e,n,t,o,s,r,i){let c=n.naturalWidth||n.width||1,l=n.naturalHeight||n.height||1,u=Math.max(s/c,r/l),d=c*u,P=l*u;_e(e,i),e.drawImage(n,t+(s-d)/2,o+(r-P)/2,d,P)}function wt(e,n){return Math.max(0,Math.min(n,e))}function Mr(e,n,t,o,s,r,i,c){let l=n.naturalWidth||n.width||1,u=n.naturalHeight||n.height||1,d=wt(Math.min(t.minU,t.maxU)*l,l),P=wt(Math.max(t.minU,t.maxU)*l,l),f=wt(Math.min(t.minV,t.maxV)*u,u),b=wt(Math.max(t.minV,t.maxV)*u,u),x=Math.floor(d),v=Math.floor(f),y=Math.ceil(P)-x,C=Math.ceil(b)-v;y<1&&(x=Math.floor(wt((t.minU+t.maxU)/2*l,l-1)),y=1),C<1&&(v=Math.floor(wt((t.minV+t.maxV)/2*u,u-1)),C=1),x=Math.max(0,Math.min(l-1,x)),v=Math.max(0,Math.min(u-1,v)),y=Math.max(1,Math.min(l-x,y)),C=Math.max(1,Math.min(u-v,C)),_e(e,c),e.drawImage(n,x,v,y,C,o,s,r,i)}function Or(e){return e==="repeat"||e==="mirrored-repeat"}function Lr(e,n){return Or(e)?Math.floor(n):0}function Rr(e,n){return Or(e)?Math.ceil(n)-1:0}function kr(e,n){return e==="mirrored-repeat"&&Math.abs(n%2)===1}function _r(e,n,t,o,s,r,i){let c=s?Lr(r,s.minU):0,l=s?Rr(r,s.maxU):0,u=s?Lr(i,s.minV):0,d=s?Rr(i,s.maxV):0;for(let P=c;P<=l;P++)for(let f=u;f<=d;f++){let b=kr(r,P),x=kr(i,f);if(!b&&!x){e.drawImage(n,P*t,f*o);continue}e.save(),e.translate((b?P+1:P)*t,(x?f+1:f)*o),e.scale(b?-1:1,x?-1:1),e.drawImage(n,0,0),e.restore()}}function Jn(e,n,t,o){for(let s=0;s<o.length;s+=2){let r=n+o[s],i=t+o[s+1];s===0?e.moveTo(r,i):e.lineTo(r,i)}e.closePath()}function yn(e,n,t,o,s,r){for(let i=0;i<o.length;i+=2){let c=n+o[i]+s,l=t+o[i+1]+r;i===0?e.moveTo(c,l):e.lineTo(c,l)}e.closePath()}function qi(e,n,t,o){_e(e,o),e.beginPath(),Jn(e,n.x,n.y,n.screenPts),e.clip(),_e(e,o),e.fillStyle=t==="dynamic"?n.polygon.color??"#cccccc":n.shadedColor,e.fillRect(n.x,n.y,n.canvasW,n.canvasH)}function bn(e,n,t,o,s){n.polygon.textureAlphaMode==="opaque"&&(_e(e,t),e.fillStyle=n.polygon.color??"#cccccc",e.fillRect(n.x+o,n.y+s,n.canvasW,n.canvasH))}function Zi(e,n,t,o,s=0,r=0){if(n.textureTriangles?.length){let i=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1;for(let l of n.textureTriangles){let u=Ui(l.screenPts,Ni*(n.bleedRatio??1));e.save(),_e(e,o),e.beginPath(),yn(e,n.x,n.y,u,s,r),e.clip(),bn(e,n,o,s,r),l.uvAffine?(_e(e,o,l.uvAffine.a/i,l.uvAffine.c/i,l.uvAffine.b/c,l.uvAffine.d/c,n.x+l.uvAffine.e+s,n.y+l.uvAffine.f+r),_r(e,t,i,c,l.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t)):l.uvSampleRect&&Mr(e,t,l.uvSampleRect,n.x+s,n.y+r,n.canvasW,n.canvasH,o),e.restore()}}else if(n.uvAffine){let i=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1,l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),_e(e,o),e.beginPath(),yn(e,n.x,n.y,n.screenPts,s,r),e.clip(),bn(e,n,o,s,r)),_e(e,o,n.uvAffine.a/i,n.uvAffine.c/i,n.uvAffine.b/c,n.uvAffine.d/c,n.x+n.uvAffine.e+s,n.y+n.uvAffine.f+r),_r(e,t,i,c,n.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t),l&&e.restore()}else if(n.uvSampleRect){let i=n.polygon.textureAlphaMode==="opaque";i&&(e.save(),_e(e,o),e.beginPath(),yn(e,n.x,n.y,n.screenPts,s,r),e.clip(),bn(e,n,o,s,r)),Mr(e,t,n.uvSampleRect,n.x+s,n.y+r,n.canvasW,n.canvasH,o),i&&e.restore()}else{let i=n.polygon.textureAlphaMode==="opaque";i&&(e.save(),_e(e,o),e.beginPath(),yn(e,n.x,n.y,n.screenPts,s,r),e.clip(),bn(e,n,o,s,r)),Xi(e,t,n.x+s,n.y+r,n.canvasW,n.canvasH,o),i&&e.restore()}}function Qi(e,n,t,o,s,r){let i=s-t,c=r-o,l=i*i+c*c;if(l<=Wi)return Math.hypot(e-t,n-o);let u=Math.max(0,Math.min(1,((e-t)*i+(n-o)*c)/l));return Math.hypot(e-(t+i*u),n-(o+c*u))}function Ki(e,n,t,o){let s=1/0,r=t.length/2;for(let i of o){if(i<0||i>=r)continue;let c=i*2,l=(i+1)%r*2;s=Math.min(s,Qi(e,n,t[c],t[c+1],t[l],t[l+1]))}return s}function Ji(e,n,t,o,s,r){let i=Math.max(0,o-r),c=Math.min(n-1,o+r),l=Math.max(0,s-r),u=Math.min(t-1,s+r),d=null,P=1/0;for(let f=l;f<=u;f++)for(let b=i;b<=c;b++){if(b===o&&f===s)continue;let x=b-o,v=f-s,y=x*x+v*v;if(y>r*r||y>=P)continue;let C=(f*n+b)*4;e[C+3]<$i||(d=C,P=y)}return d}function ea(e,n,t){if(!n.textureEdgeRepair||!n.texture||!n.textureEdgeRepairEdges||n.textureEdgeRepairEdges.size===0)return;let o=e.canvas;if(!o)return;let s=Math.max(0,Math.floor(n.x*t)),r=Math.max(0,Math.floor(n.y*t)),i=Math.max(1,Math.min(o.width-s,Math.ceil(n.canvasW*t))),c=Math.max(1,Math.min(o.height-r,Math.ceil(n.canvasH*t)));if(i<=0||c<=0)return;let l;try{l=e.getImageData(s,r,i,c)}catch{return}let u=l.data,d=new Uint8ClampedArray(u),P=Math.max(wr,wr/t),f=Math.max(2,Math.ceil(P*t)+1),b=!1;for(let x=0;x<c;x++)for(let v=0;v<i;v++){let y=(x*i+v)*4,C=u[y+3];if(C<ji||C===255)continue;let O=(s+v+.5)/t-n.x,k=(r+x+.5)/t-n.y;if(Ki(O,k,n.screenPts,n.textureEdgeRepairEdges)>P)continue;let j=Ji(d,i,c,v,x,f);j!==null&&(u[y]=d[j],u[y+1]=d[j+1],u[y+2]=d[j+2],u[y+3]=255,b=!0)}b&&e.putImageData(l,s,r)}function ta(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 na(e,n,t,o){let s=t.createElement("canvas");s.width=Math.max(1,Math.ceil(e.width*o)),s.height=Math.max(1,Math.ceil(e.height*o));let r=e.entries.some(d=>d.textureEdgeRepair&&d.texture&&d.textureEdgeRepairEdges&&d.textureEdgeRepairEdges.size>0),i=s.getContext("2d",r?{willReadFrequently:!0}:void 0);if(!i)return{width:e.width,height:e.height,url:null};let c=Array.from(new Set(e.entries.flatMap(d=>d.texture?[d.texture]:[]))),l=new Map;await Promise.all(c.map(async d=>{l.set(d,await Gi(d))}));for(let d of e.entries){let P=d.texture?l.get(d.texture):null;if(!d.texture){i.save(),qi(i,d,n,o),i.restore();continue}P&&(i.save(),_e(i,o),i.beginPath(),Jn(i,d.x,d.y,d.screenPts),i.clip(),Zi(i,d,P,o),i.restore()),d.texture&&n==="baked"&&(i.save(),_e(i,o),i.beginPath(),Jn(i,d.x,d.y,d.screenPts),i.clip(),Yi(i,d.x,d.y,d.canvasW,d.canvasH,d.textureTint,o),i.restore()),ea(i,d,o)}let u=await ta(s);return s.width=1,s.height=1,{width:e.width,height:e.height,url:u}}async function Mt(e,n,t,o,s){let r=[];for(let i of e){if(s())break;r.push(await na(i,n,t,o))}return r}import{isFullRectSolid as Be,isSolidTrianglePlan as Ke,isProjectiveQuadPlan as Ve,fullRectBounds as ip,safariCssProjectiveUnsupported as Dr,incrementCount as ap,dominantCountKey as lp,filterAtlasPlans as ra,getSolidPaintDefaultsForPlansCore as sa}from"@layoutit/polycss-core";import{parseHex as ia,rgbKey as aa}from"@layoutit/polycss-core";import{computeTextureAtlasPlan as pp,buildBasisHints as mp}from"@layoutit/polycss-core";import{resolveProjectiveQuadGuards as oa}from"@layoutit/polycss-core";function Lt(e,n){let o=e?.defaultView?.__polycssProjectiveQuadGuards,s=n&&o?{...n,...o}:o??n;return oa(s)}function Rt(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 s=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return s?s("(pointer: fine)").matches&&s("(hover: hover)").matches:!0}function eo(e){if(Ir(e))return!0;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Dr(t):!0}function Wt(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 Ir(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 la(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return/\bFirefox\//.test(t)}function Ne(e,n){return n?.disable?.includes("u")?null:Ir(e)?"corner-bevel":eo(e)?la(e)?"border-large":"border":null}function kt(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Dr(t):!0}function Gt(e,n,t,o,s){let r=new Set(o?.disable??[]);return sa(e,n,r,{solidTriangleSupported:eo(t),projectiveQuadSupported:kt(t),cornerShapeSupported:Wt(t),borderShapeSupported:Rt(t)},ia,aa,s)}function to(e,n,t=new Set,o){let s=o??(typeof document<"u"?document:null);if(!s)return{};let r=t.size>0?{disable:Array.from(t)}:void 0;return Gt(e,n,s,r)}function xn(e){let n=e??(typeof document<"u"?document:null);if(!n){if(!!!(typeof CSS<"u"?CSS:void 0)?.supports?.("border-shape","polygon(0 0, 100% 0, 0 100%) circle(0)"))return!1;let s=typeof matchMedia<"u"?matchMedia:void 0;return s?s("(pointer: fine)").matches&&s("(hover: hover)").matches:!0}return Rt(n)}function Pn(e){let n=e??(typeof document<"u"?document:null);if(!n){let t=typeof CSS<"u"?CSS:void 0;if(t?.supports?.("corner-top-left-shape","bevel")&&t.supports("corner-top-right-shape","bevel"))return!0;let o=(typeof navigator<"u"?navigator:globalThis.navigator)?.userAgent??"";if(!o)return!0;let s=/\b(?:Chrome|HeadlessChrome|Chromium|Edg|OPR)\//.test(o);return!/\bVersion\/[\d.]+.*\bSafari\//.test(o)||s}return eo(n)}function no(e,n,t,o){let s=o??(typeof document<"u"?document:null);return ra(e,n,t,{solidTriangleSupported:Pn(o),projectiveQuadSupported:s?kt(s):!0,borderShapeSupported:xn(o)})}import{ASYNC_RENDER_BUDGET_MS as Da,DEFAULT_SEAM_BLEED as Kr,DEFAULT_TILE as Ia,PROJECTIVE_QUAD_DENOM_EPS as Ha,PROJECTIVE_QUAD_MAX_WEIGHT_RATIO as Fa,PROJECTIVE_QUAD_BLEED as Qr,resolveBleedRatio as Eo}from"@layoutit/polycss-core";import{buildBasisHints as Ao,buildSeamBleedPolygonEdges as za,computeTextureAtlasPlan as en,resolvePolyTextureLeafGeometry as Jr}from"@layoutit/polycss-core";import{cornerShapeGeometryForPlan as Jt}from"@layoutit/polycss-core";import{formatCssLength as Me,formatMatrix3dValues as ua,formatSolidQuadMatrix as da,resolvePolyTextureImageRendering as pa}from"@layoutit/polycss-core";import{shadePolygon as ma}from"@layoutit/polycss-core";import{parseHex as Hr,rgbKey as Fr}from"@layoutit/polycss-core";function Pe(e,n,t){let o=e.getAttribute("style")??"",s=`${n}:${t}`,r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(^|;)\\s*${r}\\s*:[^;]*`,"i"),c=i.test(o)?o.replace(i,(l,u)=>`${u}${s}`):`${o}${o.trim()&&!o.trim().endsWith(";")?";":""}${s}`;c!==o&&e.setAttribute("style",c)}function ot(e,n){let t=e.getAttribute("style")??"";if(!t||!t.toLowerCase().includes(n.toLowerCase()))return;let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`^\\s*${o}\\s*:`,"i"),r=t.split(";").map(i=>i.trim()).filter(i=>i&&!s.test(i)).join(";");r?e.setAttribute("style",r):e.removeAttribute("style")}function Yt(e,n,t,o=!1){if(n==="dynamic"){let s=Hr(e.polygon.color??"#cccccc"),r=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return Fr(s)!==t?.dynamicColorKey&&(r+=`;--psr:${(s.r/255).toFixed(4)};--psg:${(s.g/255).toFixed(4)};--psb:${(s.b/255).toFixed(4)}`),r}return e.shadedColor?`;color:${e.shadedColor}`:""}function ca(e,n){Pe(e,"--pnx",n.normal[0].toFixed(4)),Pe(e,"--pny",n.normal[1].toFixed(4)),Pe(e,"--pnz",n.normal[2].toFixed(4))}function _t(e,n,t,o){if(t==="dynamic"){ot(e,"color"),ot(e,"background"),ca(e,n);let s=Hr(n.polygon.color??"#cccccc");Fr(s)===o?.dynamicColorKey?(ot(e,"--psr"),ot(e,"--psg"),ot(e,"--psb")):(Pe(e,"--psr",(s.r/255).toFixed(4)),Pe(e,"--psg",(s.g/255).toFixed(4)),Pe(e,"--psb",(s.b/255).toFixed(4)))}else n.shadedColor!==o?.paintColor?(ot(e,"background"),Pe(e,"color",n.shadedColor)):(ot(e,"background"),ot(e,"color"))}import{formatBorderShapeElementStyle as zr,formatCornerShapeElementStyle as Br}from"@layoutit/polycss-core";import{atlasCanonicalSizeForEntry as Sn}from"@layoutit/polycss-core";import{computeProjectiveQuadMatrix as fa,stableBasisFromPlan as ga}from"@layoutit/polycss-core";import{DEFAULT_LIGHT_DIR as ha,DEFAULT_LIGHT_COLOR as ya,DEFAULT_LIGHT_INTENSITY as ba,DEFAULT_AMBIENT_COLOR as xa,DEFAULT_AMBIENT_INTENSITY as Pa}from"@layoutit/polycss-core";var Vr="polycss-corner-shape-solid";function Xt(e){return e.atlasLeafWidth??Sn(e)}function qt(e){return e.atlasLeafHeight??Sn(e)}function Nr(e,n){return pa(e.polygon,n)}function vn(e){return e==="pixelated"?";image-rendering:pixelated":""}function so(e,n,t,o,s,r,i,c,l){e.setAttribute("data-polycss-leaf","polygon"),e.setAttribute("data-polycss-texture-backend",n),e.setAttribute("data-polycss-texture-ready",t?"true":"false"),e.setAttribute("data-polycss-texture-image-rendering",o),s?e.setAttribute("data-polycss-texture-leaf-sizing",s):e.removeAttribute("data-polycss-texture-leaf-sizing"),r?e.setAttribute("data-polycss-texture-projection",r):e.removeAttribute("data-polycss-texture-projection"),i?e.setAttribute("data-polycss-texture-lighting",i):e.removeAttribute("data-polycss-texture-lighting"),typeof c=="number"?e.setAttribute("data-polycss-texture-leaf-width",String(c)):e.removeAttribute("data-polycss-texture-leaf-width"),typeof l=="number"?e.setAttribute("data-polycss-texture-leaf-height",String(l)):e.removeAttribute("data-polycss-texture-leaf-height")}var oo=new WeakMap,ro=new WeakMap;function ye(e,n,t){let o=oo.get(e),s=ro.get(e),r=typeof t=="number";if(!n.data&&!r&&(!o||o.length===0)){e.__polycssHasDataAttrs=!1;return}let i=new Map;if(n.data)for(let[l,u]of Object.entries(n.data))i.set(l,String(u));if(n.doubleSided===!0&&i.set("polycss-double-sided","true"),r&&i.set("poly-index",String(t)),o)for(let l of o)i.has(l)||e.removeAttribute(`data-${l}`);for(let[l,u]of i)s?.get(l)!==u&&e.setAttribute(`data-${l}`,u);let c=Array.from(i.keys());c.length>0?oo.set(e,c):oo.delete(e),i.size>0?ro.set(e,i):ro.delete(e),e.__polycssHasDataAttrs=c.length>0}function Ot(e){return e.__polycssHasDataAttrs===!0}function io(e,n,t,o,s=t==="dynamic",r){if(!n.url)return;let i=Nr(o,r),c=`url(${n.url})`,l=o.canvasW||1,u=o.canvasH||1,d=Sn(o),P=Xt(o),f=qt(o),b=`${Me(-o.x/l*P)} ${Me(-o.y/u*f)}`,x=`${Me(n.width/l*P)} ${Me(n.height/u*f)}`,v=`transform:matrix3d(${o.atlasMatrix});--polycss-atlas-size:${d}px;--polycss-atlas-width:${Me(P)};--polycss-atlas-height:${Me(f)};--polycss-atlas-leaf-sizing:${o.atlasLeafSizing??"canonical"}`,y=`${v};--polycss-atlas-position:${b};--polycss-atlas-image-size:${x}`;if(t==="dynamic"){let C=s?`;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`:"";e.setAttribute("style",y+`;--polycss-atlas-url:${c}`+C+vn(i))}else e.setAttribute("style",v+`;background-image:${c};background-position:${b};background-size:${x};background-repeat:no-repeat;--pnx:${o.normal[0].toFixed(4)};--pny:${o.normal[1].toFixed(4)};--pnz:${o.normal[2].toFixed(4)}`+vn(i));so(e,"atlas",!0,i,o.atlasLeafSizing??"canonical","affine",t,P,f)}function jr(e,n,t,o){if(n.texture){if(!t.texture||n.texture!==t.texture)return!1}else if(t.texture)return!1;let s=$r(n,t);return s?(e.style.visibility="",Pe(e,"transform",`matrix3d(${s.matrix})`),o==="dynamic"&&(Pe(e,"--pnx",s.normal[0].toFixed(4)),Pe(e,"--pny",s.normal[1].toFixed(4)),Pe(e,"--pnz",s.normal[2].toFixed(4))),ye(e,t,n.index),!0):(e.style.visibility="hidden",ye(e,t,n.index),!0)}function ao(e,n,t,o,s){if(o!=="baked")return{...e,polygon:n,normal:t};let r=s.directionalLight,i=s.ambientLight,c=r?.direction??ha,l=r?.color??ya,u=Math.max(0,r?.intensity??ba),d=i?.color??xa,P=Math.max(0,i?.intensity??Pa),f=Math.hypot(c[0],c[1],c[2])||1,b=c[0]/f,x=c[1]/f,v=c[2]/f,C=s.lightOccludedPolyIndices?.has(e.index)??!1?0:u*Math.max(0,t[0]*b+t[1]*x+t[2]*v);return{...e,polygon:n,normal:t,shadedColor:ma(n.color??"#cccccc",C,l,d,P)}}function $r(e,n){let t=Ur(e,n);if(!t)return null;let{normal:o,xAxis:s,yAxis:r,tx:i,ty:c,tz:l}=t;return{normal:o,matrix:ua([s[0]*e.canvasW/Xt(e),s[1]*e.canvasW/Xt(e),s[2]*e.canvasW/Xt(e),0,r[0]*e.canvasH/qt(e),r[1]*e.canvasH/qt(e),r[2]*e.canvasH/qt(e),0,o[0],o[1],o[2],0,i,c,l,1])}}var Ur=ga;function va(e,n,t){if(e.screenPts.length!==8||n.vertices.length!==4)return null;let o=Ur(e,n);if(!o)return null;let s=fa(e.screenPts,o.xAxis,o.yAxis,o.normal,o.tx,o.ty,o.tz,t);return s?{matrix:s,normal:o.normal}:null}function lo(e,n,t,o,s=!1){let r=t.createElement("b");return r.setAttribute("style",`transform:matrix3d(${da(e)})`+Yt(e,n,o,s)),ye(r,e.polygon,e.index),r}function co(e,n,t,o,s=!1){let r=t.createElement("i");return r.setAttribute("style",zr(e)+Yt(e,n,o,s)),ye(r,e.polygon,e.index),r}function uo(e,n,t,o,s,r=!1){let i=o.createElement("u");return i.className=Vr,i.setAttribute("style",Br(e,n)+Yt(e,t,s,r)),ye(i,e.polygon,e.index),i}function po(e,n,t,o,s=!1){let r=t.createElement("b");return r.setAttribute("style",`transform:matrix3d(${e.projectiveMatrix})`+Yt(e,n,o,s)),ye(r,e.polygon,e.index),r}function Wr(e,n,t,o,s,r,i){let c=n.projectiveMatrix?va(n,t,r):$r(n,t);if(!c)return!1;let l=ao(n,t,c.normal,o,s);return e.style.visibility="",e.style.transform=`matrix3d(${c.matrix})`,_t(e,l,o,i),ye(e,l.polygon,l.index),!0}function Gr(e,n,t,o){e.style.visibility="",e.setAttribute("style",zr(n)),_t(e,n,t,o),ye(e,n.polygon,n.index)}function Yr(e,n,t,o,s){e.style.visibility="",e.className=Vr,e.setAttribute("style",Br(n,t)),_t(e,n,o,s),Pe(e,"background","currentColor"),ye(e,n.polygon,n.index)}function mo(e,n,t,o=!1,s){let r=t.createElement("s"),i=Nr(e,s),c=Sn(e),l=Xt(e),u=qt(e),d=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:${c}px;--polycss-atlas-width:${Me(l)};--polycss-atlas-height:${Me(u)};--polycss-atlas-leaf-sizing:${e.atlasLeafSizing??"canonical"};opacity:0`+d+vn(i)),so(r,"atlas",!1,i,e.atlasLeafSizing??"canonical","affine",n,l,u),ye(r,e.polygon,e.index),r}function fo(e,n,t,o=!1){let s=t.createElement("s"),r=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return s.setAttribute("style",`transform:matrix3d(${n.matrix});--polycss-atlas-width:${Me(n.leafWidth)};--polycss-atlas-height:${Me(n.leafHeight)};--polycss-atlas-leaf-sizing:image;background-image:url(${n.url});background-position:${Me(n.backgroundPosition[0])} ${Me(n.backgroundPosition[1])};background-size:${Me(n.backgroundSize[0])} ${Me(n.backgroundSize[1])};background-repeat:no-repeat;background-blend-mode:normal;mask-image:none;-webkit-mask-image:none`+r+vn(n.imageRendering)),so(s,"image",!0,n.imageRendering,"image",n.projection,n.lighting,n.leafWidth,n.leafHeight),s.setAttribute("data-polycss-texture-source-x",String(n.sourceRect.x)),s.setAttribute("data-polycss-texture-source-y",String(n.sourceRect.y)),s.setAttribute("data-polycss-texture-source-width",String(n.sourceRect.width)),s.setAttribute("data-polycss-texture-source-height",String(n.sourceRect.height)),ye(s,e.polygon,e.index),s}import{computeSolidTriangleColorPlan as Ba}from"@layoutit/polycss-core";import{computeSolidTrianglePlanFromCssPoints as Sa,computeSolidTrianglePlan as Ca}from"@layoutit/polycss-core";function rt(e,n,t,o={}){let s=o.primitive!=null?void 0:(()=>{let r=t.doc??(typeof document<"u"?document:null);return r?Ne(r,t.strategies)??"border":"border"})();return Ca(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??s})}function go(e,n,t,o,s,r,i,c,l,u,d,P,f){let b=o.primitive!=null?void 0:(()=>{let x=t.doc??(typeof document<"u"?document:null);return x?Ne(x,t.strategies)??"border":"border"})();return Sa(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??b},s,r,i,c,l,u,d,P,f)}import{buildSeamBleedPolygonEdges as Ta,DEFAULT_SEAM_BLEED as Ea,DEFAULT_TILE as Rp,resolveBleedRatio as Aa}from"@layoutit/polycss-core";import{rgbEqual as wa,stepRgbToward as Ma,rgbToCss as La,colorErrorScore as Ra}from"@layoutit/polycss-core";import{computeSolidTriangleColorPlan as Xr}from"@layoutit/polycss-core";import{stableTriangleMatrixDecimals as ho}from"@layoutit/polycss-core";var ka="0 48px 96px 48px";function yo(e,n){return Ta(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function bo(e,n,t){let o=Aa(t.seamBleed),s=Ea*o,r={...t,bleedRatio:o};return n&&s>0?{...r,seamBleed:n.has(e)?s:void 0,seamEdges:n.get(e)}:r}function Cn(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 qr(e,n){return!n.updatesDisabled&&(n.freezeFrames<=1||(n.colorFrame+e)%n.freezeFrames===0)}function st(e,n,t,o,s,r){return t?r.updatesDisabled||o==="plan-only"||o==="transform-only"?!1:s==="adaptive"||e.__polycssSolidTriangleColor===void 0?!0:qr(n,r):!0}function xo(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"?ka:""),t.__polycssSolidTrianglePrimitive=n)}function Po(e){let n=e;n.__polycssSolidTriangleHidden&&(e.style.visibility="",n.__polycssSolidTriangleHidden=!1)}function Dt(e){let n=e;n.__polycssSolidTriangleHidden||(e.style.visibility="hidden",n.__polycssSolidTriangleHidden=!0)}function Zt(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||Ot(e))&&ye(e,n.polygon)}function Zr(e,n,t,o){if(!n.colorComputed){(n.polygon.data||Ot(e))&&ye(e,n.polygon);return}let s=e,r=n.bakedColor??"",i=n.bakedRgb,c=n.bakedAlpha??1,l=s.__polycssSolidTriangleColor,u=s.__polycssSolidTriangleColorRgb,d=s.__polycssSolidTriangleColorAlpha??1,P=o??qr(n.index,t);if(!t.updatesDisabled&&l!==r&&(l===void 0||P)){let f=r,b=i;if(t.maxStep>0&&u&&i&&d===c){let x=Ma(u,i,t.maxStep);b=x,f=La(x,c)}(f!==l||!wa(b,u))&&(e.style.color=f),s.__polycssSolidTriangleColor=f,s.__polycssSolidTriangleColorRgb=b,s.__polycssSolidTriangleColorAlpha=c,s.__polycssSolidTriangleColorFrame=t.colorFrame}(n.polygon.data||Ot(e))&&ye(e,n.polygon)}function Qt(e,n,t,o){let s=e;xo(e,n.primitive),s.__polycssSolidTriangleBasis!==n.basis&&(s.__polycssSolidTriangleBasis=n.basis),Po(e),e.style.transform=n.transformText,(n.colorComputed||n.polygon.data||Ot(e))&&Zr(e,n,t,o)}function Tn(e,n,t,o){Po(e),Zr(e,n,t,o)}function Kt(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||Ot(e))&&ye(e,n.polygon)}function _a(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 vo(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)),s=Math.max(1,Math.floor(t.stableTriangleColorFreezeFrames??1));if(s<=1&&!Number.isFinite(t.stableTriangleColorBudget))return null;let r=_a(e.length,t),i=Math.max(1,Math.floor(t.stableTriangleColorMaxAge??Math.max(2,s*2))),c=[];for(let l=0;l<e.length;l++){let u=e[l],d=n[l];if(u.kind!=="triangle"||!d)continue;let P=u.element,f=P.__polycssSolidTriangleColor,b=d.bakedColor??"";if(f===b)continue;let x=P.__polycssSolidTriangleColorFrame??0,v=Math.max(0,o-x),y=Ra(f,b);c.push({index:l,score:(v>=i?1e6:0)+y*1e4+v})}return c.length===0?new Set:(c.sort((l,u)=>u.score-l.score),new Set(c.slice(0,r).map(l=>l.index)))}function En(e,n){let t=n.createElement("u");return Zt(t,e),ye(t,e.polygon,e.index),t}function Oa(e,n,t){let o=t.createElement("u");return Dt(o),ye(o,e,n),o}function So(e,n,t,o,s,r){let i=t,c=i.stableTriangleDebug,l=o&&s==="color-only";if(i.stableTriangleColorPolicy==="adaptive"||e.length!==n.length)return!1;let u=ho(i.stableTriangleMatrixDecimals),d=t.doc??(typeof document<"u"?document:null),P=d?Ne(d,t.strategies)??"border":"border";for(let b=0;b<e.length;b++){let x=e[b];if(x.kind!=="triangle"||x.polygonIndex!==b||!n[b])return!1}let f=yo(n,t);for(let b=0;b<e.length;b++){let x=e[b].element,v=n[b];if(l){if(st(x,b,o,c,i.stableTriangleColorPolicy,r)){let C=Xr(v,b,t);if(!C)continue;Tn(x,C,r)}continue}let y=rt(v,b,bo(b,f,t),{basis:x.__polycssSolidTriangleBasis,matrixDecimals:u,primitive:P,includeColor:s!=="plan-only"&&s!=="transform-only"&&st(x,b,o,c,i.stableTriangleColorPolicy,r)});if(!y){Dt(x);continue}o&&s==="plan-only"||(o&&s==="transform-only"?Kt(x,y):o?Qt(x,y,r):Zt(x,y))}return!0}function It(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=Ne(t,n.strategies);if(!o||e.some(c=>c.texture||c.vertices.length!==3))return null;let s=ho(n.stableTriangleMatrixDecimals),r=[],i=yo(e,n);for(let c=0;c<e.length;c+=1){let l=e[c],u=rt(l,c,bo(c,i,n),{matrixDecimals:s,primitive:o}),d=u?En(u,t):Oa(l,c,t);r.push({polygonIndex:c,element:d,kind:"triangle",dispose:()=>{}})}return{rendered:r,dispose(){}}}function Co(e,n,t={}){let o=t.doc??(typeof document<"u"?document:null);if(!o)return{rendered:e,dispose:()=>{}};let s=Ne(o,t.strategies);if(!s||e.some(y=>y.kind!=="triangle")||n.length!==e.length)return null;for(let y=0;y<e.length;y++)if(e[y].polygonIndex!==y)return null;let r=t.optimizeStableTriangleStyle===!0&&(t.textureLighting??"baked")==="baked",i=t,c=i.stableTriangleDebug,l=i.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full"),u=r&&l==="color-only",d=Cn(i),P=ho(i.stableTriangleMatrixDecimals);if(So(e,n,t,r,l,d))return{rendered:e,dispose(){}};let f=new Array(e.length),b=new Array(e.length),x=yo(n,t);for(let y=0;y<e.length;y++){let C=e[y].element;if(u){let O=i.stableTriangleColorPolicy==="adaptive"||st(C,y,r,c,i.stableTriangleColorPolicy,d);b[y]=O?Xr(n[y],y,t):null;continue}f[y]=rt(n[y],y,bo(y,x,t),{basis:C.__polycssSolidTriangleBasis,matrixDecimals:P,primitive:s,includeColor:l!=="plan-only"&&l!=="transform-only"&&st(C,y,r,c,i.stableTriangleColorPolicy,d)})}let v=r&&l!=="plan-only"&&l!=="transform-only"?vo(e,u?b:f,i):null;for(let y=0;y<e.length;y++){if(u){let O=b[y];O&&Tn(e[y].element,O,d,v?.has(y));continue}let C=f[y];if(!C){Dt(e[y].element);continue}r&&l==="plan-only"||(r&&l==="transform-only"?Kt(e[y].element,C):r?Qt(e[y].element,C,d,v?.has(y)):Zt(e[y].element,C))}return{rendered:e,dispose(){}}}import{stableTriangleMatrixDecimals as es}from"@layoutit/polycss-core";function ts(){return new Promise(e=>setTimeout(e,0))}async function To(e){return performance.now()-e<Da?e:(await ts(),performance.now())}function ns(e,n){let t=Eo(n.seamBleed),o=Kr*t,s={...n,bleedRatio:t};return e.seamBleedEdges?.size&&o>0?{...s,seamBleed:o,seamEdges:e.seamBleedEdges}:{...s,seamBleed:void 0,seamEdges:void 0}}function os(e,n){return za(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function rs(e,n,t){let o=Eo(t.seamBleed),s=Kr*o,r={...t,bleedRatio:o};return n&&s>0?{...r,seamBleed:n.has(e)?s:void 0,seamEdges:n.get(e)}:r}function mt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{};let o=Ao(e,n),s=Lt(t),r=e.map((i,c)=>en(i,c,n,s,o[c]));return Gt(r,n.textureLighting??"baked",t,n.strategies)}function ft(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=n.textureLighting??"baked",s=n,r=o==="dynamic"&&s.skipDynamicNormalVars===!0,i=new Set(n.strategies?.disable??[]),c=!i.has("b"),l=c&&kt(t),u=Ne(t,n.strategies),d=u!==null,P=!i.has("i")&&Wt(t),f=!i.has("i")&&Rt(t),b=Ao(e,n),x=Lt(t),v=os(e,n),y=e.map((p,g)=>en(p,g,rs(g,v,n),x,b[g])),C=n.solidPaintDefaults??(s.computeSolidPaintDefaults?Gt(y,o,t,n.strategies):void 0),O=C?{...n,solidPaintDefaults:C}:n,k=y.map(p=>p&&d&&Ke(p)?rt(p.polygon,p.index,ns(p,O),{primitive:u??void 0}):null),j=y.map(p=>p&&P&&!Ke(p)&&!(c&&Be(p))&&!(l&&Ve(p))?Jt(p):null),D=y.map(p=>p?Jr(p,{imageRendering:n.textureImageRendering,backend:n.textureBackend,projection:n.textureProjection,allowProjective:l,projectiveQuadGuards:x}):null),Z=y.map((p,g)=>D[g]?null:p&&(p.texture||!(c&&Be(p))&&!k[g]&&!(l&&Ve(p))&&!j[g]&&!f?p:null)),{packed:J,atlasScale:_}=Et(Z,n.textureQuality,t,n.textureLeafSizing),V=new Map,B=[],z=!1,A=[];for(let p=0;p<e.length;p++){let g=y[p],L=k[p],R=j[p],H=D[p];if(!g)continue;let Q=J.entries[p];if(Q){let T=mo(Q,o,t,r,n.textureImageRendering);V.set(p,T),B.push({polygonIndex:p,element:T,kind:"atlas",plan:Q,dispose:()=>{}})}else if(H){let T=fo(g,H,t,r);B.push({polygonIndex:p,element:T,kind:"image",plan:g,dispose:()=>{}})}else if(!g.texture&&c&&Be(g)){let T=lo(g,o,t,C,r);B.push({polygonIndex:p,element:T,kind:"solid",plan:g,dispose:()=>{}})}else if(!g.texture&&L){let T=En(L,t);B.push({polygonIndex:p,element:T,kind:"triangle",plan:g,dispose:()=>{}})}else if(!g.texture&&l&&Ve(g)){let T=po(g,o,t,C,r);B.push({polygonIndex:p,element:T,kind:"solid",plan:g,dispose:()=>{}})}else if(!g.texture&&R){let T=uo(g,R,o,t,C,r);B.push({polygonIndex:p,element:T,kind:"corner",plan:g,dispose:()=>{}})}else if(!g.texture&&f){let T=co(g,o,t,C,r);B.push({polygonIndex:p,element:T,kind:"border",plan:g,dispose:()=>{}})}}B.sort((p,g)=>p.polygonIndex-g.polygonIndex);let h=Mt(J.pages,o,t,_,()=>z).then(p=>{if(z){for(let g of p)g.url?.startsWith("blob:")&&URL.revokeObjectURL(g.url);return}A=p.flatMap(g=>g.url?.startsWith("blob:")?[g.url]:[]);for(let g=0;g<J.pages.length;g++){let L=J.pages[g],R=p[g];if(R)for(let H of L.entries){let Q=V.get(H.index);!Q||!R.url||io(Q,R,o,H,!0,n.textureImageRendering)}}}).catch(()=>{if(!z)for(let p of V.values())Pe(p,"opacity","0.5"),Pe(p,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:B,solidPaintDefaults:C??{},pagesReady:h,dispose(){z=!0;for(let p of A)URL.revokeObjectURL(p);A=[]}}}async function tn(e,n={},t=()=>!1){let o=n.doc??(typeof document<"u"?document:null);if(!o||t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let s=n.textureLighting??"baked",i=s==="dynamic"&&n.skipDynamicNormalVars===!0,c=new Set(n.strategies?.disable??[]),l=!c.has("b"),u=l&&kt(o),d=Ne(o,n.strategies),P=d!==null,f=!c.has("i")&&Wt(o),b=!c.has("i")&&Rt(o);if(await ts(),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let x=Ao(e,n),v=Lt(o),y=os(e,n),C=performance.now(),O=new Array(e.length);for(let p=0;p<e.length;p++)if(O[p]=en(e[p],p,rs(p,y,n),v,x[p]),C=await To(C),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let k=n.solidPaintDefaults??Gt(O,s,o,n.strategies),j=new Array(O.length),D=new Array(O.length),Z=new Array(O.length),J=new Array(O.length);for(let p=0;p<O.length;p++){let g=O[p],L=g&&P&&Ke(g)?rt(g.polygon,g.index,ns(g,{...n,solidPaintDefaults:k}),{primitive:d??void 0}):null;j[p]=L;let R=g&&f&&!Ke(g)&&!(l&&Be(g))&&!(u&&Ve(g))?Jt(g):null;D[p]=R;let H=g?Jr(g,{imageRendering:n.textureImageRendering,backend:n.textureBackend,projection:n.textureProjection,allowProjective:u,projectiveQuadGuards:v}):null;if(Z[p]=H,J[p]=H?null:g&&(g.texture||!(l&&Be(g))&&!L&&!(u&&Ve(g))&&!R&&!b?g:null),C=await To(C),t())return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}let{packed:_,atlasScale:V}=Et(J,n.textureQuality,o,n.textureLeafSizing),B=new Map,z=[],A=!1,h=[];for(let p=0;p<e.length;p++){let g=O[p],L=j[p],R=D[p],H=Z[p];if(!g)continue;let Q=_.entries[p];if(Q){let T=mo(Q,s,o,i,n.textureImageRendering);B.set(p,T),z.push({polygonIndex:p,element:T,kind:"atlas",plan:Q,dispose:()=>{}})}else if(H){let T=fo(g,H,o,i);z.push({polygonIndex:p,element:T,kind:"image",plan:g,dispose:()=>{}})}else if(!g.texture&&l&&Be(g)){let T=lo(g,s,o,k,i);z.push({polygonIndex:p,element:T,kind:"solid",plan:g,dispose:()=>{}})}else if(!g.texture&&L){let T=En(L,o);z.push({polygonIndex:p,element:T,kind:"triangle",plan:g,dispose:()=>{}})}else if(!g.texture&&u&&Ve(g)){let T=po(g,s,o,k,i);z.push({polygonIndex:p,element:T,kind:"solid",plan:g,dispose:()=>{}})}else if(!g.texture&&R){let T=uo(g,R,s,o,k,i);z.push({polygonIndex:p,element:T,kind:"corner",plan:g,dispose:()=>{}})}else if(!g.texture&&b){let T=co(g,s,o,k,i);z.push({polygonIndex:p,element:T,kind:"border",plan:g,dispose:()=>{}})}if(C=await To(C),t()){for(let T of z)T.dispose();return{rendered:[],solidPaintDefaults:k,dispose:()=>{}}}}z.sort((p,g)=>p.polygonIndex-g.polygonIndex);let E=Mt(_.pages,s,o,V,()=>A||t()).then(p=>{if(A||t()){for(let g of p)g.url?.startsWith("blob:")&&URL.revokeObjectURL(g.url);return}h=p.flatMap(g=>g.url?.startsWith("blob:")?[g.url]:[]);for(let g=0;g<_.pages.length;g++){let L=_.pages[g],R=p[g];if(R)for(let H of L.entries){let Q=B.get(H.index);!Q||!R.url||io(Q,R,s,H,!0,n.textureImageRendering)}}}).catch(()=>{if(!(A||t()))for(let p of B.values())Pe(p,"opacity","0.5"),Pe(p,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:z,solidPaintDefaults:k,pagesReady:E,dispose(){A=!0;for(let p of h)URL.revokeObjectURL(p);h=[]}}}function nn(e,n,t,o={}){let s=o.textureLighting??"baked",r=o,i=r.optimizeStableTriangleStyle===!0&&s==="baked";if(!i||r.stableTriangleColorPolicy==="adaptive"||e.length!==t.polygonCount||n.length!==t.polygonCount||t.vertices.length<t.polygonCount*9)return!1;let c=r.stableTriangleDebug,l=r.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full");if(l==="color-only")return!1;let u=es(r.stableTriangleMatrixDecimals),d=Cn(r),P=o.tileSize??Ia,f=o.layerElevation??P,b=o.doc??(typeof document<"u"?document:null),x=b?Ne(b,o.strategies)??"border":"border";for(let y=0;y<e.length;y++){let C=e[y],O=n[y];if(C.kind!=="triangle"||C.polygonIndex!==y||!O||O.vertices.length!==3||O.texture||O.material?.texture)return!1}let v=t.vertices;for(let y=0;y<e.length;y++){let C=e[y].element,O=n[y],k=y*9,j=v[k+1]*P,D=v[k]*P,Z=v[k+2]*f,J=v[k+4]*P,_=v[k+3]*P,V=v[k+5]*f,B=v[k+7]*P,z=v[k+6]*P,A=v[k+8]*f,h=go(O,y,o,{basis:C.__polycssSolidTriangleBasis,matrixDecimals:u,primitive:x,color:t.colors?.[y],includeColor:l!=="plan-only"&&l!=="transform-only"&&st(C,y,i,c,r.stableTriangleColorPolicy,d)},j,D,Z,J,_,V,B,z,A);if(!h){Dt(C);continue}l!=="plan-only"&&(l==="transform-only"?Kt(C,h):Qt(C,h,d))}return!0}function on(e,n,t={}){if(e.length!==n.length)return!1;let o=t,s=t.doc??(typeof document<"u"?document:null),r=t.textureLighting??"baked",i=new Set(t.strategies?.disable??[]),c=!i.has("b"),l=!!s&&c&&kt(s),u=!!s&&!i.has("i")&&Wt(s),d=!!s&&!i.has("i")&&Rt(s),P=Eo(o.seamBleed),f=s?Lt(s,{bleed:Qr*P}):{denomEps:Ha,maxWeightRatio:Fa,bleed:Qr*P,disableGuards:!1},b=o.optimizeStableTriangleStyle===!0&&r==="baked",x=o.stableTriangleDebug,v=o.stableTriangleUpdateMode??(x==="plan-only"||x==="transform-only"?x:"full"),y=b&&v==="color-only",C=Cn(o),O=es(o.stableTriangleMatrixDecimals),k=s?Ne(s,t.strategies)??"border":"border";if(So(e,n,t,b,v,C))return!0;let j=[],D=[],Z=[];for(let _=0;_<e.length;_++){let V=e[_];if(V.polygonIndex!==_)return!1;let B=n[_];if(!B||y&&V.kind!=="triangle")return!1;if(V.kind==="atlas"){if(!V.plan||!jr(V.element,V.plan,B,r))return!1;continue}if(V.kind==="triangle"){let z=V.element;if(y){let h=o.stableTriangleColorPolicy==="adaptive"||st(z,_,b,x,o.stableTriangleColorPolicy,C);D[_]=h?Ba(B,_,t):null;continue}let A=rt(B,_,t,{basis:z.__polycssSolidTriangleBasis,matrixDecimals:O,primitive:k,includeColor:v!=="plan-only"&&v!=="transform-only"&&st(z,_,b,x,o.stableTriangleColorPolicy,C)});if(!A){j[_]=null;continue}j[_]=A;continue}if(V.kind==="solid"){if(!V.plan||B.texture||B.vertices.length!==V.plan.polygon.vertices.length)return!1;Z[_]=V.plan;continue}if(V.kind==="border"){let z=en(B,_,t,f);if(!z||z.texture||!d||c&&Be(z)||l&&Ve(z)||u&&Jt(z))return!1;Z[_]=z;continue}if(V.kind==="corner"){let z=en(B,_,t,f);if(!z||z.texture||!u||Ke(z)||c&&Be(z)||l&&Ve(z)||!Jt(z))return!1;Z[_]=z;continue}return!1}let J=b&&v!=="plan-only"&&v!=="transform-only"?vo(e,y?D:j,o):null;for(let _=0;_<e.length;_++){let V=e[_];if(V.kind==="triangle"){if(y){let z=D[_];z&&Tn(V.element,z,C,J?.has(_));continue}let B=j[_];if(!B){Dt(V.element);continue}if(b&&v==="plan-only")continue;b&&v==="transform-only"?Kt(V.element,B):b?Qt(V.element,B,C,J?.has(_)):Zt(V.element,B)}else if(V.kind==="solid"){let B=Z[_];if(!B||!Wr(V.element,B,n[_],r,t,f,o.solidPaintDefaults))return!1}else if(V.kind==="border"){let B=Z[_];if(!B)return!1;Gr(V.element,B,r,o.solidPaintDefaults)}else if(V.kind==="corner"){let B=Z[_],z=B?Jt(B):null;if(!B||!z)return!1;Yr(V.element,B,z,r,o.solidPaintDefaults)}}return!0}import{computeTextureAtlasPlanPublic as is}from"@layoutit/polycss-core";import{formatMatrix3d as as,formatCssLengthPx as ls,formatSolidQuadEntryMatrix as cs}from"@layoutit/polycss-core";import{formatBorderShapeEntryMatrix as us,cssBorderShapeForPlan as ds}from"@layoutit/polycss-core";import{BASE_TILE as ve,computeProjectiveQuadMatrix as ja,normalFacesCamera as $a,parsePureColor as ys,PROJECTIVE_QUAD_BLEED as Ua,resolveProjectiveQuadGuards as Wa,rotateVec3 as Ga,rotateVec3InWrapperCssFrame as Ya,shadePolygon as Xa,SOLID_QUAD_CANONICAL_SIZE as qa}from"@layoutit/polycss-core";var Za=[.4,-.7,.59],Qa="#ffffff",Ka=1,Ja="#ffffff",el=.4,bs=1,tl=8,nl=Ua,Je=1e-6,ol=Wa({bleed:0}),xs={t:[0,0,1],b:[0,0,-1],fl:[0,1,0],br:[0,-1,0],fr:[1,0,0],bl:[-1,0,0]},Lo=["t","b","bl","br","fr","fl"],rl=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 ps(e){let n=[];for(let t of Lo)$a(xs[t],e)&&n.push(t);return n.join("|")}function sl(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 il(e){let n=e.vertices;if(n.length<3)return null;let t=n[0],o=0,s=0,r=0;for(let c=1;c+1<n.length;c+=1){let l=n[c],u=n[c+1],d=l[1]-t[1],P=l[0]-t[0],f=l[2]-t[2],b=u[1]-t[1],x=u[0]-t[0],v=u[2]-t[2];o-=P*v-f*x,s-=f*b-d*v,r-=d*x-P*b}let i=Math.hypot(o,s,r);return i<=1e-9?null:[Math.round(o/i),Math.round(s/i),Math.round(r/i)]}function al(e){if(e.texture||e.material||e.uvs||e.textureTriangles||e.vertices.length!==4)return null;let n=il(e),t=n?rl.get(n.join(",")):void 0;if(!t)return null;let o=1/0,s=1/0,r=1/0,i=-1/0,c=-1/0,l=-1/0;for(let P of e.vertices)o=Math.min(o,P[0]),s=Math.min(s,P[1]),r=Math.min(r,P[2]),i=Math.max(i,P[0]),c=Math.max(c,P[1]),l=Math.max(l,P[2]);let u=1e-6,d=fl(e.color);return Math.abs(l-r)<=u?{axis:"z",face:t,left:s*ve,top:o*ve,width:Math.max(0,(c-s)*ve),height:Math.max(0,(i-o)*ve),z:r*ve,baseColor:d,bleed:wo()}:Math.abs(i-o)<=u?{axis:"x",face:t,left:s*ve,top:r*ve,width:Math.max(0,(c-s)*ve),height:Math.max(0,(l-r)*ve),z:-o*ve,baseColor:d,bleed:wo()}:Math.abs(c-s)<=u?{axis:"y",face:t,left:r*ve,top:o*ve,width:Math.max(0,(l-r)*ve),height:Math.max(0,(i-o)*ve),z:-s*ve,baseColor:d,bleed:wo()}:null}function wo(){return{left:0,right:0,top:0,bottom:0}}function ll(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 ms(e){return[e[1]*ve,e[0]*ve,e[2]*ve]}function fs(e,n){return e.axis==="x"?[n[0],n[2]]:e.axis==="y"?[n[2],n[1]]:[n[0],n[1]]}function cl(e,n,t){let o=e.left,s=e.left+e.width,r=e.top,i=e.top+e.height;if(Math.abs(n[0]-t[0])<=Je){if(Math.abs(n[0]-o)<=Je)return"left";if(Math.abs(n[0]-s)<=Je)return"right"}if(Math.abs(n[1]-t[1])<=Je){if(Math.abs(n[1]-r)<=Je)return"top";if(Math.abs(n[1]-i)<=Je)return"bottom"}return null}function ul(e,n){let t=null;for(let o=0;o<3;o+=1)if(!(Math.abs(e[o]-n[o])<=Je)){if(t!==null)return null;t=o}return t}function dl(e,n,t){let o=n.vertices,s=ms(o[t]),r=ms(o[(t+1)%o.length]),i=cl(e,fs(e,s),fs(e,r));if(!i)return null;let c=ul(s,r);if(c===null)return null;let l=Math.min(s[c],r[c]),u=Math.max(s[c],r[c]);return u-l>Je?{item:e,side:i,variableAxis:c,fixed:s,start:l,end:u}:null}function gs(e){e.item.bleed[e.side]=Math.max(e.item.bleed[e.side],nl)}function pl(e,n){let t=new Map;for(let o of n){let s=e[o.sourceIndex];if(s)for(let r=0;r<s.vertices.length;r+=1){let i=dl(o,s,r);if(!i)continue;let c=ll(i),l=t.get(c);l?l.push(i):t.set(c,[i])}}for(let o of t.values()){if(o.length<2)continue;o.sort((r,i)=>r.start-i.start||r.end-i.end);let s=[];for(let r of o){s=s.filter(i=>i.end>r.start+Je);for(let i of s)i.item.sourceIndex!==r.item.sourceIndex&&(gs(i),gs(r));s.push(r)}}}function ml(e){let n=ys(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 fl(e){if(!e)return"#cccccc";let n=ys(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(${Mo(t.r)}, ${Mo(t.g)}, ${Mo(t.b)}, ${o})`}return gl(t)}function gl({r:e,g:n,b:t}){let o=s=>Math.round(Math.max(0,Math.min(255,s))).toString(16).padStart(2,"0");return`#${o(e)}${o(n)}${o(t)}`}function Mo(e){return Math.round(Math.max(0,Math.min(255,e)))}function hl(e,n,t,o){let s=t?.direction??Za,r=Math.hypot(s[0],s[1],s[2])||1,i=s[0]/r,c=s[1]/r,l=s[2]/r,u=Math.max(0,t?.intensity??Ka)*Math.max(0,e[0]*i+e[1]*c+e[2]*l),d=Math.max(0,o?.intensity??el),P=t?.color??Qa,f=o?.color??Ja,b=Xa(n,u,P,f,d),x=ml(n);if(x.alpha>=1)return b;let v=parseInt(b.slice(1,3),16),y=parseInt(b.slice(3,5),16),C=parseInt(b.slice(5,7),16);return`rgba(${v}, ${y}, ${C}, ${x.alpha})`}function yl(e){if(!e?.length)return[];let n=[];for(let t=0;t<e.length;t+=1){let o=e[t],s=al(o);if(!s||s.width<=0||s.height<=0)return[];n.push({...s,sourceIndex:t})}return pl(e,n),n}function bl(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 xl(e){let n=e.left,t=e.top,o=e.left+e.width,s=e.top+e.height;return[n,t,o,t,o,s,n,s]}function Pl(e){return new Map([[0,e.bleed.top],[1,e.bleed.right],[2,e.bleed.bottom],[3,e.bleed.left]])}function vl(e,n){let t=e.split(",").map(Number);if(t.length!==16||t.some(s=>!Number.isFinite(s)))return null;let o=qa/n;for(let s=0;s<8;s+=1)t[s]*=o;return`matrix3d(${t.map(s=>Number(s.toFixed(6))).join(",")})`}function hs(e,n){let t=e.left-e.bleed.left,o=e.top-e.bleed.top,s=e.width+e.bleed.left+e.bleed.right,r=e.height+e.bleed.top+e.bleed.bottom,i=e.z,c=s/n,l=r/n;return`matrix3d(${(e.axis==="x"?[c,0,0,0,0,0,l,0,0,-1,0,0,t,-i,o,1]:e.axis==="y"?[0,0,c,0,0,l,0,0,-1,0,0,0,-i,o,t,1]:[c,0,0,0,0,l,0,0,0,0,1,0,t,o,i,1]).map(d=>Number(d.toFixed(6))).join(",")})`}function Sl(e,n){let{xAxis:t,yAxis:o,normal:s,tx:r,ty:i,tz:c}=bl(e),l=ja(xl(e),t,o,s,r,i,c,ol,Pl(e));return l?vl(l,n)??hs(e,n):hs(e,n)}function Cl(e){let n=e.defaultView?.matchMedia;return n?n("(pointer: coarse)").matches||n("(hover: none)").matches:!1}function Tl(e){return Cl(e)?tl:bs}function El(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 Al(e,n){let t=El(e),o=n.meshRotation;o&&(t=Ya(t,o));let[s,r]=Ga(t,n.rotX,0,n.rotY);return{x:s,y:r}}function wl(e,n,t){let o=e.filter(f=>n.has(f.face)).map(f=>({item:f,...Al(f,t)}));if(o.length===0)return[];let s=1/0,r=-1/0,i=1/0,c=-1/0;for(let f of o)s=Math.min(s,f.x),r=Math.max(r,f.x),i=Math.min(i,f.y),c=Math.max(c,f.y);let l=4,u=Math.max(1e-6,r-s),d=Math.max(1e-6,c-i),P=new Map;for(let f of o){let b=Math.min(l-1,Math.max(0,Math.floor((f.x-s)/u*l))),x=Math.min(l-1,Math.max(0,Math.floor((f.y-i)/d*l))),v=`${b}:${x}`,y=P.get(v);y||(y={tx:b,ty:x,sourceIndex:f.item.sourceIndex,items:[]},P.set(v,y)),y.items.push(f.item),y.sourceIndex=Math.min(y.sourceIndex,f.item.sourceIndex)}return Array.from(P.values()).sort((f,b)=>f.ty-b.ty||f.tx-b.tx||f.sourceIndex-b.sourceIndex).flatMap(f=>f.items)}function Ps(e){let{doc:n,wrapper:t,polygons:o,directionalLight:s,ambientLight:r}=e,i=yl(o);if(i.length===0)return null;let c=new Set(i.map(h=>h.face));t.classList.add("polycss-voxel-mesh");let l=Tl(n);l!==bs&&t.style.setProperty("--polycss-voxel-primitive",`${l}px`);let u=new Map,d=(h,E)=>{let p=`${h}|${E}`,g=u.get(p);if(g)return g;let L=hl(xs[h],E,s,r);return u.set(p,L),L},P=new Map,f=new Map,b=new Map,x=new Map;for(let h of i){let E=x.get(h.face);E||(E=[],x.set(h.face,E)),E.push(h)}let v="",y=0,C=new Set,O=h=>{let E=P.get(h.sourceIndex);return E||(E=n.createElement("b"),P.set(h.sourceIndex,E),sl(E,d(h.face,h.baseColor),Sl(h,l))),E},k=h=>{let E=f.get(h);return E||(E=n.createElement("span"),E.className=`polycss-voxel-face polycss-voxel-face-${h}`,E.dataset.polycssVoxelFace=h,E.__polycssVoxelFaceHost=!0,f.set(h,E)),E},j=()=>{for(let h of Array.from(t.childNodes))if(!h.__polycssVoxelFaceHost)return h;return null},D=(h,E)=>{let p=E.map(R=>R.sourceIndex).join(",");if(b.get(h)===p)return;let g=k(h),L=n.createDocumentFragment();for(let R of E)L.appendChild(O(R));g.replaceChildren(L),b.set(h,p)},Z=()=>{for(let h of Lo)c.has(h)&&D(h,x.get(h)??[])},J=h=>new Set(h.split("|").filter(Boolean)),_=h=>{let E=J(h);return Lo.filter(p=>E.has(p)&&c.has(p))},V=h=>{let E=0;for(let p of h)E+=x.get(p)?.length??0;return E},B=h=>{let E=new Set,p=[],g=new Map;for(let L of h){E.has(L.face)||(E.add(L.face),p.push(L.face));let R=g.get(L.face);R||(R=[],g.set(L.face,R)),R.push(L)}return{orderedFaces:p,itemsByFace:g}},z=(h,E)=>{let p=new Set(h);for(let g of C){if(p.has(g))continue;let L=f.get(g);L?.parentNode===t&&t.removeChild(L)}if(E){let g=n.createDocumentFragment();for(let L of h)g.appendChild(k(L));t.insertBefore(g,j()),C=p;return}for(let g=0;g<h.length;g+=1){let L=h[g],R=k(L);if(R.parentNode===t)continue;let H=null;for(let Q=g+1;Q<h.length;Q+=1){let T=f.get(h[Q]);if(T?.parentNode===t){H=T;break}}t.insertBefore(R,H??j())}C=p},A=(h,E,p)=>{if(!p){let Q=_(h);z(Q,!1),y=V(Q);return}let g=new Set(h.split("|").filter(Boolean)),L=wl(i,g,E),{orderedFaces:R,itemsByFace:H}=B(L);for(let Q of R)D(Q,H.get(Q)??[]);z(R,!0),y=L.length};return Z(),{get brushCount(){return y},render(h){v=ps(h),A(v,h,!0)},syncCamera(h){let E=ps(h);E!==v&&(v=E,A(E,h,!1))},dispose(){for(let h of f.values())h.remove();t.classList.remove("polycss-voxel-mesh"),t.style.removeProperty("--polycss-voxel-primitive"),P.clear(),f.clear(),b.clear(),y=0,C=new Set,v=""}}}var vs="polycss-styles";function Ro(e){let n=e??(typeof document<"u"?document:void 0);if(!n||n.getElementById(vs))return;let t=n.createElement("style");t.id=vs,t.textContent=Ml,n.head.appendChild(t)}var Ml=`
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,
@@ -144,8 +144,8 @@ import{CAMERA_BACKFACE_CULL_EPS as To,DEFAULT_SEAM_BLEED as zs,VOXEL_CAMERA_CULL
144
144
  }
145
145
 
146
146
  .polycss-scene s {
147
- width: var(--polycss-atlas-size, 64px);
148
- height: var(--polycss-atlas-size, 64px);
147
+ width: var(--polycss-atlas-width, var(--polycss-atlas-size, 64px));
148
+ height: var(--polycss-atlas-height, var(--polycss-atlas-size, 64px));
149
149
  }
150
150
 
151
151
  .polycss-scene u {
@@ -516,7 +516,7 @@ import{CAMERA_BACKFACE_CULL_EPS as To,DEFAULT_SEAM_BLEED as zs,VOXEL_CAMERA_CULL
516
516
  .polycss-scene[data-polycss-lighting="dynamic"] q {
517
517
  opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1);
518
518
  }
519
- `;import{BASE_TILE as al,buildPolyMeshTransform as ll,buildPolySceneTransform as cl,worldDirectionToCss as ul,worldDirectionalLightToCss as dl,worldPositionToCss as Fp}from"@layoutit/polycss-core";var pl=1,Kt=al,ml=.1;function Jt(e){return ul(e)}function it(e){return dl(e)}function vn(e){return ll(e)}function vo(e,n=[0,0,0],t=1){let o=e.state;return cl({rotX:o.rotX,rotY:o.rotY,zoom:o.zoom??pl,distance:o.distance??0,target:o.target??[0,0,0],autoCenterOffset:n,layoutScale:t})}function fl(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 is(e){let n=e.ownerDocument?.defaultView;if(!n)return 1;let t=1;for(let o=e;o;o=o.parentElement)t*=fl(n.getComputedStyle(o).getPropertyValue("zoom"));return Number.isFinite(t)&&t>0?t:1}function as(e,n){Math.abs(n-1)<1e-6?e.style.removeProperty("zoom"):e.style.setProperty("zoom",String(1/n))}function ls(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 h=e.vertices[x],b=e.vertices[x+1],v=h[1]-n[1],P=h[0]-n[0],y=h[2]-n[2],C=b[1]-n[1],D=b[0]-n[0],k=b[2]-n[2];t-=P*k-y*D,o-=y*C-v*k,r-=v*D-P*C}let s=Math.hypot(t,o,r);if(s<1e-9)return null;t/=s,o/=s,r/=s;let i=1/ml,c=Math.round(t*i)/i,l=Math.round(o*i)/i,u=Math.round(r*i)/i,d=Math.hypot(c,l,u);return d<1e-9?null:{key:c+","+l+","+u,vec:[c/d,l/d,u/d]}}function cs(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 us(e,n){return e===n?!0:!e||!n?!1:e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}function ds(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 fs,parseHexColor as ps,parsePureColor as hl}from"@layoutit/polycss-core";var gl=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--clx","--cly","--clz"],_t="--polycss-light-preview-active",ms=`var(${_t}, 0)`,yl="max(0, calc(var(--pnx, 0) * var(--plx, 0) + var(--pny, 0) * var(--ply, 0) + var(--pnz, 1) * var(--plz, 1)))",xo=(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))`,bl=xo("--psr","--par","--plr"),vl=xo("--psg","--pag","--plg"),xl=xo("--psb","--pab","--plb");function ue(e,n,t){return e.style.getPropertyValue(n)===t?!1:(e.style.setProperty(n,t),!0)}function pt(e){for(let n of gl)e.style.getPropertyValue(n)&&e.style.removeProperty(n)}function xn(e,n){let t=n.directionalLight?.direction??[.4,-.7,.59],o=Jt(t),r=Math.hypot(o[0],o[1],o[2])||1,s=o[0]/r,i=o[1]/r,c=o[2]/r,l=ps(n.directionalLight?.color??"#ffffff")?.rgb??[255,255,255],u=ps(n.ambientLight?.color??"#ffffff")?.rgb??[255,255,255],d=n.directionalLight?.intensity??1,x=n.ambientLight?.intensity??.4,h=P=>(P/255).toFixed(4);ue(e,"--plx",s.toFixed(2)),ue(e,"--ply",i.toFixed(2)),ue(e,"--plz",c.toFixed(2)),ue(e,"--plr",h(l[0])),ue(e,"--plg",h(l[1])),ue(e,"--plb",h(l[2])),ue(e,"--pli",d.toFixed(4)),ue(e,"--par",h(u[0])),ue(e,"--pag",h(u[1])),ue(e,"--pab",h(u[2])),ue(e,"--pai",x.toFixed(4));let b=c,v=Math.sign(b||1)*Math.max(Math.abs(b),.01);ue(e,"--clx",s.toFixed(2)),ue(e,"--cly",i.toFixed(2)),ue(e,"--clz",v.toFixed(2))}function hs(e,n){let t=n.textureLighting==="dynamic";if(e.dataset.polycssLighting=n.textureLighting??"baked",!t){pt(e);return}xn(e,n)}function mt(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 gs(e,n){let t=fs(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 Po(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=t.textureLighting??"baked",r={directionalLight:it(t.directionalLight),ambientLight:t.ambientLight,textureLighting:o,textureQuality:t.textureQuality,seamBleed:t.seamBleed,strategies:t.strategies},s=qn(e.plan,n,e.plan.normal,o,r);return At(e.element,s,o),o==="baked"&&Sl(e.element),!0}function Pl(e){let n=hl(e)??{rgb:[255,255,255],alpha:1},[t,o,r]=n.rgb,s=(c,l)=>`calc(${c} * (1 - ${ms}) + var(${l}, ${c}) * ${ms})`,i=n.alpha<1?` / ${n.alpha}`:"";return`rgb(${s(t,"--polycss-preview-r")} ${s(o,"--polycss-preview-g")} ${s(r,"--polycss-preview-b")}${i})`}function ys(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=e.element,r=e.plan.normal,s=fs(n.color??"#cccccc"),i=!1;return i=ue(o,"--pnx",r[0].toFixed(4))||i,i=ue(o,"--pny",r[1].toFixed(4))||i,i=ue(o,"--pnz",r[2].toFixed(4))||i,i=ue(o,"--psr",(s.r/255).toFixed(4))||i,i=ue(o,"--psg",(s.g/255).toFixed(4))||i,i=ue(o,"--psb",(s.b/255).toFixed(4))||i,i=ue(o,"--plam",yl)||i,i=ue(o,"--polycss-preview-r",bl)||i,i=ue(o,"--polycss-preview-g",vl)||i,i=ue(o,"--polycss-preview-b",xl)||i,i=ue(o,"--polycss-paint",Pl(t))||i,o.style.getPropertyValue("color")&&(o.style.removeProperty("color"),i=!0),i}function Sl(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 Cl="http://www.w3.org/2000/svg",Pn=class{constructor(){this.groundSvg=null;this.groundVisible=!1;this.currentGroundCssZ=null;this.shadowRoot=null}};function bs(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 vs(e){e.groundSvg?.parentNode&&e.groundSvg.parentNode.removeChild(e.groundSvg),e.groundSvg=null,e.groundVisible=!1}function xs(e){e.groundSvg&&e.groundVisible&&(e.groundSvg.style.display="none",e.groundVisible=!1)}function Ps(e,n,t,o){let r=[],s=e.firstChild;for(let i=0;i<t;i++){let c=s;c&&c.tagName==="path"?s=c.nextSibling:(c=n.createElementNS(Cl,"path"),c.setAttribute("fill-rule","nonzero"),o&&(c.setAttribute("stroke-width","0.5"),c.setAttribute("stroke-linejoin","round")),e.insertBefore(c,s)),r.push(c)}for(;s;){let i=s.nextSibling;e.removeChild(s),s=i}return r}function Ss(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 Pn,receiverShadowCache:new Map,receiverShadowCacheKey:new Map,casterItemsCache:new Map,casterItemsCacheKey:new Map}}import{buildSharedEdgeMap as Tl,computeReceiverShadowFaces as El,meshScaleVec3 as Ms,prepareCasterEdgeOwners as Al,prepareCasterPolyItems as wl,prepareReceiverFacePlanes as Ml}from"@layoutit/polycss-core";function Cs(e){for(let n of e)n.svg&&n.svg.parentNode&&n.svg.parentNode.removeChild(n.svg),n.svg=null}function Ts(e,n){if(n){let t=e.receiverShadowCache.get(n);t&&Cs(t),e.receiverShadowCache.delete(n),e.receiverShadowCacheKey.delete(n)}else{for(let t of e.receiverShadowCache.values())Cs(t);e.receiverShadowCache.clear(),e.receiverShadowCacheKey.clear()}}function Es(e,n){n?(e.casterItemsCache.delete(n),e.casterItemsCacheKey.delete(n)):(e.casterItemsCache.clear(),e.casterItemsCacheKey.clear())}function As(e){vs(e.shadowSvgState),ws(e)}function So(e){return e.handle.id??e.autoMeshId}var Ll="http://www.w3.org/2000/svg",Sn=new WeakMap,Ls=new WeakMap,_s=new WeakMap,Rs=new WeakMap,ks=new WeakMap;function Os(e){let n=Sn.get(e);return n||(n=new Map,Sn.set(e,n)),n}function Co(e){let n=Sn.get(e);if(n){for(let t of n.values())t.svg&&t.svg.parentNode&&t.svg.parentNode.removeChild(t.svg);n.clear(),Sn.delete(e)}}function ws(e){for(let n of e.meshes)Co(n)}function Ds(e,n,t,o,r,s,i,c,l,u){let d=e.options.current,{receiverShadowCache:x,receiverShadowCacheKey:h,casterItemsCache:b,casterItemsCacheKey:v}=e,P=o.handle.transform.position??[0,0,0],y=o.handle.transform.rotation??[0,0,0],C=o.polygons.some(A=>A.texture!==void 0),D=Ms(o.handle.transform.scale),k=o.bboxCenterCss,z=d.shadow?.lift??.001,I=`${o.polygons.length}|${r.size}|${P.join(",")}|${y.join(",")}|${D.join(",")}|${k?k.join(","):"n"}|${z}`,Z=x.get(o);if(Z===void 0||h.get(o)!==I){Z=Ml(o.polygons,P,o.handle.transform.scale,r,z,y),x.set(o,Z),h.set(o,I);let A=Os(o);for(let g of A.values())g.svg&&g.svg.parentNode&&g.svg.parentNode.removeChild(g.svg);A.clear()}let Q=[];for(let A of n){let g=A.handle.transform.position??[0,0,0],m=A.handle.transform.rotation??[0,0,0],p=Ms(A.handle.transform.scale),E=A.bboxCenterCss,M=`${A.polygons.length}|${g.join(",")}|${m.join(",")}|${p.join(",")}|${E?E.join(","):"n"}`,R=b.get(A);if(R===void 0||v.get(A)!==M){let _=t.get(A),W=new Set;for(let q of A.rendered)q.plan&&!_.has(q.polygonIndex)&&W.add(q.polygonIndex);R=wl(A.polygons,g,A.handle.transform.scale,q=>W.has(q),m),b.set(A,R),v.set(A,M)}let L;if(A===o){let _=Ls.get(A);(_===void 0||_s.get(A)!==A.polygons)&&(_=Tl(A.polygons),Ls.set(A,_),_s.set(A,A.polygons)),L=_}let te;if(A!==o&&A.polygons.length>=40){let _=Rs.get(A);(_===void 0||ks.get(A)!==M)&&(_=Al(A.polygons,g,A.handle.transform.scale,m),Rs.set(A,_),ks.set(A,M)),te=_}Q.push({id:A,items:R,selfShadowEdgeMap:L,edgeOwners:te,casterPolygonCount:A.polygons.length})}let O={rotX:e.camera.state.rotX,rotY:e.camera.state.rotY,meshRotation:o.handle.transform.rotation},H=El({receiverPlanes:Z,receiverPolygons:o.polygons,receiverHasTexture:C,casters:Q,lightDir:s,cameraRot:O,ambientLight:d.ambientLight,directionalLight:d.directionalLight,shadow:{color:d.shadow?.color,opacity:u,maxExtend:d.shadow?.maxExtend}}),V=Os(o),U=new Set;for(let A of H){U.add(A.faceIndex);let g=V.get(A.faceIndex);g||(g={svg:null,visible:!1,width:-1,height:-1,matrixCss:""},V.set(A.faceIndex,g));let m=g.svg;m?(g.visible||(m.style.display="block"),(g.width!==A.width||g.height!==A.height)&&(m.setAttribute("width",String(A.width)),m.setAttribute("height",String(A.height)),m.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),g.width=A.width,g.height=A.height),g.matrixCss!==A.matrixCss&&(m.style.transform=A.matrixCss,g.matrixCss=A.matrixCss)):(m=e.doc.createElementNS(Ll,"svg"),m.setAttribute("class","polycss-shadow polycss-shadow-svg polycss-shadow-receiver"),d.debugShadowAttrs&&(m.setAttribute("data-poly-shadow-type","receiver"),m.setAttribute("data-poly-shadow-receiver",So(o)),m.setAttribute("data-poly-shadow-receiver-face",String(A.faceIndex)),m.setAttribute("data-poly-shadow-receiver-polys",JSON.stringify(A.memberPolyIndices))),m.setAttribute("width",String(A.width)),m.setAttribute("height",String(A.height)),m.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),m.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}`),bs(e.shadowSvgState,e.doc,e.sceneEl).appendChild(m),g.svg=m,g.width=A.width,g.height=A.height,g.matrixCss=A.matrixCss),g.visible=!0;let p=Ps(m,e.doc,A.paths.length,!0),E=A.opacity.toFixed(4),M=[],R=!!d.debugShadowAttrs;for(let L=0;L<A.paths.length;L++){let te=A.paths[L],_=R?So(te.casterId):"";R&&M.push(_);let W=p[L];if(W.setAttribute("d",te.d),W.getAttribute("fill")!==A.fill&&W.setAttribute("fill",A.fill),W.getAttribute("stroke")!==A.fill&&W.setAttribute("stroke",A.fill),W.getAttribute("opacity")!==E&&W.setAttribute("opacity",E),R){W.getAttribute("data-poly-shadow-caster")!==_&&W.setAttribute("data-poly-shadow-caster",_);let q=JSON.stringify(te.casterPolygonIndices);W.getAttribute("data-poly-shadow-caster-polys")!==q&&W.setAttribute("data-poly-shadow-caster-polys",q)}}if(R){let L=M.join(" ");m.getAttribute("data-poly-shadow-casters")!==L&&m.setAttribute("data-poly-shadow-casters",L)}}for(let[A,g]of V)U.has(A)||g.svg&&g.visible&&(g.svg.style.display="none",g.visible=!1)}var Is=Symbol.for("polycss.animation.triangleFrameTarget");var zl=750;function Vs(e){return!Object.prototype.hasOwnProperty.call(e,"seamBleed")||e.seamBleed!==void 0?e:{...e,seamBleed:zs}}var Nl={key:"non-cullable",normal:[1,1,0]};function Bs(){return[Nl]}function Ao(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&&bo(e.ownerDocument),e.ownerDocument?.defaultView&&e.ownerDocument.defaultView.getComputedStyle(e).position==="static"&&(e.style.position="relative");let{camera:o,...r}=n,s=Vs({seamBleed:zs,...r}),i=is(e),c=[0,0,0],l=e.ownerDocument??document,u=l.createElement("div");u.className="polycss-camera",Z(u,s),e.appendChild(u);let d=l.createElement("div");d.className="polycss-scene",d.setAttribute("aria-hidden","true"),Q(d,s),u.appendChild(d);let x=Ss({host:e,doc:l,cameraEl:u,sceneEl:d,camera:t,layoutScale:i,options:s}),h=x.meshes,b=new WeakMap,v=x.shadowSvgState,P=()=>xs(v),y=()=>As(x),C=null;function D(a){if(!a)return null;let f=Math.hypot(a[0],a[1],a[2]);if(!Number.isFinite(f)||f<=0)return null;let S=Math.round(a[0]/f*100)/100,T=Math.round(a[1]/f*100)/100,j=Math.round(a[2]/f*100)/100;return`${S}|${T}|${j}`}function k(){C=null}let z=a=>Ts(x,a),I=a=>Es(x,a);function Z(a,f){let S=t.perspectiveStyle;if(S==="none")a.style.perspective="1000000px";else{let T=parseFloat(S);Number.isFinite(T)&&(a.style.perspective=`${T}px`)}}function Q(a,f){as(a,i),a.style.transform=vo(t,c,i),hs(a,f)}function O(a){a.style.transform=vo(t,c,i)}function H(a){a.voxelRenderer?.dispose(),a.voxelRenderer=void 0,g(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 f of Array.from(a.wrapper.children))f instanceof HTMLElement&&f.classList.contains("polycss-bucket")&&f.remove();a.hasBuckets=!1}function V(a){for(let f of Array.from(a.wrapper.childNodes)){if(!(f instanceof HTMLElement))return f;if(f.classList.contains("polycss-bucket")||f.classList.contains("polycss-shadow"))continue;let S=f.tagName.toLowerCase();if(!(S==="b"||S==="i"||S==="s"||S==="u"||S==="q"))return f}return null}function U(a,f,S){S?.parentNode===a.wrapper?a.wrapper.insertBefore(f,S):a.wrapper.appendChild(f)}function A(a){for(let f of a.shadowRendered)f.parentNode&&f.parentNode.removeChild(f);a.shadowRendered.length=0,y()}function g(a,f){f?.();for(let S of a){try{S.dispose()}catch{}S.element.parentNode&&S.element.parentNode.removeChild(S.element)}}function m(a,f,S){a.rendered=f,a.renderedByPolygonIndex=[];for(let T of f)a.renderedByPolygonIndex[T.polygonIndex]=T;a.disposeAtlas=S,a.solidLightingPreviewPrepared=!1}function p(a,f){let S=a.renderedByPolygonIndex[f];return S?.polygonIndex===f?S:void 0}function E(a){for(let f of Array.from(a.wrapper.children))f instanceof HTMLElement&&f.classList.contains("polycss-bucket")&&f.remove();a.hasBuckets=!1;for(let f of a.rendered)f.element.parentNode&&f.element.parentNode.removeChild(f.element)}function M(a,f){let S=a.polygons[f.polygonIndex];return a.stableDom&&S?Fs(S):f.plan?.normal??(S?Fs(S):null)}function R(a){if(!q(a))return a.rendered;let f=L(a);return a.rendered.filter(S=>te(a,S,To,f))}function L(a){return{rotX:t.state.rotX,rotY:t.state.rotY,meshRotation:a.handle.transform.rotation}}function te(a,f,S=To,T=L(a)){let j=M(a,f);return j===null||Fl(j,T,S)}function _(a){if(a.excludeFromAutoCenter){a.cameraCullGroups=[];return}let f=new Map;for(let S of a.rendered){let T=M(a,S);if(!T)continue;if(!Il(T)){a.cameraCullGroups=Bs();return}let j=Rl(T);if(!f.has(j)&&(f.set(j,T),f.size>_l)){a.cameraCullGroups=Bs();return}}a.cameraCullGroups=Array.from(f,([S,T])=>({key:S,normal:T}))}function W(a){return q(a)?kl(a.cameraCullGroups,L(a)):"all"}function q(a){return!a.excludeFromAutoCenter&&Hl(a.cameraCullGroups)}function re(a){a.cameraCullSignature=q(a)?W(a):"all"}function fe(a,f){let S=new Array(a.rendered.length),T=!1,j=L(a);for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K],J=te(a,oe,f,j);S[K]=J}let B=null,F=null,$=()=>{if(!(!B||!F)){if(B===F)B.remove();else{let K=l.createRange();K.setStartBefore(B),K.setEndAfter(F),K.deleteContents(),K.detach()}B=null,F=null,T=!0}};for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K];!S[K]&&oe.element.parentNode===a.wrapper?(F&&F.nextSibling===oe.element||($(),B=oe.element),F=oe.element):$()}$();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 Ie=a.rendered[J];be(a,Ie),oe.appendChild(Ie.element)}U(a,oe,Y(K)),ae=-1,T=!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),T}function de(a,f=!1){if(a.voxelRenderer){f?a.voxelRenderer.render(L(a)):a.voxelRenderer.syncCamera(L(a)),a.cameraCullSignature="voxel-direct";return}if(!q(a)){let j=a.cameraCullSignature!=="all";a.cameraCullSignature="all",j&&ve(a);return}if(a.hasBuckets){pe(a,f);return}let S=W(a);if(!f&&S===a.cameraCullSignature)return;let T=fe(a,To);a.cameraCullSignature=S,T&&Ge(a)}function pe(a,f=!1){let S=q(a)?W(a):"all";!f&&S===a.cameraCullSignature||ve(a)}function Ce(a,f){return M(a,f)}function be(a,f){if(s.textureLighting!=="dynamic")return;let S=Ce(a,f);S&&(f.element.style.setProperty("--pnx",S[0].toFixed(4)),f.element.style.setProperty("--pny",S[1].toFixed(4)),f.element.style.setProperty("--pnz",S[2].toFixed(4)))}function Ae(a){E(a),a.hasBuckets=!1;let f=a.skipBucketNormalCleanupOnce;a.skipBucketNormalCleanupOnce=!1;let S=l.createDocumentFragment(),T=s.textureLighting==="dynamic"&&!a.stableDom,j=new Map,B=[];for(let F of R(a)){let $=a.polygons[F.polygonIndex],Y=T&&$?ls($):null;if(!Y){B.push(F);continue}let ae=Y.key+"|"+($.color??""),ne=j.get(ae);ne||(ne={vec:Y.vec,items:[]},j.set(ae,ne)),ne.items.push(F)}for(let F of B)be(a,F),S.appendChild(F.element);for(let F of j.values()){if(F.items.length<2){for(let Y of F.items)be(a,Y),S.appendChild(Y.element);continue}let $=l.createElement("div");$.className="polycss-bucket",a.hasBuckets=!0,$.style.setProperty("--pnx",String(F.vec[0])),$.style.setProperty("--pny",String(F.vec[1])),$.style.setProperty("--pnz",String(F.vec[2]));for(let Y of F.items)$.appendChild(Y.element),(!f||Y.kind==="triangle")&&(Y.element.style.removeProperty("--pnx"),Y.element.style.removeProperty("--pny"),Y.element.style.removeProperty("--pnz"));S.appendChild($)}U(a,S,V(a)),re(a)}function Ue(){return new Promise(a=>setTimeout(a,0))}async function qe(a,f){if(s.textureLighting==="dynamic"&&!a.stableDom)return Ae(a),!f();E(a);let T=l.createDocumentFragment(),j=V(a),B=0;for(let F of R(a)){if(f())return!1;be(a,F),T.appendChild(F.element),B++,B%zl===0&&(U(a,T,j),T=l.createDocumentFragment(),await Ue())}return T.childNodes.length>0&&U(a,T,j),re(a),!f()}function at(a,f){let S=s.textureLighting==="dynamic",T=s.directionalLight?.direction,j=f&&(f[0]!==0||f[1]!==0||f[2]!==0);if(!S||!j||!T){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=Eo(T,f),F=Jt(B),$=Math.hypot(F[0],F[1],F[2])||1,Y=(F[0]/$).toFixed(2),ae=(F[1]/$).toFixed(2),ne=(F[2]/$).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 yt(a){let f=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let T=a.polygons[S.polygonIndex];T&&(f=Po(S,T,s)||f)}return a.solidLightingPreviewPrepared=!1,a.solidLightingPreviewActive=!1,f}function lt(a){if((s.textureLighting??"baked")!=="baked")return!1;let f=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let T=a.polygons[S.polygonIndex];T&&(ys(S,T,S.plan.shadedColor),f=!0)}return a.solidLightingPreviewPrepared=f,f}function On(a){return(s.textureLighting??"baked")!=="baked"||!a.solidLightingPreviewPrepared&&!lt(a)?!1:(a.solidLightingPreviewActive=!0,!0)}function Dn(a){return a.kind==="atlas"||!!a.plan?.texture}function In(){if((s.textureLighting??"baked")!=="baked")return!1;let a=!1;for(let f of h)a=yt(f)||a,f.rendered.some(Dn)&&(Vt(f),a=!0);d.style.removeProperty(_t);for(let f of h)pt(f.wrapper),f.solidLightingPreviewActive=!1;return pt(d),a}function Hn(){d.style.removeProperty(_t);for(let a of h)a.solidLightingPreviewActive&&(yt(a),pt(a.wrapper));(s.textureLighting??"baked")!=="dynamic"&&(pt(d),k(),Te())}function G(a,f){let S=a.handle.transform.rotation,T=f.directionalLight?.direction??s.directionalLight?.direction;if(!(S&&(S[0]!==0||S[1]!==0||S[2]!==0))||!T){pt(a.wrapper);return}let B=Eo(T,S);xn(a.wrapper,{...s,...f,directionalLight:{...s.directionalLight,...f.directionalLight,direction:B}})}function se(a){if((s.textureLighting??"baked")!=="baked")return!1;xn(d,{...s,...a}),!a.skipShadows&&a.directionalLight?.direction&&Te(a.directionalLight.direction);let f=!1;for(let S of h)G(S,a),f=On(S)||f;return f?ue(d,_t,"1"):d.style.removeProperty(_t),f}function ie(a,f,S){let T=a.polygons[f];if(!T)return!1;let j=p(a,f);if(!j)return!1;let B=s.textureLighting??"baked";return B==="dynamic"?(gs(j.element,S),!0):B==="baked"?Po(j,T,s):!1}function we(a,f){let S=a.polygons[f];if(!S)return!1;let T=p(a,f);return T?(ye(T.element,S,f),!0):!1}function Ft(a,f,S){return!(S.length===0||!S.every(T=>T==="color"||T==="data")||S.includes("color")&&!ie(a,f,a.polygons[f]?.color)||S.includes("data")&&!we(a,f))}function Ge(a){k(),Te()}function Te(a){let f=[];for(let J of h)!J.disposed&&J.castShadow&&f.push(J);if(f.length===0){y(),C=null;return}let S=s.shadow?.color??"#000000",T=s.shadow?.opacity??.25,j=Bl(S)?.rgb??[0,0,0],B=j[0],F=j[1],$=j[2],Y=a??s.directionalLight?.direction??[.4,-.7,.59],ae=Jt(Y),ne=D(ae);if(ne!==null&&ne===C)return;let K=new Map;for(let J of f)K.set(J,Hs(J.polygons,{normalTolerance:.1,distanceTolerance:.5,overlapFraction:.95,preserveDoubleSidedBackfaces:!1}));let oe=new Map;for(let J of h)J.disposed||!J.receiveShadow||oe.set(J,new Set);P();for(let J of h)J.disposed||!J.receiveShadow||Ds(x,f,K,J,oe.get(J)??new Set,ae,B,F,$,T);C=ne}function ve(a){if(a.voxelRenderer){a.voxelRenderer.render(L(a)),a.cameraCullSignature="voxel-direct";return}A(a),Ae(a),Ge(a)}function Oe(a,f){if(!f||!a.polygons||a.polygons.length<2)return;let S=Math.hypot(f[0],f[1],f[2]);if(!Number.isFinite(S)||S<=0)return;let T=f[0]/S,j=f[1]/S,B=f[2]/S,F=K=>Math.round(K*1e3)/1e3,$=`${F(T)},${F(j)},${F(B)}`,Y=a.lightOcclusionCache;if(Y&&Y.polygons===a.polygons&&Y.lightDirKey===$)return Y.occluded;let ae=Y&&Y.polygons===a.polygons?Y.dedupDropped:Hs(a.polygons,{normalTolerance:.1,distanceTolerance:.12,overlapFraction:.98,preserveDoubleSidedBackfaces:!1}),ne=Dl(a.polygons,[T,j,B],ae);return a.lightOcclusionCache={polygons:a.polygons,lightDirKey:$,occluded:ne,dedupDropped:ae},ne}function De(a){return!!a.voxelSource&&s.textureLighting!=="dynamic"&&!a.stableDom&&!a.castShadow}function Se(a,f){H(a);let S=s.directionalLight,T=f?{...S,direction:f}:S,j=it(T),B=void 0;if(De(a)){let Y=rs({doc:l,wrapper:a.wrapper,polygons:a.parseResult.polygons,directionalLight:j,ambientLight:s.ambientLight});if(Y){a.voxelRenderer=Y,Y.render(L(a)),a.cameraCullSignature="voxel-direct";return}}let F={doc:l,directionalLight:j,ambientLight:s.ambientLight,textureLighting:s.textureLighting,textureQuality:s.textureQuality,seamBleed:s.seamBleed,strategies:s.strategies,lightOccludedPolyIndices:B},$=a.stableDom?(()=>{let Y=ut(a.polygons,F);return mt(a.wrapper,Y),Lt(a.polygons,{...F,solidPaintDefaults:Y})??dt(a.polygons,{...F,solidPaintDefaults:Y})})():dt(a.polygons,{...F,computeSolidPaintDefaults:!0,skipDynamicNormalVars:s.textureLighting==="dynamic"});a.stableDom||mt(a.wrapper,$.solidPaintDefaults??{}),m(a,$.rendered,$.dispose),a.skipBucketNormalCleanupOnce=s.textureLighting==="dynamic"&&!a.stableDom,_(a),Ae(a),Ge(a)}function Vt(a,f){if(a.rendered.length===0||a.voxelRenderer||a.stableDom||De(a)){Se(a,f);return}if(a.rendered[0]?.element.parentNode===null){Se(a,f);return}let S=s.directionalLight,T=f?{...S,direction:f}:S,j=it(T),B={doc:l,directionalLight:j,ambientLight:s.ambientLight,textureLighting:s.textureLighting,textureQuality:s.textureQuality,seamBleed:s.seamBleed,strategies:s.strategies,computeSolidPaintDefaults:!0,skipDynamicNormalVars:s.textureLighting==="dynamic"},F=dt(a.polygons,B),$=()=>{a.rebakeInFlight=!1;let ne=a.rebakeQueuedLightDir;ne!==null&&(a.rebakeQueuedLightDir=null,Vt(a,ne))},Y=()=>{if(a.disposed){F.dispose(),$();return}if(F.rendered.length!==a.rendered.length){F.dispose(),Se(a,f),$();return}for(let oe of F.rendered){let J=a.renderedByPolygonIndex[oe.polygonIndex];if(!J)continue;let Ie=oe.element.getAttribute("style");Ie!==null&&J.element.setAttribute("style",Ie)}let ne=F.solidPaintDefaults;ne&&mt(a.wrapper,ne);let K=a.disposeAtlas;a.disposeAtlas=F.dispose,K&&(typeof requestAnimationFrame=="function"?J=>{requestAnimationFrame(J)}:J=>{setTimeout(J,0)})(K),Ge(a),$()},ae=F.pagesReady;ae&&typeof ae.then=="function"?ae.then(()=>Vn(F.rendered)).then(Bn).then(Y,()=>{F.dispose(),a.disposed||Se(a,f),$()}):Y()}function Fn(a,f){if(a.rebakeInFlight){a.rebakeQueuedLightDir=f;return}a.rebakeInFlight=!0,Vt(a,f)}function Vn(a){let f=new Set;for(let S of a){let T=S.element.getAttribute("style")??"",j=/url\((blob:[^)]+)\)/g,B;for(;(B=j.exec(T))!==null;)f.add(B[1])}return Array.from(f)}function Bn(a){return a.length===0||typeof Image>"u"?Promise.resolve():Promise.all(a.map(f=>{let S=new Image;S.src=f;let T=S.decode?.();return T?T.catch(()=>{}):Promise.resolve()})).then(()=>{})}function Qe(){let a=1/0,f=!1;for(let B of h)if(!B.disposed&&B.receiveShadow){f=!0;break}for(let B of h){if(B.disposed||!(f?B.receiveShadow:B.castShadow))continue;let $=B.handle.transform.position?.[2]??0;for(let Y of B.polygons)for(let ae of Y.vertices){let ne=ae[2]+$;ne<a&&(a=ne)}}if(!Number.isFinite(a)){let B=v.currentGroundCssZ!==null;v.currentGroundCssZ=null,B&&(y(),k());return}let S=s.shadow?.lift??.05,T=(a+S)*Kt,j=v.currentGroundCssZ;v.currentGroundCssZ=T,j!==T&&(k(),Te())}async function cn(a,f){H(a);let S=it(s.directionalLight),T={doc:l,directionalLight:S,ambientLight:s.ambientLight,textureLighting:s.textureLighting,textureQuality:s.textureQuality,seamBleed:s.seamBleed,strategies:s.strategies,lightOccludedPolyIndices:void 0},j=a.stableDom?Lt(a.polygons,T):null;if(j){let $=ut(a.polygons,T);return mt(a.wrapper,$),m(a,j.rendered,j.dispose),_(a),Ae(a),Ge(a),!f()}let B=await Zt(a.polygons,{...T,skipDynamicNormalVars:s.textureLighting==="dynamic"},f);if(f())return B.dispose(),!1;mt(a.wrapper,B.solidPaintDefaults),m(a,B.rendered,B.dispose),a.skipBucketNormalCleanupOnce=s.textureLighting==="dynamic"&&!a.stableDom,_(a);let F=await qe(a,f);return F&&Ge(a),F}function ct(){let a=c,f=[0,0,0];if(s.autoCenter){let S=[];for(let T of h)!T.disposed&&!T.excludeFromAutoCenter&&S.push(...T.polygons);if(S.length>0){let T=Ol(S);f=[(T.min[0]+T.max[0])/2,(T.min[1]+T.max[1])/2,(T.min[2]+T.max[2])/2]}}a[0]===f[0]&&a[1]===f[1]&&a[2]===f[2]||(c=f,x.autoCenter.offset=f,Q(d,s))}function di(a,f={}){let T=(d.ownerDocument??document).createElement("div");T.className="polycss-mesh",f.id&&T.setAttribute("data-poly-mesh-id",f.id);let j=`polycss-mesh-${x.meshAutoCounter.next++}`;T.setAttribute("data-poly-mesh-index",j);let B={...f},F=f.merge!==!1,$=!!f.stableDom,Y=0,ae=vn(B);ae&&(T.style.transform=ae);let ne=(N,X)=>a.voxelSource?N:X?Vl(N,{meshResolution:f.meshResolution}):($||f.excludeFromAutoCenter,N),K=ne(a.polygons,F),oe=null;function J(){let N=vn(B);T.style.transform=N??""}function Ie(N){if(N.length===0){oe=null,$e&&($e.bboxCenterCss=null),J();return}let X=1/0,le=1/0,me=1/0,Me=-1/0,ce=-1/0,ge=-1/0;for(let Ye of N)for(let Fe of Ye.vertices)Fe[0]<X&&(X=Fe[0]),Fe[0]>Me&&(Me=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,$e&&($e.bboxCenterCss=null),J();return}let He=(le+ce)/2*Kt,je=(X+Me)/2*Kt,Le=(me+ge)/2*Kt;oe=[He,je,Le],$e&&($e.bboxCenterCss=oe),J()}let $e=null;Ie(K),d.appendChild(T);let w={handle:void 0,wrapper:T,parseResult:a,rendered:[],renderedByPolygonIndex:[],shadowRendered:[],polygons:K,voxelSource:a.voxelSource,disposed:!1,stableDom:$,hasBuckets:!1,skipBucketNormalCleanupOnce:!1,excludeFromAutoCenter:!!f.excludeFromAutoCenter,castShadow:!!f.castShadow,bboxCenterCss:oe,receiveShadow:!!f.receiveShadow,cameraCullGroups:[],cameraCullSignature:"",lightOverrideSignature:"clear",stableTriangleColorFrame:0,solidLightingPreviewPrepared:!1,solidLightingPreviewActive:!1,bakedRotation:f.rotation?[...f.rotation]:[0,0,0],autoMeshId:j,rebakeInFlight:!1,rebakeQueuedLightDir:null},We=null,zn=0,un=-1,Bt=null;function zt(){We=null,Bt=null,un=-1}function dr(){let N=We;if(!N||N.polygonCount!==w.polygons.length)return w.polygons;if(Bt&&un===zn)return Bt;let X=N.vertices,le=new Array(N.polygonCount);for(let me=0;me<N.polygonCount;me++){let Me=w.polygons[me],ce=me*9;le[me]={...Me,color:N.colors?.[me]??Me.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 Bt=le,un=zn,le}function pr(N,X){let le=N?.stableTriangleUpdateMode==="color-only";w.stableTriangleColorFrame++;let me=w.stableDom&&!X;if(me||Ie(w.polygons),w.stableDom&&!w.hasBuckets){let Me={doc:l,directionalLight:it(s.directionalLight),ambientLight:s.ambientLight,textureLighting:s.textureLighting,textureQuality:s.textureQuality,seamBleed:s.seamBleed},ce=w.rendered.length===w.polygons.length&&w.rendered.every(Le=>Le.kind==="triangle"),ge=w.stableDom&&!X,He=ce||ge?{}:ut(w.polygons,Me);ce||mt(w.wrapper,He);let je={...Me,solidPaintDefaults:He,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:w.stableTriangleColorFrame};if(Qt(w.rendered,w.polygons,je))return le||(_(w),de(w,!0),X&&ct()),!0}return me&&Ie(w.polygons),!1}let bt={get polygons(){return dr()},set polygons(N){zt(),w.polygons=N},element:T,id:f.id,get transform(){return B},remove(){Y++,T.parentNode&&T.parentNode.removeChild(T),H(w),h.delete(w),b.delete(T),z(w),I(w),ct(),Qe()},setPolygons(N,X){Y++,F=X?.merge??F,$=X?.stableDom??$,w.stableDom=$,w.voxelSource=void 0,w.polygons=ne(N,F),I(w),z(w),zt(),bt.polygons=w.polygons;let le=X?.recomputeAutoCenter??!0;pr(X,le)||(Se(w),le&&ct())},[Is](N,X){let le=X?.merge??F,me=X?.stableDom??$;if(!N.solidTriangles||!me||le||f.meshResolution!==void 0||w.hasBuckets||N.polygonCount!==w.polygons.length||N.vertices.length<N.polygonCount*9||w.rendered.length!==N.polygonCount)return!1;for(let ge=0;ge<w.rendered.length;ge++){let He=w.rendered[ge],je=w.polygons[ge];if(He?.kind!=="triangle"||He.polygonIndex!==ge||!je||je.vertices.length!==3||je.texture||je.material?.texture)return!1}let Me=X?.recomputeAutoCenter??!0;if(!Me){let ge=w.stableTriangleColorFrame+1,He={doc:l,directionalLight:it(s.directionalLight),ambientLight:s.ambientLight,textureLighting:s.textureLighting,textureQuality:s.textureQuality,seamBleed:s.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(qt(w.rendered,w.polygons,N,He))return Y++,F=le,$=me,w.stableDom=$,w.voxelSource=void 0,w.stableTriangleColorFrame=ge,We=N,zn++,Bt=null,un=-1,q(w)?(_(w),de(w,!0)):re(w),!0}Y++,F=le,$=me,w.stableDom=$,w.voxelSource=void 0;let ce=N.vertices;for(let ge=0;ge<N.polygonCount;ge++){let He=w.polygons[ge],je=N.colors?.[ge];je&&(He.color=je);let Le=He.vertices,Ye=ge*9;Le[0][0]=ce[Ye],Le[0][1]=ce[Ye+1],Le[0][2]=ce[Ye+2],Le[1][0]=ce[Ye+3],Le[1][1]=ce[Ye+4],Le[1][2]=ce[Ye+5],Le[2][0]=ce[Ye+6],Le[2][1]=ce[Ye+7],Le[2][2]=ce[Ye+8]}return zt(),bt.polygons=w.polygons,pr(X,Me)},updatePolygon(N,X){let le=typeof N=="number"?N:w.polygons.indexOf(N);if(le<0&&typeof N!="number"&&We&&(le=dr().indexOf(N)),le<0||le>=w.polygons.length)return;zt(),w.voxelSource=void 0,Object.assign(w.polygons[le],X);let me=Object.keys(X);Ft(w,le,me)||Se(w)},async setPolygonsChunked(N,X){let le=++Y;F=X?.merge??F,$=X?.stableDom??$,w.stableDom=$,w.voxelSource=void 0,w.polygons=ne(N,F),zt(),bt.polygons=w.polygons,Ie(w.polygons);let me=X?.recomputeAutoCenter??!0;if(!await cn(w,()=>w.disposed||le!==Y)){H(w);return}me&&ct()},setTransform(N){let X=w.castShadow,le=w.receiveShadow;N.castShadow!==void 0&&(w.castShadow=!!N.castShadow),N.receiveShadow!==void 0&&(w.receiveShadow=!!N.receiveShadow),B={...B,...N};let me=vn(B);T.style.transform=me??"",at(w,B.rotation),N.rotation!==void 0&&de(w,!0),w.castShadow!==X&&(w.voxelSource&&Se(w),Ge(w),Qe()),w.receiveShadow!==le&&(w.receiveShadow||Co(w),k(),Te()),(N.position!==void 0||N.scale!==void 0)&&(w.castShadow||w.receiveShadow)&&(Qe(),k(),Te())},dispose(){if(!w.disposed){w.disposed=!0,Y++,T.parentNode&&T.parentNode.removeChild(T),H(w);try{a.dispose()}catch{}h.delete(w),b.delete(T),ct(),Qe()}},rebakeAtlas(){w.bakedRotation=B.rotation?[...B.rotation]:[0,0,0];let N=s.directionalLight?.direction??[.4,-.7,.59],X=Eo(N,w.bakedRotation);Fn(w,X)},getPosition(){return B.position},getRotation(){return B.rotation},getScale(){return B.scale},getPolygons(){return bt.polygons}};return w.handle=bt,$e=w,b.set(T,w),h.add(w),Se(w),at(w,B.rotation),ct(),Qe(),w.receiveShadow&&(k(),Te()),bt}function pi(a){let f=!!s.autoCenter,S=s.strategies,T=s.seamBleed,j=s.textureLighting,B=s.directionalLight?.direction,F=s.shadow,$=Vs(a);s={...s,...$},x.options.current=s,Q(d,s);let Y=!!s.autoCenter;for(let We of h)at(We,We.handle.transform.rotation);let ae=a.strategies!==void 0&&!cs(a.strategies,S),ne=Object.prototype.hasOwnProperty.call(a,"seamBleed")&&$.seamBleed!==T;if(ae||ne)for(let We of h)Se(We);f!==Y&&ct();let K=a.textureLighting!==void 0&&j!==s.textureLighting,oe=s.directionalLight?.direction,J=a.directionalLight!==void 0&&!us(B,oe),Ie=s.shadow,$e=a.shadow!==void 0&&!ds(F,Ie),w=J||$e;if(K){if(!ae&&!ne)for(let We of h)Se(We);Qe(),k(),Te()}else w&&($e&&k(),Te());$e&&a.shadow?.lift!==F?.lift&&Qe()}function mi(){return s}function fi(){O(d);for(let a of h)de(a)}function hi(){let a=[];for(let f of h)a.push(f.handle);return a}function gi(a){let f=a;for(;f;){if(f instanceof HTMLElement){let S=b.get(f);if(S&&!S.disposed)return S.handle;if(f.classList.contains("polycss-mesh"))return null}f=f.parentElement}return null}function yi(){let a=Array.from(h);for(let f of a)try{f.handle.dispose()}catch{}u.parentNode&&u.parentNode.removeChild(u)}return{add:di,setOptions:pi,destroy:yi,host:e,camera:t,cameraEl:u,sceneElement:d,applyCamera:fi,getOptions:mi,meshes:hi,findMeshByElement:gi,previewBakedSolidLighting:se,commitBakedSolidLighting:In,clearBakedSolidLightingPreview:Hn}}import{buildPolyMeshTransform as Nf,buildPolySceneTransform as Uf,cssDistanceToWorld as Gf,cssDistanceToWorld as $f,cssPositionToWorld as Wf,cssPositionToWorld as jf,worldDistanceToCss as Yf,worldDistanceToCss as Xf,worldDirectionalLightToCss as Zf,worldDirectionToPolyCss as qf,worldPositionToPolyCss as Qf}from"@layoutit/polycss-core";import{createIsometricCamera as Ns}from"@layoutit/polycss-core";var Ul=32e3;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=Ns(n),o=`${e.perspective??Ul}px`;return{get state(){return t.state},update(r){t.update(r)},getStyle(r){return t.getStyle(r)},type:"perspective",perspectiveStyle:o}}function ft(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=Ns(n);return{get state(){return t.state},update(o){t.update(o)},getStyle(o){return t.getStyle(o)},type:"orthographic",perspectiveStyle:"none"}}var Gl=ft;import{BASE_TILE as $l}from"@layoutit/polycss-core";var Cn={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 tn(e){return e===!0?-1:e===!1?1:e}function kt(){let e=[],n=[],t=[];function o(i){return i==="change"?e:i==="start"?n:t}function r(i){if(e.length===0)return;let c={type:"change",camera:i()},l=e.slice();for(let u of l)try{u(c)}catch(d){console.error("[polycss] controls 'change' listener threw:",d)}}function s(i,c){let l=i==="start"?n:t;if(l.length===0)return;let u={type:i,camera:c()},d=l.slice();for(let x of d)try{x(u)}catch(h){console.error(`[polycss] controls '${i}' listener threw:`,h)}}return{changeListeners:e,startListeners:n,endListeners:t,listenerArray:o,emitChange:r,emitInteraction:s}}function Ot(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,s){let i=!1,c=null;return{onWheel:d=>{let x=n();if(!x.wheel||t())return;d.preventDefault();let h=d.deltaMode===1?16:d.deltaMode===2?100:1,b=d.deltaY*h;d.ctrlKey?b*=10:b*=3;let v=e.camera.state;if(x.dolly){let P=v.distance??0,y=Math.max(x.minDistance,Math.min(x.maxDistance,P+b*.05));e.camera.update({distance:y})}else{let P=Math.exp(-b*513e-6),y=v.zoom??1,C=Math.max(x.minZoom,Math.min(x.maxZoom,y*P));e.camera.update({zoom:C})}e.applyCamera(),i||(i=!0,s("start",o)),r(o),c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,i=!1,s("end",o)},150)},teardown:()=>{c!==null&&(clearTimeout(c),c=null),i=!1}}}function En(e,n,t,o,r,s,i){let c=null,l=0,u=b=>{if(c===null||o())return;let v=t();if(!v.animate){c=null;return}if(r())l=b;else{let P=Math.min(50,l?b-l:16.67);l=b;let y=v.animate.speed*(P/16.67),C=n.camera.state;if(v.animate.axis==="x"){let D=(((C.rotX??65)+y)%360+360)%360;n.camera.update({rotX:D})}else{let D=(((C.rotY??45)+y)%360+360)%360;n.camera.update({rotY:D})}n.applyCamera(),i(s)}c=e.requestAnimationFrame(u)};return{start:()=>{c!==null||!t().animate||o()||(l=0,c=e.requestAnimationFrame(u))},stop:()=>{c!==null&&(e.cancelAnimationFrame(c),c=null)},isRunning:()=>c!==null}}function wo(e,n={}){let t=Rt(Cn,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,s=null,i={x:0,y:0},c=!1,l=!1,u=kt(),d=Ot(e),{changeListeners:x,startListeners:h,endListeners:b,listenerArray:v,emitChange:P,emitInteraction:y}=u,C=En(r,e,()=>t,()=>l,()=>c,d,P),D=p=>{if(!(!t.drag||l)&&s===null&&p.isPrimary!==!1){p.preventDefault(),s=p.pointerId,i={x:p.clientX,y:p.clientY},o.style.cursor="grabbing";try{p.target.setPointerCapture(p.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),y("start",d)}},k=p=>{if(s===null||p.pointerId!==s||!t.drag||l)return;p.preventDefault();let E=p.clientX-i.x,M=p.clientY-i.y;i={x:p.clientX,y:p.clientY};let R=tn(t.invert),L=E/4*R,te=M/4*R,_=e.camera.state;if(p.shiftKey){let W=_.rotX??65,q=_.rotY??45,re=Math.max(.01,_.zoom??1),fe=Math.cos(W*Math.PI/180),de=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*$l,Ae=(E*Ce-M*pe/de)/be,Ue=-(E*pe+M*Ce/de)/be,qe=_.target??[0,0,0];e.camera.update({target:[qe[0]+Ae,qe[1]+Ue,qe[2]]})}else{let W=Math.max(0,Math.min(89,(_.rotX??65)-te)),q=(((_.rotY??45)-L)%360+360)%360;e.camera.update({rotX:W,rotY:q})}e.applyCamera(),P(d)},z=p=>{if(s===p.pointerId){s=null,o.style.cursor=t.drag&&!l?"grab":"";try{p.target.releasePointerCapture(p.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),y("end",d)}},I=Tn(e,()=>t,()=>l,d,P,y);function Z(){o.addEventListener("pointerdown",D),o.addEventListener("pointermove",k),o.addEventListener("pointerup",z),o.addEventListener("pointercancel",z),o.addEventListener("wheel",I.onWheel,{passive:!1}),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function Q(){o.removeEventListener("pointerdown",D),o.removeEventListener("pointermove",k),o.removeEventListener("pointerup",z),o.removeEventListener("pointercancel",z),o.removeEventListener("wheel",I.onWheel),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",I.teardown()}Z(),C.start();function O(p){let E=!!t.animate;t=Rt(t,p),!l&&s===null&&(o.style.cursor=t.drag?"grab":"");let M=!!t.animate;E&&!M?C.stop():!E&&M&&C.start()}function H(){l&&(l=!1,Z(),C.start())}function V(){l||(l=!0,Q(),C.stop(),s=null,c=!1,I.teardown())}function U(){V(),x.length=0,h.length=0,b.length=0}function A(p,E){let M=v(p);M.includes(E)||M.push(E)}function g(p,E){let M=v(p),R=M.indexOf(E);R>=0&&M.splice(R,1)}function m(p,E){return v(p).includes(E)}return{update:O,resume:H,pause:V,destroy:U,addEventListener:A,removeEventListener:g,hasEventListener:m}}import{BASE_TILE as Wl}from"@layoutit/polycss-core";function Mo(e,n={}){let t=Rt(Cn,n),o=e.host,r=o.ownerDocument?.defaultView??globalThis,s=null,i={x:0,y:0},c=!1,l=!1,u=!1,d={x:0,y:0},x=kt(),h=Ot(e),{changeListeners:b,startListeners:v,endListeners:P,listenerArray:y,emitChange:C,emitInteraction:D}=x,k=En(r,e,()=>t,()=>l,()=>c,h,C),z=_=>{if(!(!t.drag||l)&&s===null&&_.isPrimary!==!1){_.preventDefault(),s=_.pointerId,i={x:_.clientX,y:_.clientY},o.style.cursor="grabbing";try{_.target.setPointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),D("start",h)}},I=_=>{if(s===null||_.pointerId!==s||!t.drag||l)return;_.preventDefault();let W=_.clientX-i.x,q=_.clientY-i.y;i={x:_.clientX,y:_.clientY};let re=e.camera.state;if(_.shiftKey){let fe=tn(t.invert),de=W/4*fe,pe=q/4*fe,Ce=(re.rotX??65)-pe,be=(((re.rotY??45)-de)%360+360)%360;e.camera.update({rotX:Ce,rotY:be})}else{let fe=re.rotX??65,de=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(de*Math.PI/180),Ue=Math.sin(de*Math.PI/180),qe=pe*Wl,at=(W*Ue-q*Ae/be)/qe,yt=-(W*Ae+q*Ue/be)/qe,lt=re.target??[0,0,0];e.camera.update({target:[lt[0]+at,lt[1]+yt,lt[2]]})}e.applyCamera(),C(h)},Z=_=>{if(s===_.pointerId){s=null,o.style.cursor=t.drag&&!l?"grab":"";try{_.target.releasePointerCapture(_.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),D("end",h)}},Q=_=>{_.preventDefault()},O=_=>{_.button===2&&(u=!0,d={x:_.clientX,y:_.clientY},t.animate&&t.animate.pauseOnInteraction&&(c=!0),D("start",h))},H=_=>{if(!u||!t.drag)return;let W=_.clientX-d.x,q=_.clientY-d.y;d={x:_.clientX,y:_.clientY};let re=tn(t.invert),fe=W/4*re,de=q/4*re,pe=e.camera.state,Ce=(pe.rotX??65)-de,be=(((pe.rotY??45)-fe)%360+360)%360;e.camera.update({rotX:Ce,rotY:be}),e.applyCamera(),C(h)},V=_=>{_.button===2&&u&&(u=!1,D("end",h))},U=Tn(e,()=>t,()=>l,h,C,D);function A(){o.addEventListener("pointerdown",z),o.addEventListener("pointermove",I),o.addEventListener("pointerup",Z),o.addEventListener("pointercancel",Z),o.addEventListener("wheel",U.onWheel,{passive:!1}),o.addEventListener("contextmenu",Q),o.addEventListener("mousedown",O),o.addEventListener("mousemove",H),o.addEventListener("mouseup",V),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function g(){o.removeEventListener("pointerdown",z),o.removeEventListener("pointermove",I),o.removeEventListener("pointerup",Z),o.removeEventListener("pointercancel",Z),o.removeEventListener("wheel",U.onWheel),o.removeEventListener("contextmenu",Q),o.removeEventListener("mousedown",O),o.removeEventListener("mousemove",H),o.removeEventListener("mouseup",V),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",U.teardown()}A(),k.start();function m(_){let W=!!t.animate;t=Rt(t,_),!l&&s===null&&(o.style.cursor=t.drag?"grab":"");let q=!!t.animate;W&&!q?k.stop():!W&&q&&k.start()}function p(){l&&(l=!1,A(),k.start())}function E(){l||(l=!0,g(),k.stop(),s=null,c=!1,u=!1,U.teardown())}function M(){E(),b.length=0,v.length=0,P.length=0}function R(_,W){let q=y(_);q.includes(W)||q.push(W)}function L(_,W){let q=y(_),re=q.indexOf(W);re>=0&&q.splice(re,1)}function te(_,W){return y(_).includes(W)}return{update:m,resume:p,pause:E,destroy:M,addEventListener:R,removeEventListener:L,hasEventListener:te}}import{BASE_TILE as jl}from"@layoutit/polycss-core";var Yl={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 Us(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 Gs=new Set(["KeyW","ArrowUp"]),$s=new Set(["KeyS","ArrowDown"]),Ws=new Set(["KeyA","ArrowLeft"]),js=new Set(["KeyD","ArrowRight"]),Ys=new Set(["Space"]),Lo=new Set(["ControlLeft","ControlRight"]);function _o(e,n={}){let t=Us(Yl,n),o=e.host,r=e.cameraEl,s=o.ownerDocument??document,i=s.defaultView??globalThis,c=kt(),l=Ot(e),{changeListeners:u,startListeners:d,endListeners:x,listenerArray:h,emitChange:b,emitInteraction:v}=c,P=new Set,y=!1,C=!1,D=0,k=0,z=!1,I=[0,0,t.groundZ+t.eyeHeight];function Z(G,se){let ie=G*Math.PI/180,we=se*Math.PI/180;return[-Math.sin(ie)*Math.cos(we),-Math.sin(ie)*Math.sin(we),-Math.cos(ie)]}function Q(){let G=e.camera.perspectiveStyle,se=G==="none"?0:parseFloat(G);return(Number.isFinite(se)&&se>0?se:2e3)/jl}function O(){let G=e.camera.state,se=Z(G.rotX??90,G.rotY??0),ie=Q();return[I[0]+se[0]*ie,I[1]+se[1]*ie,I[2]+se[2]*ie]}function H(){let G=O();e.camera.update({target:G}),e.applyCamera()}function V(){let G=e.camera.state.target??[0,0,0];I=[G[0],G[1],t.groundZ+t.eyeHeight],H()}let U=()=>{if(!(!t.enabled||!t.lookEnabled||C||y))try{o.requestPointerLock()}catch{}},A=()=>{let G=s.pointerLockElement===o;G!==y&&(y=G,y?(z=!0,v("start",l)):z&&(z=!1,v("end",l)))},g=G=>{if(!y||!t.enabled||!t.lookEnabled||C)return;let se=G.movementX??0,ie=G.movementY??0;if(se===0&&ie===0)return;let we=e.camera.state,Ft=t.lookSensitivity,Ge=t.invertY?-1:1,Te=(((we.rotY??0)-se*Ft)%360+360)%360,ve=(we.rotX??90)-ie*Ft*Ge;ve<t.minPitch?ve=t.minPitch:ve>t.maxPitch&&(ve=t.maxPitch);let Oe=Z(ve,Te),De=Q(),Se=[I[0]+Oe[0]*De,I[1]+Oe[1]*De,I[2]+Oe[2]*De];e.camera.update({rotX:ve,rotY:Te,target:Se}),e.applyCamera(),b(l)},m=G=>Gs.has(G)||$s.has(G)||Ws.has(G)||js.has(G)||Ys.has(G)||Lo.has(G),p=G=>{if(!(!t.enabled||C)&&m(G.code)&&!(!y&&!t.moveEnabled)){if(Ys.has(G.code)){if(!t.jumpEnabled)return;G.preventDefault(),!P.has(G.code)&&D===0&&k===0&&(D=t.jumpVelocity),P.add(G.code);return}Lo.has(G.code)&&!t.crouchEnabled||!t.moveEnabled&&!Lo.has(G.code)||(G.preventDefault(),P.add(G.code))}},E=G=>{m(G.code)&&P.delete(G.code)},M=()=>{P.clear()},R=null,L=0,te=.05,_=G=>{if(R===null||C)return;let se=Math.min(te,L?(G-L)/1e3:.0167);if(L=G,t.enabled){let ie=!1,we=e.camera.state;if(t.moveEnabled){let ve=0,Oe=0;for(let De of P)Gs.has(De)?ve+=1:$s.has(De)?ve-=1:js.has(De)?Oe+=1:Ws.has(De)&&(Oe-=1);if(ve!==0||Oe!==0){let Se=(we.rotY??0)*Math.PI/180,Vt=-Math.cos(Se),Fn=-Math.sin(Se),Vn=-Math.sin(Se),Bn=Math.cos(Se),Qe=Math.hypot(ve,Oe)||1,cn=t.moveSpeed*se;I[0]+=(Vt*ve+Vn*Oe)/Qe*cn,I[1]+=(Fn*ve+Bn*Oe)/Qe*cn,ie=!0}}let Ge=t.crouchEnabled&&(P.has("ControlLeft")||P.has("ControlRight"))?t.crouchHeight:t.eyeHeight;t.jumpEnabled&&(D!==0||k>0)?(D-=t.gravity*se,k+=D*se,k<=0&&(k=0,D=0)):t.jumpEnabled||(k=0,D=0);let Te=t.groundZ+Ge+k;if(Math.abs(I[2]-Te)>1e-4&&(I[2]=Te,ie=!0),ie){let ve=O();e.camera.update({target:ve}),e.applyCamera(),b(l)}}R=i.requestAnimationFrame(_)};function W(){R!==null||C||(L=0,R=i.requestAnimationFrame(_))}function q(){R!==null&&(i.cancelAnimationFrame(R),R=null)}function re(){let se=r.ownerDocument?.defaultView?.getComputedStyle(r).perspective??"",ie=parseFloat(se),we=Number.isFinite(ie)&&ie>0?ie:2e3;r.style.setProperty("--polycss-fpv-perspective",`${we}px`),r.classList.add("polycss-fpv-host")}function fe(){r.classList.remove("polycss-fpv-host"),r.style.removeProperty("--polycss-fpv-perspective")}function de(){o.addEventListener("click",U),s.addEventListener("pointerlockchange",A),s.addEventListener("mousemove",g),i.addEventListener("keydown",p),i.addEventListener("keyup",E),i.addEventListener("blur",M),o.style.cursor=t.lookEnabled?"crosshair":"",re()}function pe(){if(o.removeEventListener("click",U),s.removeEventListener("pointerlockchange",A),s.removeEventListener("mousemove",g),i.removeEventListener("keydown",p),i.removeEventListener("keyup",E),i.removeEventListener("blur",M),o.style.cursor="",P.clear(),y)try{s.exitPointerLock()}catch{}fe()}V(),de(),W();function Ce(G){let se=t.eyeHeight,ie=t.groundZ;t=Us(t,G),C||(o.style.cursor=t.lookEnabled?"crosshair":""),(t.eyeHeight!==se||t.groundZ!==ie)&&(I[2]=t.groundZ+t.eyeHeight,H(),b(l))}function be(){C&&(C=!1,de(),W())}function Ae(){C||(C=!0,pe(),q(),z&&(z=!1,v("end",l)))}function Ue(){Ae(),u.length=0,d.length=0,x.length=0}function qe(){if(!(!t.enabled||!t.lookEnabled||C))try{o.requestPointerLock()}catch{}}function at(){if(y)try{s.exitPointerLock()}catch{}}function yt(){return y}function lt(G,se){let ie=h(G);ie.includes(se)||ie.push(se)}function On(G,se){let ie=h(G),we=ie.indexOf(se);we>=0&&ie.splice(we,1)}function Dn(G,se){return h(G).includes(se)}function In(){return[I[0],I[1],I[2]]}function Hn(G){I[0]=G[0],I[1]=G[1],I[2]=G[2],H(),b(l)}return{update:Ce,resume:be,pause:Ae,destroy:Ue,lock:qe,unlock:at,isLocked:yt,getOrigin:In,setOrigin:Hn,addEventListener:lt,removeEventListener:On,hasEventListener:Dn}}function Dt(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let r of o){let s=r.getBoundingClientRect();if(!(s.width<=0||s.height<=0)&&n>=s.left&&n<=s.right&&t>=s.top&&t<=s.bottom)return!0}return!1}function Xs(e,n,t,o){for(let r of e)if(!(o&&!o(r))&&Dt(r.element,n,t))return r;return null}function Ro(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(y){console.error("[polycss/createSelect] onChange threw:",y)}}function s(v){t=v,r()}function i(v){n.multiple?t.includes(v)||(t=[...t,v]):t=[v],r()}function c(v){t.includes(v)&&(t=t.filter(P=>P!==v),r())}function l(v){t.includes(v)?t=t.filter(P=>P!==v):n.multiple?t=[...t,v]:t=[v],r()}function u(){t.length!==0&&(t=[],r())}function d(v){return t.includes(v)}function x(v,P){return Xs(e.meshes(),v,P,y=>!y.element.classList.contains("polycss-transform-gizmo"))}let h=v=>{let P=v.target;if(P?.closest(".polycss-transform-gizmo"))return;let y=e.findMeshByElement(P)??x(v.clientX,v.clientY);if(!y){n.onPointerMissed&&n.onPointerMissed(v),n.clearOnMiss!==!1&&u();return}n.multiple&&(v.shiftKey||v.metaKey||v.ctrlKey)?l(y):t.length===1&&t[0]===y?u():s([y])};e.host.addEventListener("click",h);function b(){e.host.removeEventListener("click",h),o.clear()}return{get selected(){return t},set:s,add:i,remove:c,toggle:l,clear:u,has:d,destroy:b}}import{arrowPolygons as Xl,eulerXYZFromQuat as Zl,planePolygons as ql,quatFromAxisAngle as Ql,quatFromEulerXYZ as Kl,quatMultiply as Jl,ringQuadPolygons as ec,rotateVec3 as ko}from"@layoutit/polycss-core";var An="#ff3653",wn="#8adb00",Mn="#2c8fff",It=50,Zs=60,tc=.6,nc=.0125,oc=.15,rc=.04,sc=1,qs=.02,Oo=1.04,ic=.1,ac=.25,ei=1e-4,lc=.6,cc=.8,uc=1,et={0:1,1:0,2:2},Qs=[{cssAxis:0,sign:1,key:"x",color:An},{cssAxis:0,sign:-1,key:"-x",color:An},{cssAxis:1,sign:1,key:"y",color:wn},{cssAxis:1,sign:-1,key:"-y",color:wn},{cssAxis:2,sign:1,key:"z",color:Mn},{cssAxis:2,sign:-1,key:"-z",color:Mn}],Ks=[{cssAxis:0,key:"x",color:An},{cssAxis:1,key:"y",color:wn},{cssAxis:2,key:"z",color:Mn}],Js=[{perpAxis:2,axisA:0,axisB:1,key:"xy",color:Mn},{perpAxis:1,axisA:0,axisB:2,key:"xz",color:wn},{perpAxis:0,axisA:1,axisB:2,key:"yz",color:An}];function Do(e,n,t,o){let r=t*Math.PI/180,s=o*Math.PI/180,i=[0,0,0];i[e]=n;let c=i[0]*Math.cos(s)-i[1]*Math.sin(s),l=i[0]*Math.sin(s)+i[1]*Math.cos(s),u=i[2];return l*Math.sin(r)+u*Math.cos(r)<0}function dc(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),s=parseInt(t[3],16);return`rgba(${o}, ${r}, ${s}, ${n})`}function Ln(e,n){return!n||n<=0?e:Math.round(e/n)*n}function pc(e){if(e.length===0)return[0,0,0];let n=1/0,t=1/0,o=1/0,r=-1/0,s=-1/0,i=-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]>s&&(s=l[1]),l[2]<o&&(o=l[2]),l[2]>i&&(i=l[2]);return Number.isFinite(n)?[(n+r)/2,(t+s)/2,(o+i)/2]:[0,0,0]}function Io(e){if(e.length===0)return Zs;let n=1/0,t=1/0,o=1/0,r=-1/0,s=-1/0,i=-1/0;for(let l of e)for(let u of l.vertices)u[0]<n&&(n=u[0]),u[0]>r&&(r=u[0]),u[1]<t&&(t=u[1]),u[1]>s&&(s=u[1]),u[2]<o&&(o=u[2]),u[2]>i&&(i=u[2]);return Number.isFinite(n)?Math.max(r-n,s-t,i-o)*It*tc:Zs}function mc(e){let{cssAxis:n,sign:t,shaftLengthCss:o,wrapper:r,target:s,startClientX:i,startClientY:c,translationSnap:l,onAxisDelta:u,onMouseDown:d,onMouseUp:x,onDraggingChanged:h}=e,b=o,v=[0,0,0];v[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(${v[0]*b}px, ${v[1]*b}px, ${v[2]*b}px)`,r.appendChild(P);let y=r.getBoundingClientRect(),C=P.getBoundingClientRect();r.removeChild(P);let D=(C.left-y.left)/b,k=(C.top-y.top)/b,z=D*D+k*k;if(z<ei)return;d?.(),h?.(!0);let I=Q=>{let O=Q.clientX-i,H=Q.clientY-c,V=(O*D+H*k)/z;V=Ln(V,l),u(V,v)},Z=()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",Z),window.removeEventListener("pointercancel",Z);let Q=O=>{O.stopPropagation(),O.stopImmediatePropagation()};window.addEventListener("click",Q,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",Q,!0),0),x?.(),h?.(!1)};window.addEventListener("pointermove",I),window.addEventListener("pointerup",Z),window.addEventListener("pointercancel",Z)}function fc(e){let{axisA:n,axisB:t,probeDistanceCss:o,wrapper:r,startClientX:s,startClientY:i,translationSnap:c,onPlaneDelta:l,onMouseDown:u,onMouseUp:d,onDraggingChanged:x}=e,h=[0,0,0];h[n]=1;let b=[0,0,0];b[t]=1;function v(z){let I=r.ownerDocument.createElement("div");I.style.position="absolute",I.style.left="0",I.style.top="0",I.style.width="0",I.style.height="0",I.style.transform=`translate3d(${z[0]*o}px, ${z[1]*o}px, ${z[2]*o}px)`,r.appendChild(I);let Z=r.getBoundingClientRect(),Q=I.getBoundingClientRect();return r.removeChild(I),{x:(Q.left-Z.left)/o,y:(Q.top-Z.top)/o}}let P=v(h),y=v(b),C=P.x*y.y-y.x*P.y;if(Math.abs(C)<ei)return;u?.(),x?.(!0);let D=z=>{let I=z.clientX-s,Z=z.clientY-i,Q=(y.y*I-y.x*Z)/C,O=(-P.y*I+P.x*Z)/C;Q=Ln(Q,c),O=Ln(O,c),l(Q,O,h,b)},k=()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k);let z=I=>{I.stopPropagation(),I.stopImmediatePropagation()};window.addEventListener("click",z,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",z,!0),0),d?.(),x?.(!1)};window.addEventListener("pointermove",D),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k)}function hc(e){let{cssAxis:n,wrapper:t,target:o,startClientX:r,startClientY:s,rotationSnap:i,onAngleDelta:c,onMouseDown:l,onMouseUp:u,onDraggingChanged:d}=e,x=t.getBoundingClientRect(),h=x.left,b=x.top,v=Math.atan2(s-b,r-h),P=0;l?.(),d?.(!0);let y=D=>{let k=Math.atan2(D.clientY-b,D.clientX-h),z=k-v;z>Math.PI?z-=2*Math.PI:z<-Math.PI&&(z+=2*Math.PI),P+=z,v=k;let I=P*180/Math.PI;I=Ln(I,i),c(I)},C=()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",C),window.removeEventListener("pointercancel",C);let D=k=>{k.stopPropagation(),k.stopImmediatePropagation()};window.addEventListener("click",D,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",D,!0),0),u?.(),d?.(!1)};window.addEventListener("pointermove",y),window.addEventListener("pointerup",C),window.addEventListener("pointercancel",C)}function Ho(e,n={}){let t=null,o=n.mode??"translate",r=n.size??1,s={...n},i=new Map,c=null,l=null,u=[0,0,0];function d(){if(!t)return[0,0,0];let g=t.transform.position??[0,0,0],m=t.transform.rotation??[0,0,0],p=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,E=ko(u,m[0],m[1],m[2]);return[g[0]+p*E[0],g[1]+p*E[1],g[2]+p*E[2]]}function x(g){return l===g?uc:c===g?cc:lc}function h(){for(let[g,m]of i){let p=b(m.spec,x(g));m.handle.setPolygons(p,{recomputeAutoCenter:!1})}}function b(g,m){let E=Io(t?.polygons??[])*r,M=E/It,R=dc(g.color,m);if(g.kind==="arrow"){let _=e.camera.state,W=Do(g.cssAxis,g.sign,_.rotX??65,_.rotY??45);return Xl({axis:et[g.cssAxis],sign:g.sign,shaftLength:M,shaftHalfThickness:M*nc,headLength:M*oc,headHalfThickness:M*rc,color:R,shaft:!W})}if(g.kind==="plane"){let _=e.camera.state,W=_.rotX??65,q=_.rotY??45,re=et[g.perpAxis],fe=(re+1)%3,de=(re+2)%3,pe=et[fe],Ce=et[de],be=Do(pe,1,W,q)?-1:1,Ae=Do(Ce,1,W,q)?-1:1,Ue=M*ac;return ql({axis:re,size:M*ic,offset:[be*Ue,Ae*Ue],color:R})}let te=E*sc/It*Oo;return ec({axis:et[g.cssAxis],outerRadius:te,color:R})}function v(g){return g.kind==="arrow"?"polycss-transform-arrow":g.kind==="plane"?"polycss-transform-plane":"polycss-transform-ring"}function P(){if(o==="translate"){let g=Qs.map(p=>({kind:"arrow",key:p.key,cssAxis:p.cssAxis,sign:p.sign,color:p.color})),m=Js.map(p=>({kind:"plane",key:p.key,perpAxis:p.perpAxis,axisA:p.axisA,axisB:p.axisB,color:p.color}));return[...g,...m]}return o==="rotate"?Ks.map(g=>({kind:"ring",key:g.key,cssAxis:g.cssAxis,color:g.color})):[]}function y(){if(C(),!t)return;let g={x:s.showX!==!1,y:s.showY!==!1,z:s.showZ!==!1};function m(E){if(E.kind==="arrow"){let L=E.key.replace("-","")[0];return g[L]}if(E.kind==="ring")return g[E.key];let M=["x","y","z"][E.axisA],R=["x","y","z"][E.axisB];return g[M]&&g[R]}let p=d();for(let E of P()){if(!m(E))continue;let M=b(E,x(E.key)),R=e.add({polygons:M,objectUrls:[],warnings:[],dispose:()=>{}},{excludeFromAutoCenter:!0,id:`__poly-gizmo-${E.key}`,position:p}),L=v(E);if(R.element.classList.add("polycss-transform-gizmo",L,`${L}--${E.key}`),E.kind==="ring"){let te=(1-qs)/Oo,_=(1+qs)/Oo;R.element.style.setProperty("--ring-inner-ratio",`${te}`),R.element.style.setProperty("--ring-outer-ratio",`${_}`)}i.set(E.key,{handle:R,spec:E})}}function C(){for(let{handle:g}of i.values())g.remove();i.clear(),c=null,l=null}function D(){if(!t)return;let g=d();for(let{handle:m}of i.values())m.setTransform({position:g})}function k(){t&&(i.size===0?y():D())}function z(g){if(t=g,!g){u=[0,0,0],C();return}u=pc(g.polygons),C(),y()}function I(){z(null)}function Z(g){g!==o&&(o=g,t&&(C(),y()))}function Q(g,m,p){if(!t||!O)return;let E=p[g.cssAxis],M=et[g.cssAxis],R=m*E/It,L=O.slice();L[M]=O[M]+R,t.setTransform({position:L}),D(),s.onObjectChange?.({object:t,position:L}),s.onChange?.()}let O=null,H=null,V=g=>{if(!t||s.enabled===!1)return;let m={x:s.showX!==!1,y:s.showY!==!1,z:s.showZ!==!1};if(o==="translate"){for(let p of Js){let E=["x","y","z"][p.axisA],M=["x","y","z"][p.axisB];if(!m[E]||!m[M])continue;let R=i.get(p.key);if(R&&Dt(R.handle.element,g.clientX,g.clientY)){g.preventDefault(),g.stopPropagation(),l=p.key,h(),O=(t.transform.position??[0,0,0]).slice(),fc({axisA:p.axisA,axisB:p.axisB,probeDistanceCss:Io(t.polygons)*r,wrapper:R.handle.element,target:t,startClientX:g.clientX,startClientY:g.clientY,translationSnap:s.translationSnap??null,onPlaneDelta:(L,te,_,W)=>{if(!t||!O)return;let q=_[p.axisA],re=W[p.axisB],fe=et[p.axisA],de=et[p.axisB],pe=O.slice();pe[fe]+=L*q/It,pe[de]+=te*re/It,t.setTransform({position:pe}),D(),s.onObjectChange?.({object:t,position:pe}),s.onChange?.()},onMouseDown:s.onMouseDown,onMouseUp:s.onMouseUp,onDraggingChanged:L=>{L||(l=null,O=null,h()),s.onDraggingChanged?.(L)}});return}}for(let p of Qs){let E=p.key.replace("-","")[0];if(!m[E])continue;let M=i.get(p.key);if(M&&Dt(M.handle.element,g.clientX,g.clientY)){g.preventDefault(),g.stopPropagation(),l=p.key,h(),O=(t.transform.position??[0,0,0]).slice(),mc({cssAxis:p.cssAxis,sign:p.sign,shaftLengthCss:Io(t.polygons)*r,wrapper:M.handle.element,target:t,startClientX:g.clientX,startClientY:g.clientY,translationSnap:s.translationSnap??null,onAxisDelta:(R,L)=>Q(p,R,L),onMouseDown:s.onMouseDown,onMouseUp:s.onMouseUp,onDraggingChanged:R=>{R||(l=null,O=null,h()),s.onDraggingChanged?.(R)}});return}}}else if(o==="rotate")for(let p of Ks){if(!m[p.key])continue;let E=i.get(p.key);if(E&&Dt(E.handle.element,g.clientX,g.clientY)){g.preventDefault(),g.stopPropagation(),l=p.key,h(),H=(t.transform.rotation??[0,0,0]).slice(),O=(t.transform.position??[0,0,0]).slice(),hc({cssAxis:p.cssAxis,wrapper:E.handle.element,target:t,startClientX:g.clientX,startClientY:g.clientY,rotationSnap:s.rotationSnap??null,onAngleDelta:M=>{if(!t||!H||!O)return;let R=et[p.cssAxis],L=[0,0,0];L[R]=1;let te=-M*Math.PI/180,_=Kl(H),W=Ql(L,te),q=Zl(Jl(W,_)),re=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,fe=ko(u,H[0],H[1],H[2]),de=ko(u,q[0],q[1],q[2]),pe=[O[0]+re*(fe[0]-de[0]),O[1]+re*(fe[1]-de[1]),O[2]+re*(fe[2]-de[2])];t.setTransform({rotation:q,position:pe}),D(),s.onObjectChange?.({object:t,rotation:q,position:pe}),s.onChange?.()},onMouseDown:s.onMouseDown,onMouseUp:s.onMouseUp,onDraggingChanged:M=>{M||(l=null,H=null,O=null,h(),t?.rebakeAtlas()),s.onDraggingChanged?.(M)}});return}}};e.host.addEventListener("pointerdown",V,{capture:!0});let U=g=>{if(!t||l||s.enabled===!1)return;let m=null;for(let[p,E]of i)if(Dt(E.handle.element,g.clientX,g.clientY)){m=p;break}m!==c&&(c=m,h())};e.host.addEventListener("pointermove",U);function A(){e.host.removeEventListener("pointerdown",V,{capture:!0}),e.host.removeEventListener("pointermove",U),C()}return{attach:z,detach:I,setMode:Z,update:k,destroy:A}}var gc=typeof HTMLElement<"u"?HTMLElement:class{},yc=["perspective","rot-x","rot-y","zoom","directional-direction","directional-color","directional-intensity","ambient-color","ambient-intensity","texture-lighting","texture-quality","auto-center"];function Ne(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function bc(e){return e==="false"?!1:Ne(e)}function Fo(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 vc(e){if(e==="baked"||e==="dynamic")return e}function xc(e){return e==="auto"?"auto":Ne(e)}function Pc(e){return typeof e.getCamera=="function"}var Re=class extends gc{constructor(){super(...arguments);this._scene=null;this._implicitCamera=null}static get observedAttributes(){return[...yc]}getScene(){return this._scene}_findAncestorCamera(){let t=this.parentElement;for(;t;){if(Pc(t)){let o=t.getCamera();if(o)return o}t=t.parentElement}return null}_buildImplicitCamera(){let t=bc(this.getAttribute("perspective")),o=Ne(this.getAttribute("rot-x")),r=Ne(this.getAttribute("rot-y")),s=Ne(this.getAttribute("zoom")),i=Ne(this.getAttribute("distance")),c=Fo(this.getAttribute("target")),l={...o!==void 0?{rotX:o}:{},...r!==void 0?{rotY:r}:{},...s!==void 0?{zoom:s}:{},...i!==void 0?{distance:i}:{},...c!==void 0?{target:c}:{}};return t===!1?ft(l):t!==void 0?en({...l,perspective:t}):ft(l)}_readNonCameraOptions(){let t=this._readDirectionalLight(),o=this._readAmbientLight(),r={};r.textureLighting=vc(this.getAttribute("texture-lighting"))??"baked";let s=xc(this.getAttribute("texture-quality"));return s!==void 0&&(r.textureQuality=s),r.autoCenter=this.hasAttribute("auto-center"),t&&(r.directionalLight=t),o&&(r.ambientLight=o),r}_readDirectionalLight(){let t=Fo(this.getAttribute("directional-direction")),o=this.getAttribute("directional-color")||void 0,r=Ne(this.getAttribute("directional-intensity"));if(!t&&!o&&r===void 0)return;let s={direction:t??[.4,-.7,.59]};return o&&(s.color=o),r!==void 0&&(s.intensity=r),s}_readAmbientLight(){let t=this.getAttribute("ambient-color")||void 0,o=Ne(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=Ao(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 i=Ne(this.getAttribute("rot-x")),c=Ne(this.getAttribute("rot-y")),l=Ne(this.getAttribute("zoom")),u=Ne(this.getAttribute("distance")),d=Fo(this.getAttribute("target"));i!==void 0&&this._implicitCamera.update({rotX:i}),c!==void 0&&this._implicitCamera.update({rotY:c}),l!==void 0&&this._implicitCamera.update({zoom:l}),u!==void 0&&this._implicitCamera.update({distance:u}),d!==void 0&&this._implicitCamera.update({target:d}),this._scene.applyCamera();return}this._scene.setOptions(this._readNonCameraOptions())}}};import{computeSceneBbox as Sc,loadMesh as Cc}from"@layoutit/polycss-core";var Tc=typeof HTMLElement<"u"?HTMLElement:class{},Ec=["src","mtl","mesh-resolution","position","scale","rotation","auto-center","cast-shadow","receive-shadow","target-size","default-color","palette","include-objects","exclude-objects"];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 ti(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return nn(e)}}function Vo(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 Ac(e){let n=e.getAttribute("target-size"),t=e.getAttribute("default-color"),o=Vo(e.getAttribute("palette")),r=Vo(e.getAttribute("include-objects")),s=Vo(e.getAttribute("exclude-objects")),i=n!==null?parseFloat(n):NaN,c={};return Number.isFinite(i)&&(c.targetSize=i),t&&(c.defaultColor=t),o&&(c.palette=o),r&&(c.includeObjects=r),s&&(c.excludeObjects=s),Object.keys(c).length>0?c:void 0}function wc(e){return e.closest("poly-scene")??null}function Mc(e){if(e.length===0)return e;let n=Sc(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 s=i=>[i[0]-t,i[1]-o,i[2]-r];return e.map(i=>({...i,vertices:i.vertices.map(s),...i.textureTriangles?.length?{textureTriangles:i.textureTriangles.map(c=>({...c,vertices:c.vertices.map(s)}))}:null}))}var on=class extends Tc{constructor(){super(...arguments);this._handle=null;this._parseResult=null;this._loadToken=0}static get observedAttributes(){return[...Ec]}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:nn(this.getAttribute("position")),scale:ti(this.getAttribute("scale")),rotation:nn(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=wc(this);if(!o)return;let r=++this._loadToken,s=this.getAttribute("mtl")||void 0,c=this.getAttribute("mesh-resolution")==="lossless"?"lossless":void 0,l=Ac(this),u;try{let h=s||c!==void 0||l?{...s?{mtlUrl:s}:{},...c!==void 0?{meshResolution:c}:{},...l?{objOptions:l}:{}}:void 0;u=await Cc(t,h)}catch(h){this.dispatchEvent(new CustomEvent("polycss:error",{detail:h,bubbles:!0}));return}if(r!==this._loadToken){try{u.dispose()}catch{}return}let d=o.getScene();if(!d){try{u.dispose()}catch{}return}this.hasAttribute("auto-center")&&(u={...u,polygons:Mc(u.polygons)}),this._parseResult=u,this._handle=d.add(u,{position:nn(this.getAttribute("position")),scale:ti(this.getAttribute("scale")),rotation:nn(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 rn}from"@layoutit/polycss-core";var Lc=typeof HTMLElement<"u"?HTMLElement:class{},_c=["src","width","height","position","rotation","scale","allow","loading","referrerpolicy","sandbox","title"];function Bo(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 Rc(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Bo(e)}}function ni(e,n){if(e===null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}function kc(e){let n=e.closest("poly-scene");return n?n.querySelector(".polycss-scene"):null}function Oc(e,n,t,o,r){let s=typeof t=="number"?t:t?.[0]??1,i=typeof t=="number"?t:t?.[1]??1,c=typeof t=="number"?t:t?.[2]??1,l=s!==1||i!==1||c!==1,u=!!n&&(!!n[0]||!!n[1]||!!n[2]),d=(e?.[1]??0)*rn,x=(e?.[0]??0)*rn,h=(e?.[2]??0)*rn,b=[];return b.push(`translate3d(${d}px, ${x}px, ${h}px)`),u&&(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(${s}, ${i}, ${c})`),b.push(`translate(${-o/2}px, ${-r/2}px)`),b.join(" ")}var zo=class extends Lc{constructor(){super(...arguments);this._wrapper=null;this._iframe=null}static get observedAttributes(){return[..._c]}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 s=this.getAttribute(t);s===null?this._iframe.removeAttribute(t):this._iframe.setAttribute(t,s);return}this._applyGeometry()}}_mount(){let t=kc(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 s=o.createElement("iframe");s.style.display="block",s.style.border="0",s.style.background="#000";let i=this.getAttribute("src");i&&(s.src=i);let c=this.getAttribute("allow");c&&s.setAttribute("allow",c);for(let l of["loading","referrerpolicy","sandbox","title"]){let u=this.getAttribute(l);u!==null&&s.setAttribute(l,u)}r.appendChild(s),t.appendChild(r),this._wrapper=r,this._iframe=s,this._applyGeometry()}_applyGeometry(){if(!this._wrapper||!this._iframe)return;let t=ni(this.getAttribute("width"),16),o=ni(this.getAttribute("height"),9),r=t*rn,s=o*rn;this._iframe.style.width=`${r}px`,this._iframe.style.height=`${s}px`;let i=Bo(this.getAttribute("position")),c=Bo(this.getAttribute("rotation")),l=Rc(this.getAttribute("scale"));this._wrapper.style.transform=Oc(i,c,l,r,s)}_teardown(){this._wrapper?.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null,this._iframe=null}};var Dc=typeof HTMLElement<"u"?HTMLElement:class{},Ic=["vertices","color","texture","uvs","position","scale","rotation"];function oi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function No(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 Hc(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return No(e)}}function Fc(e){return e.closest("poly-scene")??null}var Uo=class extends Dc{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...Ic]}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=Fc(this);if(!t)return;let o=t.getScene();if(!o)return;let r=oi(this.getAttribute("vertices"));if(!r||!Array.isArray(r)||r.length<3)return;let s=this.getAttribute("color")||void 0,i=this.getAttribute("texture")||void 0,c=oi(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 d={polygons:[{vertices:r,...s!==void 0?{color:s}:{},...i!==void 0?{texture:i}:{},...c!==void 0?{uvs:c}:{},...Object.keys(l).length>0?{data:l}:{}}],objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(d,{position:No(this.getAttribute("position")),scale:Hc(this.getAttribute("scale")),rotation:No(this.getAttribute("rotation"))})}};function ee(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function _n(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 Ee(e){if(e!==null)return!(e==="false"||e==="0")}function Rn(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 kn(e){if(e==="x"||e==="y")return e}var Vc=typeof HTMLElement<"u"?HTMLElement:class{},Bc=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],Go=class extends Vc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Bc]}getControls(){return this._controls}_readAnimate(){let t=ee(this.getAttribute("animate-speed")),o=kn(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:Ee(r)}:{}}}_readOptions(){let t={},o=Ee(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Ee(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let s=ee(this.getAttribute("min-distance"));s!==void 0&&(t.minDistance=s);let i=ee(this.getAttribute("max-distance"));i!==void 0&&(t.maxDistance=i);let c=Rn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=ee(this.getAttribute("zoom-min")),u=ee(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),u!==void 0&&(t.maxZoom=u),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Re)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=wo(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 zc=typeof HTMLElement<"u"?HTMLElement:class{},Nc=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],$o=class extends zc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Nc]}_readAnimate(){let t=ee(this.getAttribute("animate-speed")),o=kn(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:Ee(r)}:{}}}_readOptions(){let t={},o=Ee(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let r=Ee(this.getAttribute("wheel"));r!==void 0&&(t.wheel=r),this.hasAttribute("dolly")&&(t.dolly=!0);let s=ee(this.getAttribute("min-distance"));s!==void 0&&(t.minDistance=s);let i=ee(this.getAttribute("max-distance"));i!==void 0&&(t.maxDistance=i);let c=Rn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=ee(this.getAttribute("zoom-min")),u=ee(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),u!==void 0&&(t.maxZoom=u),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Re)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=Mo(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 Uc=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"],Wo=class extends Uc{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Gc]}_readOptions(){let t={},o=Ee(this.getAttribute("enabled"));o!==void 0&&(t.enabled=o);let r=Ee(this.getAttribute("look-enabled"));r!==void 0&&(t.lookEnabled=r);let s=Ee(this.getAttribute("move-enabled"));s!==void 0&&(t.moveEnabled=s);let i=Ee(this.getAttribute("jump-enabled"));i!==void 0&&(t.jumpEnabled=i);let c=Ee(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=Ee(this.getAttribute("invert-y"));C!==void 0&&(t.invertY=C)}let u=ee(this.getAttribute("move-speed"));u!==void 0&&(t.moveSpeed=u);let d=ee(this.getAttribute("jump-velocity"));d!==void 0&&(t.jumpVelocity=d);let x=ee(this.getAttribute("gravity"));x!==void 0&&(t.gravity=x);let h=ee(this.getAttribute("eye-height"));h!==void 0&&(t.eyeHeight=h);let b=ee(this.getAttribute("crouch-height"));b!==void 0&&(t.crouchHeight=b);let v=ee(this.getAttribute("ground-z"));v!==void 0&&(t.groundZ=v);let P=ee(this.getAttribute("min-pitch"));P!==void 0&&(t.minPitch=P);let y=ee(this.getAttribute("max-pitch"));return y!==void 0&&(t.maxPitch=y),t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Re)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=_o(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 $c=typeof HTMLElement<"u"?HTMLElement:class{},Wc=["perspective","zoom","rot-x","rot-y","target","distance"],jo=class extends $c{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...Wc]}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:_n(this.getAttribute("target")),distance:ee(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 s=this._readOptions();if(t==="perspective"){let l=s.perspective!==void 0?`${s.perspective}px`:"32000px";this._wrapper.style.perspective=l;return}this._camera.update({rotX:s.rotX,rotY:s.rotY,zoom:s.zoom,target:s.target,distance:s.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var jc=typeof HTMLElement<"u"?HTMLElement:class{},Yc=["zoom","rot-x","rot-y","target","distance"],sn=class extends jc{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...Yc]}getCamera(){return this._camera}_readOptions(){return{zoom:ee(this.getAttribute("zoom")),rotX:ee(this.getAttribute("rot-x")),rotY:ee(this.getAttribute("rot-y")),target:_n(this.getAttribute("target")),distance:ee(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=ft(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 s=this._readOptions();s.zoom!==void 0&&this._camera.update({zoom:s.zoom}),s.rotX!==void 0&&this._camera.update({rotX:s.rotX}),s.rotY!==void 0&&this._camera.update({rotY:s.rotY}),s.target!==void 0&&this._camera.update({target:s.target}),s.distance!==void 0&&this._camera.update({distance:s.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var Yo=class extends sn{};var Xc=typeof HTMLElement<"u"?HTMLElement:class{},Zc=["mode","target","size","enabled"];function ri(e){if(e==="translate"||e==="rotate")return e}var Xo=class extends Xc{constructor(){super(...arguments);this._tc=null}static get observedAttributes(){return[...Zc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Re)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 on?r:null}_readOptions(){let t={},o=ri(this.getAttribute("mode"));o!==void 0&&(t.mode=o);let r=ee(this.getAttribute("size"));r!==void 0&&(t.size=r);let s=this.getAttribute("enabled");return s!==null&&(t.enabled=s!=="false"&&s!=="0"),t.onObjectChange=i=>{this.dispatchEvent(new CustomEvent("polycss:object-change",{bubbles:!0,detail:{position:i.position,rotation:i.rotation}}))},t}_attach(){if(this._tc)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let s=()=>{t.removeEventListener("polycss:scene-ready",s),this._attach()};t.addEventListener("polycss:scene-ready",s)}return}this._tc=Ho(o,this._readOptions());let r=this._findTargetMesh();if(r){let s=r.getMeshHandle();s&&this._tc.attach(s)}}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 s=ri(r);s&&this._tc.setMode(s)}else if(t==="target"){let s=this._findTargetMesh();this._tc.attach(s?s.getMeshHandle()??null:null)}}}};var qc=typeof HTMLElement<"u"?HTMLElement:class{},Qc=["multiple","clear-on-miss"],Zo=class extends qc{constructor(){super(...arguments);this._selection=null}static get observedAttributes(){return[...Qc]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Re)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=Ro(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())}};var qo={quad:0,clippedSolid:0,atlas:0,stableTriangle:0},Kc={polygonCount:0,mountedPolygonLeafCount:0,shadowLeafCount:0,surfaceLeafCounts:qo,bucketCount:0};function Jc(e){return typeof e=="number"?{polygonCount:e}:e??{}}function Ht(e,n){return e.querySelectorAll(n).length}function eu(e,n){let t=e;return typeof t.matches=="function"&&t.matches(n)}function tu(e,n){if(!n)return[e];let t=[];return eu(e,n)&&t.push(e),t.push(...Array.from(e.querySelectorAll(n))),t}function nu(e,n){let t=Jc(n);if(!e)return{...Kc,surfaceLeafCounts:{...qo},polygonCount:t.polygonCount??0};let o=tu(e,t.scopeSelector),r={...qo},s=0,i=0;for(let l of o)r.quad+=Ht(l,"b"),r.clippedSolid+=Ht(l,"i"),r.atlas+=Ht(l,"s"),r.stableTriangle+=Ht(l,"u"),s+=Ht(l,"q, .polycss-shadow-svg"),i+=Ht(l,".polycss-bucket");let c=r.quad+r.clippedSolid+r.atlas+r.stableTriangle;return{polygonCount:t.polygonCount??c,mountedPolygonLeafCount:c,shadowLeafCount:s,surfaceLeafCounts:r,bucketCount:i}}var ht=class extends Error{constructor(n,t,o){super(t),this.name="PolySceneSnapshotError",this.code=n,this.url=o,Object.setPrototypeOf(this,new.target.prototype)}},ou=`
519
+ `;import{BASE_TILE as Ll,buildPolyCameraSceneTransform as Rl,buildPolyMeshTransform as kl,worldDirectionToCss as _l,worldDirectionalLightToCss as Ol,worldPositionToCss as ym}from"@layoutit/polycss-core";var rn=Ll,Dl=.1;function sn(e){return _l(e)}function it(e){return Ol(e)}function An(e){return kl(e)}function ko(e,n=[0,0,0],t=1){return Rl(e.state,{autoCenterOffset:n,layoutScale:t})}function Il(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 Ss(e){let n=e.ownerDocument?.defaultView;if(!n)return 1;let t=1;for(let o=e;o;o=o.parentElement)t*=Il(n.getComputedStyle(o).getPropertyValue("zoom"));return Number.isFinite(t)&&t>0?t:1}function Cs(e,n){Math.abs(n-1)<1e-6?e.style.removeProperty("zoom"):e.style.setProperty("zoom",String(1/n))}function Ts(e){if(e.vertices.length<3)return null;let n=e.vertices[0],t=0,o=0,s=0;for(let P=1;P+1<e.vertices.length;P++){let f=e.vertices[P],b=e.vertices[P+1],x=f[1]-n[1],v=f[0]-n[0],y=f[2]-n[2],C=b[1]-n[1],O=b[0]-n[0],k=b[2]-n[2];t-=v*k-y*O,o-=y*C-x*k,s-=x*O-v*C}let r=Math.hypot(t,o,s);if(r<1e-9)return null;t/=r,o/=r,s/=r;let i=1/Dl,c=Math.round(t*i)/i,l=Math.round(o*i)/i,u=Math.round(s*i)/i,d=Math.hypot(c,l,u);return d<1e-9?null:{key:c+","+l+","+u,vec:[c/d,l/d,u/d]}}function Es(e,n){let t=e?.disable??[],o=n?.disable??[];if(t.length!==o.length)return!1;for(let s of t)if(!o.includes(s))return!1;return!0}function As(e,n){return e===n?!0:!e||!n?!1:e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}function ws(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 Rs,parseHexColor as Ms,parsePureColor as Hl}from"@layoutit/polycss-core";var Fl=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--clx","--cly","--clz"],Ht="--polycss-light-preview-active",Ls=`var(${Ht}, 0)`,zl="max(0, calc(var(--pnx, 0) * var(--plx, 0) + var(--pny, 0) * var(--ply, 0) + var(--pnz, 1) * var(--plz, 1)))",_o=(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))`,Bl=_o("--psr","--par","--plr"),Vl=_o("--psg","--pag","--plg"),Nl=_o("--psb","--pab","--plb");function ue(e,n,t){return e.style.getPropertyValue(n)===t?!1:(e.style.setProperty(n,t),!0)}function gt(e){for(let n of Fl)e.style.getPropertyValue(n)&&e.style.removeProperty(n)}function wn(e,n){let t=n.directionalLight?.direction??[.4,-.7,.59],o=sn(t),s=Math.hypot(o[0],o[1],o[2])||1,r=o[0]/s,i=o[1]/s,c=o[2]/s,l=Ms(n.directionalLight?.color??"#ffffff")?.rgb??[255,255,255],u=Ms(n.ambientLight?.color??"#ffffff")?.rgb??[255,255,255],d=n.directionalLight?.intensity??1,P=n.ambientLight?.intensity??.4,f=v=>(v/255).toFixed(4);ue(e,"--plx",r.toFixed(2)),ue(e,"--ply",i.toFixed(2)),ue(e,"--plz",c.toFixed(2)),ue(e,"--plr",f(l[0])),ue(e,"--plg",f(l[1])),ue(e,"--plb",f(l[2])),ue(e,"--pli",d.toFixed(4)),ue(e,"--par",f(u[0])),ue(e,"--pag",f(u[1])),ue(e,"--pab",f(u[2])),ue(e,"--pai",P.toFixed(4));let b=c,x=Math.sign(b||1)*Math.max(Math.abs(b),.01);ue(e,"--clx",r.toFixed(2)),ue(e,"--cly",i.toFixed(2)),ue(e,"--clz",x.toFixed(2))}function ks(e,n){let t=n.textureLighting==="dynamic";if(e.dataset.polycssLighting=n.textureLighting??"baked",!t){gt(e);return}wn(e,n)}function ht(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 _s(e,n){let t=Rs(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 Oo(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=t.textureLighting??"baked",s={directionalLight:it(t.directionalLight),ambientLight:t.ambientLight,textureLighting:o,textureQuality:t.textureQuality,seamBleed:t.seamBleed,strategies:t.strategies},r=ao(e.plan,n,e.plan.normal,o,s);return _t(e.element,r,o),o==="baked"&&$l(e.element),!0}function jl(e){let n=Hl(e)??{rgb:[255,255,255],alpha:1},[t,o,s]=n.rgb,r=(c,l)=>`calc(${c} * (1 - ${Ls}) + var(${l}, ${c}) * ${Ls})`,i=n.alpha<1?` / ${n.alpha}`:"";return`rgb(${r(t,"--polycss-preview-r")} ${r(o,"--polycss-preview-g")} ${r(s,"--polycss-preview-b")}${i})`}function Os(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=e.element,s=e.plan.normal,r=Rs(n.color??"#cccccc"),i=!1;return i=ue(o,"--pnx",s[0].toFixed(4))||i,i=ue(o,"--pny",s[1].toFixed(4))||i,i=ue(o,"--pnz",s[2].toFixed(4))||i,i=ue(o,"--psr",(r.r/255).toFixed(4))||i,i=ue(o,"--psg",(r.g/255).toFixed(4))||i,i=ue(o,"--psb",(r.b/255).toFixed(4))||i,i=ue(o,"--plam",zl)||i,i=ue(o,"--polycss-preview-r",Bl)||i,i=ue(o,"--polycss-preview-g",Vl)||i,i=ue(o,"--polycss-preview-b",Nl)||i,i=ue(o,"--polycss-paint",jl(t))||i,o.style.getPropertyValue("color")&&(o.style.removeProperty("color"),i=!0),i}function $l(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 Ul="http://www.w3.org/2000/svg",Mn=class{constructor(){this.groundSvg=null;this.groundVisible=!1;this.currentGroundCssZ=null;this.shadowRoot=null}};function Ds(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 s=t.firstChild;s?t.insertBefore(o,s):t.appendChild(o)}return o}function Is(e){e.groundSvg?.parentNode&&e.groundSvg.parentNode.removeChild(e.groundSvg),e.groundSvg=null,e.groundVisible=!1}function Hs(e){e.groundSvg&&e.groundVisible&&(e.groundSvg.style.display="none",e.groundVisible=!1)}function Fs(e,n,t,o){let s=[],r=e.firstChild;for(let i=0;i<t;i++){let c=r;c&&c.tagName==="path"?r=c.nextSibling:(c=n.createElementNS(Ul,"path"),c.setAttribute("fill-rule","nonzero"),o&&(c.setAttribute("stroke-width","0.5"),c.setAttribute("stroke-linejoin","round")),e.insertBefore(c,r)),s.push(c)}for(;r;){let i=r.nextSibling;e.removeChild(r),r=i}return s}function zs(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 Mn,receiverShadowCache:new Map,receiverShadowCacheKey:new Map,casterItemsCache:new Map,casterItemsCacheKey:new Map}}import{buildSharedEdgeMap as Wl,computeReceiverShadowFaces as Gl,meshScaleVec3 as Us,prepareCasterEdgeOwners as Yl,prepareCasterPolyItems as Xl,prepareReceiverFacePlanes as ql}from"@layoutit/polycss-core";function Bs(e){for(let n of e)n.svg&&n.svg.parentNode&&n.svg.parentNode.removeChild(n.svg),n.svg=null}function Vs(e,n){if(n){let t=e.receiverShadowCache.get(n);t&&Bs(t),e.receiverShadowCache.delete(n),e.receiverShadowCacheKey.delete(n)}else{for(let t of e.receiverShadowCache.values())Bs(t);e.receiverShadowCache.clear(),e.receiverShadowCacheKey.clear()}}function Ns(e,n){n?(e.casterItemsCache.delete(n),e.casterItemsCacheKey.delete(n)):(e.casterItemsCache.clear(),e.casterItemsCacheKey.clear())}function js(e){Is(e.shadowSvgState),$s(e)}function Do(e){return e.handle.id??e.autoMeshId}var Zl="http://www.w3.org/2000/svg",Ln=new WeakMap,Ws=new WeakMap,Gs=new WeakMap,Ys=new WeakMap,Xs=new WeakMap;function qs(e){let n=Ln.get(e);return n||(n=new Map,Ln.set(e,n)),n}function Io(e){let n=Ln.get(e);if(n){for(let t of n.values())t.svg&&t.svg.parentNode&&t.svg.parentNode.removeChild(t.svg);n.clear(),Ln.delete(e)}}function $s(e){for(let n of e.meshes)Io(n)}function Zs(e,n,t,o,s,r,i,c,l,u){let d=e.options.current,{receiverShadowCache:P,receiverShadowCacheKey:f,casterItemsCache:b,casterItemsCacheKey:x}=e,v=o.handle.transform.position??[0,0,0],y=o.handle.transform.rotation??[0,0,0],C=o.polygons.some(A=>A.texture!==void 0),O=Us(o.handle.transform.scale),k=o.bboxCenterCss,j=d.shadow?.lift??.001,D=`${o.polygons.length}|${s.size}|${v.join(",")}|${y.join(",")}|${O.join(",")}|${k?k.join(","):"n"}|${j}`,Z=P.get(o);if(Z===void 0||f.get(o)!==D){Z=ql(o.polygons,v,o.handle.transform.scale,s,j,y),P.set(o,Z),f.set(o,D);let A=qs(o);for(let h of A.values())h.svg&&h.svg.parentNode&&h.svg.parentNode.removeChild(h.svg);A.clear()}let J=[];for(let A of n){let h=A.handle.transform.position??[0,0,0],E=A.handle.transform.rotation??[0,0,0],p=Us(A.handle.transform.scale),g=A.bboxCenterCss,L=`${A.polygons.length}|${h.join(",")}|${E.join(",")}|${p.join(",")}|${g?g.join(","):"n"}`,R=b.get(A);if(R===void 0||x.get(A)!==L){let T=t.get(A),G=new Set;for(let q of A.rendered)q.plan&&!T.has(q.polygonIndex)&&G.add(q.polygonIndex);R=Xl(A.polygons,h,A.handle.transform.scale,q=>G.has(q),E),b.set(A,R),x.set(A,L)}let H;if(A===o){let T=Ws.get(A);(T===void 0||Gs.get(A)!==A.polygons)&&(T=Wl(A.polygons),Ws.set(A,T),Gs.set(A,A.polygons)),H=T}let Q;if(A!==o&&A.polygons.length>=40){let T=Ys.get(A);(T===void 0||Xs.get(A)!==L)&&(T=Yl(A.polygons,h,A.handle.transform.scale,E),Ys.set(A,T),Xs.set(A,L)),Q=T}J.push({id:A,items:R,selfShadowEdgeMap:H,edgeOwners:Q,casterPolygonCount:A.polygons.length})}let _={rotX:e.camera.state.rotX,rotY:e.camera.state.rotY,meshRotation:o.handle.transform.rotation},V=Gl({receiverPlanes:Z,receiverPolygons:o.polygons,receiverHasTexture:C,casters:J,lightDir:r,cameraRot:_,ambientLight:d.ambientLight,directionalLight:d.directionalLight,shadow:{color:d.shadow?.color,opacity:u,maxExtend:d.shadow?.maxExtend}}),B=qs(o),z=new Set;for(let A of V){z.add(A.faceIndex);let h=B.get(A.faceIndex);h||(h={svg:null,visible:!1,width:-1,height:-1,matrixCss:""},B.set(A.faceIndex,h));let E=h.svg;E?(h.visible||(E.style.display="block"),(h.width!==A.width||h.height!==A.height)&&(E.setAttribute("width",String(A.width)),E.setAttribute("height",String(A.height)),E.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),h.width=A.width,h.height=A.height),h.matrixCss!==A.matrixCss&&(E.style.transform=A.matrixCss,h.matrixCss=A.matrixCss)):(E=e.doc.createElementNS(Zl,"svg"),E.setAttribute("class","polycss-shadow polycss-shadow-svg polycss-shadow-receiver"),d.debugShadowAttrs&&(E.setAttribute("data-poly-shadow-type","receiver"),E.setAttribute("data-poly-shadow-receiver",Do(o)),E.setAttribute("data-poly-shadow-receiver-face",String(A.faceIndex)),E.setAttribute("data-poly-shadow-receiver-polys",JSON.stringify(A.memberPolyIndices))),E.setAttribute("width",String(A.width)),E.setAttribute("height",String(A.height)),E.setAttribute("viewBox",`0 0 ${A.width} ${A.height}`),E.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}`),Ds(e.shadowSvgState,e.doc,e.sceneEl).appendChild(E),h.svg=E,h.width=A.width,h.height=A.height,h.matrixCss=A.matrixCss),h.visible=!0;let p=Fs(E,e.doc,A.paths.length,!0),g=A.opacity.toFixed(4),L=[],R=!!d.debugShadowAttrs;for(let H=0;H<A.paths.length;H++){let Q=A.paths[H],T=R?Do(Q.casterId):"";R&&L.push(T);let G=p[H];if(G.setAttribute("d",Q.d),G.getAttribute("fill")!==A.fill&&G.setAttribute("fill",A.fill),G.getAttribute("stroke")!==A.fill&&G.setAttribute("stroke",A.fill),G.getAttribute("opacity")!==g&&G.setAttribute("opacity",g),R){G.getAttribute("data-poly-shadow-caster")!==T&&G.setAttribute("data-poly-shadow-caster",T);let q=JSON.stringify(Q.casterPolygonIndices);G.getAttribute("data-poly-shadow-caster-polys")!==q&&G.setAttribute("data-poly-shadow-caster-polys",q)}}if(R){let H=L.join(" ");E.getAttribute("data-poly-shadow-casters")!==H&&E.setAttribute("data-poly-shadow-casters",H)}}for(let[A,h]of B)z.has(A)||h.svg&&h.visible&&(h.svg.style.display="none",h.visible=!1)}var Qs=Symbol.for("polycss.animation.triangleFrameTarget");var lc=750;var Rn=Promise.resolve();function ei(e){return!Object.prototype.hasOwnProperty.call(e,"seamBleed")||e.seamBleed!==void 0?e:{...e,seamBleed:ni}}var cc={key:"non-cullable",normal:[1,1,0]};function ti(){return[cc]}function zo(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&&Ro(e.ownerDocument),e.ownerDocument?.defaultView&&e.ownerDocument.defaultView.getComputedStyle(e).position==="static"&&(e.style.position="relative");let{camera:o,...s}=n,r=ei({seamBleed:ni,...s}),i=Ss(e),c=[0,0,0],l=e.ownerDocument??document,u=l.createElement("div");u.className="polycss-camera",Z(u,r),e.appendChild(u);let d=l.createElement("div");d.className="polycss-scene",d.setAttribute("aria-hidden","true"),J(d,r),u.appendChild(d);let P=zs({host:e,doc:l,cameraEl:u,sceneEl:d,camera:t,layoutScale:i,options:r}),f=P.meshes,b=new WeakMap,x=P.shadowSvgState,v=()=>Hs(x),y=()=>js(P),C=null;function O(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,w=Math.round(a[1]/m*100)/100,U=Math.round(a[2]/m*100)/100;return`${S}|${w}|${U}`}function k(){C=null}let j=a=>Vs(P,a),D=a=>Ns(P,a);function Z(a,m){let S=nc(t);a.style.perspective=S.appliedPerspectiveStyle,a.dataset.polycssCameraProjection=S.projection,a.dataset.polycssCameraPerspective=S.perspectiveStyle,a.dataset.polycssCameraAppliedPerspective=S.appliedPerspectiveStyle,a.dataset.polycssCameraZoom=String(S.state.zoom),a.dataset.polycssCameraDistance=String(S.state.distance),a.dataset.polycssCameraRotX=String(S.state.rotX),a.dataset.polycssCameraRotY=String(S.state.rotY),a.dataset.polycssCameraTarget=S.state.target.join(",")}function J(a,m){Cs(a,i),a.style.transform=ko(t,c,i),ks(a,m)}function _(a){a.style.transform=ko(t,c,i)}function V(a){a.textureReadyPromise=Rn,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 B(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 z(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,y()}function h(a,m){m?.();for(let S of a){try{S.dispose()}catch{}S.element.parentNode&&S.element.parentNode.removeChild(S.element)}}function E(a,m,S,w){a.rendered=m,a.renderedByPolygonIndex=[];for(let U of m)a.renderedByPolygonIndex[U.polygonIndex]=U;a.disposeAtlas=S,a.textureReadyPromise=w?w.catch(()=>{}):Rn,a.solidLightingPreviewPrepared=!1}function p(a,m){let S=a.renderedByPolygonIndex[m];return S?.polygonIndex===m?S:void 0}function g(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 L(a,m){let S=a.polygons[m.polygonIndex];return a.stableDom&&S?Js(S):m.plan?.normal??(S?Js(S):null)}function R(a){if(!q(a))return a.rendered;let m=H(a);return a.rendered.filter(S=>Q(a,S,Ho,m))}function H(a){return{rotX:t.state.rotX,rotY:t.state.rotY,meshRotation:a.handle.transform.rotation}}function Q(a,m,S=Ho,w=H(a)){let U=L(a,m);return U===null||sc(U,w,S)}function T(a){if(a.excludeFromAutoCenter){a.cameraCullGroups=[];return}let m=new Map;for(let S of a.rendered){let w=L(a,S);if(!w)continue;if(!oc(w)){a.cameraCullGroups=ti();return}let U=Kl(w);if(!m.has(U)&&(m.set(U,w),m.size>Ql)){a.cameraCullGroups=ti();return}}a.cameraCullGroups=Array.from(m,([S,w])=>({key:S,normal:w}))}function G(a){return q(a)?Jl(a.cameraCullGroups,H(a)):"all"}function q(a){return!a.excludeFromAutoCenter&&rc(a.cameraCullGroups)}function re(a){a.cameraCullSignature=q(a)?G(a):"all"}function fe(a,m){let S=new Array(a.rendered.length),w=!1,U=H(a);for(let K=0;K<a.rendered.length;K+=1){let oe=a.rendered[K],ee=Q(a,oe,m,U);S[K]=ee}let N=null,I=null,W=()=>{if(!(!N||!I)){if(N===I)N.remove();else{let K=l.createRange();K.setStartBefore(N),K.setEndAfter(I),K.deleteContents(),K.detach()}N=null,I=null,w=!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||(W(),N=oe.element),I=oe.element):W()}W();let Y=K=>{for(let oe=K;oe<a.rendered.length;oe+=1){let ee=a.rendered[oe].element;if(ee.parentNode===a.wrapper)return ee}return B(a)},ae=-1,ne=K=>{if(ae<0)return;let oe=l.createDocumentFragment();for(let ee=ae;ee<K;ee+=1){let Le=a.rendered[ee];be(a,Le),oe.appendChild(Le.element)}z(a,oe,Y(K)),ae=-1,w=!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),w}function de(a,m=!1){if(a.voxelRenderer){m?a.voxelRenderer.render(H(a)):a.voxelRenderer.syncCamera(H(a)),a.cameraCullSignature="voxel-direct";return}if(!q(a)){let U=a.cameraCullSignature!=="all";a.cameraCullSignature="all",U&&xe(a);return}if(a.hasBuckets){pe(a,m);return}let S=G(a);if(!m&&S===a.cameraCullSignature)return;let w=fe(a,Ho);a.cameraCullSignature=S,w&&Ue(a)}function pe(a,m=!1){let S=q(a)?G(a):"all";!m&&S===a.cameraCullSignature||xe(a)}function Ce(a,m){return L(a,m)}function be(a,m){if(r.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){g(a),a.hasBuckets=!1;let m=a.skipBucketNormalCleanupOnce;a.skipBucketNormalCleanupOnce=!1;let S=l.createDocumentFragment(),w=r.textureLighting==="dynamic"&&!a.stableDom,U=new Map,N=[];for(let I of R(a)){let W=a.polygons[I.polygonIndex],Y=w&&W?Ts(W):null;if(!Y){N.push(I);continue}let ae=Y.key+"|"+(W.color??""),ne=U.get(ae);ne||(ne={vec:Y.vec,items:[]},U.set(ae,ne)),ne.items.push(I)}for(let I of N)be(a,I),S.appendChild(I.element);for(let I of U.values()){if(I.items.length<2){for(let Y of I.items)be(a,Y),S.appendChild(Y.element);continue}let W=l.createElement("div");W.className="polycss-bucket",a.hasBuckets=!0,W.style.setProperty("--pnx",String(I.vec[0])),W.style.setProperty("--pny",String(I.vec[1])),W.style.setProperty("--pnz",String(I.vec[2]));for(let Y of I.items)W.appendChild(Y.element),(!m||Y.kind==="triangle")&&(Y.element.style.removeProperty("--pnx"),Y.element.style.removeProperty("--pny"),Y.element.style.removeProperty("--pnz"));S.appendChild(W)}z(a,S,B(a)),re(a)}function $e(){return new Promise(a=>setTimeout(a,0))}async function qe(a,m){if(r.textureLighting==="dynamic"&&!a.stableDom)return Ae(a),!m();g(a);let w=l.createDocumentFragment(),U=B(a),N=0;for(let I of R(a)){if(m())return!1;be(a,I),w.appendChild(I.element),N++,N%lc===0&&(z(a,w,U),w=l.createDocumentFragment(),await $e())}return w.childNodes.length>0&&z(a,w,U),re(a),!m()}function at(a,m){let S=r.textureLighting==="dynamic",w=r.directionalLight?.direction,U=m&&(m[0]!==0||m[1]!==0||m[2]!==0);if(!S||!U||!w){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 N=Fo(w,m),I=sn(N),W=Math.hypot(I[0],I[1],I[2])||1,Y=(I[0]/W).toFixed(2),ae=(I[1]/W).toFixed(2),ne=(I[2]/W).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 vt(a){let m=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let w=a.polygons[S.polygonIndex];w&&(m=Oo(S,w,r)||m)}return a.solidLightingPreviewPrepared=!1,a.solidLightingPreviewActive=!1,m}function lt(a){if((r.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 w=a.polygons[S.polygonIndex];w&&(Os(S,w,S.plan.shadedColor),m=!0)}return a.solidLightingPreviewPrepared=m,m}function Un(a){return(r.textureLighting??"baked")!=="baked"||!a.solidLightingPreviewPrepared&&!lt(a)?!1:(a.solidLightingPreviewActive=!0,!0)}function Wn(a){return a.kind==="atlas"||!!a.plan?.texture}function Gn(){if((r.textureLighting??"baked")!=="baked")return!1;let a=!1;for(let m of f)a=vt(m)||a,m.rendered.some(Wn)&&(Ut(m),a=!0);d.style.removeProperty(Ht);for(let m of f)gt(m.wrapper),m.solidLightingPreviewActive=!1;return gt(d),a}function Yn(){d.style.removeProperty(Ht);for(let a of f)a.solidLightingPreviewActive&&(vt(a),gt(a.wrapper));(r.textureLighting??"baked")!=="dynamic"&&(gt(d),k(),Te())}function $(a,m){let S=a.handle.transform.rotation,w=m.directionalLight?.direction??r.directionalLight?.direction;if(!(S&&(S[0]!==0||S[1]!==0||S[2]!==0))||!w){gt(a.wrapper);return}let N=Fo(w,S);wn(a.wrapper,{...r,...m,directionalLight:{...r.directionalLight,...m.directionalLight,direction:N}})}function se(a){if((r.textureLighting??"baked")!=="baked")return!1;wn(d,{...r,...a}),!a.skipShadows&&a.directionalLight?.direction&&Te(a.directionalLight.direction);let m=!1;for(let S of f)$(S,a),m=Un(S)||m;return m?ue(d,Ht,"1"):d.style.removeProperty(Ht),m}function ie(a,m,S){let w=a.polygons[m];if(!w)return!1;let U=p(a,m);if(!U)return!1;let N=r.textureLighting??"baked";return N==="dynamic"?(_s(U.element,S),!0):N==="baked"?Oo(U,w,r):!1}function we(a,m){let S=a.polygons[m];if(!S)return!1;let w=p(a,m);return w?(ye(w.element,S,m),!0):!1}function $t(a,m,S){return!(S.length===0||!S.every(w=>w==="color"||w==="data")||S.includes("color")&&!ie(a,m,a.polygons[m]?.color)||S.includes("data")&&!we(a,m))}function Ue(a){k(),Te()}function Te(a){let m=[];for(let ee of f)!ee.disposed&&ee.castShadow&&m.push(ee);if(m.length===0){y(),C=null;return}let S=r.shadow?.color??"#000000",w=r.shadow?.opacity??.25,U=ac(S)?.rgb??[0,0,0],N=U[0],I=U[1],W=U[2],Y=a??r.directionalLight?.direction??[.4,-.7,.59],ae=sn(Y),ne=O(ae);if(ne!==null&&ne===C)return;let K=new Map;for(let ee of m)K.set(ee,Ks(ee.polygons,{normalTolerance:.1,distanceTolerance:.5,overlapFraction:.95,preserveDoubleSidedBackfaces:!1}));let oe=new Map;for(let ee of f)ee.disposed||!ee.receiveShadow||oe.set(ee,new Set);v();for(let ee of f)ee.disposed||!ee.receiveShadow||Zs(P,m,K,ee,oe.get(ee)??new Set,ae,N,I,W,w);C=ne}function xe(a){if(a.voxelRenderer){a.voxelRenderer.render(H(a)),a.cameraCullSignature="voxel-direct";return}A(a),Ae(a),Ue(a)}function Ie(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 w=m[0]/S,U=m[1]/S,N=m[2]/S,I=K=>Math.round(K*1e3)/1e3,W=`${I(w)},${I(U)},${I(N)}`,Y=a.lightOcclusionCache;if(Y&&Y.polygons===a.polygons&&Y.lightDirKey===W)return Y.occluded;let ae=Y&&Y.polygons===a.polygons?Y.dedupDropped:Ks(a.polygons,{normalTolerance:.1,distanceTolerance:.12,overlapFraction:.98,preserveDoubleSidedBackfaces:!1}),ne=tc(a.polygons,[w,U,N],ae);return a.lightOcclusionCache={polygons:a.polygons,lightDirKey:W,occluded:ne,dedupDropped:ae},ne}function He(a){return!!a.voxelSource&&r.textureLighting!=="dynamic"&&!a.stableDom&&!a.castShadow}function Se(a,m){V(a);let S=r.directionalLight,w=m?{...S,direction:m}:S,U=it(w),N=void 0;if(He(a)){let Y=Ps({doc:l,wrapper:a.wrapper,polygons:a.parseResult.polygons,directionalLight:U,ambientLight:r.ambientLight});if(Y){a.voxelRenderer=Y,Y.render(H(a)),a.cameraCullSignature="voxel-direct",a.textureReadyPromise=Rn;return}}let I={doc:l,directionalLight:U,ambientLight:r.ambientLight,textureLighting:r.textureLighting,textureQuality:r.textureQuality,textureLeafSizing:r.textureLeafSizing,textureImageRendering:r.textureImageRendering,textureBackend:r.textureBackend,textureProjection:r.textureProjection,seamBleed:r.seamBleed,strategies:r.strategies,lightOccludedPolyIndices:N},W=a.stableDom?(()=>{let Y=mt(a.polygons,I);return ht(a.wrapper,Y),It(a.polygons,{...I,solidPaintDefaults:Y})??ft(a.polygons,{...I,solidPaintDefaults:Y})})():ft(a.polygons,{...I,computeSolidPaintDefaults:!0,skipDynamicNormalVars:r.textureLighting==="dynamic"});a.stableDom||ht(a.wrapper,W.solidPaintDefaults??{}),E(a,W.rendered,W.dispose,W.pagesReady),a.skipBucketNormalCleanupOnce=r.textureLighting==="dynamic"&&!a.stableDom,T(a),Ae(a),Ue(a)}function Ut(a,m){if(a.rendered.length===0||a.voxelRenderer||a.stableDom||He(a)){Se(a,m);return}if(a.rendered[0]?.element.parentNode===null){Se(a,m);return}let S=r.directionalLight,w=m?{...S,direction:m}:S,U=it(w),N={doc:l,directionalLight:U,ambientLight:r.ambientLight,textureLighting:r.textureLighting,textureQuality:r.textureQuality,textureLeafSizing:r.textureLeafSizing,textureImageRendering:r.textureImageRendering,textureBackend:r.textureBackend,textureProjection:r.textureProjection,seamBleed:r.seamBleed,strategies:r.strategies,computeSolidPaintDefaults:!0,skipDynamicNormalVars:r.textureLighting==="dynamic"},I=ft(a.polygons,N),W=()=>{a.rebakeInFlight=!1;let ne=a.rebakeQueuedLightDir;ne!==null&&(a.rebakeQueuedLightDir=null,Ut(a,ne))},Y=()=>{if(a.disposed){I.dispose(),W();return}if(I.rendered.length!==a.rendered.length){I.dispose(),Se(a,m),W();return}for(let oe of I.rendered){let ee=a.renderedByPolygonIndex[oe.polygonIndex];if(!ee)continue;let Le=oe.element.getAttribute("style");Le!==null&&ee.element.setAttribute("style",Le)}let ne=I.solidPaintDefaults;ne&&ht(a.wrapper,ne);let K=a.disposeAtlas;a.disposeAtlas=I.dispose,K&&(typeof requestAnimationFrame=="function"?ee=>{requestAnimationFrame(ee)}:ee=>{setTimeout(ee,0)})(K),Ue(a),W()},ae=I.pagesReady;ae&&typeof ae.then=="function"?(a.textureReadyPromise=ae.catch(()=>{}),ae.then(()=>qn(I.rendered)).then(Zn).then(Y,()=>{I.dispose(),a.disposed||Se(a,m),W()})):Y()}function Xn(a,m){if(a.rebakeInFlight){a.rebakeQueuedLightDir=m;return}a.rebakeInFlight=!0,Ut(a,m)}function qn(a){let m=new Set;for(let S of a){let w=S.element.getAttribute("style")??"",U=/url\((blob:[^)]+)\)/g,N;for(;(N=U.exec(w))!==null;)m.add(N[1])}return Array.from(m)}function Zn(a){return a.length===0||typeof Image>"u"?Promise.resolve():Promise.all(a.map(m=>{let S=new Image;S.src=m;let w=S.decode?.();return w?w.catch(()=>{}):Promise.resolve()})).then(()=>{})}function Ze(){let a=1/0,m=!1;for(let N of f)if(!N.disposed&&N.receiveShadow){m=!0;break}for(let N of f){if(N.disposed||!(m?N.receiveShadow:N.castShadow))continue;let W=N.handle.transform.position?.[2]??0;for(let Y of N.polygons)for(let ae of Y.vertices){let ne=ae[2]+W;ne<a&&(a=ne)}}if(!Number.isFinite(a)){let N=x.currentGroundCssZ!==null;x.currentGroundCssZ=null,N&&(y(),k());return}let S=r.shadow?.lift??.05,w=(a+S)*rn,U=x.currentGroundCssZ;x.currentGroundCssZ=w,U!==w&&(k(),Te())}async function gn(a,m){V(a);let S=it(r.directionalLight),w={doc:l,directionalLight:S,ambientLight:r.ambientLight,textureLighting:r.textureLighting,textureQuality:r.textureQuality,textureLeafSizing:r.textureLeafSizing,textureImageRendering:r.textureImageRendering,textureBackend:r.textureBackend,textureProjection:r.textureProjection,seamBleed:r.seamBleed,strategies:r.strategies,lightOccludedPolyIndices:void 0},U=a.stableDom?It(a.polygons,w):null;if(U){let W=mt(a.polygons,w);return ht(a.wrapper,W),E(a,U.rendered,U.dispose,U.pagesReady),T(a),Ae(a),Ue(a),!m()}let N=await tn(a.polygons,{...w,skipDynamicNormalVars:r.textureLighting==="dynamic"},m);if(m())return N.dispose(),!1;ht(a.wrapper,N.solidPaintDefaults),E(a,N.rendered,N.dispose,N.pagesReady),a.skipBucketNormalCleanupOnce=r.textureLighting==="dynamic"&&!a.stableDom,T(a);let I=await qe(a,m);return I&&Ue(a),I}function ct(){let a=c,m=[0,0,0];if(r.autoCenter){let S=[];for(let w of f)!w.disposed&&!w.excludeFromAutoCenter&&S.push(...w.polygons);if(S.length>0){let w=ec(S);m=[(w.min[0]+w.max[0])/2,(w.min[1]+w.max[1])/2,(w.min[2]+w.max[2])/2]}}a[0]===m[0]&&a[1]===m[1]&&a[2]===m[2]||(c=m,P.autoCenter.offset=m,J(d,r))}function ki(a,m={}){let w=(d.ownerDocument??document).createElement("div");w.className="polycss-mesh",m.id&&w.setAttribute("data-poly-mesh-id",m.id);let U=`polycss-mesh-${P.meshAutoCounter.next++}`;w.setAttribute("data-poly-mesh-index",U);let N={...m},I=m.merge!==!1,W=!!m.stableDom,Y=0,ae=An(N);ae&&(w.style.transform=ae);let ne=(F,X)=>a.voxelSource?F:X?ic(F,{meshResolution:m.meshResolution}):(W||m.excludeFromAutoCenter,F),K=ne(a.polygons,I),oe=null;function ee(){let F=An(N);w.style.transform=F??""}function Le(F){if(F.length===0){oe=null,Qe&&(Qe.bboxCenterCss=null),ee();return}let X=1/0,le=1/0,me=1/0,Re=-1/0,ce=-1/0,he=-1/0;for(let Ge of F)for(let ze of Ge.vertices)ze[0]<X&&(X=ze[0]),ze[0]>Re&&(Re=ze[0]),ze[1]<le&&(le=ze[1]),ze[1]>ce&&(ce=ze[1]),ze[2]<me&&(me=ze[2]),ze[2]>he&&(he=ze[2]);if(!Number.isFinite(X)){oe=null,Qe&&(Qe.bboxCenterCss=null),ee();return}let Fe=(le+ce)/2*rn,We=(X+Re)/2*rn,ke=(me+he)/2*rn;oe=[Fe,We,ke],Qe&&(Qe.bboxCenterCss=oe),ee()}let Qe=null;Le(K),d.appendChild(w);let M={handle:void 0,wrapper:w,parseResult:a,rendered:[],renderedByPolygonIndex:[],shadowRendered:[],polygons:K,voxelSource:a.voxelSource,disposed:!1,stableDom:W,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:U,rebakeInFlight:!1,rebakeQueuedLightDir:null,textureReadyPromise:Rn},ut=null,St=0,Ct=-1,dt=null;function pt(){ut=null,dt=null,Ct=-1}function hn(){let F=ut;if(!F||F.polygonCount!==M.polygons.length)return M.polygons;if(dt&&Ct===St)return dt;let X=F.vertices,le=new Array(F.polygonCount);for(let me=0;me<F.polygonCount;me++){let Re=M.polygons[me],ce=me*9;le[me]={...Re,color:F.colors?.[me]??Re.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 dt=le,Ct=St,le}function Tt(F,X){let le=F?.stableTriangleUpdateMode==="color-only";M.stableTriangleColorFrame++;let me=M.stableDom&&!X;if(me||Le(M.polygons),M.stableDom&&!M.hasBuckets){let Re={doc:l,directionalLight:it(r.directionalLight),ambientLight:r.ambientLight,textureLighting:r.textureLighting,textureQuality:r.textureQuality,textureLeafSizing:r.textureLeafSizing,textureImageRendering:r.textureImageRendering,textureBackend:r.textureBackend,textureProjection:r.textureProjection,seamBleed:r.seamBleed},ce=M.rendered.length===M.polygons.length&&M.rendered.every(ke=>ke.kind==="triangle"),he=M.stableDom&&!X,Fe=ce||he?{}:mt(M.polygons,Re);ce||ht(M.wrapper,Fe);let We={...Re,solidPaintDefaults:Fe,optimizeStableTriangleStyle:!0,stableTriangleDebug:F?.stableTriangleDebug,stableTriangleUpdateMode:F?.stableTriangleUpdateMode,stableTriangleColorPolicy:F?.stableTriangleColorPolicy,stableTriangleColorSteps:F?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:F?.stableTriangleColorFreezeFrames,stableTriangleColorBudget:F?.stableTriangleColorBudget,stableTriangleColorMaxAge:F?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:F?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:F?.stableTriangleMatrixDecimals,stableTriangleColorFrame:M.stableTriangleColorFrame};if(on(M.rendered,M.polygons,We))return le||(T(M),de(M,!0),X&&ct()),!0}return me&&Le(M.polygons),!1}let nt={get polygons(){return hn()},set polygons(F){pt(),M.polygons=F},element:w,id:m.id,get transform(){return N},remove(){Y++,w.parentNode&&w.parentNode.removeChild(w),V(M),f.delete(M),b.delete(w),j(M),D(M),ct(),Ze()},setPolygons(F,X){Y++,I=X?.merge??I,W=X?.stableDom??W,M.stableDom=W,M.voxelSource=void 0,M.polygons=ne(F,I),D(M),j(M),pt(),nt.polygons=M.polygons;let le=X?.recomputeAutoCenter??!0;Tt(X,le)||(Se(M),le&&ct())},[Qs](F,X){let le=X?.merge??I,me=X?.stableDom??W;if(!F.solidTriangles||!me||le||m.meshResolution!==void 0||M.hasBuckets||F.polygonCount!==M.polygons.length||F.vertices.length<F.polygonCount*9||M.rendered.length!==F.polygonCount)return!1;for(let he=0;he<M.rendered.length;he++){let Fe=M.rendered[he],We=M.polygons[he];if(Fe?.kind!=="triangle"||Fe.polygonIndex!==he||!We||We.vertices.length!==3||We.texture||We.material?.texture)return!1}let Re=X?.recomputeAutoCenter??!0;if(!Re){let he=M.stableTriangleColorFrame+1,Fe={doc:l,directionalLight:it(r.directionalLight),ambientLight:r.ambientLight,textureLighting:r.textureLighting,textureQuality:r.textureQuality,textureLeafSizing:r.textureLeafSizing,textureImageRendering:r.textureImageRendering,textureBackend:r.textureBackend,textureProjection:r.textureProjection,seamBleed:r.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:he};if(nn(M.rendered,M.polygons,F,Fe))return Y++,I=le,W=me,M.stableDom=W,M.voxelSource=void 0,M.stableTriangleColorFrame=he,ut=F,St++,dt=null,Ct=-1,q(M)?(T(M),de(M,!0)):re(M),!0}Y++,I=le,W=me,M.stableDom=W,M.voxelSource=void 0;let ce=F.vertices;for(let he=0;he<F.polygonCount;he++){let Fe=M.polygons[he],We=F.colors?.[he];We&&(Fe.color=We);let ke=Fe.vertices,Ge=he*9;ke[0][0]=ce[Ge],ke[0][1]=ce[Ge+1],ke[0][2]=ce[Ge+2],ke[1][0]=ce[Ge+3],ke[1][1]=ce[Ge+4],ke[1][2]=ce[Ge+5],ke[2][0]=ce[Ge+6],ke[2][1]=ce[Ge+7],ke[2][2]=ce[Ge+8]}return pt(),nt.polygons=M.polygons,Tt(X,Re)},updatePolygon(F,X){let le=typeof F=="number"?F:M.polygons.indexOf(F);if(le<0&&typeof F!="number"&&ut&&(le=hn().indexOf(F)),le<0||le>=M.polygons.length)return;pt(),M.voxelSource=void 0,Object.assign(M.polygons[le],X);let me=Object.keys(X);$t(M,le,me)||Se(M)},async setPolygonsChunked(F,X){let le=++Y;I=X?.merge??I,W=X?.stableDom??W,M.stableDom=W,M.voxelSource=void 0,M.polygons=ne(F,I),pt(),nt.polygons=M.polygons,Le(M.polygons);let me=X?.recomputeAutoCenter??!0;if(!await gn(M,()=>M.disposed||le!==Y)){V(M);return}me&&ct()},setTransform(F){let X=M.castShadow,le=M.receiveShadow;F.castShadow!==void 0&&(M.castShadow=!!F.castShadow),F.receiveShadow!==void 0&&(M.receiveShadow=!!F.receiveShadow),N={...N,...F};let me=An(N);w.style.transform=me??"",at(M,N.rotation),F.rotation!==void 0&&de(M,!0),M.castShadow!==X&&(M.voxelSource&&Se(M),Ue(M),Ze()),M.receiveShadow!==le&&(M.receiveShadow||Io(M),k(),Te()),(F.position!==void 0||F.scale!==void 0)&&(M.castShadow||M.receiveShadow)&&(Ze(),k(),Te())},dispose(){if(!M.disposed){M.disposed=!0,Y++,w.parentNode&&w.parentNode.removeChild(w),V(M);try{a.dispose()}catch{}f.delete(M),b.delete(w),ct(),Ze()}},rebakeAtlas(){M.bakedRotation=N.rotation?[...N.rotation]:[0,0,0];let F=r.directionalLight?.direction??[.4,-.7,.59],X=Fo(F,M.bakedRotation);Xn(M,X)},whenTexturesReady(){return M.textureReadyPromise},getPosition(){return N.position},getRotation(){return N.rotation},getScale(){return N.scale},getPolygons(){return nt.polygons}};return M.handle=nt,Qe=M,b.set(w,M),f.add(M),Se(M),at(M,N.rotation),ct(),Ze(),M.receiveShadow&&(k(),Te()),nt}function _i(a){let m=!!r.autoCenter,S=r.strategies,w=r.seamBleed,U=r.textureLeafSizing,N=r.textureImageRendering,I=r.textureBackend,W=r.textureProjection,Y=r.textureLighting,ae=r.directionalLight?.direction,ne=r.shadow,K=ei(a);r={...r,...K},P.options.current=r,J(d,r);let oe=!!r.autoCenter;for(let F of f)at(F,F.handle.transform.rotation);let ee=a.strategies!==void 0&&!Es(a.strategies,S),Le=Object.prototype.hasOwnProperty.call(a,"seamBleed")&&K.seamBleed!==w,Qe=Object.prototype.hasOwnProperty.call(a,"textureLeafSizing")&&K.textureLeafSizing!==U,M=Object.prototype.hasOwnProperty.call(a,"textureImageRendering")&&K.textureImageRendering!==N,ut=Object.prototype.hasOwnProperty.call(a,"textureBackend")&&K.textureBackend!==I,St=Object.prototype.hasOwnProperty.call(a,"textureProjection")&&K.textureProjection!==W;if(ee||Le||Qe||M||ut||St)for(let F of f)Se(F);m!==oe&&ct();let Ct=a.textureLighting!==void 0&&Y!==r.textureLighting,dt=r.directionalLight?.direction,pt=a.directionalLight!==void 0&&!As(ae,dt),hn=r.shadow,Tt=a.shadow!==void 0&&!ws(ne,hn),nt=pt||Tt;if(Ct){if(!ee&&!Le&&!Qe&&!M&&!ut&&!St)for(let F of f)Se(F);Ze(),k(),Te()}else nt&&(Tt&&k(),Te());Tt&&a.shadow?.lift!==ne?.lift&&Ze()}function Oi(){return r}function Di(){Z(u,r),_(d);for(let a of f)de(a)}function Ii(){let a=[];for(let m of f)a.push(m.handle);return a}function Hi(){return Promise.all(Array.from(f,a=>a.handle.whenTexturesReady())).then(()=>{})}function Fi(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 zi(){let a=Array.from(f);for(let m of a)try{m.handle.dispose()}catch{}u.parentNode&&u.parentNode.removeChild(u)}return{add:ki,setOptions:_i,destroy:zi,host:e,camera:t,cameraEl:u,sceneElement:d,applyCamera:Di,getOptions:Oi,meshes:Ii,whenTexturesReady:Hi,findMeshByElement:Fi,previewBakedSolidLighting:se,commitBakedSolidLighting:Gn,clearBakedSolidLightingPreview:Yn}}import{buildPolyMeshTransform as vg,buildPolySceneTransform as Sg,cssDistanceToWorld as Cg,cssDistanceToWorld as Tg,cssPositionToWorld as Eg,cssPositionToWorld as Ag,worldDistanceToCss as wg,worldDistanceToCss as Mg,worldDirectionalLightToCss as Lg,worldDirectionToPolyCss as Rg,worldPositionToPolyCss as kg}from"@layoutit/polycss-core";import{createIsometricCamera as oi}from"@layoutit/polycss-core";var uc=32e3;function an(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=oi(n),o=`${e.perspective??uc}px`;return{get state(){return t.state},update(s){t.update(s)},getStyle(s){return t.getStyle(s)},type:"perspective",perspectiveStyle:o}}function yt(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=oi(n);return{get state(){return t.state},update(o){t.update(o)},getStyle(o){return t.getStyle(o)},type:"orthographic",perspectiveStyle:"none"}}var dc=yt;import{BASE_TILE as pc}from"@layoutit/polycss-core";var kn={drag:!0,wheel:!0,dolly:!1,invert:!1,minZoom:.1,maxZoom:10,minDistance:0,maxDistance:1/0,animate:!1};function Ft(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 ln(e){return e===!0?-1:e===!1?1:e}function zt(){let e=[],n=[],t=[];function o(i){return i==="change"?e:i==="start"?n:t}function s(i){if(e.length===0)return;let c={type:"change",camera:i()},l=e.slice();for(let u of l)try{u(c)}catch(d){console.error("[polycss] controls 'change' listener threw:",d)}}function r(i,c){let l=i==="start"?n:t;if(l.length===0)return;let u={type:i,camera:c()},d=l.slice();for(let P of d)try{P(u)}catch(f){console.error(`[polycss] controls '${i}' listener threw:`,f)}}return{changeListeners:e,startListeners:n,endListeners:t,listenerArray:o,emitChange:s,emitInteraction:r}}function Bt(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 _n(e,n,t,o,s,r){let i=!1,c=null;return{onWheel:d=>{let P=n();if(!P.wheel||t())return;d.preventDefault();let f=d.deltaMode===1?16:d.deltaMode===2?100:1,b=d.deltaY*f;d.ctrlKey?b*=10:b*=3;let x=e.camera.state;if(P.dolly){let v=x.distance??0,y=Math.max(P.minDistance,Math.min(P.maxDistance,v+b*.05));e.camera.update({distance:y})}else{let v=Math.exp(-b*513e-6),y=x.zoom??1,C=Math.max(P.minZoom,Math.min(P.maxZoom,y*v));e.camera.update({zoom:C})}e.applyCamera(),i||(i=!0,r("start",o)),s(o),c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,i=!1,r("end",o)},150)},teardown:()=>{c!==null&&(clearTimeout(c),c=null),i=!1}}}function On(e,n,t,o,s,r,i){let c=null,l=0,u=b=>{if(c===null||o())return;let x=t();if(!x.animate){c=null;return}if(s())l=b;else{let v=Math.min(50,l?b-l:16.67);l=b;let y=x.animate.speed*(v/16.67),C=n.camera.state;if(x.animate.axis==="x"){let O=(((C.rotX??65)+y)%360+360)%360;n.camera.update({rotX:O})}else{let O=(((C.rotY??45)+y)%360+360)%360;n.camera.update({rotY:O})}n.applyCamera(),i(r)}c=e.requestAnimationFrame(u)};return{start:()=>{c!==null||!t().animate||o()||(l=0,c=e.requestAnimationFrame(u))},stop:()=>{c!==null&&(e.cancelAnimationFrame(c),c=null)},isRunning:()=>c!==null}}function Bo(e,n={}){let t=Ft(kn,n),o=e.host,s=o.ownerDocument?.defaultView??globalThis,r=null,i={x:0,y:0},c=!1,l=!1,u=zt(),d=Bt(e),{changeListeners:P,startListeners:f,endListeners:b,listenerArray:x,emitChange:v,emitInteraction:y}=u,C=On(s,e,()=>t,()=>l,()=>c,d,v),O=p=>{if(!(!t.drag||l)&&r===null&&p.isPrimary!==!1){p.preventDefault(),r=p.pointerId,i={x:p.clientX,y:p.clientY},o.style.cursor="grabbing";try{p.target.setPointerCapture(p.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),y("start",d)}},k=p=>{if(r===null||p.pointerId!==r||!t.drag||l)return;p.preventDefault();let g=p.clientX-i.x,L=p.clientY-i.y;i={x:p.clientX,y:p.clientY};let R=ln(t.invert),H=g/4*R,Q=L/4*R,T=e.camera.state;if(p.shiftKey){let G=T.rotX??65,q=T.rotY??45,re=Math.max(.01,T.zoom??1),fe=Math.cos(G*Math.PI/180),de=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*pc,Ae=(g*Ce-L*pe/de)/be,$e=-(g*pe+L*Ce/de)/be,qe=T.target??[0,0,0];e.camera.update({target:[qe[0]+Ae,qe[1]+$e,qe[2]]})}else{let G=Math.max(0,Math.min(89,(T.rotX??65)-Q)),q=(((T.rotY??45)-H)%360+360)%360;e.camera.update({rotX:G,rotY:q})}e.applyCamera(),v(d)},j=p=>{if(r===p.pointerId){r=null,o.style.cursor=t.drag&&!l?"grab":"";try{p.target.releasePointerCapture(p.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),y("end",d)}},D=_n(e,()=>t,()=>l,d,v,y);function Z(){o.addEventListener("pointerdown",O),o.addEventListener("pointermove",k),o.addEventListener("pointerup",j),o.addEventListener("pointercancel",j),o.addEventListener("wheel",D.onWheel,{passive:!1}),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function J(){o.removeEventListener("pointerdown",O),o.removeEventListener("pointermove",k),o.removeEventListener("pointerup",j),o.removeEventListener("pointercancel",j),o.removeEventListener("wheel",D.onWheel),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",D.teardown()}Z(),C.start();function _(p){let g=!!t.animate;t=Ft(t,p),!l&&r===null&&(o.style.cursor=t.drag?"grab":"");let L=!!t.animate;g&&!L?C.stop():!g&&L&&C.start()}function V(){l&&(l=!1,Z(),C.start())}function B(){l||(l=!0,J(),C.stop(),r=null,c=!1,D.teardown())}function z(){B(),P.length=0,f.length=0,b.length=0}function A(p,g){let L=x(p);L.includes(g)||L.push(g)}function h(p,g){let L=x(p),R=L.indexOf(g);R>=0&&L.splice(R,1)}function E(p,g){return x(p).includes(g)}return{update:_,resume:V,pause:B,destroy:z,addEventListener:A,removeEventListener:h,hasEventListener:E}}import{BASE_TILE as mc}from"@layoutit/polycss-core";function Vo(e,n={}){let t=Ft(kn,n),o=e.host,s=o.ownerDocument?.defaultView??globalThis,r=null,i={x:0,y:0},c=!1,l=!1,u=!1,d={x:0,y:0},P=zt(),f=Bt(e),{changeListeners:b,startListeners:x,endListeners:v,listenerArray:y,emitChange:C,emitInteraction:O}=P,k=On(s,e,()=>t,()=>l,()=>c,f,C),j=T=>{if(!(!t.drag||l)&&r===null&&T.isPrimary!==!1){T.preventDefault(),r=T.pointerId,i={x:T.clientX,y:T.clientY},o.style.cursor="grabbing";try{T.target.setPointerCapture(T.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),O("start",f)}},D=T=>{if(r===null||T.pointerId!==r||!t.drag||l)return;T.preventDefault();let G=T.clientX-i.x,q=T.clientY-i.y;i={x:T.clientX,y:T.clientY};let re=e.camera.state;if(T.shiftKey){let fe=ln(t.invert),de=G/4*fe,pe=q/4*fe,Ce=(re.rotX??65)-pe,be=(((re.rotY??45)-de)%360+360)%360;e.camera.update({rotX:Ce,rotY:be})}else{let fe=re.rotX??65,de=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(de*Math.PI/180),$e=Math.sin(de*Math.PI/180),qe=pe*mc,at=(G*$e-q*Ae/be)/qe,vt=-(G*Ae+q*$e/be)/qe,lt=re.target??[0,0,0];e.camera.update({target:[lt[0]+at,lt[1]+vt,lt[2]]})}e.applyCamera(),C(f)},Z=T=>{if(r===T.pointerId){r=null,o.style.cursor=t.drag&&!l?"grab":"";try{T.target.releasePointerCapture(T.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),O("end",f)}},J=T=>{T.preventDefault()},_=T=>{T.button===2&&(u=!0,d={x:T.clientX,y:T.clientY},t.animate&&t.animate.pauseOnInteraction&&(c=!0),O("start",f))},V=T=>{if(!u||!t.drag)return;let G=T.clientX-d.x,q=T.clientY-d.y;d={x:T.clientX,y:T.clientY};let re=ln(t.invert),fe=G/4*re,de=q/4*re,pe=e.camera.state,Ce=(pe.rotX??65)-de,be=(((pe.rotY??45)-fe)%360+360)%360;e.camera.update({rotX:Ce,rotY:be}),e.applyCamera(),C(f)},B=T=>{T.button===2&&u&&(u=!1,O("end",f))},z=_n(e,()=>t,()=>l,f,C,O);function A(){o.addEventListener("pointerdown",j),o.addEventListener("pointermove",D),o.addEventListener("pointerup",Z),o.addEventListener("pointercancel",Z),o.addEventListener("wheel",z.onWheel,{passive:!1}),o.addEventListener("contextmenu",J),o.addEventListener("mousedown",_),o.addEventListener("mousemove",V),o.addEventListener("mouseup",B),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function h(){o.removeEventListener("pointerdown",j),o.removeEventListener("pointermove",D),o.removeEventListener("pointerup",Z),o.removeEventListener("pointercancel",Z),o.removeEventListener("wheel",z.onWheel),o.removeEventListener("contextmenu",J),o.removeEventListener("mousedown",_),o.removeEventListener("mousemove",V),o.removeEventListener("mouseup",B),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",z.teardown()}A(),k.start();function E(T){let G=!!t.animate;t=Ft(t,T),!l&&r===null&&(o.style.cursor=t.drag?"grab":"");let q=!!t.animate;G&&!q?k.stop():!G&&q&&k.start()}function p(){l&&(l=!1,A(),k.start())}function g(){l||(l=!0,h(),k.stop(),r=null,c=!1,u=!1,z.teardown())}function L(){g(),b.length=0,x.length=0,v.length=0}function R(T,G){let q=y(T);q.includes(G)||q.push(G)}function H(T,G){let q=y(T),re=q.indexOf(G);re>=0&&q.splice(re,1)}function Q(T,G){return y(T).includes(G)}return{update:E,resume:p,pause:g,destroy:L,addEventListener:R,removeEventListener:H,hasEventListener:Q}}import{BASE_TILE as fc}from"@layoutit/polycss-core";var gc={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 ri(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 si=new Set(["KeyW","ArrowUp"]),ii=new Set(["KeyS","ArrowDown"]),ai=new Set(["KeyA","ArrowLeft"]),li=new Set(["KeyD","ArrowRight"]),ci=new Set(["Space"]),No=new Set(["ControlLeft","ControlRight"]);function jo(e,n={}){let t=ri(gc,n),o=e.host,s=e.cameraEl,r=o.ownerDocument??document,i=r.defaultView??globalThis,c=zt(),l=Bt(e),{changeListeners:u,startListeners:d,endListeners:P,listenerArray:f,emitChange:b,emitInteraction:x}=c,v=new Set,y=!1,C=!1,O=0,k=0,j=!1,D=[0,0,t.groundZ+t.eyeHeight];function Z($,se){let ie=$*Math.PI/180,we=se*Math.PI/180;return[-Math.sin(ie)*Math.cos(we),-Math.sin(ie)*Math.sin(we),-Math.cos(ie)]}function J(){let $=e.camera.perspectiveStyle,se=$==="none"?0:parseFloat($);return(Number.isFinite(se)&&se>0?se:2e3)/fc}function _(){let $=e.camera.state,se=Z($.rotX??90,$.rotY??0),ie=J();return[D[0]+se[0]*ie,D[1]+se[1]*ie,D[2]+se[2]*ie]}function V(){let $=_();e.camera.update({target:$}),e.applyCamera()}function B(){let $=e.camera.state.target??[0,0,0];D=[$[0],$[1],t.groundZ+t.eyeHeight],V()}let z=()=>{if(!(!t.enabled||!t.lookEnabled||C||y))try{o.requestPointerLock()}catch{}},A=()=>{let $=r.pointerLockElement===o;$!==y&&(y=$,y?(j=!0,x("start",l)):j&&(j=!1,x("end",l)))},h=$=>{if(!y||!t.enabled||!t.lookEnabled||C)return;let se=$.movementX??0,ie=$.movementY??0;if(se===0&&ie===0)return;let we=e.camera.state,$t=t.lookSensitivity,Ue=t.invertY?-1:1,Te=(((we.rotY??0)-se*$t)%360+360)%360,xe=(we.rotX??90)-ie*$t*Ue;xe<t.minPitch?xe=t.minPitch:xe>t.maxPitch&&(xe=t.maxPitch);let Ie=Z(xe,Te),He=J(),Se=[D[0]+Ie[0]*He,D[1]+Ie[1]*He,D[2]+Ie[2]*He];e.camera.update({rotX:xe,rotY:Te,target:Se}),e.applyCamera(),b(l)},E=$=>si.has($)||ii.has($)||ai.has($)||li.has($)||ci.has($)||No.has($),p=$=>{if(!(!t.enabled||C)&&E($.code)&&!(!y&&!t.moveEnabled)){if(ci.has($.code)){if(!t.jumpEnabled)return;$.preventDefault(),!v.has($.code)&&O===0&&k===0&&(O=t.jumpVelocity),v.add($.code);return}No.has($.code)&&!t.crouchEnabled||!t.moveEnabled&&!No.has($.code)||($.preventDefault(),v.add($.code))}},g=$=>{E($.code)&&v.delete($.code)},L=()=>{v.clear()},R=null,H=0,Q=.05,T=$=>{if(R===null||C)return;let se=Math.min(Q,H?($-H)/1e3:.0167);if(H=$,t.enabled){let ie=!1,we=e.camera.state;if(t.moveEnabled){let xe=0,Ie=0;for(let He of v)si.has(He)?xe+=1:ii.has(He)?xe-=1:li.has(He)?Ie+=1:ai.has(He)&&(Ie-=1);if(xe!==0||Ie!==0){let Se=(we.rotY??0)*Math.PI/180,Ut=-Math.cos(Se),Xn=-Math.sin(Se),qn=-Math.sin(Se),Zn=Math.cos(Se),Ze=Math.hypot(xe,Ie)||1,gn=t.moveSpeed*se;D[0]+=(Ut*xe+qn*Ie)/Ze*gn,D[1]+=(Xn*xe+Zn*Ie)/Ze*gn,ie=!0}}let Ue=t.crouchEnabled&&(v.has("ControlLeft")||v.has("ControlRight"))?t.crouchHeight:t.eyeHeight;t.jumpEnabled&&(O!==0||k>0)?(O-=t.gravity*se,k+=O*se,k<=0&&(k=0,O=0)):t.jumpEnabled||(k=0,O=0);let Te=t.groundZ+Ue+k;if(Math.abs(D[2]-Te)>1e-4&&(D[2]=Te,ie=!0),ie){let xe=_();e.camera.update({target:xe}),e.applyCamera(),b(l)}}R=i.requestAnimationFrame(T)};function G(){R!==null||C||(H=0,R=i.requestAnimationFrame(T))}function q(){R!==null&&(i.cancelAnimationFrame(R),R=null)}function re(){let se=s.ownerDocument?.defaultView?.getComputedStyle(s).perspective??"",ie=parseFloat(se),we=Number.isFinite(ie)&&ie>0?ie:2e3;s.style.setProperty("--polycss-fpv-perspective",`${we}px`),s.classList.add("polycss-fpv-host")}function fe(){s.classList.remove("polycss-fpv-host"),s.style.removeProperty("--polycss-fpv-perspective")}function de(){o.addEventListener("click",z),r.addEventListener("pointerlockchange",A),r.addEventListener("mousemove",h),i.addEventListener("keydown",p),i.addEventListener("keyup",g),i.addEventListener("blur",L),o.style.cursor=t.lookEnabled?"crosshair":"",re()}function pe(){if(o.removeEventListener("click",z),r.removeEventListener("pointerlockchange",A),r.removeEventListener("mousemove",h),i.removeEventListener("keydown",p),i.removeEventListener("keyup",g),i.removeEventListener("blur",L),o.style.cursor="",v.clear(),y)try{r.exitPointerLock()}catch{}fe()}B(),de(),G();function Ce($){let se=t.eyeHeight,ie=t.groundZ;t=ri(t,$),C||(o.style.cursor=t.lookEnabled?"crosshair":""),(t.eyeHeight!==se||t.groundZ!==ie)&&(D[2]=t.groundZ+t.eyeHeight,V(),b(l))}function be(){C&&(C=!1,de(),G())}function Ae(){C||(C=!0,pe(),q(),j&&(j=!1,x("end",l)))}function $e(){Ae(),u.length=0,d.length=0,P.length=0}function qe(){if(!(!t.enabled||!t.lookEnabled||C))try{o.requestPointerLock()}catch{}}function at(){if(y)try{r.exitPointerLock()}catch{}}function vt(){return y}function lt($,se){let ie=f($);ie.includes(se)||ie.push(se)}function Un($,se){let ie=f($),we=ie.indexOf(se);we>=0&&ie.splice(we,1)}function Wn($,se){return f($).includes(se)}function Gn(){return[D[0],D[1],D[2]]}function Yn($){D[0]=$[0],D[1]=$[1],D[2]=$[2],V(),b(l)}return{update:Ce,resume:be,pause:Ae,destroy:$e,lock:qe,unlock:at,isLocked:vt,getOrigin:Gn,setOrigin:Yn,addEventListener:lt,removeEventListener:Un,hasEventListener:Wn}}function Vt(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let s of o){let r=s.getBoundingClientRect();if(!(r.width<=0||r.height<=0)&&n>=r.left&&n<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}function ui(e,n,t,o){for(let s of e)if(!(o&&!o(s))&&Vt(s.element,n,t))return s;return null}function $o(e,n={}){let t=[],o=new Set;n.onChange&&o.add(n.onChange);function s(){t=n.filter?n.filter(t):t;for(let v of o)try{v(t)}catch(y){console.error("[polycss/createSelect] onChange threw:",y)}}function r(x){t=x,s()}function i(x){n.multiple?t.includes(x)||(t=[...t,x]):t=[x],s()}function c(x){t.includes(x)&&(t=t.filter(v=>v!==x),s())}function l(x){t.includes(x)?t=t.filter(v=>v!==x):n.multiple?t=[...t,x]:t=[x],s()}function u(){t.length!==0&&(t=[],s())}function d(x){return t.includes(x)}function P(x,v){return ui(e.meshes(),x,v,y=>!y.element.classList.contains("polycss-transform-gizmo"))}let f=x=>{let v=x.target;if(v?.closest(".polycss-transform-gizmo"))return;let y=e.findMeshByElement(v)??P(x.clientX,x.clientY);if(!y){n.onPointerMissed&&n.onPointerMissed(x),n.clearOnMiss!==!1&&u();return}n.multiple&&(x.shiftKey||x.metaKey||x.ctrlKey)?l(y):t.length===1&&t[0]===y?u():r([y])};e.host.addEventListener("click",f);function b(){e.host.removeEventListener("click",f),o.clear()}return{get selected(){return t},set:r,add:i,remove:c,toggle:l,clear:u,has:d,destroy:b}}import{arrowPolygons as hc,eulerXYZFromQuat as yc,planePolygons as bc,quatFromAxisAngle as xc,quatFromEulerXYZ as Pc,quatMultiply as vc,ringQuadPolygons as Sc,rotateVec3 as Uo}from"@layoutit/polycss-core";var Dn="#ff3653",In="#8adb00",Hn="#2c8fff",Nt=50,di=60,Cc=.6,Tc=.0125,Ec=.15,Ac=.04,wc=1,pi=.02,Wo=1.04,Mc=.1,Lc=.25,hi=1e-4,Rc=.6,kc=.8,_c=1,et={0:1,1:0,2:2},mi=[{cssAxis:0,sign:1,key:"x",color:Dn},{cssAxis:0,sign:-1,key:"-x",color:Dn},{cssAxis:1,sign:1,key:"y",color:In},{cssAxis:1,sign:-1,key:"-y",color:In},{cssAxis:2,sign:1,key:"z",color:Hn},{cssAxis:2,sign:-1,key:"-z",color:Hn}],fi=[{cssAxis:0,key:"x",color:Dn},{cssAxis:1,key:"y",color:In},{cssAxis:2,key:"z",color:Hn}],gi=[{perpAxis:2,axisA:0,axisB:1,key:"xy",color:Hn},{perpAxis:1,axisA:0,axisB:2,key:"xz",color:In},{perpAxis:0,axisA:1,axisB:2,key:"yz",color:Dn}];function Go(e,n,t,o){let s=t*Math.PI/180,r=o*Math.PI/180,i=[0,0,0];i[e]=n;let c=i[0]*Math.cos(r)-i[1]*Math.sin(r),l=i[0]*Math.sin(r)+i[1]*Math.cos(r),u=i[2];return l*Math.sin(s)+u*Math.cos(s)<0}function Oc(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),s=parseInt(t[2],16),r=parseInt(t[3],16);return`rgba(${o}, ${s}, ${r}, ${n})`}function Fn(e,n){return!n||n<=0?e:Math.round(e/n)*n}function Dc(e){if(e.length===0)return[0,0,0];let n=1/0,t=1/0,o=1/0,s=-1/0,r=-1/0,i=-1/0;for(let c of e)for(let l of c.vertices)l[0]<n&&(n=l[0]),l[0]>s&&(s=l[0]),l[1]<t&&(t=l[1]),l[1]>r&&(r=l[1]),l[2]<o&&(o=l[2]),l[2]>i&&(i=l[2]);return Number.isFinite(n)?[(n+s)/2,(t+r)/2,(o+i)/2]:[0,0,0]}function Yo(e){if(e.length===0)return di;let n=1/0,t=1/0,o=1/0,s=-1/0,r=-1/0,i=-1/0;for(let l of e)for(let u of l.vertices)u[0]<n&&(n=u[0]),u[0]>s&&(s=u[0]),u[1]<t&&(t=u[1]),u[1]>r&&(r=u[1]),u[2]<o&&(o=u[2]),u[2]>i&&(i=u[2]);return Number.isFinite(n)?Math.max(s-n,r-t,i-o)*Nt*Cc:di}function Ic(e){let{cssAxis:n,sign:t,shaftLengthCss:o,wrapper:s,target:r,startClientX:i,startClientY:c,translationSnap:l,onAxisDelta:u,onMouseDown:d,onMouseUp:P,onDraggingChanged:f}=e,b=o,x=[0,0,0];x[n]=t;let v=s.ownerDocument.createElement("div");v.style.position="absolute",v.style.left="0",v.style.top="0",v.style.width="0",v.style.height="0",v.style.transform=`translate3d(${x[0]*b}px, ${x[1]*b}px, ${x[2]*b}px)`,s.appendChild(v);let y=s.getBoundingClientRect(),C=v.getBoundingClientRect();s.removeChild(v);let O=(C.left-y.left)/b,k=(C.top-y.top)/b,j=O*O+k*k;if(j<hi)return;d?.(),f?.(!0);let D=J=>{let _=J.clientX-i,V=J.clientY-c,B=(_*O+V*k)/j;B=Fn(B,l),u(B,x)},Z=()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",Z),window.removeEventListener("pointercancel",Z);let J=_=>{_.stopPropagation(),_.stopImmediatePropagation()};window.addEventListener("click",J,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",J,!0),0),P?.(),f?.(!1)};window.addEventListener("pointermove",D),window.addEventListener("pointerup",Z),window.addEventListener("pointercancel",Z)}function Hc(e){let{axisA:n,axisB:t,probeDistanceCss:o,wrapper:s,startClientX:r,startClientY:i,translationSnap:c,onPlaneDelta:l,onMouseDown:u,onMouseUp:d,onDraggingChanged:P}=e,f=[0,0,0];f[n]=1;let b=[0,0,0];b[t]=1;function x(j){let D=s.ownerDocument.createElement("div");D.style.position="absolute",D.style.left="0",D.style.top="0",D.style.width="0",D.style.height="0",D.style.transform=`translate3d(${j[0]*o}px, ${j[1]*o}px, ${j[2]*o}px)`,s.appendChild(D);let Z=s.getBoundingClientRect(),J=D.getBoundingClientRect();return s.removeChild(D),{x:(J.left-Z.left)/o,y:(J.top-Z.top)/o}}let v=x(f),y=x(b),C=v.x*y.y-y.x*v.y;if(Math.abs(C)<hi)return;u?.(),P?.(!0);let O=j=>{let D=j.clientX-r,Z=j.clientY-i,J=(y.y*D-y.x*Z)/C,_=(-v.y*D+v.x*Z)/C;J=Fn(J,c),_=Fn(_,c),l(J,_,f,b)},k=()=>{window.removeEventListener("pointermove",O),window.removeEventListener("pointerup",k),window.removeEventListener("pointercancel",k);let j=D=>{D.stopPropagation(),D.stopImmediatePropagation()};window.addEventListener("click",j,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",j,!0),0),d?.(),P?.(!1)};window.addEventListener("pointermove",O),window.addEventListener("pointerup",k),window.addEventListener("pointercancel",k)}function Fc(e){let{cssAxis:n,wrapper:t,target:o,startClientX:s,startClientY:r,rotationSnap:i,onAngleDelta:c,onMouseDown:l,onMouseUp:u,onDraggingChanged:d}=e,P=t.getBoundingClientRect(),f=P.left,b=P.top,x=Math.atan2(r-b,s-f),v=0;l?.(),d?.(!0);let y=O=>{let k=Math.atan2(O.clientY-b,O.clientX-f),j=k-x;j>Math.PI?j-=2*Math.PI:j<-Math.PI&&(j+=2*Math.PI),v+=j,x=k;let D=v*180/Math.PI;D=Fn(D,i),c(D)},C=()=>{window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",C),window.removeEventListener("pointercancel",C);let O=k=>{k.stopPropagation(),k.stopImmediatePropagation()};window.addEventListener("click",O,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",O,!0),0),u?.(),d?.(!1)};window.addEventListener("pointermove",y),window.addEventListener("pointerup",C),window.addEventListener("pointercancel",C)}function Xo(e,n={}){let t=null,o=n.mode??"translate",s=n.size??1,r={...n},i=new Map,c=null,l=null,u=[0,0,0];function d(){if(!t)return[0,0,0];let h=t.transform.position??[0,0,0],E=t.transform.rotation??[0,0,0],p=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,g=Uo(u,E[0],E[1],E[2]);return[h[0]+p*g[0],h[1]+p*g[1],h[2]+p*g[2]]}function P(h){return l===h?_c:c===h?kc:Rc}function f(){for(let[h,E]of i){let p=b(E.spec,P(h));E.handle.setPolygons(p,{recomputeAutoCenter:!1})}}function b(h,E){let g=Yo(t?.polygons??[])*s,L=g/Nt,R=Oc(h.color,E);if(h.kind==="arrow"){let T=e.camera.state,G=Go(h.cssAxis,h.sign,T.rotX??65,T.rotY??45);return hc({axis:et[h.cssAxis],sign:h.sign,shaftLength:L,shaftHalfThickness:L*Tc,headLength:L*Ec,headHalfThickness:L*Ac,color:R,shaft:!G})}if(h.kind==="plane"){let T=e.camera.state,G=T.rotX??65,q=T.rotY??45,re=et[h.perpAxis],fe=(re+1)%3,de=(re+2)%3,pe=et[fe],Ce=et[de],be=Go(pe,1,G,q)?-1:1,Ae=Go(Ce,1,G,q)?-1:1,$e=L*Lc;return bc({axis:re,size:L*Mc,offset:[be*$e,Ae*$e],color:R})}let Q=g*wc/Nt*Wo;return Sc({axis:et[h.cssAxis],outerRadius:Q,color:R})}function x(h){return h.kind==="arrow"?"polycss-transform-arrow":h.kind==="plane"?"polycss-transform-plane":"polycss-transform-ring"}function v(){if(o==="translate"){let h=mi.map(p=>({kind:"arrow",key:p.key,cssAxis:p.cssAxis,sign:p.sign,color:p.color})),E=gi.map(p=>({kind:"plane",key:p.key,perpAxis:p.perpAxis,axisA:p.axisA,axisB:p.axisB,color:p.color}));return[...h,...E]}return o==="rotate"?fi.map(h=>({kind:"ring",key:h.key,cssAxis:h.cssAxis,color:h.color})):[]}function y(){if(C(),!t)return;let h={x:r.showX!==!1,y:r.showY!==!1,z:r.showZ!==!1};function E(g){if(g.kind==="arrow"){let H=g.key.replace("-","")[0];return h[H]}if(g.kind==="ring")return h[g.key];let L=["x","y","z"][g.axisA],R=["x","y","z"][g.axisB];return h[L]&&h[R]}let p=d();for(let g of v()){if(!E(g))continue;let L=b(g,P(g.key)),R=e.add({polygons:L,objectUrls:[],warnings:[],dispose:()=>{}},{excludeFromAutoCenter:!0,id:`__poly-gizmo-${g.key}`,position:p}),H=x(g);if(R.element.classList.add("polycss-transform-gizmo",H,`${H}--${g.key}`),g.kind==="ring"){let Q=(1-pi)/Wo,T=(1+pi)/Wo;R.element.style.setProperty("--ring-inner-ratio",`${Q}`),R.element.style.setProperty("--ring-outer-ratio",`${T}`)}i.set(g.key,{handle:R,spec:g})}}function C(){for(let{handle:h}of i.values())h.remove();i.clear(),c=null,l=null}function O(){if(!t)return;let h=d();for(let{handle:E}of i.values())E.setTransform({position:h})}function k(){t&&(i.size===0?y():O())}function j(h){if(t=h,!h){u=[0,0,0],C();return}u=Dc(h.polygons),C(),y()}function D(){j(null)}function Z(h){h!==o&&(o=h,t&&(C(),y()))}function J(h,E,p){if(!t||!_)return;let g=p[h.cssAxis],L=et[h.cssAxis],R=E*g/Nt,H=_.slice();H[L]=_[L]+R,t.setTransform({position:H}),O(),r.onObjectChange?.({object:t,position:H}),r.onChange?.()}let _=null,V=null,B=h=>{if(!t||r.enabled===!1)return;let E={x:r.showX!==!1,y:r.showY!==!1,z:r.showZ!==!1};if(o==="translate"){for(let p of gi){let g=["x","y","z"][p.axisA],L=["x","y","z"][p.axisB];if(!E[g]||!E[L])continue;let R=i.get(p.key);if(R&&Vt(R.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=p.key,f(),_=(t.transform.position??[0,0,0]).slice(),Hc({axisA:p.axisA,axisB:p.axisB,probeDistanceCss:Yo(t.polygons)*s,wrapper:R.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,translationSnap:r.translationSnap??null,onPlaneDelta:(H,Q,T,G)=>{if(!t||!_)return;let q=T[p.axisA],re=G[p.axisB],fe=et[p.axisA],de=et[p.axisB],pe=_.slice();pe[fe]+=H*q/Nt,pe[de]+=Q*re/Nt,t.setTransform({position:pe}),O(),r.onObjectChange?.({object:t,position:pe}),r.onChange?.()},onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:H=>{H||(l=null,_=null,f()),r.onDraggingChanged?.(H)}});return}}for(let p of mi){let g=p.key.replace("-","")[0];if(!E[g])continue;let L=i.get(p.key);if(L&&Vt(L.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=p.key,f(),_=(t.transform.position??[0,0,0]).slice(),Ic({cssAxis:p.cssAxis,sign:p.sign,shaftLengthCss:Yo(t.polygons)*s,wrapper:L.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,translationSnap:r.translationSnap??null,onAxisDelta:(R,H)=>J(p,R,H),onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:R=>{R||(l=null,_=null,f()),r.onDraggingChanged?.(R)}});return}}}else if(o==="rotate")for(let p of fi){if(!E[p.key])continue;let g=i.get(p.key);if(g&&Vt(g.handle.element,h.clientX,h.clientY)){h.preventDefault(),h.stopPropagation(),l=p.key,f(),V=(t.transform.rotation??[0,0,0]).slice(),_=(t.transform.position??[0,0,0]).slice(),Fc({cssAxis:p.cssAxis,wrapper:g.handle.element,target:t,startClientX:h.clientX,startClientY:h.clientY,rotationSnap:r.rotationSnap??null,onAngleDelta:L=>{if(!t||!V||!_)return;let R=et[p.cssAxis],H=[0,0,0];H[R]=1;let Q=-L*Math.PI/180,T=Pc(V),G=xc(H,Q),q=yc(vc(G,T)),re=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,fe=Uo(u,V[0],V[1],V[2]),de=Uo(u,q[0],q[1],q[2]),pe=[_[0]+re*(fe[0]-de[0]),_[1]+re*(fe[1]-de[1]),_[2]+re*(fe[2]-de[2])];t.setTransform({rotation:q,position:pe}),O(),r.onObjectChange?.({object:t,rotation:q,position:pe}),r.onChange?.()},onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:L=>{L||(l=null,V=null,_=null,f(),t?.rebakeAtlas()),r.onDraggingChanged?.(L)}});return}}};e.host.addEventListener("pointerdown",B,{capture:!0});let z=h=>{if(!t||l||r.enabled===!1)return;let E=null;for(let[p,g]of i)if(Vt(g.handle.element,h.clientX,h.clientY)){E=p;break}E!==c&&(c=E,f())};e.host.addEventListener("pointermove",z);function A(){e.host.removeEventListener("pointerdown",B,{capture:!0}),e.host.removeEventListener("pointermove",z),C()}return{attach:j,detach:D,setMode:Z,update:k,destroy:A}}var zc=typeof HTMLElement<"u"?HTMLElement:class{},Bc=["perspective","rot-x","rot-y","zoom","directional-direction","directional-color","directional-intensity","ambient-color","ambient-intensity","texture-lighting","texture-quality","texture-leaf-sizing","texture-image-rendering","texture-backend","texture-projection","auto-center"];function je(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function Vc(e){return e==="false"?!1:je(e)}function qo(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 Nc(e){if(e==="baked"||e==="dynamic")return e}function jc(e){return e==="auto"?"auto":je(e)}function $c(e){if(e==="canonical"||e==="local"||e==="raster")return e}function Uc(e){if(e==="auto"||e==="pixelated")return e}function Wc(e){if(e==="auto"||e==="atlas"||e==="image")return e}function Gc(e){if(e==="affine"||e==="projective")return e}function Yc(e){return typeof e.getCamera=="function"}var Oe=class extends zc{constructor(){super(...arguments);this._scene=null;this._implicitCamera=null}static get observedAttributes(){return[...Bc]}getScene(){return this._scene}_findAncestorCamera(){let t=this.parentElement;for(;t;){if(Yc(t)){let o=t.getCamera();if(o)return o}t=t.parentElement}return null}_buildImplicitCamera(){let t=Vc(this.getAttribute("perspective")),o=je(this.getAttribute("rot-x")),s=je(this.getAttribute("rot-y")),r=je(this.getAttribute("zoom")),i=je(this.getAttribute("distance")),c=qo(this.getAttribute("target")),l={...o!==void 0?{rotX:o}:{},...s!==void 0?{rotY:s}:{},...r!==void 0?{zoom:r}:{},...i!==void 0?{distance:i}:{},...c!==void 0?{target:c}:{}};return t===!1?yt(l):t!==void 0?an({...l,perspective:t}):yt(l)}_readNonCameraOptions(){let t=this._readDirectionalLight(),o=this._readAmbientLight(),s={};s.textureLighting=Nc(this.getAttribute("texture-lighting"))??"baked";let r=jc(this.getAttribute("texture-quality"));r!==void 0&&(s.textureQuality=r),s.textureLeafSizing=$c(this.getAttribute("texture-leaf-sizing"))??"canonical";let i=Uc(this.getAttribute("texture-image-rendering"));i!==void 0&&(s.textureImageRendering=i);let c=Wc(this.getAttribute("texture-backend"));c!==void 0&&(s.textureBackend=c);let l=Gc(this.getAttribute("texture-projection"));return l!==void 0&&(s.textureProjection=l),s.autoCenter=this.hasAttribute("auto-center"),t&&(s.directionalLight=t),o&&(s.ambientLight=o),s}_readDirectionalLight(){let t=qo(this.getAttribute("directional-direction")),o=this.getAttribute("directional-color")||void 0,s=je(this.getAttribute("directional-intensity"));if(!t&&!o&&s===void 0)return;let r={direction:t??[.4,-.7,.59]};return o&&(r.color=o),s!==void 0&&(r.intensity=s),r}_readAmbientLight(){let t=this.getAttribute("ambient-color")||void 0,o=je(this.getAttribute("ambient-intensity"));if(!t&&o===void 0)return;let s={};return t&&(s.color=t),o!==void 0&&(s.intensity=o),s}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=zo(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,s){if(o!==s&&this._scene){if(this._implicitCamera&&["rot-x","rot-y","zoom","distance","target"].includes(t)){let i=je(this.getAttribute("rot-x")),c=je(this.getAttribute("rot-y")),l=je(this.getAttribute("zoom")),u=je(this.getAttribute("distance")),d=qo(this.getAttribute("target"));i!==void 0&&this._implicitCamera.update({rotX:i}),c!==void 0&&this._implicitCamera.update({rotY:c}),l!==void 0&&this._implicitCamera.update({zoom:l}),u!==void 0&&this._implicitCamera.update({distance:u}),d!==void 0&&this._implicitCamera.update({target:d}),this._scene.applyCamera();return}this._scene.setOptions(this._readNonCameraOptions())}}};import{computeSceneBbox as Xc,loadMesh as qc}from"@layoutit/polycss-core";var Zc=typeof HTMLElement<"u"?HTMLElement:class{},Qc=["src","mtl","mesh-resolution","position","scale","rotation","auto-center","cast-shadow","receive-shadow","target-size","default-color","palette","include-objects","exclude-objects"];function cn(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 yi(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return cn(e)}}function Zo(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 Kc(e){let n=e.getAttribute("target-size"),t=e.getAttribute("default-color"),o=Zo(e.getAttribute("palette")),s=Zo(e.getAttribute("include-objects")),r=Zo(e.getAttribute("exclude-objects")),i=n!==null?parseFloat(n):NaN,c={};return Number.isFinite(i)&&(c.targetSize=i),t&&(c.defaultColor=t),o&&(c.palette=o),s&&(c.includeObjects=s),r&&(c.excludeObjects=r),Object.keys(c).length>0?c:void 0}function Jc(e){return e.closest("poly-scene")??null}function eu(e){if(e.length===0)return e;let n=Xc(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,s=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&s===0)return e;let r=i=>[i[0]-t,i[1]-o,i[2]-s];return e.map(i=>({...i,vertices:i.vertices.map(r),...i.textureTriangles?.length?{textureTriangles:i.textureTriangles.map(c=>({...c,vertices:c.vertices.map(r)}))}:null}))}var un=class extends Zc{constructor(){super(...arguments);this._handle=null;this._parseResult=null;this._loadToken=0}static get observedAttributes(){return[...Qc]}getMeshHandle(){return this._handle}connectedCallback(){this._maybeLoad()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,s){if(o!==s){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:cn(this.getAttribute("position")),scale:yi(this.getAttribute("scale")),rotation:cn(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=Jc(this);if(!o)return;let s=++this._loadToken,r=this.getAttribute("mtl")||void 0,c=this.getAttribute("mesh-resolution")==="lossless"?"lossless":void 0,l=Kc(this),u;try{let f=r||c!==void 0||l?{...r?{mtlUrl:r}:{},...c!==void 0?{meshResolution:c}:{},...l?{objOptions:l}:{}}:void 0;u=await qc(t,f)}catch(f){this.dispatchEvent(new CustomEvent("polycss:error",{detail:f,bubbles:!0}));return}if(s!==this._loadToken){try{u.dispose()}catch{}return}let d=o.getScene();if(!d){try{u.dispose()}catch{}return}this.hasAttribute("auto-center")&&(u={...u,polygons:eu(u.polygons)}),this._parseResult=u,this._handle=d.add(u,{position:cn(this.getAttribute("position")),scale:yi(this.getAttribute("scale")),rotation:cn(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 dn}from"@layoutit/polycss-core";var tu=typeof HTMLElement<"u"?HTMLElement:class{},nu=["src","width","height","position","rotation","scale","allow","loading","referrerpolicy","sandbox","title"];function Qo(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 ou(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Qo(e)}}function bi(e,n){if(e===null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}function ru(e){let n=e.closest("poly-scene");return n?n.querySelector(".polycss-scene"):null}function su(e,n,t,o,s){let r=typeof t=="number"?t:t?.[0]??1,i=typeof t=="number"?t:t?.[1]??1,c=typeof t=="number"?t:t?.[2]??1,l=r!==1||i!==1||c!==1,u=!!n&&(!!n[0]||!!n[1]||!!n[2]),d=(e?.[1]??0)*dn,P=(e?.[0]??0)*dn,f=(e?.[2]??0)*dn,b=[];return b.push(`translate3d(${d}px, ${P}px, ${f}px)`),u&&(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(${r}, ${i}, ${c})`),b.push(`translate(${-o/2}px, ${-s/2}px)`),b.join(" ")}var Ko=class extends tu{constructor(){super(...arguments);this._wrapper=null;this._iframe=null}static get observedAttributes(){return[...nu]}getIframeElement(){return this._iframe}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,s){if(o!==s&&!(!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 r=this.getAttribute(t);r===null?this._iframe.removeAttribute(t):this._iframe.setAttribute(t,r);return}this._applyGeometry()}}_mount(){let t=ru(this);if(!t)return;let o=this.ownerDocument;if(!o)return;let s=o.createElement("div");s.className="polycss-iframe",s.style.position="absolute",s.style.left="0",s.style.top="0",s.style.transformOrigin="0 0",s.style.transformStyle="preserve-3d";let r=o.createElement("iframe");r.style.display="block",r.style.border="0",r.style.background="#000";let i=this.getAttribute("src");i&&(r.src=i);let c=this.getAttribute("allow");c&&r.setAttribute("allow",c);for(let l of["loading","referrerpolicy","sandbox","title"]){let u=this.getAttribute(l);u!==null&&r.setAttribute(l,u)}s.appendChild(r),t.appendChild(s),this._wrapper=s,this._iframe=r,this._applyGeometry()}_applyGeometry(){if(!this._wrapper||!this._iframe)return;let t=bi(this.getAttribute("width"),16),o=bi(this.getAttribute("height"),9),s=t*dn,r=o*dn;this._iframe.style.width=`${s}px`,this._iframe.style.height=`${r}px`;let i=Qo(this.getAttribute("position")),c=Qo(this.getAttribute("rotation")),l=ou(this.getAttribute("scale"));this._wrapper.style.transform=su(i,c,l,s,r)}_teardown(){this._wrapper?.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null,this._iframe=null}};var iu=typeof HTMLElement<"u"?HTMLElement:class{},au=["vertices","color","texture","uvs","position","scale","rotation"];function xi(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Jo(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 lu(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Jo(e)}}function cu(e){return e.closest("poly-scene")??null}var er=class extends iu{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...au]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,s){o!==s&&(this._tearDown(),this.isConnected&&this._mount())}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=cu(this);if(!t)return;let o=t.getScene();if(!o)return;let s=xi(this.getAttribute("vertices"));if(!s||!Array.isArray(s)||s.length<3)return;let r=this.getAttribute("color")||void 0,i=this.getAttribute("texture")||void 0,c=xi(this.getAttribute("uvs"))??void 0,l={};for(let P of Array.from(this.attributes))P.name.startsWith("data-")&&(l[P.name.slice(5)]=P.value);let d={polygons:[{vertices:s,...r!==void 0?{color:r}:{},...i!==void 0?{texture:i}:{},...c!==void 0?{uvs:c}:{},...Object.keys(l).length>0?{data:l}:{}}],objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(d,{position:Jo(this.getAttribute("position")),scale:lu(this.getAttribute("scale")),rotation:Jo(this.getAttribute("rotation"))})}};function te(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function zn(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 Ee(e){if(e!==null)return!(e==="false"||e==="0")}function Bn(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 Vn(e){if(e==="x"||e==="y")return e}var uu=typeof HTMLElement<"u"?HTMLElement:class{},du=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],tr=class extends uu{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...du]}getControls(){return this._controls}_readAnimate(){let t=te(this.getAttribute("animate-speed")),o=Vn(this.getAttribute("animate-axis")),s=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}:{},...s!==null?{pauseOnInteraction:Ee(s)}:{}}}_readOptions(){let t={},o=Ee(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let s=Ee(this.getAttribute("wheel"));s!==void 0&&(t.wheel=s),this.hasAttribute("dolly")&&(t.dolly=!0);let r=te(this.getAttribute("min-distance"));r!==void 0&&(t.minDistance=r);let i=te(this.getAttribute("max-distance"));i!==void 0&&(t.maxDistance=i);let c=Bn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=te(this.getAttribute("zoom-min")),u=te(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),u!==void 0&&(t.maxZoom=u),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Oe)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let s=()=>{t.removeEventListener("polycss:scene-ready",s),this._attach()};t.addEventListener("polycss:scene-ready",s)}return}this._controls=Bo(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,s){o!==s&&this._controls&&this._controls.update(this._readOptions())}};var pu=typeof HTMLElement<"u"?HTMLElement:class{},mu=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],nr=class extends pu{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...mu]}_readAnimate(){let t=te(this.getAttribute("animate-speed")),o=Vn(this.getAttribute("animate-axis")),s=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}:{},...s!==null?{pauseOnInteraction:Ee(s)}:{}}}_readOptions(){let t={},o=Ee(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let s=Ee(this.getAttribute("wheel"));s!==void 0&&(t.wheel=s),this.hasAttribute("dolly")&&(t.dolly=!0);let r=te(this.getAttribute("min-distance"));r!==void 0&&(t.minDistance=r);let i=te(this.getAttribute("max-distance"));i!==void 0&&(t.maxDistance=i);let c=Bn(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=te(this.getAttribute("zoom-min")),u=te(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),u!==void 0&&(t.maxZoom=u),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Oe)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let s=()=>{t.removeEventListener("polycss:scene-ready",s),this._attach()};t.addEventListener("polycss:scene-ready",s)}return}this._controls=Vo(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,s){o!==s&&this._controls&&this._controls.update(this._readOptions())}};var fu=typeof HTMLElement<"u"?HTMLElement:class{},gu=["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"],or=class extends fu{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...gu]}_readOptions(){let t={},o=Ee(this.getAttribute("enabled"));o!==void 0&&(t.enabled=o);let s=Ee(this.getAttribute("look-enabled"));s!==void 0&&(t.lookEnabled=s);let r=Ee(this.getAttribute("move-enabled"));r!==void 0&&(t.moveEnabled=r);let i=Ee(this.getAttribute("jump-enabled"));i!==void 0&&(t.jumpEnabled=i);let c=Ee(this.getAttribute("crouch-enabled"));c!==void 0&&(t.crouchEnabled=c);let l=te(this.getAttribute("look-sensitivity"));if(l!==void 0&&(t.lookSensitivity=l),this.hasAttribute("invert-y")){let C=Ee(this.getAttribute("invert-y"));C!==void 0&&(t.invertY=C)}let u=te(this.getAttribute("move-speed"));u!==void 0&&(t.moveSpeed=u);let d=te(this.getAttribute("jump-velocity"));d!==void 0&&(t.jumpVelocity=d);let P=te(this.getAttribute("gravity"));P!==void 0&&(t.gravity=P);let f=te(this.getAttribute("eye-height"));f!==void 0&&(t.eyeHeight=f);let b=te(this.getAttribute("crouch-height"));b!==void 0&&(t.crouchHeight=b);let x=te(this.getAttribute("ground-z"));x!==void 0&&(t.groundZ=x);let v=te(this.getAttribute("min-pitch"));v!==void 0&&(t.minPitch=v);let y=te(this.getAttribute("max-pitch"));return y!==void 0&&(t.maxPitch=y),t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Oe)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let s=()=>{t.removeEventListener("polycss:scene-ready",s),this._attach()};t.addEventListener("polycss:scene-ready",s)}return}this._controls=jo(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,s){o!==s&&this._controls&&this._controls.update(this._readOptions())}};var hu=typeof HTMLElement<"u"?HTMLElement:class{},yu=["perspective","zoom","rot-x","rot-y","target","distance"],rr=class extends hu{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...yu]}getCamera(){return this._camera}_readOptions(){return{perspective:te(this.getAttribute("perspective")),zoom:te(this.getAttribute("zoom")),rotX:te(this.getAttribute("rot-x")),rotY:te(this.getAttribute("rot-y")),target:zn(this.getAttribute("target")),distance:te(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=an(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,s){if(o===s||!this._camera||!this._wrapper)return;let r=this._readOptions();if(t==="perspective"){let l=r.perspective!==void 0?`${r.perspective}px`:"32000px";this._wrapper.style.perspective=l;return}this._camera.update({rotX:r.rotX,rotY:r.rotY,zoom:r.zoom,target:r.target,distance:r.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var bu=typeof HTMLElement<"u"?HTMLElement:class{},xu=["zoom","rot-x","rot-y","target","distance"],pn=class extends bu{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...xu]}getCamera(){return this._camera}_readOptions(){return{zoom:te(this.getAttribute("zoom")),rotX:te(this.getAttribute("rot-x")),rotY:te(this.getAttribute("rot-y")),target:zn(this.getAttribute("target")),distance:te(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=yt(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,s){if(o===s||!this._camera)return;let r=this._readOptions();r.zoom!==void 0&&this._camera.update({zoom:r.zoom}),r.rotX!==void 0&&this._camera.update({rotX:r.rotX}),r.rotY!==void 0&&this._camera.update({rotY:r.rotY}),r.target!==void 0&&this._camera.update({target:r.target}),r.distance!==void 0&&this._camera.update({distance:r.distance}),this.querySelector("poly-scene")?.getScene?.()?.applyCamera()}};var sr=class extends pn{};var Pu=typeof HTMLElement<"u"?HTMLElement:class{},vu=["mode","target","size","enabled"];function Pi(e){if(e==="translate"||e==="rotate")return e}var ir=class extends Pu{constructor(){super(...arguments);this._tc=null}static get observedAttributes(){return[...vu]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Oe)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 s=null;try{s=o.querySelector(`#${t}`)??o.querySelector(t)}catch{s=o.querySelector(`[id="${t}"]`)}return s instanceof un?s:null}_readOptions(){let t={},o=Pi(this.getAttribute("mode"));o!==void 0&&(t.mode=o);let s=te(this.getAttribute("size"));s!==void 0&&(t.size=s);let r=this.getAttribute("enabled");return r!==null&&(t.enabled=r!=="false"&&r!=="0"),t.onObjectChange=i=>{this.dispatchEvent(new CustomEvent("polycss:object-change",{bubbles:!0,detail:{position:i.position,rotation:i.rotation}}))},t}_attach(){if(this._tc)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._tc=Xo(o,this._readOptions());let s=this._findTargetMesh();if(s){let r=s.getMeshHandle();r&&this._tc.attach(r)}}connectedCallback(){this._attach()}disconnectedCallback(){this._tc&&(this._tc.destroy(),this._tc=null)}attributeChangedCallback(t,o,s){if(o!==s&&this._tc){if(t==="mode"){let r=Pi(s);r&&this._tc.setMode(r)}else if(t==="target"){let r=this._findTargetMesh();this._tc.attach(r?r.getMeshHandle()??null:null)}}}};var Su=typeof HTMLElement<"u"?HTMLElement:class{},Cu=["multiple","clear-on-miss"],ar=class extends Su{constructor(){super(...arguments);this._selection=null}static get observedAttributes(){return[...Cu]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof Oe)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 s=()=>{t.removeEventListener("polycss:scene-ready",s),this._attach()};t.addEventListener("polycss:scene-ready",s)}return}this._selection=$o(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._selection&&(this._selection.destroy(),this._selection=null)}attributeChangedCallback(t,o,s){o!==s&&(this._selection&&(this._selection.destroy(),this._selection=null),this._attach())}};var lr={quad:0,clippedSolid:0,atlas:0,stableTriangle:0},cr={ready:!0,textureLeafCount:0,readyTextureLeafCount:0,pendingTextureLeafCount:0,atlasTextureLeafCount:0,imageTextureLeafCount:0};function ur(){return{ready:!0,leafCount:0,atlasCount:0,imageCount:0,pendingCount:0,sizingCounts:{canonical:0,local:0,raster:0,image:0,unknown:0},imageRenderingCounts:{auto:0,pixelated:0,unknown:0},projectionCounts:{affine:0,projective:0,fallback:0,unknown:0},minLeafWidth:0,maxLeafWidth:0,minLeafHeight:0,maxLeafHeight:0,doubleSidedCount:0}}function dr(){return{runtimeAtlasUrlCount:0,snapshotAtlasCount:0,snapshotBackgroundCount:0,selfContained:!0}}function Nn(){return{rootFound:!1,projection:"unknown",perspectiveStyle:"",appliedPerspectiveStyle:""}}var Tu={polygonCount:0,mountedPolygonLeafCount:0,shadowLeafCount:0,surfaceLeafCounts:lr,textureReadiness:cr,textureStats:ur(),snapshotStats:dr(),cameraStats:Nn(),bucketCount:0};function jn(e){return typeof e=="number"?{polygonCount:e}:e??{}}function bt(e,n){return e.querySelectorAll(n).length}function vi(e,n){return(Ci(e,n)?1:0)+bt(e,n)}function Si(e){if(!e)return!1;let n=/url\((?:"([^"]*)"|'([^']*)'|([^)]*))\)/g,t;for(;t=n.exec(e);){let o=(t[1]??t[2]??t[3]??"").trim();if(o&&!o.startsWith("data:"))return!0}return!1}function Eu(e){let n=0,t=e instanceof HTMLElement?e:null;t&&Si(t.getAttribute("style"))&&n++;for(let o of Array.from(e.querySelectorAll("[style]")))o instanceof HTMLElement&&Si(o.getAttribute("style"))&&n++;return n}function Ci(e,n){let t=e;return typeof t.matches=="function"&&t.matches(n)}function $n(e,n){if(!n)return[e];let t=[];return Ci(e,n)&&t.push(e),t.push(...Array.from(e.querySelectorAll(n))),t}function Au(e){switch(e.toLowerCase()){case"b":return"quad";case"i":return"clippedSolid";case"s":return"atlas";case"u":return"stableTriangle";default:return null}}function wu(e){if(e==null||e==="")return;let n=Number.parseInt(e,10);return Number.isFinite(n)?n:void 0}function jt(e){if(e==null||e==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}function Mu(e){if(e==null||e==="")return;let n=e.split(",").map(t=>Number(t));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return n}function Lu(e){return e==="orthographic"||e==="perspective"?e:"unknown"}function Ru(e,n){if(!n)return;let t=e.getAttribute("data-polycss-texture-ready");return t==="true"?!0:t==="false"?!1:e.style.opacity!=="0"}function pr(e,n){if(!e)return[];let t=jn(n),o=[];for(let s of $n(e,t.scopeSelector))for(let r of Array.from(s.querySelectorAll("b,i,s,u"))){let i=r,c=Au(i.tagName);if(!c)continue;let l=i.getAttribute("data-polycss-texture-backend")??(c==="atlas"?"atlas":void 0),u=Ru(i,l);o.push({element:i,strategy:c,polygonIndex:wu(i.getAttribute("data-poly-index")),textureBackend:l,textureReady:u,textureLeafSizing:i.getAttribute("data-polycss-texture-leaf-sizing")??void 0,textureImageRendering:i.getAttribute("data-polycss-texture-image-rendering")??void 0,textureProjection:i.getAttribute("data-polycss-texture-projection")??void 0,textureLeafWidth:jt(i.getAttribute("data-polycss-texture-leaf-width")),textureLeafHeight:jt(i.getAttribute("data-polycss-texture-leaf-height")),doubleSided:i.getAttribute("data-polycss-double-sided")==="true"})}return o}function Ti(e,n){let t={...cr};for(let o of pr(e,n))o.textureBackend&&(t.textureLeafCount++,o.textureBackend==="image"?t.imageTextureLeafCount++:t.atlasTextureLeafCount++,o.textureReady===!1?t.pendingTextureLeafCount++:t.readyTextureLeafCount++);return t.ready=t.pendingTextureLeafCount===0,t}function ku(e,n){let t=ur(),o=!1,s=!1;for(let r of pr(e,n))if(r.textureBackend){switch(t.leafCount++,r.textureBackend==="image"?t.imageCount++:t.atlasCount++,r.textureReady===!1&&t.pendingCount++,r.textureLeafSizing){case"canonical":case"local":case"raster":case"image":t.sizingCounts[r.textureLeafSizing]++;break;default:t.sizingCounts.unknown++;break}switch(r.textureImageRendering){case"auto":case"pixelated":t.imageRenderingCounts[r.textureImageRendering]++;break;default:t.imageRenderingCounts.unknown++;break}switch(r.textureProjection){case"affine":case"projective":case"fallback":t.projectionCounts[r.textureProjection]++;break;default:t.projectionCounts.unknown++;break}typeof r.textureLeafWidth=="number"&&(t.minLeafWidth=o?Math.min(t.minLeafWidth,r.textureLeafWidth):r.textureLeafWidth,t.maxLeafWidth=o?Math.max(t.maxLeafWidth,r.textureLeafWidth):r.textureLeafWidth,o=!0),typeof r.textureLeafHeight=="number"&&(t.minLeafHeight=s?Math.min(t.minLeafHeight,r.textureLeafHeight):r.textureLeafHeight,t.maxLeafHeight=s?Math.max(t.maxLeafHeight,r.textureLeafHeight):r.textureLeafHeight,s=!0),r.doubleSided&&t.doubleSidedCount++}return t.pendingCount=Math.min(t.pendingCount,t.leafCount),t.ready=t.pendingCount===0,t}function _u(e,n){let t=dr();if(!e)return t;let o=jn(n);for(let s of $n(e,o.scopeSelector))t.runtimeAtlasUrlCount+=Eu(s),t.snapshotAtlasCount+=vi(s,"[data-polycss-snapshot-atlas]"),t.snapshotBackgroundCount+=vi(s,"[data-polycss-snapshot-bg]");return t.selfContained=t.runtimeAtlasUrlCount===0,t}function Ou(e){let n=e instanceof HTMLElement?e:null;if(n){if(n.classList.contains("polycss-camera"))return n;let o=n.closest(".polycss-camera");if(o instanceof HTMLElement)return o}let t=e.querySelector(".polycss-camera");return t instanceof HTMLElement?t:null}function Du(e,n){if(!e)return Nn();let t=jn(n),o=null;for(let s of $n(e,t.scopeSelector))if(o=Ou(s),o)break;return o?{rootFound:!0,projection:Lu(o.getAttribute("data-polycss-camera-projection")),perspectiveStyle:o.getAttribute("data-polycss-camera-perspective")??"",appliedPerspectiveStyle:o.getAttribute("data-polycss-camera-applied-perspective")??o.style.perspective??"",zoom:jt(o.getAttribute("data-polycss-camera-zoom")),distance:jt(o.getAttribute("data-polycss-camera-distance")),rotX:jt(o.getAttribute("data-polycss-camera-rot-x")),rotY:jt(o.getAttribute("data-polycss-camera-rot-y")),target:Mu(o.getAttribute("data-polycss-camera-target"))}:Nn()}function Iu(e,n){let t=jn(n);if(!e)return{...Tu,surfaceLeafCounts:{...lr},textureReadiness:{...cr},textureStats:ur(),snapshotStats:dr(),cameraStats:Nn(),polygonCount:t.polygonCount??0};let o=$n(e,t.scopeSelector),s={...lr},r=0,i=0;for(let l of o)s.quad+=bt(l,"b"),s.clippedSolid+=bt(l,"i"),s.atlas+=bt(l,"s"),s.stableTriangle+=bt(l,"u"),r+=bt(l,"q, .polycss-shadow-svg"),i+=bt(l,".polycss-bucket");let c=s.quad+s.clippedSolid+s.atlas+s.stableTriangle;return{polygonCount:t.polygonCount??c,mountedPolygonLeafCount:c,shadowLeafCount:r,surfaceLeafCounts:s,textureReadiness:Ti(e,t),textureStats:ku(e,t),snapshotStats:_u(e,t),cameraStats:Du(e,t),bucketCount:i}}var xt=class extends Error{constructor(n,t,o){super(t),this.name="PolySceneSnapshotError",this.code=n,this.url=o,Object.setPrototypeOf(this,new.target.prototype)}},Hu=`
520
520
  html,
521
521
  body {
522
522
  width: 100%;
@@ -528,10 +528,10 @@ body {
528
528
  position: relative;
529
529
  overflow: hidden;
530
530
  }
531
- `,Qo=["b","i","s","u"],ru=["b","i","u"],su=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--pnx","--pny","--pnz","--psr","--psg","--psb","--plam","--polycss-light-preview-active","--polycss-preview-r","--polycss-preview-g","--polycss-preview-b"],iu=["--clx","--cly","--clz","--shadow-ground-cssz"],au=["--polycss-atlas-size","--polycss-atlas-url","--polycss-atlas-position","--polycss-atlas-image-size"];function lu(e){return!!e&&typeof e.querySelector=="function"&&typeof e.cloneNode=="function"}function cu(e){let n=e.closest(".polycss-camera");if(n)return n;let t=e.closest(".polycss-scene");return t?t.closest(".polycss-camera")??t:e.querySelector(".polycss-camera")??e.querySelector(".polycss-scene")}function ln(e){return[e,...Array.from(e.querySelectorAll("*"))]}function tt(e,n){return e.matches(n)||!!e.querySelector(n)}function si(e,n){return e.tagName.toLowerCase()===n||!!e.querySelector(n)}function uu(e){let n=Qo.filter(o=>si(e,o)),t=ru.filter(o=>n.includes(o));return{hasCamera:tt(e,".polycss-camera"),hasScene:tt(e,".polycss-scene"),hasMesh:tt(e,".polycss-mesh"),hasFpvHost:tt(e,".polycss-fpv-host"),hasBucket:tt(e,".polycss-bucket"),hasVoxelMesh:tt(e,".polycss-voxel-mesh"),hasTransformGizmo:tt(e,".polycss-transform-gizmo"),hasTransformRing:tt(e,".polycss-transform-ring"),hasDynamicLighting:tt(e,'.polycss-scene[data-polycss-lighting="dynamic"]'),hasQ:si(e,"q"),leafTags:n,solidLeafTags:t}}function an(e,n=".polycss-scene "){return e.map(t=>`${n}${t}`).join(`,
532
- `)}function du(e){return e.map(n=>`.polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > ${n}`).join(`,
533
- `)}function pu(e){let n=['@property --plx { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --ply { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --plz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plr { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plg { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plb { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pli { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --par { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pag { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pab { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pai { syntax: "<number>"; inherits: true; initial-value: 0.4; }','@property --pnx { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --pny { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --pnz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psr { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psg { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psb { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plam { syntax: "<number>"; inherits: true; initial-value: 0; }'];return e&&n.push('@property --clx { syntax: "<number>"; inherits: true; initial-value: 0.01; }','@property --cly { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --clz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --shadow-ground-cssz { syntax: "<number>"; inherits: true; initial-value: 0; }'),n.join(`
534
- `)}function mu(e){let n=[pu(e.hasQ)];return e.hasBucket&&n.push(`
531
+ `,mr=["b","i","s","u"],Fu=["b","i","u"],zu=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--pnx","--pny","--pnz","--psr","--psg","--psb","--plam","--polycss-light-preview-active","--polycss-preview-r","--polycss-preview-g","--polycss-preview-b"],Bu=["--clx","--cly","--clz","--shadow-ground-cssz"],Vu=["--polycss-atlas-size","--polycss-atlas-width","--polycss-atlas-height","--polycss-atlas-leaf-sizing","--polycss-atlas-url","--polycss-atlas-position","--polycss-atlas-image-size"],Nu=["--polycss-atlas-size","--polycss-atlas-width","--polycss-atlas-height","--polycss-atlas-leaf-sizing"];function ju(e){return!!e&&typeof e.querySelector=="function"&&typeof e.cloneNode=="function"}function $u(e){let n=e.closest(".polycss-camera");if(n)return n;let t=e.closest(".polycss-scene");return t?t.closest(".polycss-camera")??t:e.querySelector(".polycss-camera")??e.querySelector(".polycss-scene")}function fn(e){return[e,...Array.from(e.querySelectorAll("*"))]}function tt(e,n){return e.matches(n)||!!e.querySelector(n)}function Ei(e,n){return e.tagName.toLowerCase()===n||!!e.querySelector(n)}function Uu(e){let n=mr.filter(o=>Ei(e,o)),t=Fu.filter(o=>n.includes(o));return{hasCamera:tt(e,".polycss-camera"),hasScene:tt(e,".polycss-scene"),hasMesh:tt(e,".polycss-mesh"),hasFpvHost:tt(e,".polycss-fpv-host"),hasBucket:tt(e,".polycss-bucket"),hasVoxelMesh:tt(e,".polycss-voxel-mesh"),hasTransformGizmo:tt(e,".polycss-transform-gizmo"),hasTransformRing:tt(e,".polycss-transform-ring"),hasDynamicLighting:tt(e,'.polycss-scene[data-polycss-lighting="dynamic"]'),hasQ:Ei(e,"q"),leafTags:n,solidLeafTags:t}}function mn(e,n=".polycss-scene "){return e.map(t=>`${n}${t}`).join(`,
532
+ `)}function Wu(e){return e.map(n=>`.polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > ${n}`).join(`,
533
+ `)}function Gu(e){let n=['@property --plx { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --ply { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --plz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plr { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plg { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plb { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pli { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --par { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pag { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pab { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --pai { syntax: "<number>"; inherits: true; initial-value: 0.4; }','@property --pnx { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --pny { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --pnz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psr { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psg { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --psb { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --plam { syntax: "<number>"; inherits: true; initial-value: 0; }'];return e&&n.push('@property --clx { syntax: "<number>"; inherits: true; initial-value: 0.01; }','@property --cly { syntax: "<number>"; inherits: true; initial-value: 0; }','@property --clz { syntax: "<number>"; inherits: true; initial-value: 1; }','@property --shadow-ground-cssz { syntax: "<number>"; inherits: true; initial-value: 0; }'),n.join(`
534
+ `)}function Yu(e){let n=[Gu(e.hasQ)];return e.hasBucket&&n.push(`
535
535
  .polycss-scene[data-polycss-lighting="dynamic"] .polycss-bucket {
536
536
  --plam: max(0, calc(
537
537
  var(--pnx) * var(--plx) +
@@ -540,7 +540,7 @@ body {
540
540
  ));
541
541
  }
542
542
  `),e.leafTags.length>0&&n.push(`
543
- ${du(e.leafTags)} {
543
+ ${Wu(e.leafTags)} {
544
544
  --plam: max(0, calc(
545
545
  var(--pnx) * var(--plx) +
546
546
  var(--pny) * var(--ply) +
@@ -574,7 +574,7 @@ ${du(e.leafTags)} {
574
574
  -webkit-mask-size: var(--polycss-atlas-image-size);
575
575
  }
576
576
  `),e.solidLeafTags.length>0&&n.push(`
577
- ${an(e.solidLeafTags)} {
577
+ ${mn(e.solidLeafTags)} {
578
578
  color: rgb(
579
579
  calc(255 * var(--psr) * (var(--par) * var(--pai)
580
580
  + var(--plr) * var(--pli) * var(--plam)))
@@ -604,7 +604,7 @@ ${an(e.solidLeafTags)} {
604
604
  opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1);
605
605
  }
606
606
  `),n.join(`
607
- `)}function fu(e){let n=[ou];if(e.hasScene&&n.push(`
607
+ `)}function Xu(e){let n=[Hu];if(e.hasScene&&n.push(`
608
608
  .polycss-scene,
609
609
  .polycss-scene *,
610
610
  .polycss-scene *::before,
@@ -643,7 +643,7 @@ ${an(e.solidLeafTags)} {
643
643
  transform-style: preserve-3d;
644
644
  }
645
645
  `),e.leafTags.length>0&&n.push(`
646
- ${an(e.leafTags)} {
646
+ ${mn(e.leafTags)} {
647
647
  position: absolute;
648
648
  display: block;
649
649
  transform-origin: 0 0;
@@ -659,7 +659,7 @@ ${an(e.leafTags)} {
659
659
  background-repeat: no-repeat;
660
660
  }
661
661
  `),e.solidLeafTags.length>0&&!e.hasDynamicLighting&&n.push(`
662
- ${an(e.solidLeafTags)} {
662
+ ${mn(e.solidLeafTags)} {
663
663
  color: currentColor;
664
664
  }
665
665
  `),e.leafTags.includes("b")&&n.push(`
@@ -766,13 +766,13 @@ ${an(e.solidLeafTags)} {
766
766
  .polycss-scene q::after {
767
767
  content: none;
768
768
  }
769
- `),e.hasTransformGizmo){let t=e.leafTags.length>0?e.leafTags:Qo;n.push(`
770
- ${an(t,".polycss-mesh.polycss-transform-gizmo ")} {
769
+ `),e.hasTransformGizmo){let t=e.leafTags.length>0?e.leafTags:mr;n.push(`
770
+ ${mn(t,".polycss-mesh.polycss-transform-gizmo ")} {
771
771
  backface-visibility: visible;
772
772
  transition: color 150ms ease-out, border-color 150ms ease-out, background-color 150ms ease-out;
773
773
  }
774
- `)}if(e.hasTransformRing){let t=e.leafTags.length>0?e.leafTags:Qo;n.push(`
775
- ${an(t,".polycss-mesh.polycss-transform-ring ")} {
774
+ `)}if(e.hasTransformRing){let t=e.leafTags.length>0?e.leafTags:mr;n.push(`
775
+ ${mn(t,".polycss-mesh.polycss-transform-ring ")} {
776
776
  --ring-inner-r: calc(var(--ring-inner-ratio, 0.92) * 50%);
777
777
  --ring-outer-r: calc(var(--ring-outer-ratio, 1) * 50%);
778
778
  -webkit-mask: radial-gradient(circle at 50% 50%,
@@ -788,12 +788,12 @@ ${an(t,".polycss-mesh.polycss-transform-ring ")} {
788
788
  black var(--ring-outer-r),
789
789
  transparent var(--ring-outer-r));
790
790
  }
791
- `)}return e.hasDynamicLighting&&n.push(mu(e)),n.map(t=>t.trim()).filter(Boolean).join(`
791
+ `)}return e.hasDynamicLighting&&n.push(Yu(e)),n.map(t=>t.trim()).filter(Boolean).join(`
792
792
 
793
- `)}function Jo(e){let n=e.style;return n&&typeof n.getPropertyValue=="function"?n:null}function ai(e){let n=e.getAttribute("style");n!==null&&n.trim()===""&&e.removeAttribute("style")}function hu(e,n){let t=e;for(;t;){let o=Jo(t)?.getPropertyValue(n).trim();if(o)return o;t=t.parentElement}return""}function gu(e,n,t){let o=ln(e),r=ln(n);for(let s=0;s<r.length;s++){let i=o[s],c=r[s];if(!i||!c)continue;let l=Jo(c);if(!l)continue;if(c.classList.contains("polycss-mesh")){let d=l.getPropertyValue("--origin").trim();d&&(l.setProperty("transform-origin",d),l.removeProperty("--origin"))}let u=c.tagName.toLowerCase();if(u==="s"){let d=l.getPropertyValue("--polycss-atlas-size").trim();if(d&&(l.setProperty("width",d),l.setProperty("height",d)),t.hasDynamicLighting)l.removeProperty("--polycss-atlas-size");else for(let x of au)l.removeProperty(x)}else if(u==="b"||u==="i"||u==="u"){let d=hu(i,"--polycss-paint"),x=t.hasDynamicLighting?"":i.ownerDocument.defaultView?.getComputedStyle(i).color;x?l.setProperty("color",x):d&&!l.getPropertyValue("color")&&l.setProperty("color",d)}if(!t.hasDynamicLighting)for(let d of su)l.removeProperty(d);if(!t.hasQ)for(let d of iu)l.removeProperty(d);l.removeProperty("will-change"),l.removeProperty("--polycss-paint"),ai(c)}}function yu(e){for(let n of Array.from(e.querySelectorAll("script")))n.remove();for(let n of ln(e))for(let t of Array.from(n.attributes))t.name.toLowerCase().startsWith("on")&&n.removeAttribute(t.name)}function li(e){let n=e.trim();return n===""||n.startsWith("#")||/^data:/i.test(n)}function bu(e,n){return/^data:/i.test(e.trim())?e.trim():ci(e,n.baseUrl)}function ii(e){let n=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/i.exec(e);return(n?.[2]??n?.[3]??"").trim()||null}function vu(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ")}function ci(e,n){try{return new URL(e,n).href}catch{throw new ht("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not resolve asset URL "${e}".`,e)}}function xu(e){let n=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.toLowerCase()}})();return n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".png")?"image/png":n.endsWith(".webp")?"image/webp":n.endsWith(".gif")?"image/gif":n.endsWith(".svg")?"image/svg+xml":n.endsWith(".avif")?"image/avif":"application/octet-stream"}function Pu(e){let n=new Uint8Array(e),t=32768,o="";for(let r=0;r<n.length;r+=t){let s=n.subarray(r,r+t);o+=String.fromCharCode(...s)}return btoa(o)}function Su(e){return/^(blob|filesystem):/i.test(e.trim())}function Cu(e){return new Promise((n,t)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType="blob",o.onload=()=>{o.status===0||o.status>=200&&o.status<300?n(o.response):t(new Error(`XHR ${o.status}`))},o.onerror=()=>t(new Error("XHR request failed")),o.send()})}async function Tu(e){let n=Su(e);try{if(typeof fetch!="function")throw new Error("fetch is not available");let t=await fetch(e,n?void 0:{credentials:"same-origin"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.blob()}catch(t){if(n&&typeof XMLHttpRequest=="function")return Cu(e);throw t}}async function ui(e,n){if(li(e))return e;let t=ci(e,n.baseUrl),o=n.cache.get(t);if(o)return o;let r=(async()=>{try{let s=await Tu(t),i=s.type||xu(t),c=Pu(await s.arrayBuffer());return`data:${i};base64,${c}`}catch{throw new ht("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not inline asset "${t}".`,t)}})();return n.cache.set(t,r),r}async function Ko(e,n){let t=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/gi,o="",r=0,s;for(;(s=t.exec(e))!==null;){o+=e.slice(r,s.index);let i=(s[2]??s[3]??"").trim(),c=await ui(i,n);o+=li(i)?s[0]:`url("${c}")`,r=t.lastIndex}return o+e.slice(r)}async function Eu(e,n){for(let t of ln(e)){let o=t.getAttribute("style");o&&t.setAttribute("style",await Ko(o,n))}for(let t of Array.from(e.querySelectorAll("style")))t.textContent=await Ko(t.textContent??"",n)}function Au(e){return{position:e.getPropertyValue("background-position").trim(),size:e.getPropertyValue("background-size").trim(),repeat:e.getPropertyValue("background-repeat").trim()}}function wu(e,n){n.position&&e.setProperty("background-position",n.position),n.size&&e.setProperty("background-size",n.size),n.repeat&&e.setProperty("background-repeat",n.repeat)}async function Mu(e,n){let t=[],o=new Map,r=new Map,s=async l=>{let u=bu(l,n),d=o.get(u);if(d)return d;let x=`a${o.size}`;return o.set(u,x),r.set(u,await ui(l,n)),x},i=l=>{for(let[u,d]of o)if(d===l)return r.get(u)??"";return""};for(let l of ln(e)){let u=Jo(l);if(!u||l.tagName.toLowerCase()!=="s")continue;let d=ii(u.getPropertyValue("--polycss-atlas-url"));if(d&&!d.startsWith("#")){let P=await s(d),y="data-polycss-snapshot-atlas";l.setAttribute(y,P),u.removeProperty("--polycss-atlas-url"),t.push({attr:y,value:P,property:"--polycss-atlas-url",dataUrl:i(P)})}let x=ii(u.getPropertyValue("background-image"));if(!x||x.startsWith("#"))continue;let h=await s(x),b="data-polycss-snapshot-bg",v=Au(u);l.setAttribute(b,h),u.removeProperty("background"),u.removeProperty("background-image"),wu(u,v),t.push({attr:b,value:h,property:"background-image",dataUrl:i(h)}),ai(l)}let c=new Set;return t.filter(l=>{let u=`${l.attr}|${l.value}|${l.property}`;return c.has(u)?!1:(c.add(u),!0)}).map(l=>`.polycss-scene [${l.attr}="${l.value}"] {
794
- ${l.property}: url("${vu(l.dataUrl)}");
793
+ `)}function gr(e){let n=e.style;return n&&typeof n.getPropertyValue=="function"?n:null}function wi(e){let n=e.getAttribute("style");n!==null&&n.trim()===""&&e.removeAttribute("style")}function qu(e,n){let t=e;for(;t;){let o=gr(t)?.getPropertyValue(n).trim();if(o)return o;t=t.parentElement}return""}function Zu(e,n,t){let o=fn(e),s=fn(n);for(let r=0;r<s.length;r++){let i=o[r],c=s[r];if(!i||!c)continue;let l=gr(c);if(!l)continue;if(c.classList.contains("polycss-mesh")){let d=l.getPropertyValue("--origin").trim();d&&(l.setProperty("transform-origin",d),l.removeProperty("--origin"))}let u=c.tagName.toLowerCase();if(u==="s"){let d=l.getPropertyValue("--polycss-atlas-size").trim(),P=l.getPropertyValue("--polycss-atlas-width").trim()||d,f=l.getPropertyValue("--polycss-atlas-height").trim()||d;if(P&&l.setProperty("width",P),f&&l.setProperty("height",f),t.hasDynamicLighting)for(let b of Nu)l.removeProperty(b);else for(let b of Vu)l.removeProperty(b)}else if(u==="b"||u==="i"||u==="u"){let d=qu(i,"--polycss-paint"),P=t.hasDynamicLighting?"":i.ownerDocument.defaultView?.getComputedStyle(i).color;P?l.setProperty("color",P):d&&!l.getPropertyValue("color")&&l.setProperty("color",d)}if(!t.hasDynamicLighting)for(let d of zu)l.removeProperty(d);if(!t.hasQ)for(let d of Bu)l.removeProperty(d);l.removeProperty("will-change"),l.removeProperty("--polycss-paint"),wi(c)}}function Qu(e){for(let n of Array.from(e.querySelectorAll("script")))n.remove();for(let n of fn(e))for(let t of Array.from(n.attributes))t.name.toLowerCase().startsWith("on")&&n.removeAttribute(t.name)}function Mi(e){let n=e.trim();return n===""||n.startsWith("#")||/^data:/i.test(n)}function Ku(e,n){return/^data:/i.test(e.trim())?e.trim():Li(e,n.baseUrl)}function Ai(e){let n=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/i.exec(e);return(n?.[2]??n?.[3]??"").trim()||null}function Ju(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ")}function Li(e,n){try{return new URL(e,n).href}catch{throw new xt("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not resolve asset URL "${e}".`,e)}}function ed(e){let n=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.toLowerCase()}})();return n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".png")?"image/png":n.endsWith(".webp")?"image/webp":n.endsWith(".gif")?"image/gif":n.endsWith(".svg")?"image/svg+xml":n.endsWith(".avif")?"image/avif":"application/octet-stream"}function td(e){let n=new Uint8Array(e),t=32768,o="";for(let s=0;s<n.length;s+=t){let r=n.subarray(s,s+t);o+=String.fromCharCode(...r)}return btoa(o)}function nd(e){return/^(blob|filesystem):/i.test(e.trim())}function od(e){return new Promise((n,t)=>{let o=new XMLHttpRequest;o.open("GET",e,!0),o.responseType="blob",o.onload=()=>{o.status===0||o.status>=200&&o.status<300?n(o.response):t(new Error(`XHR ${o.status}`))},o.onerror=()=>t(new Error("XHR request failed")),o.send()})}async function rd(e){let n=nd(e);try{if(typeof fetch!="function")throw new Error("fetch is not available");let t=await fetch(e,n?void 0:{credentials:"same-origin"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.blob()}catch(t){if(n&&typeof XMLHttpRequest=="function")return od(e);throw t}}async function Ri(e,n){if(Mi(e))return e;let t=Li(e,n.baseUrl),o=n.cache.get(t);if(o)return o;let s=(async()=>{try{let r=await rd(t),i=r.type||ed(t),c=td(await r.arrayBuffer());return`data:${i};base64,${c}`}catch{throw new xt("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not inline asset "${t}".`,t)}})();return n.cache.set(t,s),s}async function fr(e,n){let t=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/gi,o="",s=0,r;for(;(r=t.exec(e))!==null;){o+=e.slice(s,r.index);let i=(r[2]??r[3]??"").trim(),c=await Ri(i,n);o+=Mi(i)?r[0]:`url("${c}")`,s=t.lastIndex}return o+e.slice(s)}async function sd(e,n){for(let t of fn(e)){let o=t.getAttribute("style");o&&t.setAttribute("style",await fr(o,n))}for(let t of Array.from(e.querySelectorAll("style")))t.textContent=await fr(t.textContent??"",n)}function id(e){return{position:e.getPropertyValue("background-position").trim(),size:e.getPropertyValue("background-size").trim(),repeat:e.getPropertyValue("background-repeat").trim()}}function ad(e,n){n.position&&e.setProperty("background-position",n.position),n.size&&e.setProperty("background-size",n.size),n.repeat&&e.setProperty("background-repeat",n.repeat)}async function ld(e,n){let t=[],o=new Map,s=new Map,r=async l=>{let u=Ku(l,n),d=o.get(u);if(d)return d;let P=`a${o.size}`;return o.set(u,P),s.set(u,await Ri(l,n)),P},i=l=>{for(let[u,d]of o)if(d===l)return s.get(u)??"";return""};for(let l of fn(e)){let u=gr(l);if(!u||l.tagName.toLowerCase()!=="s")continue;let d=Ai(u.getPropertyValue("--polycss-atlas-url"));if(d&&!d.startsWith("#")){let v=await r(d),y="data-polycss-snapshot-atlas";l.setAttribute(y,v),u.removeProperty("--polycss-atlas-url"),t.push({attr:y,value:v,property:"--polycss-atlas-url",dataUrl:i(v)})}let P=Ai(u.getPropertyValue("background-image"));if(!P||P.startsWith("#"))continue;let f=await r(P),b="data-polycss-snapshot-bg",x=id(u);l.setAttribute(b,f),u.removeProperty("background"),u.removeProperty("background-image"),ad(u,x),t.push({attr:b,value:f,property:"background-image",dataUrl:i(f)}),wi(l)}let c=new Set;return t.filter(l=>{let u=`${l.attr}|${l.value}|${l.property}`;return c.has(u)?!1:(c.add(u),!0)}).map(l=>`.polycss-scene [${l.attr}="${l.value}"] {
794
+ ${l.property}: url("${Ju(l.dataUrl)}");
795
795
  }`).join(`
796
796
 
797
- `)}function Lu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function _u(e){return e.replace(/<\/style/gi,"<\\/style")}function Ru(e){return e.baseURI||e.URL||e.defaultView?.location.href||"http://localhost/"}async function ku(e){if(!lu(e))throw new ht("INVALID_TARGET","exportPolySceneSnapshot: target must be an Element.");let n=cu(e);if(!n)throw new ht("SCENE_NOT_FOUND","exportPolySceneSnapshot: target is not inside and does not contain a rendered PolyCSS scene.");let t=e.ownerDocument,o={baseUrl:Ru(t),cache:new Map},r=n.cloneNode(!0),s=uu(r);gu(n,r,s),yu(r);let i=await Mu(r,o);await Eu(r,o);let c=await Ko([fu(s),i].filter(Boolean).join(`
797
+ `)}function cd(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ud(e){return e.replace(/<\/style/gi,"<\\/style")}function dd(e){return e.baseURI||e.URL||e.defaultView?.location.href||"http://localhost/"}async function pd(e){if(!ju(e))throw new xt("INVALID_TARGET","exportPolySceneSnapshot: target must be an Element.");let n=$u(e);if(!n)throw new xt("SCENE_NOT_FOUND","exportPolySceneSnapshot: target is not inside and does not contain a rendered PolyCSS scene.");let t=e.ownerDocument,o={baseUrl:dd(t),cache:new Map},s=n.cloneNode(!0),r=Uu(s);Zu(n,s,r),Qu(s);let i=await ld(s,o);await sd(s,o);let c=await fr([Xu(r),i].filter(Boolean).join(`
798
798
 
799
- `),o);return["<!doctype html>","<html>","<head>",'<meta charset="utf-8">',t.title?`<title>${Lu(t.title)}</title>`:"",`<style>${_u(c)}</style>`,"</head>","<body>",r.outerHTML,"</body>","</html>"].filter(Boolean).join("")}import{boxPolygons as Ou,planePolygons as Du,ringPolygons as Iu,octahedronPolygons as Hu,spherePolygons as Fu,tetrahedronPolygons as Vu,icosahedronPolygons as Bu,dodecahedronPolygons as zu,cylinderPolygons as Nu,conePolygons as Uu,torusPolygons as Gu}from"@layoutit/polycss-core";function Xe(e){return{polygons:e,objectUrls:[],warnings:[],dispose:()=>{}}}function $u(e={}){return Xe(Ou(e))}function Wu(e){return Xe(Du(e))}function ju(e){return Xe(Iu(e))}function Yu(e){return Xe(Hu(e))}function Xu(e={}){return Xe(Fu(e))}function Zu(e={}){return Xe(Vu(e))}function qu(e={}){return Xe(Bu(e))}function Qu(e={}){return Xe(zu(e))}function Ku(e={}){return Xe(Nu(e))}function Ju(e={}){return Xe(Uu(e))}function ed(e={}){return Xe(Gu(e))}import{boxPolygons as td,planePolygons as nd,ringPolygons as od,octahedronPolygons as rd,spherePolygons as sd,tetrahedronPolygons as id,icosahedronPolygons as ad,dodecahedronPolygons as ld,cylinderPolygons as cd,conePolygons as ud,torusPolygons as dd,computeSceneBbox as pd}from"@layoutit/polycss-core";var md=typeof HTMLElement<"u"?HTMLElement:class{};function fd(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 gt(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 hd(e){if(e.length===0)return e;let n=pd(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 s=i=>[i[0]-t,i[1]-o,i[2]-r];return e.map(i=>({...i,vertices:i.vertices.map(s)}))}var ke=class extends md{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:gt(this,"position"),scale:(()=>{let s=this.getAttribute("scale");if(!s)return;if(s.includes(","))return gt(this,"scale");let i=parseFloat(s);return Number.isFinite(i)?i:void 0})(),rotation:gt(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=fd(this);if(!t)return;let o=t.getScene?.();if(!o)return;let r=this.buildPolygons();this.hasAttribute("auto-center")&&(r=hd(r));let s={polygons:r,objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(s,{position:gt(this,"position"),scale:(()=>{let i=this.getAttribute("scale");if(!i)return;if(i.includes(","))return gt(this,"scale");let c=parseFloat(i);return Number.isFinite(c)?c:void 0})(),rotation:gt(this,"rotation"),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow"),excludeFromAutoCenter:this.hasAttribute("exclude-from-auto-center"),merge:!1})}},er=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 td({size:t!==void 0&&Number.isFinite(t)?t:void 0,color:Ze(this,"color")})}},tr=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 nd({axis:t,size:he(this,"size",.4),offset:Number.isFinite(r)?r:0,color:Ze(this,"color")})}},nr=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 od({axis:t,radius:he(this,"radius",50),segments:he(this,"segments",32),halfThickness:o?parseFloat(o):void 0,color:Ze(this,"color")})}},or=class extends ke{static get observedAttributes(){return["size","color","center","auto-center","position","scale","rotation"]}buildPolygons(){return rd({center:gt(this,"center")??[0,0,0],size:he(this,"size",50),color:Ze(this,"color")})}},rr=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return id({size:he(this,"size",100),color:Ze(this,"color")})}},sr=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return ad({size:he(this,"size",100),color:Ze(this,"color")})}},ir=class extends ke{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return ld({size:he(this,"size",100),color:Ze(this,"color")})}},ar=class extends ke{static get observedAttributes(){return["radius","subdivisions","color","auto-center","position","scale","rotation"]}buildPolygons(){return sd({radius:he(this,"radius",50),subdivisions:he(this,"subdivisions",1),color:Ze(this,"color")})}},lr=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 cd({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")})}},cr=class extends ke{static get observedAttributes(){return["radius","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return ud({radius:he(this,"radius",50),height:he(this,"height",100),radialSegments:he(this,"radial-segments",12),color:Ze(this,"color")})}},ur=class extends ke{static get observedAttributes(){return["radius","tube","radial-segments","tubular-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return dd({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")})}};export*from"@layoutit/polycss-core";export{er as PolyBoxElement,Yo as PolyCameraElement,cr as PolyConeElement,lr as PolyCylinderElement,ir as PolyDodecahedronElement,Wo as PolyFirstPersonControlsElement,sr as PolyIcosahedronElement,zo as PolyIframeElement,$o as PolyMapControlsElement,on as PolyMeshElement,or as PolyOctahedronElement,Go as PolyOrbitControlsElement,sn as PolyOrthographicCameraElement,jo as PolyPerspectiveCameraElement,tr as PolyPlaneElement,Uo as PolyPolygonElement,nr as PolyRingElement,Re as PolySceneElement,ht as PolySceneSnapshotError,Zo as PolySelectElement,ar as PolySphereElement,rr as PolyTetrahedronElement,ur as PolyTorusElement,Xo as PolyTransformControlsElement,St as buildAtlasPages,Nf as buildPolyMeshTransform,Uf as buildPolySceneTransform,Gr as buildTextureEdgeRepairSets,nu as collectPolyRenderStats,$r as computeTextureAtlasPlanPublic,$u as createPolyBox,Gl as createPolyCamera,Ju as createPolyCone,Ku as createPolyCylinder,Qu as createPolyDodecahedron,_o as createPolyFirstPersonControls,qu as createPolyIcosahedron,Mo as createPolyMapControls,Yu as createPolyOctahedron,wo as createPolyOrbitControls,ft as createPolyOrthographicCamera,en as createPolyPerspectiveCamera,Wu as createPolyPlane,ju as createPolyRing,Ao as createPolyScene,Xu as createPolySphere,Zu as createPolyTetrahedron,ed as createPolyTorus,Ro as createSelect,Ho as createTransformControls,Zr as cssBorderShapeForPlan,Gf as cssDistanceToWorld,Wf as cssPositionToWorld,ku as exportPolySceneSnapshot,jn as filterAtlasPlans,Xr as formatBorderShapeEntryMatrix,jr as formatCssLengthPx,Wr as formatMatrix3d,Yr as formatSolidQuadEntryMatrix,ut as getSolidPaintDefaults,Wn as getSolidPaintDefaultsFromPlans,bo as injectPolyBaseStyles,mn as isBorderShapeSupported,Ve as isFullRectSolid,Be as isProjectiveQuadPlan,Ke as isSolidTrianglePlan,fn as isSolidTriangleSupported,vt as packTextureAtlasPlansWithScale,$f as polyCssDistanceToWorld,jf as polyCssPositionToWorld,Lt as renderPolygonsWithStableTriangles,dt as renderPolygonsWithTextureAtlas,Zt as renderPolygonsWithTextureAtlasAsync,Qt as updatePolygonsWithStableTopology,uo as updatePolygonsWithStableTriangles,qt as updateStableTriangleFrame,qf as worldDirectionToPolyCss,Zf as worldDirectionalLightToPolyCss,Yf as worldDistanceToCss,Xf as worldDistanceToPolyCss,Qf as worldPositionToPolyCss};
799
+ `),o);return["<!doctype html>","<html>","<head>",'<meta charset="utf-8">',t.title?`<title>${cd(t.title)}</title>`:"",`<style>${ud(c)}</style>`,"</head>","<body>",s.outerHTML,"</body>","</html>"].filter(Boolean).join("")}import{boxPolygons as md,planePolygons as fd,ringPolygons as gd,octahedronPolygons as hd,spherePolygons as yd,tetrahedronPolygons as bd,icosahedronPolygons as xd,dodecahedronPolygons as Pd,cylinderPolygons as vd,conePolygons as Sd,torusPolygons as Cd}from"@layoutit/polycss-core";function Ye(e){return{polygons:e,objectUrls:[],warnings:[],dispose:()=>{}}}function Td(e={}){return Ye(md(e))}function Ed(e){return Ye(fd(e))}function Ad(e){return Ye(gd(e))}function wd(e){return Ye(hd(e))}function Md(e={}){return Ye(yd(e))}function Ld(e={}){return Ye(bd(e))}function Rd(e={}){return Ye(xd(e))}function kd(e={}){return Ye(Pd(e))}function _d(e={}){return Ye(vd(e))}function Od(e={}){return Ye(Sd(e))}function Dd(e={}){return Ye(Cd(e))}import{boxPolygons as Id,planePolygons as Hd,ringPolygons as Fd,octahedronPolygons as zd,spherePolygons as Bd,tetrahedronPolygons as Vd,icosahedronPolygons as Nd,dodecahedronPolygons as jd,cylinderPolygons as $d,conePolygons as Ud,torusPolygons as Wd,computeSceneBbox as Gd}from"@layoutit/polycss-core";var Yd=typeof HTMLElement<"u"?HTMLElement:class{};function Xd(e){return e.closest("poly-scene")??null}function ge(e,n,t){let o=e.getAttribute(n);if(!o)return t;let s=parseFloat(o);return Number.isFinite(s)?s:t}function Xe(e,n,t){return e.getAttribute(n)??t}function Pt(e,n){let t=e.getAttribute(n);if(!t)return;let o=t.split(",").map(s=>parseFloat(s.trim()));if(!(o.length!==3||o.some(s=>!Number.isFinite(s))))return[o[0],o[1],o[2]]}function qd(e){if(e.length===0)return e;let n=Gd(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,s=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&s===0)return e;let r=i=>[i[0]-t,i[1]-o,i[2]-s];return e.map(i=>({...i,vertices:i.vertices.map(r)}))}var De=class extends Yd{constructor(){super(...arguments);this._handle=null}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,s){if(o!==s&&this._handle){if(t==="position"||t==="scale"||t==="rotation"||t==="cast-shadow"||t==="receive-shadow"){this._handle.setTransform({position:Pt(this,"position"),scale:(()=>{let r=this.getAttribute("scale");if(!r)return;if(r.includes(","))return Pt(this,"scale");let i=parseFloat(r);return Number.isFinite(i)?i:void 0})(),rotation:Pt(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=Xd(this);if(!t)return;let o=t.getScene?.();if(!o)return;let s=this.buildPolygons();this.hasAttribute("auto-center")&&(s=qd(s));let r={polygons:s,objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(r,{position:Pt(this,"position"),scale:(()=>{let i=this.getAttribute("scale");if(!i)return;if(i.includes(","))return Pt(this,"scale");let c=parseFloat(i);return Number.isFinite(c)?c:void 0})(),rotation:Pt(this,"rotation"),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow"),excludeFromAutoCenter:this.hasAttribute("exclude-from-auto-center"),merge:!1})}},hr=class extends De{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("size"),t=n?parseFloat(n):void 0;return Id({size:t!==void 0&&Number.isFinite(t)?t:void 0,color:Xe(this,"color")})}},yr=class extends De{static get observedAttributes(){return["axis","size","offset","color","auto-center","position","scale","rotation","cast-shadow","receive-shadow"]}buildPolygons(){let n=ge(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("offset"),s=o===null?0:parseFloat(o);return Hd({axis:t,size:ge(this,"size",.4),offset:Number.isFinite(s)?s:0,color:Xe(this,"color")})}},br=class extends De{static get observedAttributes(){return["axis","radius","segments","half-thickness","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=ge(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("half-thickness");return Fd({axis:t,radius:ge(this,"radius",50),segments:ge(this,"segments",32),halfThickness:o?parseFloat(o):void 0,color:Xe(this,"color")})}},xr=class extends De{static get observedAttributes(){return["size","color","center","auto-center","position","scale","rotation"]}buildPolygons(){return zd({center:Pt(this,"center")??[0,0,0],size:ge(this,"size",50),color:Xe(this,"color")})}},Pr=class extends De{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return Vd({size:ge(this,"size",100),color:Xe(this,"color")})}},vr=class extends De{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return Nd({size:ge(this,"size",100),color:Xe(this,"color")})}},Sr=class extends De{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return jd({size:ge(this,"size",100),color:Xe(this,"color")})}},Cr=class extends De{static get observedAttributes(){return["radius","subdivisions","color","auto-center","position","scale","rotation"]}buildPolygons(){return Bd({radius:ge(this,"radius",50),subdivisions:ge(this,"subdivisions",1),color:Xe(this,"color")})}},Tr=class extends De{static get observedAttributes(){return["radius","radius-top","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("radius-top");return $d({radius:ge(this,"radius",50),radiusTop:n?parseFloat(n):void 0,height:ge(this,"height",100),radialSegments:ge(this,"radial-segments",12),color:Xe(this,"color")})}},Er=class extends De{static get observedAttributes(){return["radius","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return Ud({radius:ge(this,"radius",50),height:ge(this,"height",100),radialSegments:ge(this,"radial-segments",12),color:Xe(this,"color")})}},Ar=class extends De{static get observedAttributes(){return["radius","tube","radial-segments","tubular-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return Wd({radius:ge(this,"radius",50),tube:ge(this,"tube",15),radialSegments:ge(this,"radial-segments",12),tubularSegments:ge(this,"tubular-segments",16),color:Xe(this,"color")})}};export*from"@layoutit/polycss-core";export{hr as PolyBoxElement,sr as PolyCameraElement,Er as PolyConeElement,Tr as PolyCylinderElement,Sr as PolyDodecahedronElement,or as PolyFirstPersonControlsElement,vr as PolyIcosahedronElement,Ko as PolyIframeElement,nr as PolyMapControlsElement,un as PolyMeshElement,xr as PolyOctahedronElement,tr as PolyOrbitControlsElement,pn as PolyOrthographicCameraElement,rr as PolyPerspectiveCameraElement,yr as PolyPlaneElement,er as PolyPolygonElement,br as PolyRingElement,Oe as PolySceneElement,xt as PolySceneSnapshotError,ar as PolySelectElement,Cr as PolySphereElement,Pr as PolyTetrahedronElement,Ar as PolyTorusElement,ir as PolyTransformControlsElement,Mt as buildAtlasPages,vg as buildPolyMeshTransform,Sg as buildPolySceneTransform,ss as buildTextureEdgeRepairSets,Iu as collectPolyRenderStats,Ti as collectPolyTextureReadiness,is as computeTextureAtlasPlanPublic,Td as createPolyBox,dc as createPolyCamera,Od as createPolyCone,_d as createPolyCylinder,kd as createPolyDodecahedron,jo as createPolyFirstPersonControls,Rd as createPolyIcosahedron,Vo as createPolyMapControls,wd as createPolyOctahedron,Bo as createPolyOrbitControls,yt as createPolyOrthographicCamera,an as createPolyPerspectiveCamera,Ed as createPolyPlane,Ad as createPolyRing,zo as createPolyScene,Md as createPolySphere,Ld as createPolyTetrahedron,Dd as createPolyTorus,$o as createSelect,Xo as createTransformControls,ds as cssBorderShapeForPlan,Cg as cssDistanceToWorld,Eg as cssPositionToWorld,pd as exportPolySceneSnapshot,no as filterAtlasPlans,us as formatBorderShapeEntryMatrix,ls as formatCssLengthPx,as as formatMatrix3d,cs as formatSolidQuadEntryMatrix,mt as getSolidPaintDefaults,to as getSolidPaintDefaultsFromPlans,Ro as injectPolyBaseStyles,xn as isBorderShapeSupported,Be as isFullRectSolid,Ve as isProjectiveQuadPlan,Ke as isSolidTrianglePlan,Pn as isSolidTriangleSupported,Et as packTextureAtlasPlansWithScale,Tg as polyCssDistanceToWorld,Ag as polyCssPositionToWorld,pr as queryPolyLeaves,It as renderPolygonsWithStableTriangles,ft as renderPolygonsWithTextureAtlas,tn as renderPolygonsWithTextureAtlasAsync,on as updatePolygonsWithStableTopology,Co as updatePolygonsWithStableTriangles,nn as updateStableTriangleFrame,Rg as worldDirectionToPolyCss,Lg as worldDirectionalLightToPolyCss,wg as worldDistanceToCss,Mg as worldDistanceToPolyCss,kg as worldPositionToPolyCss};