@layoutit/polycss 0.2.6 → 0.2.8

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/three.js ADDED
@@ -0,0 +1,799 @@
1
+ var Br=Object.defineProperty;var pa=Object.getOwnPropertyDescriptor;var ma=Object.getOwnPropertyNames;var fa=Object.prototype.hasOwnProperty;var ga=(e,n)=>{for(var t in n)Br(e,t,{get:n[t],enumerable:!0})},zr=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ma(n))!fa.call(e,i)&&i!==t&&Br(e,i,{get:()=>n[i],enumerable:!(o=pa(n,i))||o.enumerable});return e},me=(e,n,t)=>(zr(e,n,"default"),t&&zr(t,n,"default"));import{PerspectiveCamera as Ap}from"@layoutit/polycss-core/three";var le={};ga(le,{PolyBoxElement:()=>xo,PolyCameraElement:()=>po,PolyConeElement:()=>Mo,PolyCylinderElement:()=>wo,PolyDodecahedronElement:()=>Eo,PolyFirstPersonControlsElement:()=>co,PolyIcosahedronElement:()=>To,PolyIframeElement:()=>no,PolyMapControlsElement:()=>lo,PolyMeshElement:()=>Qt,PolyOctahedronElement:()=>So,PolyOrbitControlsElement:()=>ao,PolyOrthographicCameraElement:()=>Kt,PolyPerspectiveCameraElement:()=>uo,PolyPlaneElement:()=>Po,PolyPolygonElement:()=>oo,PolyRingElement:()=>vo,PolySceneElement:()=>De,PolySceneSnapshotError:()=>vt,PolySelectElement:()=>fo,PolySphereElement:()=>Ao,PolyTetrahedronElement:()=>Co,PolyTorusElement:()=>Lo,PolyTransformControlsElement:()=>mo,buildAtlasPages:()=>At,buildPolyMeshTransform:()=>gp,buildPolySceneTransform:()=>hp,buildTextureEdgeRepairSets:()=>sr,collectPolyRenderStats:()=>Ds,collectPolyTextureReadiness:()=>Dr,computeTextureAtlasPlanPublic:()=>ar,createPolyBox:()=>js,createPolyCamera:()=>ms,createPolyCone:()=>Qs,createPolyCylinder:()=>Zs,createPolyDodecahedron:()=>qs,createPolyFirstPersonControls:()=>qn,createPolyIcosahedron:()=>Xs,createPolyMapControls:()=>Xn,createPolyOctahedron:()=>Us,createPolyOrbitControls:()=>Yn,createPolyOrthographicCamera:()=>st,createPolyPerspectiveCamera:()=>Pt,createPolyPlane:()=>$s,createPolyRing:()=>Ws,createPolyScene:()=>Ut,createPolySphere:()=>Gs,createPolyTetrahedron:()=>Ys,createPolyTorus:()=>Ks,createSelect:()=>Zn,createTransformControls:()=>to,cssBorderShapeForPlan:()=>pr,cssDistanceToWorld:()=>yp,cssPositionToWorld:()=>xp,exportPolySceneSnapshot:()=>Ns,filterAtlasPlans:()=>Rn,formatBorderShapeEntryMatrix:()=>dr,formatCssLengthPx:()=>cr,formatMatrix3d:()=>lr,formatSolidQuadEntryMatrix:()=>ur,getSolidPaintDefaults:()=>yt,getSolidPaintDefaultsFromPlans:()=>Ln,injectPolyBaseStyles:()=>Fn,isBorderShapeSupported:()=>an,isFullRectSolid:()=>ze,isProjectiveQuadPlan:()=>Be,isSolidTrianglePlan:()=>it,isSolidTriangleSupported:()=>ln,packTextureAtlasPlansWithScale:()=>Et,polyCssDistanceToWorld:()=>bp,polyCssPositionToWorld:()=>Pp,queryPolyLeaves:()=>bo,renderPolygonsWithStableTriangles:()=>wt,renderPolygonsWithTextureAtlas:()=>bt,renderPolygonsWithTextureAtlasAsync:()=>Nt,updatePolygonsWithStableTopology:()=>$t,updatePolygonsWithStableTriangles:()=>Hn,updateStableTriangleFrame:()=>jt,worldDirectionToPolyCss:()=>Tp,worldDirectionalLightToPolyCss:()=>Cp,worldDistanceToCss:()=>vp,worldDistanceToPolyCss:()=>Sp,worldPositionToPolyCss:()=>Ep});import{CAMERA_BACKFACE_CULL_EPS as Pr,DEFAULT_SEAM_BLEED as ds,VOXEL_CAMERA_CULL_NORMAL_LIMIT as Rc,cameraCullNormalKey as kc,cameraCullVisibleSignature as _c,computeSceneBbox as Oc,computeLightVisibility as Dc,capturePolyCameraSnapshot as Ic,findOverlappingPolygonDuplicates as as,inverseRotateVec3 as jn,isAxisAlignedSurfaceNormal as Hc,isVoxelCameraCullableNormalGroups as Fc,normalFacesCamera as zc,optimizeMeshPolygons as Bc,parseHexColor as Vc,polygonCssSurfaceNormal as ls}from"@layoutit/polycss-core";import{packTextureAtlasPlansWithScaleCore as ha}from"@layoutit/polycss-core";function ya(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 ha(e,n,ya(t),o)}import{buildTextureEdgeRepairSets as sr,buildSeamBleedPolygonEdges as yl,buildSeamBleedPolygonSet as bl}from"@layoutit/polycss-core";import{TEXTURE_TRIANGLE_BLEED as ba,TEXTURE_EDGE_REPAIR_ALPHA_MIN as xa,TEXTURE_EDGE_REPAIR_SOURCE_ALPHA_MIN as Pa,TEXTURE_EDGE_REPAIR_RADIUS as Vr}from"@layoutit/polycss-core";import{expandClipPoints as va}from"@layoutit/polycss-core";import{BASIS_EPS as Sa}from"@layoutit/polycss-core";var Ot=new Map;function Ca(e){let n=Ot.get(e);return n||(n=new Promise((t,o)=>{let i=new Image;i.decoding="async",i.crossOrigin="anonymous",i.onload=()=>t(i),i.onerror=()=>o(new Error(`texture load failed: ${e}`)),i.src=e}),Ot.set(e,n),n.then(()=>{Ot.get(e)===n&&Ot.delete(e)},()=>{Ot.get(e)===n&&Ot.delete(e)})),n}function Fe(e,n,t=1,o=0,i=0,r=1,s=0,c=0){e.setTransform(t*n,o*n,i*n,r*n,s*n,c*n)}function Do(e){let n=e/255;return n<=.04045?n/12.92:Math.pow((n+.055)/1.055,2.4)}function Io(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 Ta(e,n,t,o,i,r,s){let c=Math.round(n*s),l=Math.round(t*s),d=Math.max(1,Math.round(o*s)),p=Math.max(1,Math.round(i*s)),y=e.getImageData(c,l,d,p),g=y.data,b=r.r,x=r.g,v=r.b;for(let h=0;h<g.length;h+=4)g[h+3]!==0&&(g[h]=Io(Do(g[h])*b),g[h+1]=Io(Do(g[h+1])*x),g[h+2]=Io(Do(g[h+2])*v));e.putImageData(y,c,l)}function Ea(e,n,t,o,i,r,s){let c=n.naturalWidth||n.width||1,l=n.naturalHeight||n.height||1,d=Math.max(i/c,r/l),p=c*d,y=l*d;Fe(e,s),e.drawImage(n,t+(i-p)/2,o+(r-y)/2,p,y)}function Dt(e,n){return Math.max(0,Math.min(n,e))}function Nr(e,n,t,o,i,r,s,c){let l=n.naturalWidth||n.width||1,d=n.naturalHeight||n.height||1,p=Dt(Math.min(t.minU,t.maxU)*l,l),y=Dt(Math.max(t.minU,t.maxU)*l,l),g=Dt(Math.min(t.minV,t.maxV)*d,d),b=Dt(Math.max(t.minV,t.maxV)*d,d),x=Math.floor(p),v=Math.floor(g),h=Math.ceil(y)-x,C=Math.ceil(b)-v;h<1&&(x=Math.floor(Dt((t.minU+t.maxU)/2*l,l-1)),h=1),C<1&&(v=Math.floor(Dt((t.minV+t.maxV)/2*d,d-1)),C=1),x=Math.max(0,Math.min(l-1,x)),v=Math.max(0,Math.min(d-1,v)),h=Math.max(1,Math.min(l-x,h)),C=Math.max(1,Math.min(d-v,C)),Fe(e,c),e.drawImage(n,x,v,h,C,o,i,r,s)}function Gr(e){return e==="repeat"||e==="mirrored-repeat"}function jr(e,n){return Gr(e)?Math.floor(n):0}function $r(e,n){return Gr(e)?Math.ceil(n)-1:0}function Wr(e,n){return e==="mirrored-repeat"&&Math.abs(n%2)===1}function Ur(e,n,t,o,i,r,s){let c=i?jr(r,i.minU):0,l=i?$r(r,i.maxU):0,d=i?jr(s,i.minV):0,p=i?$r(s,i.maxV):0;for(let y=c;y<=l;y++)for(let g=d;g<=p;g++){let b=Wr(r,y),x=Wr(s,g);if(!b&&!x){e.drawImage(n,y*t,g*o);continue}e.save(),e.translate((b?y+1:y)*t,(x?g+1:g)*o),e.scale(b?-1:1,x?-1:1),e.drawImage(n,0,0),e.restore()}}function Ho(e,n,t,o){for(let i=0;i<o.length;i+=2){let r=n+o[i],s=t+o[i+1];i===0?e.moveTo(r,s):e.lineTo(r,s)}e.closePath()}function wn(e,n,t,o,i,r){for(let s=0;s<o.length;s+=2){let c=n+o[s]+i,l=t+o[s+1]+r;s===0?e.moveTo(c,l):e.lineTo(c,l)}e.closePath()}function Aa(e,n,t,o){Fe(e,o),e.beginPath(),Ho(e,n.x,n.y,n.screenPts),e.clip(),Fe(e,o),e.fillStyle=t==="dynamic"?n.polygon.color??"#cccccc":n.shadedColor,e.fillRect(n.x,n.y,n.canvasW,n.canvasH)}function Mn(e,n,t,o,i){n.polygon.textureAlphaMode==="opaque"&&(Fe(e,t),e.fillStyle=n.polygon.color??"#cccccc",e.fillRect(n.x+o,n.y+i,n.canvasW,n.canvasH))}function wa(e,n,t,o,i=0,r=0){if(n.textureTriangles?.length){let s=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1;for(let l of n.textureTriangles){let d=va(l.screenPts,ba*(n.bleedRatio??1));e.save(),Fe(e,o),e.beginPath(),wn(e,n.x,n.y,d,i,r),e.clip(),Mn(e,n,o,i,r),l.uvAffine?(Fe(e,o,l.uvAffine.a/s,l.uvAffine.c/s,l.uvAffine.b/c,l.uvAffine.d/c,n.x+l.uvAffine.e+i,n.y+l.uvAffine.f+r),Ur(e,t,s,c,l.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t)):l.uvSampleRect&&Nr(e,t,l.uvSampleRect,n.x+i,n.y+r,n.canvasW,n.canvasH,o),e.restore()}}else if(n.uvAffine){let s=t.naturalWidth||t.width||1,c=t.naturalHeight||t.height||1,l=n.polygon.textureAlphaMode==="opaque";l&&(e.save(),Fe(e,o),e.beginPath(),wn(e,n.x,n.y,n.screenPts,i,r),e.clip(),Mn(e,n,o,i,r)),Fe(e,o,n.uvAffine.a/s,n.uvAffine.c/s,n.uvAffine.b/c,n.uvAffine.d/c,n.x+n.uvAffine.e+i,n.y+n.uvAffine.f+r),Ur(e,t,s,c,n.uvSampleRect,n.polygon.textureWrap?.s,n.polygon.textureWrap?.t),l&&e.restore()}else if(n.uvSampleRect){let s=n.polygon.textureAlphaMode==="opaque";s&&(e.save(),Fe(e,o),e.beginPath(),wn(e,n.x,n.y,n.screenPts,i,r),e.clip(),Mn(e,n,o,i,r)),Nr(e,t,n.uvSampleRect,n.x+i,n.y+r,n.canvasW,n.canvasH,o),s&&e.restore()}else{let s=n.polygon.textureAlphaMode==="opaque";s&&(e.save(),Fe(e,o),e.beginPath(),wn(e,n.x,n.y,n.screenPts,i,r),e.clip(),Mn(e,n,o,i,r)),Ea(e,t,n.x+i,n.y+r,n.canvasW,n.canvasH,o),s&&e.restore()}}function Ma(e,n,t,o,i,r){let s=i-t,c=r-o,l=s*s+c*c;if(l<=Sa)return Math.hypot(e-t,n-o);let d=Math.max(0,Math.min(1,((e-t)*s+(n-o)*c)/l));return Math.hypot(e-(t+s*d),n-(o+c*d))}function La(e,n,t,o){let i=1/0,r=t.length/2;for(let s of o){if(s<0||s>=r)continue;let c=s*2,l=(s+1)%r*2;i=Math.min(i,Ma(e,n,t[c],t[c+1],t[l],t[l+1]))}return i}function Ra(e,n,t,o,i,r){let s=Math.max(0,o-r),c=Math.min(n-1,o+r),l=Math.max(0,i-r),d=Math.min(t-1,i+r),p=null,y=1/0;for(let g=l;g<=d;g++)for(let b=s;b<=c;b++){if(b===o&&g===i)continue;let x=b-o,v=g-i,h=x*x+v*v;if(h>r*r||h>=y)continue;let C=(g*n+b)*4;e[C+3]<Pa||(p=C,y=h)}return p}function ka(e,n,t){if(!n.textureEdgeRepair||!n.texture||!n.textureEdgeRepairEdges||n.textureEdgeRepairEdges.size===0)return;let o=e.canvas;if(!o)return;let i=Math.max(0,Math.floor(n.x*t)),r=Math.max(0,Math.floor(n.y*t)),s=Math.max(1,Math.min(o.width-i,Math.ceil(n.canvasW*t))),c=Math.max(1,Math.min(o.height-r,Math.ceil(n.canvasH*t)));if(s<=0||c<=0)return;let l;try{l=e.getImageData(i,r,s,c)}catch{return}let d=l.data,p=new Uint8ClampedArray(d),y=Math.max(Vr,Vr/t),g=Math.max(2,Math.ceil(y*t)+1),b=!1;for(let x=0;x<c;x++)for(let v=0;v<s;v++){let h=(x*s+v)*4,C=d[h+3];if(C<xa||C===255)continue;let R=(i+v+.5)/t-n.x,I=(r+x+.5)/t-n.y;if(La(R,I,n.screenPts,n.textureEdgeRepairEdges)>y)continue;let z=Ra(p,s,c,v,x,g);z!==null&&(d[h]=p[z],d[h+1]=p[z+1],d[h+2]=p[z+2],d[h+3]=255,b=!0)}b&&e.putImageData(l,i,r)}function _a(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 Oa(e,n,t,o){let i=t.createElement("canvas");i.width=Math.max(1,Math.ceil(e.width*o)),i.height=Math.max(1,Math.ceil(e.height*o));let r=e.entries.some(p=>p.textureEdgeRepair&&p.texture&&p.textureEdgeRepairEdges&&p.textureEdgeRepairEdges.size>0),s=i.getContext("2d",r?{willReadFrequently:!0}:void 0);if(!s)return{width:e.width,height:e.height,url:null};let c=Array.from(new Set(e.entries.flatMap(p=>p.texture?[p.texture]:[]))),l=new Map;await Promise.all(c.map(async p=>{l.set(p,await Ca(p))}));for(let p of e.entries){let y=p.texture?l.get(p.texture):null;if(!p.texture){s.save(),Aa(s,p,n,o),s.restore();continue}y&&(s.save(),Fe(s,o),s.beginPath(),Ho(s,p.x,p.y,p.screenPts),s.clip(),wa(s,p,y,o),s.restore()),p.texture&&n==="baked"&&(s.save(),Fe(s,o),s.beginPath(),Ho(s,p.x,p.y,p.screenPts),s.clip(),Ta(s,p.x,p.y,p.canvasW,p.canvasH,p.textureTint,o),s.restore()),ka(s,p,o)}let d=await _a(i);return i.width=1,i.height=1,{width:e.width,height:e.height,url:d}}async function At(e,n,t,o,i){let r=[];for(let s of e){if(i())break;r.push(await Oa(s,n,t,o))}return r}import{isFullRectSolid as ze,isSolidTrianglePlan as it,isProjectiveQuadPlan as Be,fullRectBounds as Vp,safariCssProjectiveUnsupported as Yr,incrementCount as Np,dominantCountKey as jp,filterAtlasPlans as Ia,getSolidPaintDefaultsForPlansCore as Ha}from"@layoutit/polycss-core";import{parseHex as Fa,rgbKey as za}from"@layoutit/polycss-core";import{computeTextureAtlasPlan as Gp,buildBasisHints as Yp}from"@layoutit/polycss-core";import{resolveProjectiveQuadGuards as Da}from"@layoutit/polycss-core";function It(e,n){let o=e?.defaultView?.__polycssProjectiveQuadGuards,i=n&&o?{...n,...o}:o??n;return Da(i)}function Ht(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 i=(e.defaultView??(typeof window<"u"?window:void 0))?.matchMedia;return i?i("(pointer: fine)").matches&&i("(hover: hover)").matches:!0}function Fo(e){if(Xr(e))return!0;let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Yr(t):!0}function rn(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 Xr(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 Ba(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return/\bFirefox\//.test(t)}function Ge(e,n){return n?.disable?.includes("u")?null:Xr(e)?"corner-bevel":Fo(e)?Ba(e)?"border-large":"border":null}function Ft(e){let t=(e.defaultView??(typeof window<"u"?window:void 0))?.navigator?.userAgent??"";return t?!Yr(t):!0}function sn(e,n,t,o,i){let r=new Set(o?.disable??[]);return Ha(e,n,r,{solidTriangleSupported:Fo(t),projectiveQuadSupported:Ft(t),cornerShapeSupported:rn(t),borderShapeSupported:Ht(t)},Fa,za,i)}function Ln(e,n,t=new Set,o){let i=o??(typeof document<"u"?document:null);if(!i)return{};let r=t.size>0?{disable:Array.from(t)}:void 0;return sn(e,n,i,r)}function an(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 i=typeof matchMedia<"u"?matchMedia:void 0;return i?i("(pointer: fine)").matches&&i("(hover: hover)").matches:!0}return Ht(n)}function ln(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 i=/\b(?:Chrome|HeadlessChrome|Chromium|Edg|OPR)\//.test(o);return!/\bVersion\/[\d.]+.*\bSafari\//.test(o)||i}return Fo(n)}function Rn(e,n,t,o){let i=o??(typeof document<"u"?document:null);return Ia(e,n,t,{solidTriangleSupported:ln(o),projectiveQuadSupported:i?Ft(i):!0,borderShapeSupported:an(o)})}import{ASYNC_RENDER_BUDGET_MS as dl,DEFAULT_SEAM_BLEED as di,DEFAULT_TILE as pl,PROJECTIVE_QUAD_DENOM_EPS as ml,PROJECTIVE_QUAD_MAX_WEIGHT_RATIO as fl,PROJECTIVE_QUAD_BLEED as ui,resolveBleedRatio as rr}from"@layoutit/polycss-core";import{buildBasisHints as ir,buildSeamBleedPolygonEdges as gl,computeTextureAtlasPlan as hn,resolvePolyTextureLeafGeometry as pi}from"@layoutit/polycss-core";import{cornerShapeGeometryForPlan as gn}from"@layoutit/polycss-core";import{formatCssLength as Oe,formatMatrix3dValues as Na,formatSolidQuadMatrix as ja,resolvePolyTextureImageRendering as $a}from"@layoutit/polycss-core";import{shadePolygon as Wa}from"@layoutit/polycss-core";import{parseHex as qr,rgbKey as Zr}from"@layoutit/polycss-core";function Te(e,n,t){let o=e.getAttribute("style")??"",i=`${n}:${t}`,r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(`(^|;)\\s*${r}\\s*:[^;]*`,"i"),c=s.test(o)?o.replace(s,(l,d)=>`${d}${i}`):`${o}${o.trim()&&!o.trim().endsWith(";")?";":""}${i}`;c!==o&&e.setAttribute("style",c)}function ft(e,n){let t=e.getAttribute("style")??"";if(!t||!t.toLowerCase().includes(n.toLowerCase()))return;let o=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`^\\s*${o}\\s*:`,"i"),r=t.split(";").map(s=>s.trim()).filter(s=>s&&!i.test(s)).join(";");r?e.setAttribute("style",r):e.removeAttribute("style")}function cn(e,n,t,o=!1){if(n==="dynamic"){let i=qr(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 Zr(i)!==t?.dynamicColorKey&&(r+=`;--psr:${(i.r/255).toFixed(4)};--psg:${(i.g/255).toFixed(4)};--psb:${(i.b/255).toFixed(4)}`),r}return e.shadedColor?`;color:${e.shadedColor}`:""}function Va(e,n){Te(e,"--pnx",n.normal[0].toFixed(4)),Te(e,"--pny",n.normal[1].toFixed(4)),Te(e,"--pnz",n.normal[2].toFixed(4))}function zt(e,n,t,o){if(t==="dynamic"){ft(e,"color"),ft(e,"background"),Va(e,n);let i=qr(n.polygon.color??"#cccccc");Zr(i)===o?.dynamicColorKey?(ft(e,"--psr"),ft(e,"--psg"),ft(e,"--psb")):(Te(e,"--psr",(i.r/255).toFixed(4)),Te(e,"--psg",(i.g/255).toFixed(4)),Te(e,"--psb",(i.b/255).toFixed(4)))}else n.shadedColor!==o?.paintColor?(ft(e,"background"),Te(e,"color",n.shadedColor)):(ft(e,"background"),ft(e,"color"))}import{formatBorderShapeElementStyle as Qr,formatCornerShapeElementStyle as Kr}from"@layoutit/polycss-core";import{atlasCanonicalSizeForEntry as _n}from"@layoutit/polycss-core";import{computeProjectiveQuadMatrix as Ua,stableBasisFromPlan as Ga}from"@layoutit/polycss-core";import{DEFAULT_LIGHT_DIR as Ya,DEFAULT_LIGHT_COLOR as Xa,DEFAULT_LIGHT_INTENSITY as qa,DEFAULT_AMBIENT_COLOR as Za,DEFAULT_AMBIENT_INTENSITY as Qa}from"@layoutit/polycss-core";var Jr="polycss-corner-shape-solid";function un(e){return e.atlasLeafWidth??_n(e)}function dn(e){return e.atlasLeafHeight??_n(e)}function ei(e,n){return $a(e.polygon,n)}function kn(e){return e==="pixelated"?";image-rendering:pixelated":""}function Vo(e,n,t,o,i,r,s,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),i?e.setAttribute("data-polycss-texture-leaf-sizing",i):e.removeAttribute("data-polycss-texture-leaf-sizing"),r?e.setAttribute("data-polycss-texture-projection",r):e.removeAttribute("data-polycss-texture-projection"),s?e.setAttribute("data-polycss-texture-lighting",s):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 zo=new WeakMap,Bo=new WeakMap;function Ce(e,n,t){let o=zo.get(e),i=Bo.get(e),r=typeof t=="number";if(!n.data&&!r&&(!o||o.length===0)){e.__polycssHasDataAttrs=!1;return}let s=new Map;if(n.data)for(let[l,d]of Object.entries(n.data))s.set(l,String(d));if(n.doubleSided===!0&&s.set("polycss-double-sided","true"),r&&s.set("poly-index",String(t)),o)for(let l of o)s.has(l)||e.removeAttribute(`data-${l}`);for(let[l,d]of s)i?.get(l)!==d&&e.setAttribute(`data-${l}`,d);let c=Array.from(s.keys());c.length>0?zo.set(e,c):zo.delete(e),s.size>0?Bo.set(e,s):Bo.delete(e),e.__polycssHasDataAttrs=c.length>0}function Bt(e){return e.__polycssHasDataAttrs===!0}function No(e,n,t,o,i=t==="dynamic",r){if(!n.url)return;let s=ei(o,r),c=`url(${n.url})`,l=o.canvasW||1,d=o.canvasH||1,p=_n(o),y=un(o),g=dn(o),b=`${Oe(-o.x/l*y)} ${Oe(-o.y/d*g)}`,x=`${Oe(n.width/l*y)} ${Oe(n.height/d*g)}`,v=`transform:matrix3d(${o.atlasMatrix});--polycss-atlas-size:${p}px;--polycss-atlas-width:${Oe(y)};--polycss-atlas-height:${Oe(g)};--polycss-atlas-leaf-sizing:${o.atlasLeafSizing??"canonical"}`,h=`${v};--polycss-atlas-position:${b};--polycss-atlas-image-size:${x}`;if(t==="dynamic"){let C=i?`;--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:${c}`+C+kn(s))}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)}`+kn(s));Vo(e,"atlas",!0,s,o.atlasLeafSizing??"canonical","affine",t,y,g)}function ti(e,n,t,o){if(n.texture){if(!t.texture||n.texture!==t.texture)return!1}else if(t.texture)return!1;let i=ni(n,t);return i?(e.style.visibility="",Te(e,"transform",`matrix3d(${i.matrix})`),o==="dynamic"&&(Te(e,"--pnx",i.normal[0].toFixed(4)),Te(e,"--pny",i.normal[1].toFixed(4)),Te(e,"--pnz",i.normal[2].toFixed(4))),Ce(e,t,n.index),!0):(e.style.visibility="hidden",Ce(e,t,n.index),!0)}function jo(e,n,t,o,i){if(o!=="baked")return{...e,polygon:n,normal:t};let r=i.directionalLight,s=i.ambientLight,c=r?.direction??Ya,l=r?.color??Xa,d=Math.max(0,r?.intensity??qa),p=s?.color??Za,y=Math.max(0,s?.intensity??Qa),g=Math.hypot(c[0],c[1],c[2])||1,b=c[0]/g,x=c[1]/g,v=c[2]/g,C=i.lightOccludedPolyIndices?.has(e.index)??!1?0:d*Math.max(0,t[0]*b+t[1]*x+t[2]*v);return{...e,polygon:n,normal:t,shadedColor:Wa(n.color??"#cccccc",C,l,p,y)}}function ni(e,n){let t=oi(e,n);if(!t)return null;let{normal:o,xAxis:i,yAxis:r,tx:s,ty:c,tz:l}=t;return{normal:o,matrix:Na([i[0]*e.canvasW/un(e),i[1]*e.canvasW/un(e),i[2]*e.canvasW/un(e),0,r[0]*e.canvasH/dn(e),r[1]*e.canvasH/dn(e),r[2]*e.canvasH/dn(e),0,o[0],o[1],o[2],0,s,c,l,1])}}var oi=Ga;function Ka(e,n,t){if(e.screenPts.length!==8||n.vertices.length!==4)return null;let o=oi(e,n);if(!o)return null;let i=Ua(e.screenPts,o.xAxis,o.yAxis,o.normal,o.tx,o.ty,o.tz,t);return i?{matrix:i,normal:o.normal}:null}function $o(e,n,t,o,i=!1){let r=t.createElement("b");return r.setAttribute("style",`transform:matrix3d(${ja(e)})`+cn(e,n,o,i)),Ce(r,e.polygon,e.index),r}function Wo(e,n,t,o,i=!1){let r=t.createElement("i");return r.setAttribute("style",Qr(e)+cn(e,n,o,i)),Ce(r,e.polygon,e.index),r}function Uo(e,n,t,o,i,r=!1){let s=o.createElement("u");return s.className=Jr,s.setAttribute("style",Kr(e,n)+cn(e,t,i,r)),Ce(s,e.polygon,e.index),s}function Go(e,n,t,o,i=!1){let r=t.createElement("b");return r.setAttribute("style",`transform:matrix3d(${e.projectiveMatrix})`+cn(e,n,o,i)),Ce(r,e.polygon,e.index),r}function ri(e,n,t,o,i,r,s){let c=n.projectiveMatrix?Ka(n,t,r):ni(n,t);if(!c)return!1;let l=jo(n,t,c.normal,o,i);return e.style.visibility="",e.style.transform=`matrix3d(${c.matrix})`,zt(e,l,o,s),Ce(e,l.polygon,l.index),!0}function ii(e,n,t,o){e.style.visibility="",e.setAttribute("style",Qr(n)),zt(e,n,t,o),Ce(e,n.polygon,n.index)}function si(e,n,t,o,i){e.style.visibility="",e.className=Jr,e.setAttribute("style",Kr(n,t)),zt(e,n,o,i),Te(e,"background","currentColor"),Ce(e,n.polygon,n.index)}function Yo(e,n,t,o=!1,i){let r=t.createElement("s"),s=ei(e,i),c=_n(e),l=un(e),d=dn(e),p=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:${Oe(l)};--polycss-atlas-height:${Oe(d)};--polycss-atlas-leaf-sizing:${e.atlasLeafSizing??"canonical"};opacity:0`+p+kn(s)),Vo(r,"atlas",!1,s,e.atlasLeafSizing??"canonical","affine",n,l,d),Ce(r,e.polygon,e.index),r}function Xo(e,n,t,o=!1){let i=t.createElement("s"),r=o?"":`;--pnx:${e.normal[0].toFixed(4)};--pny:${e.normal[1].toFixed(4)};--pnz:${e.normal[2].toFixed(4)}`;return i.setAttribute("style",`transform:matrix3d(${n.matrix});--polycss-atlas-width:${Oe(n.leafWidth)};--polycss-atlas-height:${Oe(n.leafHeight)};--polycss-atlas-leaf-sizing:image;background-image:url(${n.url});background-position:${Oe(n.backgroundPosition[0])} ${Oe(n.backgroundPosition[1])};background-size:${Oe(n.backgroundSize[0])} ${Oe(n.backgroundSize[1])};background-repeat:no-repeat;background-blend-mode:normal;mask-image:none;-webkit-mask-image:none`+r+kn(n.imageRendering)),Vo(i,"image",!0,n.imageRendering,"image",n.projection,n.lighting,n.leafWidth,n.leafHeight),i.setAttribute("data-polycss-texture-source-x",String(n.sourceRect.x)),i.setAttribute("data-polycss-texture-source-y",String(n.sourceRect.y)),i.setAttribute("data-polycss-texture-source-width",String(n.sourceRect.width)),i.setAttribute("data-polycss-texture-source-height",String(n.sourceRect.height)),Ce(i,e.polygon,e.index),i}import{computeSolidTriangleColorPlan as hl}from"@layoutit/polycss-core";import{computeSolidTrianglePlanFromCssPoints as Ja,computeSolidTrianglePlan as el}from"@layoutit/polycss-core";function gt(e,n,t,o={}){let i=o.primitive!=null?void 0:(()=>{let r=t.doc??(typeof document<"u"?document:null);return r?Ge(r,t.strategies)??"border":"border"})();return el(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??i})}function qo(e,n,t,o,i,r,s,c,l,d,p,y,g){let b=o.primitive!=null?void 0:(()=>{let x=t.doc??(typeof document<"u"?document:null);return x?Ge(x,t.strategies)??"border":"border"})();return Ja(e,n,t,{...o,resolvedPrimitive:o.resolvedPrimitive??b},i,r,s,c,l,d,p,y,g)}import{buildSeamBleedPolygonEdges as tl,DEFAULT_SEAM_BLEED as nl,DEFAULT_TILE as um,resolveBleedRatio as ol}from"@layoutit/polycss-core";import{rgbEqual as rl,stepRgbToward as il,rgbToCss as sl,colorErrorScore as al}from"@layoutit/polycss-core";import{computeSolidTriangleColorPlan as ai}from"@layoutit/polycss-core";import{stableTriangleMatrixDecimals as Zo}from"@layoutit/polycss-core";var ll="0 48px 96px 48px";function Qo(e,n){return tl(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function Ko(e,n,t){let o=ol(t.seamBleed),i=nl*o,r={...t,bleedRatio:o};return n&&i>0?{...r,seamBleed:n.has(e)?i:void 0,seamEdges:n.get(e)}:r}function On(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 li(e,n){return!n.updatesDisabled&&(n.freezeFrames<=1||(n.colorFrame+e)%n.freezeFrames===0)}function ht(e,n,t,o,i,r){return t?r.updatesDisabled||o==="plan-only"||o==="transform-only"?!1:i==="adaptive"||e.__polycssSolidTriangleColor===void 0?!0:li(n,r):!0}function Jo(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"?ll:""),t.__polycssSolidTrianglePrimitive=n)}function er(e){let n=e;n.__polycssSolidTriangleHidden&&(e.style.visibility="",n.__polycssSolidTriangleHidden=!1)}function Vt(e){let n=e;n.__polycssSolidTriangleHidden||(e.style.visibility="hidden",n.__polycssSolidTriangleHidden=!0)}function pn(e,n){e.setAttribute("style",n.styleText),Jo(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||Bt(e))&&Ce(e,n.polygon)}function ci(e,n,t,o){if(!n.colorComputed){(n.polygon.data||Bt(e))&&Ce(e,n.polygon);return}let i=e,r=n.bakedColor??"",s=n.bakedRgb,c=n.bakedAlpha??1,l=i.__polycssSolidTriangleColor,d=i.__polycssSolidTriangleColorRgb,p=i.__polycssSolidTriangleColorAlpha??1,y=o??li(n.index,t);if(!t.updatesDisabled&&l!==r&&(l===void 0||y)){let g=r,b=s;if(t.maxStep>0&&d&&s&&p===c){let x=il(d,s,t.maxStep);b=x,g=sl(x,c)}(g!==l||!rl(b,d))&&(e.style.color=g),i.__polycssSolidTriangleColor=g,i.__polycssSolidTriangleColorRgb=b,i.__polycssSolidTriangleColorAlpha=c,i.__polycssSolidTriangleColorFrame=t.colorFrame}(n.polygon.data||Bt(e))&&Ce(e,n.polygon)}function mn(e,n,t,o){let i=e;Jo(e,n.primitive),i.__polycssSolidTriangleBasis!==n.basis&&(i.__polycssSolidTriangleBasis=n.basis),er(e),e.style.transform=n.transformText,(n.colorComputed||n.polygon.data||Bt(e))&&ci(e,n,t,o)}function Dn(e,n,t,o){er(e),ci(e,n,t,o)}function fn(e,n){let t=e;Jo(e,n.primitive),t.__polycssSolidTriangleBasis!==n.basis&&(t.__polycssSolidTriangleBasis=n.basis),er(e),e.style.transform=n.transformText,(n.polygon.data||Bt(e))&&Ce(e,n.polygon)}function cl(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 tr(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)),i=Math.max(1,Math.floor(t.stableTriangleColorFreezeFrames??1));if(i<=1&&!Number.isFinite(t.stableTriangleColorBudget))return null;let r=cl(e.length,t),s=Math.max(1,Math.floor(t.stableTriangleColorMaxAge??Math.max(2,i*2))),c=[];for(let l=0;l<e.length;l++){let d=e[l],p=n[l];if(d.kind!=="triangle"||!p)continue;let y=d.element,g=y.__polycssSolidTriangleColor,b=p.bakedColor??"";if(g===b)continue;let x=y.__polycssSolidTriangleColorFrame??0,v=Math.max(0,o-x),h=al(g,b);c.push({index:l,score:(v>=s?1e6:0)+h*1e4+v})}return c.length===0?new Set:(c.sort((l,d)=>d.score-l.score),new Set(c.slice(0,r).map(l=>l.index)))}function In(e,n){let t=n.createElement("u");return pn(t,e),Ce(t,e.polygon,e.index),t}function ul(e,n,t){let o=t.createElement("u");return Vt(o),Ce(o,e,n),o}function nr(e,n,t,o,i,r){let s=t,c=s.stableTriangleDebug,l=o&&i==="color-only";if(s.stableTriangleColorPolicy==="adaptive"||e.length!==n.length)return!1;let d=Zo(s.stableTriangleMatrixDecimals),p=t.doc??(typeof document<"u"?document:null),y=p?Ge(p,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 g=Qo(n,t);for(let b=0;b<e.length;b++){let x=e[b].element,v=n[b];if(l){if(ht(x,b,o,c,s.stableTriangleColorPolicy,r)){let C=ai(v,b,t);if(!C)continue;Dn(x,C,r)}continue}let h=gt(v,b,Ko(b,g,t),{basis:x.__polycssSolidTriangleBasis,matrixDecimals:d,primitive:y,includeColor:i!=="plan-only"&&i!=="transform-only"&&ht(x,b,o,c,s.stableTriangleColorPolicy,r)});if(!h){Vt(x);continue}o&&i==="plan-only"||(o&&i==="transform-only"?fn(x,h):o?mn(x,h,r):pn(x,h))}return!0}function wt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=Ge(t,n.strategies);if(!o||e.some(c=>c.texture||c.vertices.length!==3))return null;let i=Zo(n.stableTriangleMatrixDecimals),r=[],s=Qo(e,n);for(let c=0;c<e.length;c+=1){let l=e[c],d=gt(l,c,Ko(c,s,n),{matrixDecimals:i,primitive:o}),p=d?In(d,t):ul(l,c,t);r.push({polygonIndex:c,element:p,kind:"triangle",dispose:()=>{}})}return{rendered:r,dispose(){}}}function Hn(e,n,t={}){let o=t.doc??(typeof document<"u"?document:null);if(!o)return{rendered:e,dispose:()=>{}};let i=Ge(o,t.strategies);if(!i||e.some(h=>h.kind!=="triangle")||n.length!==e.length)return null;for(let h=0;h<e.length;h++)if(e[h].polygonIndex!==h)return null;let r=t.optimizeStableTriangleStyle===!0&&(t.textureLighting??"baked")==="baked",s=t,c=s.stableTriangleDebug,l=s.stableTriangleUpdateMode??(c==="plan-only"||c==="transform-only"?c:"full"),d=r&&l==="color-only",p=On(s),y=Zo(s.stableTriangleMatrixDecimals);if(nr(e,n,t,r,l,p))return{rendered:e,dispose(){}};let g=new Array(e.length),b=new Array(e.length),x=Qo(n,t);for(let h=0;h<e.length;h++){let C=e[h].element;if(d){let R=s.stableTriangleColorPolicy==="adaptive"||ht(C,h,r,c,s.stableTriangleColorPolicy,p);b[h]=R?ai(n[h],h,t):null;continue}g[h]=gt(n[h],h,Ko(h,x,t),{basis:C.__polycssSolidTriangleBasis,matrixDecimals:y,primitive:i,includeColor:l!=="plan-only"&&l!=="transform-only"&&ht(C,h,r,c,s.stableTriangleColorPolicy,p)})}let v=r&&l!=="plan-only"&&l!=="transform-only"?tr(e,d?b:g,s):null;for(let h=0;h<e.length;h++){if(d){let R=b[h];R&&Dn(e[h].element,R,p,v?.has(h));continue}let C=g[h];if(!C){Vt(e[h].element);continue}r&&l==="plan-only"||(r&&l==="transform-only"?fn(e[h].element,C):r?mn(e[h].element,C,p,v?.has(h)):pn(e[h].element,C))}return{rendered:e,dispose(){}}}import{stableTriangleMatrixDecimals as mi}from"@layoutit/polycss-core";function fi(){return new Promise(e=>setTimeout(e,0))}async function or(e){return performance.now()-e<dl?e:(await fi(),performance.now())}function gi(e,n){let t=rr(n.seamBleed),o=di*t,i={...n,bleedRatio:t};return e.seamBleedEdges?.size&&o>0?{...i,seamBleed:o,seamEdges:e.seamBleedEdges}:{...i,seamBleed:void 0,seamEdges:void 0}}function hi(e,n){return gl(e,{tileSize:n.tileSize,layerElevation:n.layerElevation,directionalLight:n.directionalLight,ambientLight:n.ambientLight})}function yi(e,n,t){let o=rr(t.seamBleed),i=di*o,r={...t,bleedRatio:o};return n&&i>0?{...r,seamBleed:n.has(e)?i:void 0,seamEdges:n.get(e)}:r}function yt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{};let o=ir(e,n),i=It(t),r=e.map((s,c)=>hn(s,c,n,i,o[c]));return sn(r,n.textureLighting??"baked",t,n.strategies)}function bt(e,n={}){let t=n.doc??(typeof document<"u"?document:null);if(!t)return{rendered:[],dispose:()=>{}};let o=n.textureLighting??"baked",i=n,r=o==="dynamic"&&i.skipDynamicNormalVars===!0,s=new Set(n.strategies?.disable??[]),c=!s.has("b"),l=c&&Ft(t),d=Ge(t,n.strategies),p=d!==null,y=!s.has("i")&&rn(t),g=!s.has("i")&&Ht(t),b=ir(e,n),x=It(t),v=hi(e,n),h=e.map((u,m)=>hn(u,m,yi(m,v,n),x,b[m])),C=n.solidPaintDefaults??(i.computeSolidPaintDefaults?sn(h,o,t,n.strategies):void 0),R=C?{...n,solidPaintDefaults:C}:n,I=h.map(u=>u&&p&&it(u)?gt(u.polygon,u.index,gi(u,R),{primitive:d??void 0}):null),z=h.map(u=>u&&y&&!it(u)&&!(c&&ze(u))&&!(l&&Be(u))?gn(u):null),D=h.map(u=>u?pi(u,{imageRendering:n.textureImageRendering,backend:n.textureBackend,projection:n.textureProjection,allowProjective:l,projectiveQuadGuards:x}):null),X=h.map((u,m)=>D[m]?null:u&&(u.texture||!(c&&ze(u))&&!I[m]&&!(l&&Be(u))&&!z[m]&&!g?u:null)),{packed:q,atlasScale:M}=Et(X,n.textureQuality,t,n.textureLeafSizing),V=new Map,B=[],F=!1,re=[];for(let u=0;u<e.length;u++){let m=h[u],A=I[u],k=z[u],N=D[u];if(!m)continue;let Y=q.entries[u];if(Y){let w=Yo(Y,o,t,r,n.textureImageRendering);V.set(u,w),B.push({polygonIndex:u,element:w,kind:"atlas",plan:Y,dispose:()=>{}})}else if(N){let w=Xo(m,N,t,r);B.push({polygonIndex:u,element:w,kind:"image",plan:m,dispose:()=>{}})}else if(!m.texture&&c&&ze(m)){let w=$o(m,o,t,C,r);B.push({polygonIndex:u,element:w,kind:"solid",plan:m,dispose:()=>{}})}else if(!m.texture&&A){let w=In(A,t);B.push({polygonIndex:u,element:w,kind:"triangle",plan:m,dispose:()=>{}})}else if(!m.texture&&l&&Be(m)){let w=Go(m,o,t,C,r);B.push({polygonIndex:u,element:w,kind:"solid",plan:m,dispose:()=>{}})}else if(!m.texture&&k){let w=Uo(m,k,o,t,C,r);B.push({polygonIndex:u,element:w,kind:"corner",plan:m,dispose:()=>{}})}else if(!m.texture&&g){let w=Wo(m,o,t,C,r);B.push({polygonIndex:u,element:w,kind:"border",plan:m,dispose:()=>{}})}}B.sort((u,m)=>u.polygonIndex-m.polygonIndex);let P=At(q.pages,o,t,M,()=>F).then(u=>{if(F){for(let m of u)m.url?.startsWith("blob:")&&URL.revokeObjectURL(m.url);return}re=u.flatMap(m=>m.url?.startsWith("blob:")?[m.url]:[]);for(let m=0;m<q.pages.length;m++){let A=q.pages[m],k=u[m];if(k)for(let N of A.entries){let Y=V.get(N.index);!Y||!k.url||No(Y,k,o,N,!0,n.textureImageRendering)}}}).catch(()=>{if(!F)for(let u of V.values())Te(u,"opacity","0.5"),Te(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:B,solidPaintDefaults:C??{},pagesReady:P,dispose(){F=!0;for(let u of re)URL.revokeObjectURL(u);re=[]}}}async function Nt(e,n={},t=()=>!1){let o=n.doc??(typeof document<"u"?document:null);if(!o||t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let i=n.textureLighting??"baked",s=i==="dynamic"&&n.skipDynamicNormalVars===!0,c=new Set(n.strategies?.disable??[]),l=!c.has("b"),d=l&&Ft(o),p=Ge(o,n.strategies),y=p!==null,g=!c.has("i")&&rn(o),b=!c.has("i")&&Ht(o);if(await fi(),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let x=ir(e,n),v=It(o),h=hi(e,n),C=performance.now(),R=new Array(e.length);for(let u=0;u<e.length;u++)if(R[u]=hn(e[u],u,yi(u,h,n),v,x[u]),C=await or(C),t())return{rendered:[],solidPaintDefaults:{},dispose:()=>{}};let I=n.solidPaintDefaults??sn(R,i,o,n.strategies),z=new Array(R.length),D=new Array(R.length),X=new Array(R.length),q=new Array(R.length);for(let u=0;u<R.length;u++){let m=R[u],A=m&&y&&it(m)?gt(m.polygon,m.index,gi(m,{...n,solidPaintDefaults:I}),{primitive:p??void 0}):null;z[u]=A;let k=m&&g&&!it(m)&&!(l&&ze(m))&&!(d&&Be(m))?gn(m):null;D[u]=k;let N=m?pi(m,{imageRendering:n.textureImageRendering,backend:n.textureBackend,projection:n.textureProjection,allowProjective:d,projectiveQuadGuards:v}):null;if(X[u]=N,q[u]=N?null:m&&(m.texture||!(l&&ze(m))&&!A&&!(d&&Be(m))&&!k&&!b?m:null),C=await or(C),t())return{rendered:[],solidPaintDefaults:I,dispose:()=>{}}}let{packed:M,atlasScale:V}=Et(q,n.textureQuality,o,n.textureLeafSizing),B=new Map,F=[],re=!1,P=[];for(let u=0;u<e.length;u++){let m=R[u],A=z[u],k=D[u],N=X[u];if(!m)continue;let Y=M.entries[u];if(Y){let w=Yo(Y,i,o,s,n.textureImageRendering);B.set(u,w),F.push({polygonIndex:u,element:w,kind:"atlas",plan:Y,dispose:()=>{}})}else if(N){let w=Xo(m,N,o,s);F.push({polygonIndex:u,element:w,kind:"image",plan:m,dispose:()=>{}})}else if(!m.texture&&l&&ze(m)){let w=$o(m,i,o,I,s);F.push({polygonIndex:u,element:w,kind:"solid",plan:m,dispose:()=>{}})}else if(!m.texture&&A){let w=In(A,o);F.push({polygonIndex:u,element:w,kind:"triangle",plan:m,dispose:()=>{}})}else if(!m.texture&&d&&Be(m)){let w=Go(m,i,o,I,s);F.push({polygonIndex:u,element:w,kind:"solid",plan:m,dispose:()=>{}})}else if(!m.texture&&k){let w=Uo(m,k,i,o,I,s);F.push({polygonIndex:u,element:w,kind:"corner",plan:m,dispose:()=>{}})}else if(!m.texture&&b){let w=Wo(m,i,o,I,s);F.push({polygonIndex:u,element:w,kind:"border",plan:m,dispose:()=>{}})}if(C=await or(C),t()){for(let w of F)w.dispose();return{rendered:[],solidPaintDefaults:I,dispose:()=>{}}}}F.sort((u,m)=>u.polygonIndex-m.polygonIndex);let L=At(M.pages,i,o,V,()=>re||t()).then(u=>{if(re||t()){for(let m of u)m.url?.startsWith("blob:")&&URL.revokeObjectURL(m.url);return}P=u.flatMap(m=>m.url?.startsWith("blob:")?[m.url]:[]);for(let m=0;m<M.pages.length;m++){let A=M.pages[m],k=u[m];if(k)for(let N of A.entries){let Y=B.get(N.index);!Y||!k.url||No(Y,k,i,N,!0,n.textureImageRendering)}}}).catch(()=>{if(!(re||t()))for(let u of B.values())Te(u,"opacity","0.5"),Te(u,"outline","1px dashed rgba(255, 0, 0, 0.6)")});return{rendered:F,solidPaintDefaults:I,pagesReady:L,dispose(){re=!0;for(let u of P)URL.revokeObjectURL(u);P=[]}}}function jt(e,n,t,o={}){let i=o.textureLighting??"baked",r=o,s=r.optimizeStableTriangleStyle===!0&&i==="baked";if(!s||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 d=mi(r.stableTriangleMatrixDecimals),p=On(r),y=o.tileSize??pl,g=o.layerElevation??y,b=o.doc??(typeof document<"u"?document:null),x=b?Ge(b,o.strategies)??"border":"border";for(let h=0;h<e.length;h++){let C=e[h],R=n[h];if(C.kind!=="triangle"||C.polygonIndex!==h||!R||R.vertices.length!==3||R.texture||R.material?.texture)return!1}let v=t.vertices;for(let h=0;h<e.length;h++){let C=e[h].element,R=n[h],I=h*9,z=v[I+1]*y,D=v[I]*y,X=v[I+2]*g,q=v[I+4]*y,M=v[I+3]*y,V=v[I+5]*g,B=v[I+7]*y,F=v[I+6]*y,re=v[I+8]*g,P=qo(R,h,o,{basis:C.__polycssSolidTriangleBasis,matrixDecimals:d,primitive:x,color:t.colors?.[h],includeColor:l!=="plan-only"&&l!=="transform-only"&&ht(C,h,s,c,r.stableTriangleColorPolicy,p)},z,D,X,q,M,V,B,F,re);if(!P){Vt(C);continue}l!=="plan-only"&&(l==="transform-only"?fn(C,P):mn(C,P,p))}return!0}function $t(e,n,t={}){if(e.length!==n.length)return!1;let o=t,i=t.doc??(typeof document<"u"?document:null),r=t.textureLighting??"baked",s=new Set(t.strategies?.disable??[]),c=!s.has("b"),l=!!i&&c&&Ft(i),d=!!i&&!s.has("i")&&rn(i),p=!!i&&!s.has("i")&&Ht(i),y=rr(o.seamBleed),g=i?It(i,{bleed:ui*y}):{denomEps:ml,maxWeightRatio:fl,bleed:ui*y,disableGuards:!1},b=o.optimizeStableTriangleStyle===!0&&r==="baked",x=o.stableTriangleDebug,v=o.stableTriangleUpdateMode??(x==="plan-only"||x==="transform-only"?x:"full"),h=b&&v==="color-only",C=On(o),R=mi(o.stableTriangleMatrixDecimals),I=i?Ge(i,t.strategies)??"border":"border";if(nr(e,n,t,b,v,C))return!0;let z=[],D=[],X=[];for(let M=0;M<e.length;M++){let V=e[M];if(V.polygonIndex!==M)return!1;let B=n[M];if(!B||h&&V.kind!=="triangle")return!1;if(V.kind==="atlas"){if(!V.plan||!ti(V.element,V.plan,B,r))return!1;continue}if(V.kind==="triangle"){let F=V.element;if(h){let P=o.stableTriangleColorPolicy==="adaptive"||ht(F,M,b,x,o.stableTriangleColorPolicy,C);D[M]=P?hl(B,M,t):null;continue}let re=gt(B,M,t,{basis:F.__polycssSolidTriangleBasis,matrixDecimals:R,primitive:I,includeColor:v!=="plan-only"&&v!=="transform-only"&&ht(F,M,b,x,o.stableTriangleColorPolicy,C)});if(!re){z[M]=null;continue}z[M]=re;continue}if(V.kind==="solid"){if(!V.plan||B.texture||B.vertices.length!==V.plan.polygon.vertices.length)return!1;X[M]=V.plan;continue}if(V.kind==="border"){let F=hn(B,M,t,g);if(!F||F.texture||!p||c&&ze(F)||l&&Be(F)||d&&gn(F))return!1;X[M]=F;continue}if(V.kind==="corner"){let F=hn(B,M,t,g);if(!F||F.texture||!d||it(F)||c&&ze(F)||l&&Be(F)||!gn(F))return!1;X[M]=F;continue}return!1}let q=b&&v!=="plan-only"&&v!=="transform-only"?tr(e,h?D:z,o):null;for(let M=0;M<e.length;M++){let V=e[M];if(V.kind==="triangle"){if(h){let F=D[M];F&&Dn(V.element,F,C,q?.has(M));continue}let B=z[M];if(!B){Vt(V.element);continue}if(b&&v==="plan-only")continue;b&&v==="transform-only"?fn(V.element,B):b?mn(V.element,B,C,q?.has(M)):pn(V.element,B)}else if(V.kind==="solid"){let B=X[M];if(!B||!ri(V.element,B,n[M],r,t,g,o.solidPaintDefaults))return!1}else if(V.kind==="border"){let B=X[M];if(!B)return!1;ii(V.element,B,r,o.solidPaintDefaults)}else if(V.kind==="corner"){let B=X[M],F=B?gn(B):null;if(!B||!F)return!1;si(V.element,B,F,r,o.solidPaintDefaults)}}return!0}import{computeTextureAtlasPlanPublic as ar}from"@layoutit/polycss-core";import{formatMatrix3d as lr,formatCssLengthPx as cr,formatSolidQuadEntryMatrix as ur}from"@layoutit/polycss-core";import{formatBorderShapeEntryMatrix as dr,cssBorderShapeForPlan as pr}from"@layoutit/polycss-core";import{BASE_TILE as Ee,computeProjectiveQuadMatrix as xl,normalFacesCamera as Pl,parsePureColor as Ci,PROJECTIVE_QUAD_BLEED as vl,resolveProjectiveQuadGuards as Sl,rotateVec3 as Cl,rotateVec3InWrapperCssFrame as Tl,shadePolygon as El,SOLID_QUAD_CANONICAL_SIZE as Al}from"@layoutit/polycss-core";var wl=[.4,-.7,.59],Ml="#ffffff",Ll=1,Rl="#ffffff",kl=.4,Ti=1,_l=8,Ol=vl,lt=1e-6,Dl=Sl({bleed:0}),Ei={t:[0,0,1],b:[0,0,-1],fl:[0,1,0],br:[0,-1,0],fr:[1,0,0],bl:[-1,0,0]},gr=["t","b","bl","br","fr","fl"],Il=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 bi(e){let n=[];for(let t of gr)Pl(Ei[t],e)&&n.push(t);return n.join("|")}function Hl(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 Fl(e){let n=e.vertices;if(n.length<3)return null;let t=n[0],o=0,i=0,r=0;for(let c=1;c+1<n.length;c+=1){let l=n[c],d=n[c+1],p=l[1]-t[1],y=l[0]-t[0],g=l[2]-t[2],b=d[1]-t[1],x=d[0]-t[0],v=d[2]-t[2];o-=y*v-g*x,i-=g*b-p*v,r-=p*x-y*b}let s=Math.hypot(o,i,r);return s<=1e-9?null:[Math.round(o/s),Math.round(i/s),Math.round(r/s)]}function zl(e){if(e.texture||e.material||e.uvs||e.textureTriangles||e.vertices.length!==4)return null;let n=Fl(e),t=n?Il.get(n.join(",")):void 0;if(!t)return null;let o=1/0,i=1/0,r=1/0,s=-1/0,c=-1/0,l=-1/0;for(let y of e.vertices)o=Math.min(o,y[0]),i=Math.min(i,y[1]),r=Math.min(r,y[2]),s=Math.max(s,y[0]),c=Math.max(c,y[1]),l=Math.max(l,y[2]);let d=1e-6,p=Ul(e.color);return Math.abs(l-r)<=d?{axis:"z",face:t,left:i*Ee,top:o*Ee,width:Math.max(0,(c-i)*Ee),height:Math.max(0,(s-o)*Ee),z:r*Ee,baseColor:p,bleed:mr()}:Math.abs(s-o)<=d?{axis:"x",face:t,left:i*Ee,top:r*Ee,width:Math.max(0,(c-i)*Ee),height:Math.max(0,(l-r)*Ee),z:-o*Ee,baseColor:p,bleed:mr()}:Math.abs(c-i)<=d?{axis:"y",face:t,left:r*Ee,top:o*Ee,width:Math.max(0,(l-r)*Ee),height:Math.max(0,(s-o)*Ee),z:-i*Ee,baseColor:p,bleed:mr()}:null}function mr(){return{left:0,right:0,top:0,bottom:0}}function Bl(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 xi(e){return[e[1]*Ee,e[0]*Ee,e[2]*Ee]}function Pi(e,n){return e.axis==="x"?[n[0],n[2]]:e.axis==="y"?[n[2],n[1]]:[n[0],n[1]]}function Vl(e,n,t){let o=e.left,i=e.left+e.width,r=e.top,s=e.top+e.height;if(Math.abs(n[0]-t[0])<=lt){if(Math.abs(n[0]-o)<=lt)return"left";if(Math.abs(n[0]-i)<=lt)return"right"}if(Math.abs(n[1]-t[1])<=lt){if(Math.abs(n[1]-r)<=lt)return"top";if(Math.abs(n[1]-s)<=lt)return"bottom"}return null}function Nl(e,n){let t=null;for(let o=0;o<3;o+=1)if(!(Math.abs(e[o]-n[o])<=lt)){if(t!==null)return null;t=o}return t}function jl(e,n,t){let o=n.vertices,i=xi(o[t]),r=xi(o[(t+1)%o.length]),s=Vl(e,Pi(e,i),Pi(e,r));if(!s)return null;let c=Nl(i,r);if(c===null)return null;let l=Math.min(i[c],r[c]),d=Math.max(i[c],r[c]);return d-l>lt?{item:e,side:s,variableAxis:c,fixed:i,start:l,end:d}:null}function vi(e){e.item.bleed[e.side]=Math.max(e.item.bleed[e.side],Ol)}function $l(e,n){let t=new Map;for(let o of n){let i=e[o.sourceIndex];if(i)for(let r=0;r<i.vertices.length;r+=1){let s=jl(o,i,r);if(!s)continue;let c=Bl(s),l=t.get(c);l?l.push(s):t.set(c,[s])}}for(let o of t.values()){if(o.length<2)continue;o.sort((r,s)=>r.start-s.start||r.end-s.end);let i=[];for(let r of o){i=i.filter(s=>s.end>r.start+lt);for(let s of i)s.item.sourceIndex!==r.item.sourceIndex&&(vi(s),vi(r));i.push(r)}}}function Wl(e){let n=Ci(e);return n?{r:n.rgb[0],g:n.rgb[1],b:n.rgb[2],alpha:n.alpha}:{r:255,g:255,b:255,alpha:1}}function Ul(e){if(!e)return"#cccccc";let n=Ci(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(${fr(t.r)}, ${fr(t.g)}, ${fr(t.b)}, ${o})`}return Gl(t)}function Gl({r:e,g:n,b:t}){let o=i=>Math.round(Math.max(0,Math.min(255,i))).toString(16).padStart(2,"0");return`#${o(e)}${o(n)}${o(t)}`}function fr(e){return Math.round(Math.max(0,Math.min(255,e)))}function Yl(e,n,t,o){let i=t?.direction??wl,r=Math.hypot(i[0],i[1],i[2])||1,s=i[0]/r,c=i[1]/r,l=i[2]/r,d=Math.max(0,t?.intensity??Ll)*Math.max(0,e[0]*s+e[1]*c+e[2]*l),p=Math.max(0,o?.intensity??kl),y=t?.color??Ml,g=o?.color??Rl,b=El(n,d,y,g,p),x=Wl(n);if(x.alpha>=1)return b;let v=parseInt(b.slice(1,3),16),h=parseInt(b.slice(3,5),16),C=parseInt(b.slice(5,7),16);return`rgba(${v}, ${h}, ${C}, ${x.alpha})`}function Xl(e){if(!e?.length)return[];let n=[];for(let t=0;t<e.length;t+=1){let o=e[t],i=zl(o);if(!i||i.width<=0||i.height<=0)return[];n.push({...i,sourceIndex:t})}return $l(e,n),n}function ql(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 Zl(e){let n=e.left,t=e.top,o=e.left+e.width,i=e.top+e.height;return[n,t,o,t,o,i,n,i]}function Ql(e){return new Map([[0,e.bleed.top],[1,e.bleed.right],[2,e.bleed.bottom],[3,e.bleed.left]])}function Kl(e,n){let t=e.split(",").map(Number);if(t.length!==16||t.some(i=>!Number.isFinite(i)))return null;let o=Al/n;for(let i=0;i<8;i+=1)t[i]*=o;return`matrix3d(${t.map(i=>Number(i.toFixed(6))).join(",")})`}function Si(e,n){let t=e.left-e.bleed.left,o=e.top-e.bleed.top,i=e.width+e.bleed.left+e.bleed.right,r=e.height+e.bleed.top+e.bleed.bottom,s=e.z,c=i/n,l=r/n;return`matrix3d(${(e.axis==="x"?[c,0,0,0,0,0,l,0,0,-1,0,0,t,-s,o,1]:e.axis==="y"?[0,0,c,0,0,l,0,0,-1,0,0,0,-s,o,t,1]:[c,0,0,0,0,l,0,0,0,0,1,0,t,o,s,1]).map(p=>Number(p.toFixed(6))).join(",")})`}function Jl(e,n){let{xAxis:t,yAxis:o,normal:i,tx:r,ty:s,tz:c}=ql(e),l=xl(Zl(e),t,o,i,r,s,c,Dl,Ql(e));return l?Kl(l,n)??Si(e,n):Si(e,n)}function ec(e){let n=e.defaultView?.matchMedia;return n?n("(pointer: coarse)").matches||n("(hover: none)").matches:!1}function tc(e){return ec(e)?_l:Ti}function nc(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 oc(e,n){let t=nc(e),o=n.meshRotation;o&&(t=Tl(t,o));let[i,r]=Cl(t,n.rotX,0,n.rotY);return{x:i,y:r}}function rc(e,n,t){let o=e.filter(g=>n.has(g.face)).map(g=>({item:g,...oc(g,t)}));if(o.length===0)return[];let i=1/0,r=-1/0,s=1/0,c=-1/0;for(let g of o)i=Math.min(i,g.x),r=Math.max(r,g.x),s=Math.min(s,g.y),c=Math.max(c,g.y);let l=4,d=Math.max(1e-6,r-i),p=Math.max(1e-6,c-s),y=new Map;for(let g of o){let b=Math.min(l-1,Math.max(0,Math.floor((g.x-i)/d*l))),x=Math.min(l-1,Math.max(0,Math.floor((g.y-s)/p*l))),v=`${b}:${x}`,h=y.get(v);h||(h={tx:b,ty:x,sourceIndex:g.item.sourceIndex,items:[]},y.set(v,h)),h.items.push(g.item),h.sourceIndex=Math.min(h.sourceIndex,g.item.sourceIndex)}return Array.from(y.values()).sort((g,b)=>g.ty-b.ty||g.tx-b.tx||g.sourceIndex-b.sourceIndex).flatMap(g=>g.items)}function Ai(e){let{doc:n,wrapper:t,polygons:o,directionalLight:i,ambientLight:r}=e,s=Xl(o);if(s.length===0)return null;let c=new Set(s.map(P=>P.face));t.classList.add("polycss-voxel-mesh");let l=tc(n);l!==Ti&&t.style.setProperty("--polycss-voxel-primitive",`${l}px`);let d=new Map,p=(P,L)=>{let u=`${P}|${L}`,m=d.get(u);if(m)return m;let A=Yl(Ei[P],L,i,r);return d.set(u,A),A},y=new Map,g=new Map,b=new Map,x=new Map;for(let P of s){let L=x.get(P.face);L||(L=[],x.set(P.face,L)),L.push(P)}let v="",h=0,C=new Set,R=P=>{let L=y.get(P.sourceIndex);return L||(L=n.createElement("b"),y.set(P.sourceIndex,L),Hl(L,p(P.face,P.baseColor),Jl(P,l))),L},I=P=>{let L=g.get(P);return L||(L=n.createElement("span"),L.className=`polycss-voxel-face polycss-voxel-face-${P}`,L.dataset.polycssVoxelFace=P,L.__polycssVoxelFaceHost=!0,g.set(P,L)),L},z=()=>{for(let P of Array.from(t.childNodes))if(!P.__polycssVoxelFaceHost)return P;return null},D=(P,L)=>{let u=L.map(k=>k.sourceIndex).join(",");if(b.get(P)===u)return;let m=I(P),A=n.createDocumentFragment();for(let k of L)A.appendChild(R(k));m.replaceChildren(A),b.set(P,u)},X=()=>{for(let P of gr)c.has(P)&&D(P,x.get(P)??[])},q=P=>new Set(P.split("|").filter(Boolean)),M=P=>{let L=q(P);return gr.filter(u=>L.has(u)&&c.has(u))},V=P=>{let L=0;for(let u of P)L+=x.get(u)?.length??0;return L},B=P=>{let L=new Set,u=[],m=new Map;for(let A of P){L.has(A.face)||(L.add(A.face),u.push(A.face));let k=m.get(A.face);k||(k=[],m.set(A.face,k)),k.push(A)}return{orderedFaces:u,itemsByFace:m}},F=(P,L)=>{let u=new Set(P);for(let m of C){if(u.has(m))continue;let A=g.get(m);A?.parentNode===t&&t.removeChild(A)}if(L){let m=n.createDocumentFragment();for(let A of P)m.appendChild(I(A));t.insertBefore(m,z()),C=u;return}for(let m=0;m<P.length;m+=1){let A=P[m],k=I(A);if(k.parentNode===t)continue;let N=null;for(let Y=m+1;Y<P.length;Y+=1){let w=g.get(P[Y]);if(w?.parentNode===t){N=w;break}}t.insertBefore(k,N??z())}C=u},re=(P,L,u)=>{if(!u){let Y=M(P);F(Y,!1),h=V(Y);return}let m=new Set(P.split("|").filter(Boolean)),A=rc(s,m,L),{orderedFaces:k,itemsByFace:N}=B(A);for(let Y of k)D(Y,N.get(Y)??[]);F(k,!0),h=A.length};return X(),{get brushCount(){return h},render(P){v=bi(P),re(v,P,!0)},syncCamera(P){let L=bi(P);L!==v&&(v=L,re(L,P,!1))},dispose(){for(let P of g.values())P.remove();t.classList.remove("polycss-voxel-mesh"),t.style.removeProperty("--polycss-voxel-primitive"),y.clear(),g.clear(),b.clear(),h=0,C=new Set,v=""}}}var wi="polycss-styles";function Fn(e){let n=e??(typeof document<"u"?document:void 0);if(!n||n.getElementById(wi))return;let t=n.createElement("style");t.id=wi,t.textContent=ic,n.head.appendChild(t)}var ic=`
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
+
4
+ .polycss-scene,
5
+ .polycss-scene *,
6
+ .polycss-scene *::before,
7
+ .polycss-scene *::after {
8
+ box-sizing: border-box;
9
+ }
10
+
11
+ /* Camera wrapper (mounted by createPolyCamera / PolyPerspectiveCamera /
12
+ PolyOrthographicCamera). Fills its parent so the scene inside has a
13
+ positioned, sized layout context for its top: 50% / left: 50% pin to
14
+ resolve against. Inline styles win on specificity if the user sizes
15
+ the camera explicitly. */
16
+ .polycss-camera {
17
+ position: relative;
18
+ display: block;
19
+ width: 100%;
20
+ height: 100%;
21
+ }
22
+
23
+ .polycss-scene {
24
+ position: absolute;
25
+ top: 50%;
26
+ left: 50%;
27
+ width: 0;
28
+ height: 0;
29
+ transform-style: preserve-3d;
30
+ /* Pin the scene as a composited layer. Without this, mobile Chrome
31
+ re-rasterizes every descendant tile when the scene transform changes
32
+ each animation frame, which overruns the raster budget on textured
33
+ meshes (faces drop, fragments float). With will-change, the GPU
34
+ reuses the cached layer pixels and only re-composites. */
35
+ will-change: transform;
36
+ }
37
+
38
+ /* \u2500\u2500 First-person controls perspective context \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 */
39
+
40
+ /* PolyFirstPersonControls toggles this class on the camera wrapper
41
+ (scene.cameraEl in vanilla; the camera wrapper div in react/vue). FPV needs a real perspective
42
+ context so scene Z translation produces visible depth motion - without
43
+ it, walking forward looks like a planar pan. The class wins over inline
44
+ perspective styles (e.g. PolyOrthographicCamera's perspective: none)
45
+ via !important. The actual perspective value is set inline by the
46
+ controls as the --polycss-fpv-perspective custom property; the default
47
+ of 2000px matches the controls' lookOffset fallback so the FPV math and
48
+ visual perspective stay in sync. */
49
+ .polycss-fpv-host {
50
+ perspective: var(--polycss-fpv-perspective, 2000px) !important;
51
+ transform-style: preserve-3d !important;
52
+ }
53
+
54
+ /* \u2500\u2500 Shadow root wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
55
+
56
+ /* Single 0\xD70 preserve-3d container that owns every shadow SVG (ground +
57
+ per-face receiver). Children composite via their own absolute matrix3d
58
+ transforms exactly as if mounted on .polycss-scene directly. The wrapper
59
+ exists so the DOM has one obvious "shadows live here" node and so
60
+ future toggles (clip-region, hide-all-shadows) flip a single ancestor. */
61
+ .polycss-shadows {
62
+ position: absolute;
63
+ top: 0;
64
+ left: 0;
65
+ width: 0;
66
+ height: 0;
67
+ transform-style: preserve-3d;
68
+ pointer-events: none;
69
+ }
70
+
71
+ /* \u2500\u2500 Mesh wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
72
+
73
+ .polycss-mesh {
74
+ position: absolute;
75
+ transform-style: preserve-3d;
76
+ /* Pivot at wrapper local (0,0,0) for three.js mesh.position/rotation/scale
77
+ parity. Geometry is positioned by the parser (bbox-min-at-origin by
78
+ default, or pre-centered via parseGltf/parseObj { center: true }). */
79
+ transform-origin: 0 0 0;
80
+ }
81
+
82
+ /* \u2500\u2500 Polygon leaf element \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
83
+
84
+ .polycss-scene b,
85
+ .polycss-scene i,
86
+ .polycss-scene s,
87
+ .polycss-scene u {
88
+ position: absolute;
89
+ display: block;
90
+ transform-origin: 0 0;
91
+ transform-style: preserve-3d;
92
+ margin: 0;
93
+ padding: 0;
94
+ font: inherit;
95
+ font-weight: normal;
96
+ font-style: normal;
97
+ line-height: 0;
98
+ text-decoration: none;
99
+ backface-visibility: hidden;
100
+ background-repeat: no-repeat;
101
+ }
102
+
103
+ .polycss-scene b,
104
+ .polycss-scene i,
105
+ .polycss-scene u {
106
+ color: var(--polycss-paint, currentColor);
107
+ }
108
+
109
+ .polycss-scene b {
110
+ background: currentColor;
111
+ width: 64px;
112
+ height: 64px;
113
+ }
114
+
115
+ .polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face {
116
+ position: absolute;
117
+ display: block;
118
+ top: 0;
119
+ left: 0;
120
+ width: 0;
121
+ height: 0;
122
+ transform-style: preserve-3d;
123
+ transform-origin: 0 0;
124
+ margin: 0;
125
+ padding: 0;
126
+ font: inherit;
127
+ line-height: 0;
128
+ pointer-events: none;
129
+ }
130
+
131
+ .polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face > b {
132
+ top: 0;
133
+ left: 0;
134
+ width: var(--polycss-voxel-primitive, 1px);
135
+ height: var(--polycss-voxel-primitive, 1px);
136
+ backface-visibility: visible;
137
+ pointer-events: none;
138
+ }
139
+
140
+ .polycss-scene i {
141
+ width: 16px;
142
+ height: 16px;
143
+ border-color: currentColor;
144
+ }
145
+
146
+ .polycss-scene s {
147
+ width: var(--polycss-atlas-width, var(--polycss-atlas-size, 64px));
148
+ height: var(--polycss-atlas-height, var(--polycss-atlas-size, 64px));
149
+ }
150
+
151
+ .polycss-scene u {
152
+ width: 0;
153
+ height: 0;
154
+ background: transparent;
155
+ box-sizing: content-box;
156
+ border: 0 solid transparent;
157
+ border-color: transparent transparent currentColor transparent;
158
+ border-width: 0 16px 32px 16px;
159
+ }
160
+
161
+ @supports (corner-top-left-shape: bevel) and (corner-top-right-shape: bevel) {
162
+ .polycss-scene > u,
163
+ .polycss-mesh > u,
164
+ .polycss-bucket > u {
165
+ border-width: 0;
166
+ width: 32px;
167
+ height: 32px;
168
+ background-color: currentColor;
169
+ border-top-left-radius: 50% 100%;
170
+ border-top-right-radius: 50% 100%;
171
+ corner-top-left-shape: bevel;
172
+ corner-top-right-shape: bevel;
173
+ }
174
+
175
+ .polycss-scene > u.polycss-corner-shape-solid,
176
+ .polycss-mesh > u.polycss-corner-shape-solid,
177
+ .polycss-bucket > u.polycss-corner-shape-solid {
178
+ width: 16px;
179
+ height: 16px;
180
+ box-sizing: border-box;
181
+ border: 0;
182
+ background: currentColor;
183
+ border-radius: 0;
184
+ corner-top-left-shape: initial;
185
+ corner-top-right-shape: initial;
186
+ corner-bottom-right-shape: initial;
187
+ corner-bottom-left-shape: initial;
188
+ }
189
+ }
190
+
191
+ /* Reserved internal <q> shadow element rules. Current shadow emission uses SVG
192
+ surfaces; these rules keep any retained <q> markup styled as a plain
193
+ border-shape leaf instead of inheriting UA quote styling. */
194
+ .polycss-scene q {
195
+ position: absolute;
196
+ display: block;
197
+ transform-origin: 0 0;
198
+ transform-style: preserve-3d;
199
+ margin: 0;
200
+ padding: 0;
201
+ font: inherit;
202
+ font-weight: normal;
203
+ font-style: normal;
204
+ line-height: 0;
205
+ text-decoration: none;
206
+ backface-visibility: visible;
207
+ border-color: currentColor;
208
+ pointer-events: none;
209
+ will-change: transform;
210
+ }
211
+ .polycss-scene q::before,
212
+ .polycss-scene q::after {
213
+ content: none;
214
+ }
215
+
216
+ /* \u2500\u2500 Gizmo override (createTransformControls) \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 */
217
+
218
+ /*
219
+ * Translate arrows + rotate rings render through the same polygon
220
+ * pipeline as user content but the gizmo is a UI affordance \u2014 both
221
+ * faces of every polygon should remain visible regardless of camera
222
+ * orientation, otherwise the cuboid shafts and pyramid heads end up
223
+ * half-culled. Transitions on color, border-color, and background-color
224
+ * smooth the idle / hover / drag alpha changes.
225
+ */
226
+ .polycss-mesh.polycss-transform-gizmo i,
227
+ .polycss-mesh.polycss-transform-gizmo b,
228
+ .polycss-mesh.polycss-transform-gizmo s,
229
+ .polycss-mesh.polycss-transform-gizmo u {
230
+ backface-visibility: visible;
231
+ transition: color 150ms ease-out, border-color 150ms ease-out, background-color 150ms ease-out;
232
+ }
233
+
234
+ /*
235
+ * Rotate rings are rendered as a single square quad per ring, then masked
236
+ * to a donut via a radial-gradient. The --ring-inner-ratio CSS var is set
237
+ * inline by createTransformControls (= innerR / outerR, where outerR maps
238
+ * to the quad's edge at 50%). Hit-testing has to use the donut shape too.
239
+ * Single DOM node per ring instead of N segment quads.
240
+ */
241
+ .polycss-mesh.polycss-transform-ring i,
242
+ .polycss-mesh.polycss-transform-ring b,
243
+ .polycss-mesh.polycss-transform-ring s,
244
+ .polycss-mesh.polycss-transform-ring u {
245
+ --ring-inner-r: calc(var(--ring-inner-ratio, 0.92) * 50%);
246
+ --ring-outer-r: calc(var(--ring-outer-ratio, 1) * 50%);
247
+ -webkit-mask: radial-gradient(circle at 50% 50%,
248
+ transparent 0%,
249
+ transparent var(--ring-inner-r),
250
+ black var(--ring-inner-r),
251
+ black var(--ring-outer-r),
252
+ transparent var(--ring-outer-r));
253
+ mask: radial-gradient(circle at 50% 50%,
254
+ transparent 0%,
255
+ transparent var(--ring-inner-r),
256
+ black var(--ring-inner-r),
257
+ black var(--ring-outer-r),
258
+ transparent var(--ring-outer-r));
259
+ }
260
+
261
+ /* \u2500\u2500 Dynamic lighting cascade vars (scene root \u2192 polygons) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
262
+
263
+ /*
264
+ * Dynamic mode: the scene root carries the directional + ambient light
265
+ * setup as custom properties. Each polygon leaf bakes its own normal
266
+ * directly into an inline calc() that reads these vars to resolve the
267
+ * Lambert dot product and per-channel tint. Sliding the light only
268
+ * writes these scene-root vars \u2014 no JS, no atlas redraw.
269
+ *
270
+ * Registering with @property forces the browser to parse the values as
271
+ * <number>s instead of opaque token streams; that makes the polygon-level
272
+ * calc() expressions resolve reliably across engines.
273
+ */
274
+
275
+ @property --plx { syntax: "<number>"; inherits: true; initial-value: 0; }
276
+ @property --ply { syntax: "<number>"; inherits: true; initial-value: 0; }
277
+ @property --plz { syntax: "<number>"; inherits: true; initial-value: 1; }
278
+
279
+ /* CSS-space light components (world-Y\u2192cssX, world-X\u2192cssY, world-Z\u2192cssZ).
280
+ Used by the shadow projection matrix. --clx is clamped away from 0 in JS
281
+ to avoid divide-by-zero when the light is near-horizontal. */
282
+ @property --clx { syntax: "<number>"; inherits: true; initial-value: 0.01; }
283
+ @property --cly { syntax: "<number>"; inherits: true; initial-value: 0; }
284
+ @property --clz { syntax: "<number>"; inherits: true; initial-value: 1; }
285
+
286
+ /* Ground-plane position in CSS pixels along the CSS-Z axis (= world-Z, the
287
+ up axis in PolyCSS's world convention). Stored as a <number> so it can be
288
+ used directly inside matrix3d() calc() expressions (matrix3d requires
289
+ dimensionless entries \u2014 no px units).
290
+ Set by recomputeShadowGround() from the min world-Z of casting meshes. */
291
+ @property --shadow-ground-cssz { syntax: "<number>"; inherits: true; initial-value: 0; }
292
+ @property --plr { syntax: "<number>"; inherits: true; initial-value: 1; }
293
+ @property --plg { syntax: "<number>"; inherits: true; initial-value: 1; }
294
+ @property --plb { syntax: "<number>"; inherits: true; initial-value: 1; }
295
+ @property --pli { syntax: "<number>"; inherits: true; initial-value: 1; }
296
+ @property --par { syntax: "<number>"; inherits: true; initial-value: 1; }
297
+ @property --pag { syntax: "<number>"; inherits: true; initial-value: 1; }
298
+ @property --pab { syntax: "<number>"; inherits: true; initial-value: 1; }
299
+ @property --pai { syntax: "<number>"; inherits: true; initial-value: 0.4; }
300
+
301
+ /* Per-polygon surface normal \u2014 set inline by the renderer per leaf, OR by
302
+ a .polycss-bucket wrapper that groups axis-aligned polys sharing the
303
+ same face direction. inherits:true so polys inside a bucket pick up
304
+ the wrapper's normal automatically; polys outside any bucket still
305
+ override it inline. */
306
+ @property --pnx { syntax: "<number>"; inherits: true; initial-value: 0; }
307
+ @property --pny { syntax: "<number>"; inherits: true; initial-value: 0; }
308
+ @property --pnz { syntax: "<number>"; inherits: true; initial-value: 1; }
309
+ @property --psr { syntax: "<number>"; inherits: true; initial-value: 1; }
310
+ @property --psg { syntax: "<number>"; inherits: true; initial-value: 1; }
311
+ @property --psb { syntax: "<number>"; inherits: true; initial-value: 1; }
312
+
313
+ /* Hoisted Lambert dot product \u2014 computed once per element it's set on.
314
+ inherits:true so a bucket wrapper computes lambert ONCE for its whole
315
+ group (one calc per bucket, not per polygon). Solo polys still set it
316
+ themselves via the per-poly rule below. */
317
+ @property --plam { syntax: "<number>"; inherits: true; initial-value: 0; }
318
+
319
+ /* Calc-driven Lambert + tint, scoped to dynamic-lighting scenes. Lives
320
+ here (not inline per polygon) so each leaf only carries its tiny normal
321
+ declarations \u2014 ~12\xD7 smaller per-polygon style payload on big meshes.
322
+ --plam is computed once and reused 3\xD7 (one per channel),
323
+ cutting the dot-product calc count from 3 \u2192 1 per polygon per frame. */
324
+ /* Lambert-bucket wrapper: createPolyScene groups axis-aligned polys
325
+ sharing one face direction inside a .polycss-bucket div with the
326
+ bucket's normal as inline CSS vars. Lambert is computed ONCE per
327
+ bucket (inherits:true on --plam propagates the value to
328
+ every leaf child). For voxel meshes this collapses thousands of
329
+ per-frame dot products into a few dozen. */
330
+ .polycss-bucket {
331
+ position: absolute;
332
+ transform-style: preserve-3d;
333
+ }
334
+
335
+ /* Per-bucket lambert calc \u2014 runs once per bucket per frame. */
336
+ .polycss-scene[data-polycss-lighting="dynamic"] .polycss-bucket {
337
+ --plam: max(0, calc(
338
+ var(--pnx) * var(--plx) +
339
+ var(--pny) * var(--ply) +
340
+ var(--pnz) * var(--plz)
341
+ ));
342
+ }
343
+
344
+ /* Per-poly lambert calc \u2014 applies to any leaf whose direct parent is NOT
345
+ a .polycss-bucket. Covers:
346
+ - vanilla createPolyScene polys not inside a bucket (e.g. off-axis
347
+ curved polys that didn't make a bucket group)
348
+ - React <PolyScene polygons> path (leaves are direct children of
349
+ .polycss-scene; no <PolyMesh> wrapper)
350
+ - React <PolyScene><PolyMesh polygons></PolyMesh> path (leaves are
351
+ direct children of .polycss-mesh)
352
+ Bucketed leaves are skipped \u2014 their parent IS .polycss-bucket so they
353
+ inherit the bucket's hoisted lambert (one calc per bucket, not per
354
+ leaf). */
355
+ .polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > i,
356
+ .polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > b,
357
+ .polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > s,
358
+ .polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > u {
359
+ --plam: max(0, calc(
360
+ var(--pnx) * var(--plx) +
361
+ var(--pny) * var(--ply) +
362
+ var(--pnz) * var(--plz)
363
+ ));
364
+ }
365
+
366
+ /* Atlas polys: containment + background-color from lambert (inherited or
367
+ own) and the scene-level light vars. Splitting this from the lambert
368
+ calc above lets bucketed polys skip the dot-product entirely. */
369
+ .polycss-scene[data-polycss-lighting="dynamic"] s {
370
+ /* Isolate each leaf's layout/style/paint walks from siblings. Works
371
+ because the leaf transform-style:preserve-3d was dropped above \u2014
372
+ the 3D context lives on .polycss-scene / .polycss-mesh, not the
373
+ leaves, so there's nothing inside a leaf that needs to participate
374
+ in 3D compositing across the contain boundary. */
375
+ contain: strict;
376
+ /*
377
+ * Three.js MeshLambertMaterial parity for textured surfaces:
378
+ *
379
+ * target = sRGB_encode(albedo_linear \xD7 irradiance_linear / \u03C0)
380
+ *
381
+ * background-blend-mode: multiply produces (bitmap \xD7 tint) in sRGB
382
+ * \u2014 approximately sRGB(albedo_linear \xD7 tint_linear) when bitmap \u2248
383
+ * sRGB(albedo_linear). So we want tint = sRGB_encode(irradiance /\u03C0).
384
+ *
385
+ * Each light/ambient colour channel is sRGB-to-linearised
386
+ * via pow((c + 0.055) / 1.055, 2.4) before the dot product so the
387
+ * irradiance accumulates in linear space; final encode is
388
+ * 1.055 \xD7 pow(c, 1/2.4) - 0.055. min(1, \u2026) clamps inside the encode
389
+ * domain. Matches the solid <b>/<i>/<u> pipeline below.
390
+ */
391
+ background-color: rgb(
392
+ calc(255 * max(0, 1.055 * pow(min(1, (
393
+ pow((var(--par) + 0.055) / 1.055, 2.4) * var(--pai) +
394
+ pow((var(--plr) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
395
+ ) / 3.14159265), 0.4167) - 0.055))
396
+ calc(255 * max(0, 1.055 * pow(min(1, (
397
+ pow((var(--pag) + 0.055) / 1.055, 2.4) * var(--pai) +
398
+ pow((var(--plg) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
399
+ ) / 3.14159265), 0.4167) - 0.055))
400
+ calc(255 * max(0, 1.055 * pow(min(1, (
401
+ pow((var(--pab) + 0.055) / 1.055, 2.4) * var(--pai) +
402
+ pow((var(--plb) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
403
+ ) / 3.14159265), 0.4167) - 0.055))
404
+ );
405
+ background-blend-mode: multiply;
406
+ background-image: var(--polycss-atlas-url);
407
+ background-position: var(--polycss-atlas-position);
408
+ background-repeat: no-repeat;
409
+ background-size: var(--polycss-atlas-image-size);
410
+ mask-image: var(--polycss-atlas-url);
411
+ mask-mode: alpha;
412
+ mask-position: var(--polycss-atlas-position);
413
+ mask-repeat: no-repeat;
414
+ mask-size: var(--polycss-atlas-image-size);
415
+ -webkit-mask-image: var(--polycss-atlas-url);
416
+ -webkit-mask-position: var(--polycss-atlas-position);
417
+ -webkit-mask-repeat: no-repeat;
418
+ -webkit-mask-size: var(--polycss-atlas-image-size);
419
+ }
420
+
421
+ .polycss-scene[data-polycss-lighting="dynamic"] b,
422
+ .polycss-scene[data-polycss-lighting="dynamic"] i,
423
+ .polycss-scene[data-polycss-lighting="dynamic"] u {
424
+ /*
425
+ * Three.js MeshLambertMaterial parity (default useLegacyLights=false,
426
+ * physically-correct pipeline):
427
+ *
428
+ * lit_linear = albedo_linear \xD7 (lightColor_linear \xD7 intensity \xD7 lambert
429
+ * + ambient_linear \xD7 ambientIntensity) / \u03C0
430
+ * output = 255 \xD7 sRGB_encode(min(1, lit_linear))
431
+ *
432
+ * sRGB\u2192linear: pow((c + 0.055) / 1.055, 2.4) for c > 0.04045
433
+ * 12.92 \xD7 c otherwise (skipped \u2014 tiny)
434
+ * linear\u2192sRGB: 1.055 \xD7 pow(c, 1/2.4) - 0.055 for c > 0.0031308
435
+ * 12.92 \xD7 c otherwise (skipped \u2014 tiny)
436
+ *
437
+ * The naive pow(c, 2.4) shortcut undershoots by ~2x for small c
438
+ * (dark channels of a saturated colour) \u2014 the +0.055/1.055 offset
439
+ * is load-bearing for the G/B drift on saturated fixtures.
440
+ *
441
+ * Verified against per-pixel screenshots in bench/three-parity.html
442
+ * (cube #dc2626 top face): drift <3 per channel across i=0.5..3,
443
+ * ambient=0..0.3, lambert=0..1.
444
+ */
445
+ color: rgb(
446
+ calc(255 * max(0, 1.055 * pow(min(1,
447
+ pow((var(--psr) + 0.055) / 1.055, 2.4) * (
448
+ pow((var(--par) + 0.055) / 1.055, 2.4) * var(--pai) +
449
+ pow((var(--plr) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
450
+ ) / 3.14159265
451
+ ), 0.4167) - 0.055))
452
+ calc(255 * max(0, 1.055 * pow(min(1,
453
+ pow((var(--psg) + 0.055) / 1.055, 2.4) * (
454
+ pow((var(--pag) + 0.055) / 1.055, 2.4) * var(--pai) +
455
+ pow((var(--plg) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
456
+ ) / 3.14159265
457
+ ), 0.4167) - 0.055))
458
+ calc(255 * max(0, 1.055 * pow(min(1,
459
+ pow((var(--psb) + 0.055) / 1.055, 2.4) * (
460
+ pow((var(--pab) + 0.055) / 1.055, 2.4) * var(--pai) +
461
+ pow((var(--plb) + 0.055) / 1.055, 2.4) * var(--pli) * var(--plam)
462
+ ) / 3.14159265
463
+ ), 0.4167) - 0.055))
464
+ );
465
+ }
466
+
467
+ /* \u2500\u2500 Retained <q> shadow projection (dynamic-mode CSS path) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 */
468
+
469
+ /*
470
+ * Projection matrix for retained internal <q> shadow leaves. Projects any
471
+ * 3D point P onto the horizontal ground plane (cssZ \u2248 G) along the CSS-space
472
+ * light direction (--clx/y/z).
473
+ *
474
+ * In PolyCSS's world convention world Z is up (red-green plane is the
475
+ * floor in the axes helper). After the world\u2192CSS swap (Y\u2194X), world Z stays
476
+ * as CSS Z, so the ground plane normal in CSS space is +cssZ.
477
+ *
478
+ * The strict projection formula would set m22=0 (output.z is a constant G,
479
+ * the polygon is exactly flat). But Chromium SKIPS rendering elements
480
+ * whose composed transform matrix is non-invertible (singular). m22=0
481
+ * makes the matrix singular, so the shadow paints nothing even though it
482
+ * has a valid layout box. The fix: collapse along z by a near-zero
483
+ * scale (Z_SQUASH = 0.01) instead of exactly zero \u2014 output.z is then
484
+ * approximately G with ~1% drift from the input, full-rank and renderable.
485
+ * The result still looks flat to the eye (the drift is sub-pixel for
486
+ * any realistic scene size).
487
+ *
488
+ * out.cssX = P.cssX - (--clx/--clz) * (P.cssZ - G)
489
+ * out.cssY = P.cssY - (--cly/--clz) * (P.cssZ - G)
490
+ * out.cssZ = Z_SQUASH * P.cssZ + (1 - Z_SQUASH) * G
491
+ *
492
+ * As column-major 4\xD74 (CSS matrix3d order):
493
+ * col1: [1, 0, 0, 0]
494
+ * col2: [0, 1, 0, 0]
495
+ * col3: [-(--clx/--clz), -(--cly/--clz), Z_SQUASH, 0]
496
+ * col4: [G*(--clx/--clz), G*(--cly/--clz), G*(1-Z_SQUASH), 1]
497
+ */
498
+ .polycss-scene[data-polycss-lighting="dynamic"] {
499
+ --shadow-proj: matrix3d(
500
+ 1, 0, 0, 0,
501
+ 0, 1, 0, 0,
502
+ calc(-1 * var(--clx) / var(--clz)),
503
+ calc(-1 * var(--cly) / var(--clz)),
504
+ 0.01,
505
+ 0,
506
+ calc(var(--shadow-ground-cssz) * var(--clx) / var(--clz)),
507
+ calc(var(--shadow-ground-cssz) * var(--cly) / var(--clz)),
508
+ calc(var(--shadow-ground-cssz) * 0.99),
509
+ 1
510
+ );
511
+ }
512
+
513
+ /* Retained <q> opacity gate. Polygons facing the light cast full shadow;
514
+ polygons facing away cast zero shadow. The * 10 multiplier sharpens the
515
+ cutoff so small positive Lambert values jump quickly to 1. */
516
+ .polycss-scene[data-polycss-lighting="dynamic"] q {
517
+ opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1);
518
+ }
519
+ `;import{BASE_TILE as sc,buildPolyCameraSceneTransform as ac,buildPolyMeshTransform as lc,worldDirectionToCss as cc,worldDirectionalLightToCss as uc,worldPositionToCss as dc}from"@layoutit/polycss-core";var yn=sc,pc=.1;function Mi(e){return dc(e)}function bn(e){return cc(e)}function xt(e){return uc(e)}function zn(e){return lc(e)}function hr(e,n=[0,0,0],t=1){return ac(e.state,{autoCenterOffset:n,layoutScale:t})}function mc(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 Li(e){let n=e.ownerDocument?.defaultView;if(!n)return 1;let t=1;for(let o=e;o;o=o.parentElement)t*=mc(n.getComputedStyle(o).getPropertyValue("zoom"));return Number.isFinite(t)&&t>0?t:1}function Ri(e,n){Math.abs(n-1)<1e-6?e.style.removeProperty("zoom"):e.style.setProperty("zoom",String(1/n))}function ki(e){if(e.vertices.length<3)return null;let n=e.vertices[0],t=0,o=0,i=0;for(let y=1;y+1<e.vertices.length;y++){let g=e.vertices[y],b=e.vertices[y+1],x=g[1]-n[1],v=g[0]-n[0],h=g[2]-n[2],C=b[1]-n[1],R=b[0]-n[0],I=b[2]-n[2];t-=v*I-h*R,o-=h*C-x*I,i-=x*R-v*C}let r=Math.hypot(t,o,i);if(r<1e-9)return null;t/=r,o/=r,i/=r;let s=1/pc,c=Math.round(t*s)/s,l=Math.round(o*s)/s,d=Math.round(i*s)/s,p=Math.hypot(c,l,d);return p<1e-9?null:{key:c+","+l+","+d,vec:[c/p,l/p,d/p]}}function _i(e,n){let t=e?.disable??[],o=n?.disable??[];if(t.length!==o.length)return!1;for(let i of t)if(!o.includes(i))return!1;return!0}function Oi(e,n){return e===n?!0:!e||!n?!1:e[0]===n[0]&&e[1]===n[1]&&e[2]===n[2]}function Di(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)&&(e?.parametric??!1)===(n?.parametric??!1)&&(e?.definition??16)===(n?.definition??16)&&(e?.dragDefinition??-1)===(n?.dragDefinition??-1)&&(e?.style??"vector")===(n?.style??"vector")&&(e?.followAnimation??!1)===(n?.followAnimation??!1)}import{parseHex as Fi,parseHexColor as Ii,parsePureColor as fc}from"@layoutit/polycss-core";var gc=["--plx","--ply","--plz","--plr","--plg","--plb","--pli","--par","--pag","--pab","--pai","--clx","--cly","--clz"],Wt="--polycss-light-preview-active",Hi=`var(${Wt}, 0)`,hc="max(0, calc(var(--pnx, 0) * var(--plx, 0) + var(--pny, 0) * var(--ply, 0) + var(--pnz, 1) * var(--plz, 1)))",yr=(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))`,yc=yr("--psr","--par","--plr"),bc=yr("--psg","--pag","--plg"),xc=yr("--psb","--pab","--plb");function ge(e,n,t){return e.style.getPropertyValue(n)===t?!1:(e.style.setProperty(n,t),!0)}function Mt(e){for(let n of gc)e.style.getPropertyValue(n)&&e.style.removeProperty(n)}function Bn(e,n){let t=n.directionalLight?.direction??[.4,-.7,.59],o=bn(t),i=Math.hypot(o[0],o[1],o[2])||1,r=o[0]/i,s=o[1]/i,c=o[2]/i,l=Ii(n.directionalLight?.color??"#ffffff")?.rgb??[255,255,255],d=Ii(n.ambientLight?.color??"#ffffff")?.rgb??[255,255,255],p=n.directionalLight?.intensity??1,y=n.ambientLight?.intensity??.4,g=v=>(v/255).toFixed(4);ge(e,"--plx",r.toFixed(2)),ge(e,"--ply",s.toFixed(2)),ge(e,"--plz",c.toFixed(2)),ge(e,"--plr",g(l[0])),ge(e,"--plg",g(l[1])),ge(e,"--plb",g(l[2])),ge(e,"--pli",p.toFixed(4)),ge(e,"--par",g(d[0])),ge(e,"--pag",g(d[1])),ge(e,"--pab",g(d[2])),ge(e,"--pai",y.toFixed(4));let b=c,x=Math.sign(b||1)*Math.max(Math.abs(b),.01);ge(e,"--clx",r.toFixed(2)),ge(e,"--cly",s.toFixed(2)),ge(e,"--clz",x.toFixed(2))}function zi(e,n){let t=n.textureLighting==="dynamic";if(e.dataset.polycssLighting=n.textureLighting??"baked",!t){Mt(e);return}Bn(e,n)}function Lt(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 Bi(e,n){let t=Fi(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 br(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=t.textureLighting??"baked",i={directionalLight:xt(t.directionalLight),ambientLight:t.ambientLight,textureLighting:o,textureQuality:t.textureQuality,seamBleed:t.seamBleed,strategies:t.strategies},r=jo(e.plan,n,e.plan.normal,o,i);return zt(e.element,r,o),o==="baked"&&vc(e.element),!0}function Pc(e){let n=fc(e)??{rgb:[255,255,255],alpha:1},[t,o,i]=n.rgb,r=(c,l)=>`calc(${c} * (1 - ${Hi}) + var(${l}, ${c}) * ${Hi})`,s=n.alpha<1?` / ${n.alpha}`:"";return`rgb(${r(t,"--polycss-preview-r")} ${r(o,"--polycss-preview-g")} ${r(i,"--polycss-preview-b")}${s})`}function Vi(e,n,t){if(!e.plan||e.kind==="atlas"||e.plan.texture)return!1;let o=e.element,i=e.plan.normal,r=Fi(n.color??"#cccccc"),s=!1;return s=ge(o,"--pnx",i[0].toFixed(4))||s,s=ge(o,"--pny",i[1].toFixed(4))||s,s=ge(o,"--pnz",i[2].toFixed(4))||s,s=ge(o,"--psr",(r.r/255).toFixed(4))||s,s=ge(o,"--psg",(r.g/255).toFixed(4))||s,s=ge(o,"--psb",(r.b/255).toFixed(4))||s,s=ge(o,"--plam",hc)||s,s=ge(o,"--polycss-preview-r",yc)||s,s=ge(o,"--polycss-preview-g",bc)||s,s=ge(o,"--polycss-preview-b",xc)||s,s=ge(o,"--polycss-paint",Pc(t))||s,o.style.getPropertyValue("color")&&(o.style.removeProperty("color"),s=!0),s}function vc(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 Vn=class{constructor(){this.groundSvg=null;this.groundVisible=!1;this.currentGroundCssZ=null;this.shadowRoot=null}};function Ni(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 i=t.firstChild;i?t.insertBefore(o,i):t.appendChild(o)}return o}function ji(e){e.groundSvg?.parentNode&&e.groundSvg.parentNode.removeChild(e.groundSvg),e.groundSvg=null,e.groundVisible=!1}function $i(e){e.groundSvg&&e.groundVisible&&(e.groundSvg.style.display="none",e.groundVisible=!1)}function Wi(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 Vn,receiverShadowCache:new Map,receiverShadowCacheKey:new Map,casterItemsCache:new Map,casterItemsCacheKey:new Map,shadowDragActive:!1}}import{buildParametricCasterOverride as Sc,buildSharedEdgeMap as Cc,computeMergedReceiverShadows as Tc,meshScaleVec3 as Qi,prepareCasterEdgeOwners as Ec,prepareCasterPolyItems as Ac,prepareReceiverFacePlanes as wc}from"@layoutit/polycss-core";function Ui(e){for(let n of e)n.svg&&n.svg.parentNode&&n.svg.parentNode.removeChild(n.svg),n.svg=null}function Gi(e,n){if(n){let t=e.receiverShadowCache.get(n);t&&Ui(t),e.receiverShadowCache.delete(n),e.receiverShadowCacheKey.delete(n)}else{for(let t of e.receiverShadowCache.values())Ui(t);e.receiverShadowCache.clear(),e.receiverShadowCacheKey.clear()}}function Yi(e,n){n?(e.casterItemsCache.delete(n),e.casterItemsCacheKey.delete(n)):(e.casterItemsCache.clear(),e.casterItemsCacheKey.clear())}function Xi(e){ji(e.shadowSvgState),Zi(e)}function qi(e){return e.handle.id??e.autoMeshId}var os="http://www.w3.org/2000/svg",Nn=new WeakMap,Ki=new WeakMap,Ji=new WeakMap,es=new WeakMap,ts=new WeakMap;function Mc(e){let n=Nn.get(e);return n||(n=new Map,Nn.set(e,n)),n}function Lc(e,n){let t=Mc(e),o=t.get(n);return o||(o=new Map,t.set(n,o)),o}function rs(e){let n=Nn.get(e);if(n){for(let t of n.values()){for(let o of t.values())o.svg&&o.svg.parentNode&&o.svg.parentNode.removeChild(o.svg);t.clear()}n.clear()}}function xr(e){rs(e),Nn.delete(e)}function Zi(e){for(let n of e.meshes)xr(n)}function is(e,n,t,o,i,r,s,c,l,d,p){let y=e.options.current,{receiverShadowCache:g,receiverShadowCacheKey:b,casterItemsCache:x,casterItemsCacheKey:v}=e,h=o.handle.transform.position??[0,0,0],C=o.handle.transform.rotation??[0,0,0],R=o.polygons.some(u=>u.texture!==void 0),I=Qi(o.handle.transform.scale),z=o.bboxCenterCss,D=y.shadow?.lift??.001,X=`${o.polygons.length}|${i.size}|${h.join(",")}|${C.join(",")}|${I.join(",")}|${z?z.join(","):"n"}|${D}`,q=g.get(o);(q===void 0||b.get(o)!==X)&&(q=wc(o.polygons,h,o.handle.transform.scale,i,D,C),g.set(o,q),b.set(o,X),rs(o));let M=[];for(let u of n){let m=u.handle.transform.position??[0,0,0],A=u.handle.transform.rotation??[0,0,0],k=Qi(u.handle.transform.scale),N=u.bboxCenterCss,Y=`${u.polygons.length}|${m.join(",")}|${A.join(",")}|${k.join(",")}|${N?N.join(","):"n"}`,w=x.get(u);(w===void 0||v.get(u)!==Y)&&(w=Ac(u.polygons,m,u.handle.transform.scale,()=>!0,A),x.set(u,w),v.set(u,Y));let K;if(u===o){let Q=Ki.get(u);(Q===void 0||Ji.get(u)!==u.polygons)&&(Q=Cc(u.polygons),Ki.set(u,Q),Ji.set(u,u.polygons)),K=Q}let J;if(u!==o&&(u.polygons.length>=40||p.points.length>0)){let Q=es.get(u);(Q===void 0||ts.get(u)!==Y)&&(Q=Ec(u.polygons,m,u.handle.transform.scale,A),es.set(u,Q),ts.set(u,Y)),J=Q}let ee,he;if(y.shadow?.parametric){let Q=u.shadowDefinition??y.shadow.definition??16,fe=e.shadowDragActive?Math.min(Q,y.shadow.dragDefinition??Q):Q,be=Sc({polysWorldVerts:w.map(Pe=>Pe.wv),lightDir:r,definition:fe,isSelf:u===o,style:y.shadow.style,pointLights:p.points.map(Pe=>({position:Pe.lightPos,index:Pe.index}))});ee=be.overrideSilhouette,he=be.overridePointSilhouettes}M.push({id:u,items:w,selfShadowEdgeMap:K,edgeOwners:J,casterPolygonCount:u.polygons.length,overrideSilhouette:ee,overridePointSilhouettes:he})}let V={rotX:e.camera.state.rotX,rotY:e.camera.state.rotY,meshRotation:o.handle.transform.rotation},B=Tc({receiverPlanes:q,receiverPolygons:o.polygons,receiverHasTexture:R,casters:M,lightDir:r,runDirectional:p.runDirectional,pointPasses:p.points,allPointLights:p.allPointLights,cameraRot:V,ambientLight:y.ambientLight,directionalLight:y.directionalLight,shadow:{color:y.shadow?.color,opacity:d,maxExtend:y.shadow?.maxExtend}}),F=Lc(o,"m"),re=new Set,P=!!y.debugShadowAttrs,L=Ni(e.shadowSvgState,e.doc,e.sceneEl);for(let u of B){re.add(u.faceIndex);let m=F.get(u.faceIndex);m||(m={svg:null,visible:!1,width:-1,height:-1,matrixCss:""},F.set(u.faceIndex,m));let A=m.svg;A||(A=e.doc.createElementNS(os,"svg"),A.setAttribute("class","polycss-shadow polycss-shadow-svg polycss-shadow-receiver"),L.appendChild(A),m.svg=A),m.visible||(A.style.display="block"),m.visible=!0,(m.width!==u.width||m.height!==u.height)&&(A.setAttribute("width",String(u.width)),A.setAttribute("height",String(u.height)),A.setAttribute("viewBox",`0 0 ${u.width} ${u.height}`),m.width=u.width,m.height=u.height);let k=`position:absolute;top:0;left:0;display:block;overflow:hidden;transform-origin:0 0;pointer-events:none;will-change:transform;opacity:${u.svgOpacity.toFixed(4)};transform:${u.matrixCss}`;for(m.matrixCss!==k&&(A.setAttribute("style",k),m.matrixCss=k),P&&(A.setAttribute("data-poly-shadow-type","receiver"),A.setAttribute("data-poly-shadow-receiver",qi(o)),A.setAttribute("data-poly-shadow-receiver-face",String(u.faceIndex)),A.setAttribute("data-poly-shadow-receiver-polys",JSON.stringify(u.memberPolyIndices)),A.setAttribute("data-poly-shadow-layers",String(u.layers.length)));A.firstChild;)A.removeChild(A.firstChild);u.baseFill&&u.baseD&&A.appendChild(ns(e.doc,u.baseD,u.baseFill,!1,1));for(let N of u.layers)A.appendChild(ns(e.doc,N.d,N.fill,N.multiply,N.opacity))}for(let[u,m]of F)re.has(u)||m.svg&&m.visible&&(m.svg.style.display="none",m.visible=!1)}function ns(e,n,t,o,i){let r=e.createElementNS(os,"path");return r.setAttribute("d",n),r.setAttribute("fill",t),r.setAttribute("fill-rule","nonzero"),i!==1&&r.setAttribute("opacity",i.toFixed(4)),o&&(r.style.mixBlendMode="multiply"),r}var ss=Symbol.for("polycss.animation.triangleFrameTarget");var Nc=750;var $n=Promise.resolve();function cs(e){return!Object.prototype.hasOwnProperty.call(e,"seamBleed")||e.seamBleed!==void 0?e:{...e,seamBleed:ds}}var jc={key:"non-cullable",normal:[1,1,0]};function us(){return[jc]}function Ut(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&&Fn(e.ownerDocument),e.ownerDocument?.defaultView&&e.ownerDocument.defaultView.getComputedStyle(e).position==="static"&&(e.style.position="relative");let{camera:o,...i}=n,r=cs({seamBleed:ds,...i}),s=Li(e),c=[0,0,0],l=e.ownerDocument??document,d=l.createElement("div");d.className="polycss-camera",F(d,r),e.appendChild(d);let p=l.createElement("div");p.className="polycss-scene",p.setAttribute("aria-hidden","true"),re(p,r),d.appendChild(p);let y=Wi({host:e,doc:l,cameraEl:d,sceneEl:p,camera:t,layoutScale:s,options:r}),g=y.meshes,b=new WeakMap,x=y.shadowSvgState,v=()=>$i(x),h=()=>Xi(y),C=null,R=null,I=140,z=0,D=80;function X(a){if(!r.shadow?.followAnimation||!a.castShadow&&!a.receiveShadow)return;let f=typeof performance<"u"?performance.now():Date.now();f-z<D||(z=f,M(),_e())}function q(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,E=Math.round(a[1]/f*100)/100,j=Math.round(a[2]/f*100)/100;return`${S}|${E}|${j}`}function M(){C=null}let V=a=>Gi(y,a),B=a=>Yi(y,a);function F(a,f){let S=Ic(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 re(a,f){Ri(a,s),a.style.transform=hr(t,c,s),zi(a,f)}function P(a){a.style.transform=hr(t,c,s)}function L(a){a.textureReadyPromise=$n,a.voxelRenderer?.dispose(),a.voxelRenderer=void 0,k(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 u(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 m(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,h()}function k(a,f){f?.();for(let S of a){try{S.dispose()}catch{}S.element.parentNode&&S.element.parentNode.removeChild(S.element)}}function N(a,f,S,E){a.rendered=f,a.renderedByPolygonIndex=[];for(let j of f)a.renderedByPolygonIndex[j.polygonIndex]=j;a.disposeAtlas=S,a.textureReadyPromise=E?E.catch(()=>{}):$n,a.solidLightingPreviewPrepared=!1}function Y(a,f){let S=a.renderedByPolygonIndex[f];return S?.polygonIndex===f?S:void 0}function w(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 K(a,f){let S=a.polygons[f.polygonIndex];return a.stableDom&&S?ls(S):f.plan?.normal??(S?ls(S):null)}function J(a){if(!be(a))return a.rendered;let f=ee(a);return a.rendered.filter(S=>he(a,S,Pr,f))}function ee(a){return{rotX:t.state.rotX,rotY:t.state.rotY,meshRotation:a.handle.transform.rotation}}function he(a,f,S=Pr,E=ee(a)){let j=K(a,f);return j===null||zc(j,E,S)}function Q(a){if(a.excludeFromAutoCenter){a.cameraCullGroups=[];return}let f=new Map;for(let S of a.rendered){let E=K(a,S);if(!E)continue;if(!Hc(E)){a.cameraCullGroups=us();return}let j=kc(E);if(!f.has(j)&&(f.set(j,E),f.size>Rc)){a.cameraCullGroups=us();return}}a.cameraCullGroups=Array.from(f,([S,E])=>({key:S,normal:E}))}function fe(a){return be(a)?_c(a.cameraCullGroups,ee(a)):"all"}function be(a){return!a.excludeFromAutoCenter&&Fc(a.cameraCullGroups)}function Pe(a){a.cameraCullSignature=be(a)?fe(a):"all"}function Xe(a,f){let S=new Array(a.rendered.length),E=!1,j=ee(a);for(let Z=0;Z<a.rendered.length;Z+=1){let ie=a.rendered[Z],xe=he(a,ie,f,j);S[Z]=xe}let H=null,_=null,$=()=>{if(!(!H||!_)){if(H===_)H.remove();else{let Z=l.createRange();Z.setStartBefore(H),Z.setEndAfter(_),Z.deleteContents(),Z.detach()}H=null,_=null,E=!0}};for(let Z=0;Z<a.rendered.length;Z+=1){let ie=a.rendered[Z];!S[Z]&&ie.element.parentNode===a.wrapper?(_&&_.nextSibling===ie.element||($(),H=ie.element),_=ie.element):$()}$();let G=Z=>{for(let ie=Z;ie<a.rendered.length;ie+=1){let xe=a.rendered[ie].element;if(xe.parentNode===a.wrapper)return xe}return u(a)},de=-1,ae=Z=>{if(de<0)return;let ie=l.createDocumentFragment();for(let xe=de;xe<Z;xe+=1){let Se=a.rendered[xe];dt(a,Se),ie.appendChild(Se.element)}m(a,ie,G(Z)),de=-1,E=!0};for(let Z=0;Z<a.rendered.length;Z+=1){let ie=a.rendered[Z];S[Z]&&ie.element.parentNode!==a.wrapper?de<0&&(de=Z):ae(Z)}return ae(a.rendered.length),E}function Le(a,f=!1){if(a.voxelRenderer){f?a.voxelRenderer.render(ee(a)):a.voxelRenderer.syncCamera(ee(a)),a.cameraCullSignature="voxel-direct";return}if(!be(a)){let j=a.cameraCullSignature!=="all";a.cameraCullSignature="all",j&&En(a);return}if(a.hasBuckets){tt(a,f);return}let S=fe(a);if(!f&&S===a.cameraCullSignature)return;let E=Xe(a,Pr);a.cameraCullSignature=S,E&&ke(a)}function tt(a,f=!1){let S=be(a)?fe(a):"all";!f&&S===a.cameraCullSignature||En(a)}function en(a,f){return K(a,f)}function dt(a,f){if(r.textureLighting!=="dynamic")return;let S=en(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 nt(a){w(a),a.hasBuckets=!1;let f=a.skipBucketNormalCleanupOnce;a.skipBucketNormalCleanupOnce=!1;let S=l.createDocumentFragment(),E=r.textureLighting==="dynamic"&&!a.stableDom,j=new Map,H=[];for(let _ of J(a)){let $=a.polygons[_.polygonIndex],G=E&&$?ki($):null;if(!G){H.push(_);continue}let de=G.key+"|"+($.color??""),ae=j.get(de);ae||(ae={vec:G.vec,items:[]},j.set(de,ae)),ae.items.push(_)}for(let _ of H)dt(a,_),S.appendChild(_.element);for(let _ of j.values()){if(_.items.length<2){for(let G of _.items)dt(a,G),S.appendChild(G.element);continue}let $=l.createElement("div");$.className="polycss-bucket",a.hasBuckets=!0,$.style.setProperty("--pnx",String(_.vec[0])),$.style.setProperty("--pny",String(_.vec[1])),$.style.setProperty("--pnz",String(_.vec[2]));for(let G of _.items)$.appendChild(G.element),(!f||G.kind==="triangle")&&(G.element.style.removeProperty("--pnx"),G.element.style.removeProperty("--pny"),G.element.style.removeProperty("--pnz"));S.appendChild($)}m(a,S,u(a)),Pe(a)}function Ro(){return new Promise(a=>setTimeout(a,0))}async function ko(a,f){if(r.textureLighting==="dynamic"&&!a.stableDom)return nt(a),!f();w(a);let E=l.createDocumentFragment(),j=u(a),H=0;for(let _ of J(a)){if(f())return!1;dt(a,_),E.appendChild(_.element),H++,H%Nc===0&&(m(a,E,j),E=l.createDocumentFragment(),await Ro())}return E.childNodes.length>0&&m(a,E,j),Pe(a),!f()}function tn(a,f){let S=r.textureLighting==="dynamic",E=r.directionalLight?.direction,j=f&&(f[0]!==0||f[1]!==0||f[2]!==0);if(!S||!j||!E){if(a.lightOverrideSignature==="clear")return;a.wrapper.style.removeProperty("--plx"),a.wrapper.style.removeProperty("--ply"),a.wrapper.style.removeProperty("--plz"),a.lightOverrideSignature="clear";return}let H=jn(E,f),_=bn(H),$=Math.hypot(_[0],_[1],_[2])||1,G=(_[0]/$).toFixed(2),de=(_[1]/$).toFixed(2),ae=(_[2]/$).toFixed(2),Z=`${G}|${de}|${ae}`;a.lightOverrideSignature!==Z&&(a.wrapper.style.setProperty("--plx",G),a.wrapper.style.setProperty("--ply",de),a.wrapper.style.setProperty("--plz",ae),a.lightOverrideSignature=Z)}function Tn(a){let f=!1;for(let S of a.rendered){if(!S.plan||S.kind==="atlas"||S.plan.texture)continue;let E=a.polygons[S.polygonIndex];E&&(f=br(S,E,r)||f)}return a.solidLightingPreviewPrepared=!1,a.solidLightingPreviewActive=!1,f}function W(a){if((r.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 E=a.polygons[S.polygonIndex];E&&(Vi(S,E,S.plan.shadedColor),f=!0)}return a.solidLightingPreviewPrepared=f,f}function ce(a){return(r.textureLighting??"baked")!=="baked"||!a.solidLightingPreviewPrepared&&!W(a)?!1:(a.solidLightingPreviewActive=!0,!0)}function ue(a){return a.kind==="atlas"||!!a.plan?.texture}function Re(){if((r.textureLighting??"baked")!=="baked")return!1;let a=!1;for(let f of g)a=Tn(f)||a,f.rendered.some(ue)&&(Oo(f),a=!0);p.style.removeProperty(Wt);for(let f of g)Mt(f.wrapper),f.solidLightingPreviewActive=!1;return Mt(p),a}function nn(){p.style.removeProperty(Wt);for(let a of g)a.solidLightingPreviewActive&&(Tn(a),Mt(a.wrapper));(r.textureLighting??"baked")!=="dynamic"&&(Mt(p),M(),_e())}function on(a,f){let S=a.handle.transform.rotation,E=f.directionalLight?.direction??r.directionalLight?.direction;if(!(S&&(S[0]!==0||S[1]!==0||S[2]!==0))||!E){Mt(a.wrapper);return}let H=jn(E,S);Bn(a.wrapper,{...r,...f,directionalLight:{...r.directionalLight,...f.directionalLight,direction:H}})}function St(a){if((r.textureLighting??"baked")!=="baked")return!1;Bn(p,{...r,...a}),!a.skipShadows&&a.directionalLight?.direction&&_e(a.directionalLight.direction,{progressive:!0});let f=!1;for(let S of g)on(S,a),f=ce(S)||f;return f?ge(p,Wt,"1"):p.style.removeProperty(Wt),f}function Ae(a,f,S){let E=a.polygons[f];if(!E)return!1;let j=Y(a,f);if(!j)return!1;let H=r.textureLighting??"baked";return H==="dynamic"?(Bi(j.element,S),!0):H==="baked"?br(j,E,r):!1}function Ne(a,f){let S=a.polygons[f];if(!S)return!1;let E=Y(a,f);return E?(Ce(E.element,S,f),!0):!1}function qe(a,f,S){return!(S.length===0||!S.every(E=>E==="color"||E==="data")||S.includes("color")&&!Ae(a,f,a.polygons[f]?.color)||S.includes("data")&&!Ne(a,f))}function ke(a){M(),_e()}function _e(a,f){let S=r.shadow,E=!!f?.progressive&&!!S?.parametric&&S?.dragDefinition!=null&&S.dragDefinition<(S.definition??16);y.shadowDragActive=E,E&&(R&&clearTimeout(R),R=setTimeout(()=>{R=null,y.shadowDragActive=!1,M(),_e()},I));let j=[];for(let te of g)!te.disposed&&te.castShadow&&j.push(te);if(j.length===0){h(),C=null;return}let H=r.shadow?.color??"#000000",_=r.shadow?.opacity??.25,$=Vc(H)?.rgb??[0,0,0],G=$[0],de=$[1],ae=$[2],Z=a??r.directionalLight?.direction??[.4,-.7,.59],ie=bn(Z),xe=r.textureLighting==="dynamic"?[]:r.pointLights??[],Se=xe.map(te=>({position:Mi(te.position),color:te.color,intensity:te.intensity})),je=xe.map((te,O)=>te.castShadow?O:-1).filter(te=>te>=0),T=je.map(te=>Se[te].position),ot=r.directionalLight,pt=!!ot?.direction&&(ot.intensity??1)>0,rt=q(ie),Ze=T.map(te=>`${Math.round(te[0])},${Math.round(te[1])},${Math.round(te[2])}`).join(";"),$e=rt===null&&Ze===""?null:`${rt??""}|${Ze}`;if($e!==null&&$e===C)return;let mt=new Map;for(let te of j)mt.set(te,as(te.polygons,{normalTolerance:.1,distanceTolerance:.5,overlapFraction:.95,preserveDoubleSidedBackfaces:!1}));let at=new Map;for(let te of g)te.disposed||!te.receiveShadow||at.set(te,new Set);v();for(let te of g){if(te.disposed||!te.receiveShadow)continue;let O=at.get(te)??new Set;is(y,j,mt,te,O,ie,G,de,ae,_,{runDirectional:pt,points:T.map((U,se)=>({lightPos:U,index:je[se]})),allPointLights:Se})}C=$e}function En(a){if(a.voxelRenderer){a.voxelRenderer.render(ee(a)),a.cameraCullSignature="voxel-direct";return}A(a),nt(a),ke(a)}function _o(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 E=f[0]/S,j=f[1]/S,H=f[2]/S,_=Z=>Math.round(Z*1e3)/1e3,$=`${_(E)},${_(j)},${_(H)}`,G=a.lightOcclusionCache;if(G&&G.polygons===a.polygons&&G.lightDirKey===$)return G.occluded;let de=G&&G.polygons===a.polygons?G.dedupDropped:as(a.polygons,{normalTolerance:.1,distanceTolerance:.12,overlapFraction:.98,preserveDoubleSidedBackfaces:!1}),ae=Dc(a.polygons,[E,j,H],de);return a.lightOcclusionCache={polygons:a.polygons,lightDirKey:$,occluded:ae,dedupDropped:de},ae}function An(a){return!!a.voxelSource&&r.textureLighting!=="dynamic"&&!a.stableDom&&!a.castShadow}function _t(a){let f=r.pointLights;if(!f||f.length===0)return;let S=a.handle.transform.position??[0,0,0],E=a.handle.transform.rotation??[0,0,0],j=E[0]!==0||E[1]!==0||E[2]!==0;return f.map(H=>{let _=[H.position[0]-S[0],H.position[1]-S[1],H.position[2]-S[2]],$=j?jn(_,E):_;return{...H,position:$}})}function Ie(a,f){L(a);let S=r.directionalLight,E=f?{...S,direction:f}:S,j=xt(E),H=void 0;if(An(a)){let G=Ai({doc:l,wrapper:a.wrapper,polygons:a.parseResult.polygons,directionalLight:j,ambientLight:r.ambientLight});if(G){a.voxelRenderer=G,G.render(ee(a)),a.cameraCullSignature="voxel-direct",a.textureReadyPromise=$n;return}}let _={doc:l,directionalLight:j,pointLights:_t(a),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:H},$=a.stableDom?(()=>{let G=yt(a.polygons,_);return Lt(a.wrapper,G),wt(a.polygons,{..._,solidPaintDefaults:G})??bt(a.polygons,{..._,solidPaintDefaults:G})})():bt(a.polygons,{..._,computeSolidPaintDefaults:!0,skipDynamicNormalVars:r.textureLighting==="dynamic"});a.stableDom||Lt(a.wrapper,$.solidPaintDefaults??{}),N(a,$.rendered,$.dispose,$.pagesReady),a.skipBucketNormalCleanupOnce=r.textureLighting==="dynamic"&&!a.stableDom,Q(a),nt(a),ke(a)}function Oo(a,f){if(a.rendered.length===0||a.voxelRenderer||a.stableDom||An(a)){Ie(a,f);return}if(a.rendered[0]?.element.parentNode===null){Ie(a,f);return}let S=r.directionalLight,E=f?{...S,direction:f}:S,j=xt(E),H={doc:l,directionalLight:j,pointLights:_t(a),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"},_=bt(a.polygons,H),$=()=>{a.rebakeInFlight=!1;let ae=a.rebakeQueuedLightDir;ae!==null&&(a.rebakeQueuedLightDir=null,Oo(a,ae))},G=()=>{if(a.disposed){_.dispose(),$();return}if(_.rendered.length!==a.rendered.length){_.dispose(),Ie(a,f),$();return}for(let ie of _.rendered){let xe=a.renderedByPolygonIndex[ie.polygonIndex];if(!xe)continue;let Se=ie.element.getAttribute("style");Se!==null&&xe.element.setAttribute("style",Se)}let ae=_.solidPaintDefaults;ae&&Lt(a.wrapper,ae);let Z=a.disposeAtlas;a.disposeAtlas=_.dispose,Z&&(typeof requestAnimationFrame=="function"?xe=>{requestAnimationFrame(xe)}:xe=>{setTimeout(xe,0)})(Z),ke(a),$()},de=_.pagesReady;de&&typeof de.then=="function"?(a.textureReadyPromise=de.catch(()=>{}),de.then(()=>ta(_.rendered)).then(na).then(G,()=>{_.dispose(),a.disposed||Ie(a,f),$()})):G()}function ea(a,f){if(a.rebakeInFlight){a.rebakeQueuedLightDir=f;return}a.rebakeInFlight=!0,Oo(a,f)}function ta(a){let f=new Set;for(let S of a){let E=S.element.getAttribute("style")??"",j=/url\((blob:[^)]+)\)/g,H;for(;(H=j.exec(E))!==null;)f.add(H[1])}return Array.from(f)}function na(a){return a.length===0||typeof Image>"u"?Promise.resolve():Promise.all(a.map(f=>{let S=new Image;S.src=f;let E=S.decode?.();return E?E.catch(()=>{}):Promise.resolve()})).then(()=>{})}function Ct(){let a=1/0,f=!1;for(let H of g)if(!H.disposed&&H.receiveShadow){f=!0;break}for(let H of g){if(H.disposed||!(f?H.receiveShadow:H.castShadow))continue;let $=H.handle.transform.position?.[2]??0;for(let G of H.polygons)for(let de of G.vertices){let ae=de[2]+$;ae<a&&(a=ae)}}if(!Number.isFinite(a)){let H=x.currentGroundCssZ!==null;x.currentGroundCssZ=null,H&&(h(),M());return}let S=r.shadow?.lift??.05,E=(a+S)*yn,j=x.currentGroundCssZ;x.currentGroundCssZ=E,j!==E&&(M(),_e())}async function oa(a,f){L(a);let S=xt(r.directionalLight),E={doc:l,directionalLight:S,pointLights:_t(a),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},j=a.stableDom?wt(a.polygons,E):null;if(j){let $=yt(a.polygons,E);return Lt(a.wrapper,$),N(a,j.rendered,j.dispose,j.pagesReady),Q(a),nt(a),ke(a),!f()}let H=await Nt(a.polygons,{...E,skipDynamicNormalVars:r.textureLighting==="dynamic"},f);if(f())return H.dispose(),!1;Lt(a.wrapper,H.solidPaintDefaults),N(a,H.rendered,H.dispose,H.pagesReady),a.skipBucketNormalCleanupOnce=r.textureLighting==="dynamic"&&!a.stableDom,Q(a);let _=await ko(a,f);return _&&ke(a),_}function Tt(){let a=c,f=[0,0,0];if(r.autoCenter){let S=[];for(let E of g)!E.disposed&&!E.excludeFromAutoCenter&&S.push(...E.polygons);if(S.length>0){let E=Oc(S);f=[(E.min[0]+E.max[0])/2,(E.min[1]+E.max[1])/2,(E.min[2]+E.max[2])/2]}}a[0]===f[0]&&a[1]===f[1]&&a[2]===f[2]||(c=f,y.autoCenter.offset=f,re(p,r))}function ra(a,f={}){let E=(p.ownerDocument??document).createElement("div");E.className="polycss-mesh",f.id&&E.setAttribute("data-poly-mesh-id",f.id);let j=`polycss-mesh-${y.meshAutoCounter.next++}`;E.setAttribute("data-poly-mesh-index",j);let H={...f},_=f.merge!==!1,$=!!f.stableDom,G=0,de=zn(H);de&&(E.style.transform=de);let ae=(O,U)=>a.voxelSource?O:U?Bc(O,{meshResolution:f.meshResolution}):($||f.excludeFromAutoCenter,O),Z=ae(a.polygons,_),ie=null;function xe(){let O=zn(H);E.style.transform=O??""}function Se(O){if(O.length===0){ie=null,je&&(je.bboxCenterCss=null),xe();return}let U=1/0,se=1/0,pe=1/0,we=-1/0,ne=-1/0,ye=-1/0;for(let Ke of O)for(let Ue of Ke.vertices)Ue[0]<U&&(U=Ue[0]),Ue[0]>we&&(we=Ue[0]),Ue[1]<se&&(se=Ue[1]),Ue[1]>ne&&(ne=Ue[1]),Ue[2]<pe&&(pe=Ue[2]),Ue[2]>ye&&(ye=Ue[2]);if(!Number.isFinite(U)){ie=null,je&&(je.bboxCenterCss=null),xe();return}let We=(se+ne)/2*yn,Qe=(U+we)/2*yn,He=(pe+ye)/2*yn;ie=[We,Qe,He],je&&(je.bboxCenterCss=ie),xe()}let je=null;Se(Z),p.appendChild(E);let T={handle:void 0,wrapper:E,parseResult:a,rendered:[],renderedByPolygonIndex:[],shadowRendered:[],polygons:Z,voxelSource:a.voxelSource,disposed:!1,stableDom:$,hasBuckets:!1,skipBucketNormalCleanupOnce:!1,excludeFromAutoCenter:!!f.excludeFromAutoCenter,castShadow:!!f.castShadow,bboxCenterCss:ie,receiveShadow:!!f.receiveShadow,shadowDefinition:f.shadowDefinition,cameraCullGroups:[],cameraCullSignature:"",lightOverrideSignature:"clear",stableTriangleColorFrame:0,solidLightingPreviewPrepared:!1,solidLightingPreviewActive:!1,bakedRotation:f.rotation?[...f.rotation]:[0,0,0],autoMeshId:j,rebakeInFlight:!1,rebakeQueuedLightDir:null,textureReadyPromise:$n},ot=null,pt=0,rt=-1,Ze=null;function $e(){ot=null,Ze=null,rt=-1}function mt(){let O=ot;if(!O||O.polygonCount!==T.polygons.length)return T.polygons;if(Ze&&rt===pt)return Ze;let U=O.vertices,se=new Array(O.polygonCount);for(let pe=0;pe<O.polygonCount;pe++){let we=T.polygons[pe],ne=pe*9;se[pe]={...we,color:O.colors?.[pe]??we.color,vertices:[[U[ne],U[ne+1],U[ne+2]],[U[ne+3],U[ne+4],U[ne+5]],[U[ne+6],U[ne+7],U[ne+8]]]}}return Ze=se,rt=pt,se}function at(O,U){let se=O?.stableTriangleUpdateMode==="color-only";T.stableTriangleColorFrame++;let pe=T.stableDom&&!U;if(pe||Se(T.polygons),T.stableDom&&!T.hasBuckets){let we={doc:l,directionalLight:xt(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},ne=T.rendered.length===T.polygons.length&&T.rendered.every(He=>He.kind==="triangle"),ye=T.stableDom&&!U,We=ne||ye?{}:yt(T.polygons,we);ne||Lt(T.wrapper,We);let Qe={...we,solidPaintDefaults:We,optimizeStableTriangleStyle:!0,stableTriangleDebug:O?.stableTriangleDebug,stableTriangleUpdateMode:O?.stableTriangleUpdateMode,stableTriangleColorPolicy:O?.stableTriangleColorPolicy,stableTriangleColorSteps:O?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:O?.stableTriangleColorFreezeFrames,stableTriangleColorBudget:O?.stableTriangleColorBudget,stableTriangleColorMaxAge:O?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:O?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:O?.stableTriangleMatrixDecimals,stableTriangleColorFrame:T.stableTriangleColorFrame};if($t(T.rendered,T.polygons,Qe))return se||(Q(T),Le(T,!0),U&&Tt()),!0}return pe&&Se(T.polygons),!1}let te={get polygons(){return mt()},set polygons(O){$e(),T.polygons=O},element:E,id:f.id,get transform(){return H},remove(){G++,E.parentNode&&E.parentNode.removeChild(E),L(T),g.delete(T),b.delete(E),V(T),B(T),Tt(),Ct()},setPolygons(O,U){G++,_=U?.merge??_,$=U?.stableDom??$,T.stableDom=$,T.voxelSource=void 0,T.polygons=ae(O,_),B(T),V(T),$e(),te.polygons=T.polygons;let se=U?.recomputeAutoCenter??!0;X(T),!at(U,se)&&(Ie(T),se&&Tt())},[ss](O,U){let se=U?.merge??_,pe=U?.stableDom??$;if(!O.solidTriangles||!pe||se||f.meshResolution!==void 0||T.hasBuckets||O.polygonCount!==T.polygons.length||O.vertices.length<O.polygonCount*9||T.rendered.length!==O.polygonCount)return!1;for(let ye=0;ye<T.rendered.length;ye++){let We=T.rendered[ye],Qe=T.polygons[ye];if(We?.kind!=="triangle"||We.polygonIndex!==ye||!Qe||Qe.vertices.length!==3||Qe.texture||Qe.material?.texture)return!1}let we=U?.recomputeAutoCenter??!0;if(!we){let ye=T.stableTriangleColorFrame+1,We={doc:l,directionalLight:xt(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:U?.stableTriangleDebug,stableTriangleUpdateMode:U?.stableTriangleUpdateMode,stableTriangleColorPolicy:U?.stableTriangleColorPolicy,stableTriangleColorSteps:U?.stableTriangleColorSteps,stableTriangleColorFreezeFrames:U?.stableTriangleColorFreezeFrames??0,stableTriangleColorBudget:U?.stableTriangleColorBudget,stableTriangleColorMaxAge:U?.stableTriangleColorMaxAge,stableTriangleColorMaxStep:U?.stableTriangleColorMaxStep,stableTriangleMatrixDecimals:U?.stableTriangleMatrixDecimals,stableTriangleColorFrame:ye};if(jt(T.rendered,T.polygons,O,We))return G++,_=se,$=pe,T.stableDom=$,T.voxelSource=void 0,T.stableTriangleColorFrame=ye,ot=O,pt++,Ze=null,rt=-1,be(T)?(Q(T),Le(T,!0)):Pe(T),!0}G++,_=se,$=pe,T.stableDom=$,T.voxelSource=void 0;let ne=O.vertices;for(let ye=0;ye<O.polygonCount;ye++){let We=T.polygons[ye],Qe=O.colors?.[ye];Qe&&(We.color=Qe);let He=We.vertices,Ke=ye*9;He[0][0]=ne[Ke],He[0][1]=ne[Ke+1],He[0][2]=ne[Ke+2],He[1][0]=ne[Ke+3],He[1][1]=ne[Ke+4],He[1][2]=ne[Ke+5],He[2][0]=ne[Ke+6],He[2][1]=ne[Ke+7],He[2][2]=ne[Ke+8]}return $e(),te.polygons=T.polygons,at(U,we)},updatePolygon(O,U){let se=typeof O=="number"?O:T.polygons.indexOf(O);if(se<0&&typeof O!="number"&&ot&&(se=mt().indexOf(O)),se<0||se>=T.polygons.length)return;$e(),T.voxelSource=void 0,Object.assign(T.polygons[se],U);let pe=Object.keys(U);qe(T,se,pe)||Ie(T)},async setPolygonsChunked(O,U){let se=++G;_=U?.merge??_,$=U?.stableDom??$,T.stableDom=$,T.voxelSource=void 0,T.polygons=ae(O,_),$e(),te.polygons=T.polygons,Se(T.polygons);let pe=U?.recomputeAutoCenter??!0;if(!await oa(T,()=>T.disposed||se!==G)){L(T);return}pe&&Tt()},setTransform(O){let U=T.castShadow,se=T.receiveShadow,pe=T.shadowDefinition;O.castShadow!==void 0&&(T.castShadow=!!O.castShadow),O.receiveShadow!==void 0&&(T.receiveShadow=!!O.receiveShadow),O.shadowDefinition!==void 0&&(T.shadowDefinition=O.shadowDefinition),H={...H,...O};let we=zn(H);E.style.transform=we??"",tn(T,H.rotation),O.rotation!==void 0&&Le(T,!0),T.castShadow!==U&&(T.voxelSource&&Ie(T),ke(T),Ct()),T.receiveShadow!==se&&(T.receiveShadow||xr(T),M(),_e()),(O.position!==void 0||O.scale!==void 0)&&(T.castShadow||T.receiveShadow)&&(Ct(),M(),_e()),T.shadowDefinition!==pe&&(T.castShadow||T.receiveShadow)&&(M(),_e())},dispose(){if(!T.disposed){T.disposed=!0,G++,E.parentNode&&E.parentNode.removeChild(E),L(T);try{a.dispose()}catch{}g.delete(T),b.delete(E),Tt(),Ct()}},rebakeAtlas(){T.bakedRotation=H.rotation?[...H.rotation]:[0,0,0];let O=r.directionalLight?.direction??[.4,-.7,.59],U=jn(O,T.bakedRotation);ea(T,U)},whenTexturesReady(){return T.textureReadyPromise},getPosition(){return H.position},getRotation(){return H.rotation},getScale(){return H.scale},getPolygons(){return te.polygons}};return T.handle=te,je=T,b.set(E,T),g.add(T),Ie(T),tn(T,H.rotation),Tt(),Ct(),T.receiveShadow&&(M(),_e()),te}function ia(a){let f=!!r.autoCenter,S=r.strategies,E=r.seamBleed,j=r.textureLeafSizing,H=r.textureImageRendering,_=r.textureBackend,$=r.textureProjection,G=r.textureLighting,de=r.directionalLight?.direction,ae=r.directionalLight?.intensity,Z=r.directionalLight?.color,ie=r.shadow,xe=r.pointLights,Se=cs(a);r={...r,...Se},y.options.current=r,re(p,r);let je=!!r.autoCenter;for(let ne of g)tn(ne,ne.handle.transform.rotation);let T=a.strategies!==void 0&&!_i(a.strategies,S),ot=Object.prototype.hasOwnProperty.call(a,"seamBleed")&&Se.seamBleed!==E,pt=Object.prototype.hasOwnProperty.call(a,"textureLeafSizing")&&Se.textureLeafSizing!==j,rt=Object.prototype.hasOwnProperty.call(a,"textureImageRendering")&&Se.textureImageRendering!==H,Ze=Object.prototype.hasOwnProperty.call(a,"textureBackend")&&Se.textureBackend!==_,$e=Object.prototype.hasOwnProperty.call(a,"textureProjection")&&Se.textureProjection!==$,mt=ne=>(ne??[]).map(ye=>`${ye.position.join(",")}|${ye.color??""}|${ye.intensity??1}|${ye.castShadow?1:0}`).join(";"),at=Object.prototype.hasOwnProperty.call(a,"pointLights")&&mt(r.pointLights)!==mt(xe);if(T||ot||pt||rt||Ze||$e||at)for(let ne of g)Ie(ne);f!==je&&Tt();let te=a.textureLighting!==void 0&&G!==r.textureLighting,O=r.directionalLight,U=a.directionalLight!==void 0&&(!Oi(de,O?.direction)||(ae??1)!==(O?.intensity??1)||(Z??"#ffffff")!==(O?.color??"#ffffff")),se=r.shadow,pe=a.shadow!==void 0&&!Di(ie,se),we=U||pe||at;if(te){if(!T&&!ot&&!pt&&!rt&&!Ze&&!$e)for(let ne of g)Ie(ne);Ct(),M(),_e()}else we&&((pe||U)&&M(),_e(void 0,{progressive:(U||at)&&!pe}));pe&&a.shadow?.lift!==ie?.lift&&Ct()}function sa(){return r}function aa(){F(d,r),P(p);for(let a of g)Le(a)}function la(){let a=[];for(let f of g)a.push(f.handle);return a}function ca(){return Promise.all(Array.from(g,a=>a.handle.whenTexturesReady())).then(()=>{})}function ua(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 da(){R&&(clearTimeout(R),R=null);let a=Array.from(g);for(let f of a)try{f.handle.dispose()}catch{}d.parentNode&&d.parentNode.removeChild(d)}return{add:ra,setOptions:ia,destroy:da,host:e,camera:t,cameraEl:d,sceneElement:p,applyCamera:aa,getOptions:sa,meshes:la,whenTexturesReady:ca,findMeshByElement:ua,previewBakedSolidLighting:St,commitBakedSolidLighting:Re,clearBakedSolidLightingPreview:nn}}import{buildPolyMeshTransform as gp,buildPolySceneTransform as hp,cssDistanceToWorld as yp,cssDistanceToWorld as bp,cssPositionToWorld as xp,cssPositionToWorld as Pp,worldDistanceToCss as vp,worldDistanceToCss as Sp,worldDirectionalLightToCss as Cp,worldDirectionToPolyCss as Tp,worldPositionToPolyCss as Ep}from"@layoutit/polycss-core";import{createIsometricCamera as ps}from"@layoutit/polycss-core";var $c=32e3;function Pt(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=ps(n),o=`${e.perspective??$c}px`;return{get state(){return t.state},update(i){t.update(i)},getStyle(i){return t.getStyle(i)},type:"perspective",perspectiveStyle:o}}function st(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=ps(n);return{get state(){return t.state},update(o){t.update(o)},getStyle(o){return t.getStyle(o)},type:"orthographic",perspectiveStyle:"none"}}var ms=st;import{BASE_TILE as Wc}from"@layoutit/polycss-core";var Wn={drag:!0,wheel:!0,dolly:!1,invert:!1,minZoom:.1,maxZoom:10,minDistance:0,maxDistance:1/0,animate:!1};function Gt(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 xn(e){return e===!0?-1:e===!1?1:e}function Yt(){let e=[],n=[],t=[];function o(s){return s==="change"?e:s==="start"?n:t}function i(s){if(e.length===0)return;let c={type:"change",camera:s()},l=e.slice();for(let d of l)try{d(c)}catch(p){console.error("[polycss] controls 'change' listener threw:",p)}}function r(s,c){let l=s==="start"?n:t;if(l.length===0)return;let d={type:s,camera:c()},p=l.slice();for(let y of p)try{y(d)}catch(g){console.error(`[polycss] controls '${s}' listener threw:`,g)}}return{changeListeners:e,startListeners:n,endListeners:t,listenerArray:o,emitChange:i,emitInteraction:r}}function Xt(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 Un(e,n,t,o,i,r){let s=!1,c=null;return{onWheel:p=>{let y=n();if(!y.wheel||t())return;p.preventDefault();let g=p.deltaMode===1?16:p.deltaMode===2?100:1,b=p.deltaY*g;p.ctrlKey?b*=10:b*=3;let x=e.camera.state;if(y.dolly){let v=x.distance??0,h=Math.max(y.minDistance,Math.min(y.maxDistance,v+b*.05));e.camera.update({distance:h})}else{let v=Math.exp(-b*513e-6),h=x.zoom??1,C=Math.max(y.minZoom,Math.min(y.maxZoom,h*v));e.camera.update({zoom:C})}e.applyCamera(),s||(s=!0,r("start",o)),i(o),c!==null&&clearTimeout(c),c=setTimeout(()=>{c=null,s=!1,r("end",o)},150)},teardown:()=>{c!==null&&(clearTimeout(c),c=null),s=!1}}}function Gn(e,n,t,o,i,r,s){let c=null,l=0,d=b=>{if(c===null||o())return;let x=t();if(!x.animate){c=null;return}if(i())l=b;else{let v=Math.min(50,l?b-l:16.67);l=b;let h=x.animate.speed*(v/16.67),C=n.camera.state;if(x.animate.axis==="x"){let R=(((C.rotX??65)+h)%360+360)%360;n.camera.update({rotX:R})}else{let R=(((C.rotY??45)+h)%360+360)%360;n.camera.update({rotY:R})}n.applyCamera(),s(r)}c=e.requestAnimationFrame(d)};return{start:()=>{c!==null||!t().animate||o()||(l=0,c=e.requestAnimationFrame(d))},stop:()=>{c!==null&&(e.cancelAnimationFrame(c),c=null)},isRunning:()=>c!==null}}function Yn(e,n={}){let t=Gt(Wn,n),o=e.host,i=o.ownerDocument?.defaultView??globalThis,r=null,s={x:0,y:0},c=!1,l=!1,d=Yt(),p=Xt(e),{changeListeners:y,startListeners:g,endListeners:b,listenerArray:x,emitChange:v,emitInteraction:h}=d,C=Gn(i,e,()=>t,()=>l,()=>c,p,v),R=u=>{if(!(!t.drag||l)&&r===null&&u.isPrimary!==!1){u.preventDefault(),r=u.pointerId,s={x:u.clientX,y:u.clientY},o.style.cursor="grabbing";try{u.target.setPointerCapture(u.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),h("start",p)}},I=u=>{if(r===null||u.pointerId!==r||!t.drag||l)return;u.preventDefault();let m=u.clientX-s.x,A=u.clientY-s.y;s={x:u.clientX,y:u.clientY};let k=xn(t.invert),N=m/4*k,Y=A/4*k,w=e.camera.state;if(u.shiftKey){let K=w.rotX??65,J=w.rotY??45,ee=Math.max(.01,w.zoom??1),he=Math.cos(K*Math.PI/180),Q=he>=0?Math.max(.1,he):Math.min(-.1,he),fe=Math.cos(J*Math.PI/180),be=Math.sin(J*Math.PI/180),Pe=ee*Wc,Xe=(m*be-A*fe/Q)/Pe,Le=-(m*fe+A*be/Q)/Pe,tt=w.target??[0,0,0];e.camera.update({target:[tt[0]+Xe,tt[1]+Le,tt[2]]})}else{let K=Math.max(0,Math.min(89,(w.rotX??65)-Y)),J=(((w.rotY??45)-N)%360+360)%360;e.camera.update({rotX:K,rotY:J})}e.applyCamera(),v(p)},z=u=>{if(r===u.pointerId){r=null,o.style.cursor=t.drag&&!l?"grab":"";try{u.target.releasePointerCapture(u.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),h("end",p)}},D=Un(e,()=>t,()=>l,p,v,h);function X(){o.addEventListener("pointerdown",R),o.addEventListener("pointermove",I),o.addEventListener("pointerup",z),o.addEventListener("pointercancel",z),o.addEventListener("wheel",D.onWheel,{passive:!1}),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function q(){o.removeEventListener("pointerdown",R),o.removeEventListener("pointermove",I),o.removeEventListener("pointerup",z),o.removeEventListener("pointercancel",z),o.removeEventListener("wheel",D.onWheel),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",D.teardown()}X(),C.start();function M(u){let m=!!t.animate;t=Gt(t,u),!l&&r===null&&(o.style.cursor=t.drag?"grab":"");let A=!!t.animate;m&&!A?C.stop():!m&&A&&C.start()}function V(){l&&(l=!1,X(),C.start())}function B(){l||(l=!0,q(),C.stop(),r=null,c=!1,D.teardown())}function F(){B(),y.length=0,g.length=0,b.length=0}function re(u,m){let A=x(u);A.includes(m)||A.push(m)}function P(u,m){let A=x(u),k=A.indexOf(m);k>=0&&A.splice(k,1)}function L(u,m){return x(u).includes(m)}return{update:M,resume:V,pause:B,destroy:F,addEventListener:re,removeEventListener:P,hasEventListener:L}}import{BASE_TILE as Uc}from"@layoutit/polycss-core";function Xn(e,n={}){let t=Gt(Wn,n),o=e.host,i=o.ownerDocument?.defaultView??globalThis,r=null,s={x:0,y:0},c=!1,l=!1,d=!1,p={x:0,y:0},y=Yt(),g=Xt(e),{changeListeners:b,startListeners:x,endListeners:v,listenerArray:h,emitChange:C,emitInteraction:R}=y,I=Gn(i,e,()=>t,()=>l,()=>c,g,C),z=w=>{if(!(!t.drag||l)&&r===null&&w.isPrimary!==!1){w.preventDefault(),r=w.pointerId,s={x:w.clientX,y:w.clientY},o.style.cursor="grabbing";try{w.target.setPointerCapture(w.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!0),R("start",g)}},D=w=>{if(r===null||w.pointerId!==r||!t.drag||l)return;w.preventDefault();let K=w.clientX-s.x,J=w.clientY-s.y;s={x:w.clientX,y:w.clientY};let ee=e.camera.state;if(w.shiftKey){let he=xn(t.invert),Q=K/4*he,fe=J/4*he,be=(ee.rotX??65)-fe,Pe=(((ee.rotY??45)-Q)%360+360)%360;e.camera.update({rotX:be,rotY:Pe})}else{let he=ee.rotX??65,Q=ee.rotY??45,fe=Math.max(.01,ee.zoom??1),be=Math.cos(he*Math.PI/180),Pe=be>=0?Math.max(.1,be):Math.min(-.1,be),Xe=Math.cos(Q*Math.PI/180),Le=Math.sin(Q*Math.PI/180),tt=fe*Uc,en=(K*Le-J*Xe/Pe)/tt,dt=-(K*Xe+J*Le/Pe)/tt,nt=ee.target??[0,0,0];e.camera.update({target:[nt[0]+en,nt[1]+dt,nt[2]]})}e.applyCamera(),C(g)},X=w=>{if(r===w.pointerId){r=null,o.style.cursor=t.drag&&!l?"grab":"";try{w.target.releasePointerCapture(w.pointerId)}catch{}t.animate&&t.animate.pauseOnInteraction&&(c=!1),R("end",g)}},q=w=>{w.preventDefault()},M=w=>{w.button===2&&(d=!0,p={x:w.clientX,y:w.clientY},t.animate&&t.animate.pauseOnInteraction&&(c=!0),R("start",g))},V=w=>{if(!d||!t.drag)return;let K=w.clientX-p.x,J=w.clientY-p.y;p={x:w.clientX,y:w.clientY};let ee=xn(t.invert),he=K/4*ee,Q=J/4*ee,fe=e.camera.state,be=(fe.rotX??65)-Q,Pe=(((fe.rotY??45)-he)%360+360)%360;e.camera.update({rotX:be,rotY:Pe}),e.applyCamera(),C(g)},B=w=>{w.button===2&&d&&(d=!1,R("end",g))},F=Un(e,()=>t,()=>l,g,C,R);function re(){o.addEventListener("pointerdown",z),o.addEventListener("pointermove",D),o.addEventListener("pointerup",X),o.addEventListener("pointercancel",X),o.addEventListener("wheel",F.onWheel,{passive:!1}),o.addEventListener("contextmenu",q),o.addEventListener("mousedown",M),o.addEventListener("mousemove",V),o.addEventListener("mouseup",B),o.style.cursor=t.drag?"grab":"",o.style.touchAction="none",o.style.userSelect="none"}function P(){o.removeEventListener("pointerdown",z),o.removeEventListener("pointermove",D),o.removeEventListener("pointerup",X),o.removeEventListener("pointercancel",X),o.removeEventListener("wheel",F.onWheel),o.removeEventListener("contextmenu",q),o.removeEventListener("mousedown",M),o.removeEventListener("mousemove",V),o.removeEventListener("mouseup",B),o.style.cursor="",o.style.touchAction="",o.style.userSelect="",F.teardown()}re(),I.start();function L(w){let K=!!t.animate;t=Gt(t,w),!l&&r===null&&(o.style.cursor=t.drag?"grab":"");let J=!!t.animate;K&&!J?I.stop():!K&&J&&I.start()}function u(){l&&(l=!1,re(),I.start())}function m(){l||(l=!0,P(),I.stop(),r=null,c=!1,d=!1,F.teardown())}function A(){m(),b.length=0,x.length=0,v.length=0}function k(w,K){let J=h(w);J.includes(K)||J.push(K)}function N(w,K){let J=h(w),ee=J.indexOf(K);ee>=0&&J.splice(ee,1)}function Y(w,K){return h(w).includes(K)}return{update:L,resume:u,pause:m,destroy:A,addEventListener:k,removeEventListener:N,hasEventListener:Y}}import{BASE_TILE as Gc}from"@layoutit/polycss-core";var Yc={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 fs(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"]),hs=new Set(["KeyS","ArrowDown"]),ys=new Set(["KeyA","ArrowLeft"]),bs=new Set(["KeyD","ArrowRight"]),xs=new Set(["Space"]),vr=new Set(["ControlLeft","ControlRight"]);function qn(e,n={}){let t=fs(Yc,n),o=e.host,i=e.cameraEl,r=o.ownerDocument??document,s=r.defaultView??globalThis,c=Yt(),l=Xt(e),{changeListeners:d,startListeners:p,endListeners:y,listenerArray:g,emitChange:b,emitInteraction:x}=c,v=new Set,h=!1,C=!1,R=0,I=0,z=!1,D=[0,0,t.groundZ+t.eyeHeight];function X(W,ce){let ue=W*Math.PI/180,Re=ce*Math.PI/180;return[-Math.sin(ue)*Math.cos(Re),-Math.sin(ue)*Math.sin(Re),-Math.cos(ue)]}function q(){let W=e.camera.perspectiveStyle,ce=W==="none"?0:parseFloat(W);return(Number.isFinite(ce)&&ce>0?ce:2e3)/Gc}function M(){let W=e.camera.state,ce=X(W.rotX??90,W.rotY??0),ue=q();return[D[0]+ce[0]*ue,D[1]+ce[1]*ue,D[2]+ce[2]*ue]}function V(){let W=M();e.camera.update({target:W}),e.applyCamera()}function B(){let W=e.camera.state.target??[0,0,0];D=[W[0],W[1],t.groundZ+t.eyeHeight],V()}let F=()=>{if(!(!t.enabled||!t.lookEnabled||C||h))try{o.requestPointerLock()}catch{}},re=()=>{let W=r.pointerLockElement===o;W!==h&&(h=W,h?(z=!0,x("start",l)):z&&(z=!1,x("end",l)))},P=W=>{if(!h||!t.enabled||!t.lookEnabled||C)return;let ce=W.movementX??0,ue=W.movementY??0;if(ce===0&&ue===0)return;let Re=e.camera.state,nn=t.lookSensitivity,on=t.invertY?-1:1,St=(((Re.rotY??0)-ce*nn)%360+360)%360,Ae=(Re.rotX??90)-ue*nn*on;Ae<t.minPitch?Ae=t.minPitch:Ae>t.maxPitch&&(Ae=t.maxPitch);let Ne=X(Ae,St),qe=q(),ke=[D[0]+Ne[0]*qe,D[1]+Ne[1]*qe,D[2]+Ne[2]*qe];e.camera.update({rotX:Ae,rotY:St,target:ke}),e.applyCamera(),b(l)},L=W=>gs.has(W)||hs.has(W)||ys.has(W)||bs.has(W)||xs.has(W)||vr.has(W),u=W=>{if(!(!t.enabled||C)&&L(W.code)&&!(!h&&!t.moveEnabled)){if(xs.has(W.code)){if(!t.jumpEnabled)return;W.preventDefault(),!v.has(W.code)&&R===0&&I===0&&(R=t.jumpVelocity),v.add(W.code);return}vr.has(W.code)&&!t.crouchEnabled||!t.moveEnabled&&!vr.has(W.code)||(W.preventDefault(),v.add(W.code))}},m=W=>{L(W.code)&&v.delete(W.code)},A=()=>{v.clear()},k=null,N=0,Y=.05,w=W=>{if(k===null||C)return;let ce=Math.min(Y,N?(W-N)/1e3:.0167);if(N=W,t.enabled){let ue=!1,Re=e.camera.state;if(t.moveEnabled){let Ae=0,Ne=0;for(let qe of v)gs.has(qe)?Ae+=1:hs.has(qe)?Ae-=1:bs.has(qe)?Ne+=1:ys.has(qe)&&(Ne-=1);if(Ae!==0||Ne!==0){let ke=(Re.rotY??0)*Math.PI/180,_e=-Math.cos(ke),En=-Math.sin(ke),_o=-Math.sin(ke),An=Math.cos(ke),_t=Math.hypot(Ae,Ne)||1,Ie=t.moveSpeed*ce;D[0]+=(_e*Ae+_o*Ne)/_t*Ie,D[1]+=(En*Ae+An*Ne)/_t*Ie,ue=!0}}let on=t.crouchEnabled&&(v.has("ControlLeft")||v.has("ControlRight"))?t.crouchHeight:t.eyeHeight;t.jumpEnabled&&(R!==0||I>0)?(R-=t.gravity*ce,I+=R*ce,I<=0&&(I=0,R=0)):t.jumpEnabled||(I=0,R=0);let St=t.groundZ+on+I;if(Math.abs(D[2]-St)>1e-4&&(D[2]=St,ue=!0),ue){let Ae=M();e.camera.update({target:Ae}),e.applyCamera(),b(l)}}k=s.requestAnimationFrame(w)};function K(){k!==null||C||(N=0,k=s.requestAnimationFrame(w))}function J(){k!==null&&(s.cancelAnimationFrame(k),k=null)}function ee(){let ce=i.ownerDocument?.defaultView?.getComputedStyle(i).perspective??"",ue=parseFloat(ce),Re=Number.isFinite(ue)&&ue>0?ue:2e3;i.style.setProperty("--polycss-fpv-perspective",`${Re}px`),i.classList.add("polycss-fpv-host")}function he(){i.classList.remove("polycss-fpv-host"),i.style.removeProperty("--polycss-fpv-perspective")}function Q(){o.addEventListener("click",F),r.addEventListener("pointerlockchange",re),r.addEventListener("mousemove",P),s.addEventListener("keydown",u),s.addEventListener("keyup",m),s.addEventListener("blur",A),o.style.cursor=t.lookEnabled?"crosshair":"",ee()}function fe(){if(o.removeEventListener("click",F),r.removeEventListener("pointerlockchange",re),r.removeEventListener("mousemove",P),s.removeEventListener("keydown",u),s.removeEventListener("keyup",m),s.removeEventListener("blur",A),o.style.cursor="",v.clear(),h)try{r.exitPointerLock()}catch{}he()}B(),Q(),K();function be(W){let ce=t.eyeHeight,ue=t.groundZ;t=fs(t,W),C||(o.style.cursor=t.lookEnabled?"crosshair":""),(t.eyeHeight!==ce||t.groundZ!==ue)&&(D[2]=t.groundZ+t.eyeHeight,V(),b(l))}function Pe(){C&&(C=!1,Q(),K())}function Xe(){C||(C=!0,fe(),J(),z&&(z=!1,x("end",l)))}function Le(){Xe(),d.length=0,p.length=0,y.length=0}function tt(){if(!(!t.enabled||!t.lookEnabled||C))try{o.requestPointerLock()}catch{}}function en(){if(h)try{r.exitPointerLock()}catch{}}function dt(){return h}function nt(W,ce){let ue=g(W);ue.includes(ce)||ue.push(ce)}function Ro(W,ce){let ue=g(W),Re=ue.indexOf(ce);Re>=0&&ue.splice(Re,1)}function ko(W,ce){return g(W).includes(ce)}function tn(){return[D[0],D[1],D[2]]}function Tn(W){D[0]=W[0],D[1]=W[1],D[2]=W[2],V(),b(l)}return{update:be,resume:Pe,pause:Xe,destroy:Le,lock:tt,unlock:en,isLocked:dt,getOrigin:tn,setOrigin:Tn,addEventListener:nt,removeEventListener:Ro,hasEventListener:ko}}function qt(e,n,t){let o=Array.from(e.querySelectorAll("i,b,s,u"));for(let i of o){let r=i.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 Ps(e,n,t,o){for(let i of e)if(!(o&&!o(i))&&qt(i.element,n,t))return i;return null}function Zn(e,n={}){let t=[],o=new Set;n.onChange&&o.add(n.onChange);function i(){t=n.filter?n.filter(t):t;for(let v of o)try{v(t)}catch(h){console.error("[polycss/createSelect] onChange threw:",h)}}function r(x){t=x,i()}function s(x){n.multiple?t.includes(x)||(t=[...t,x]):t=[x],i()}function c(x){t.includes(x)&&(t=t.filter(v=>v!==x),i())}function l(x){t.includes(x)?t=t.filter(v=>v!==x):n.multiple?t=[...t,x]:t=[x],i()}function d(){t.length!==0&&(t=[],i())}function p(x){return t.includes(x)}function y(x,v){return Ps(e.meshes(),x,v,h=>!h.element.classList.contains("polycss-transform-gizmo"))}let g=x=>{let v=x.target;if(v?.closest(".polycss-transform-gizmo"))return;let h=e.findMeshByElement(v)??y(x.clientX,x.clientY);if(!h){n.onPointerMissed&&n.onPointerMissed(x),n.clearOnMiss!==!1&&d();return}n.multiple&&(x.shiftKey||x.metaKey||x.ctrlKey)?l(h):t.length===1&&t[0]===h?d():r([h])};e.host.addEventListener("click",g);function b(){e.host.removeEventListener("click",g),o.clear()}return{get selected(){return t},set:r,add:s,remove:c,toggle:l,clear:d,has:p,destroy:b}}import{arrowPolygons as Xc,eulerXYZFromQuat as qc,planePolygons as Zc,quatFromAxisAngle as Qc,quatFromEulerXYZ as Kc,quatMultiply as Jc,ringQuadPolygons as eu,rotateVec3 as Sr}from"@layoutit/polycss-core";var Qn="#ff3653",Kn="#8adb00",Jn="#2c8fff",Zt=50,vs=60,tu=.6,nu=.0125,ou=.15,ru=.04,iu=1,Ss=.02,Cr=1.04,su=.1,au=.25,As=1e-4,lu=.6,cu=.8,uu=1,ct={0:1,1:0,2:2},Cs=[{cssAxis:0,sign:1,key:"x",color:Qn},{cssAxis:0,sign:-1,key:"-x",color:Qn},{cssAxis:1,sign:1,key:"y",color:Kn},{cssAxis:1,sign:-1,key:"-y",color:Kn},{cssAxis:2,sign:1,key:"z",color:Jn},{cssAxis:2,sign:-1,key:"-z",color:Jn}],Ts=[{cssAxis:0,key:"x",color:Qn},{cssAxis:1,key:"y",color:Kn},{cssAxis:2,key:"z",color:Jn}],Es=[{perpAxis:2,axisA:0,axisB:1,key:"xy",color:Jn},{perpAxis:1,axisA:0,axisB:2,key:"xz",color:Kn},{perpAxis:0,axisA:1,axisB:2,key:"yz",color:Qn}];function Tr(e,n,t,o){let i=t*Math.PI/180,r=o*Math.PI/180,s=[0,0,0];s[e]=n;let c=s[0]*Math.cos(r)-s[1]*Math.sin(r),l=s[0]*Math.sin(r)+s[1]*Math.cos(r),d=s[2];return l*Math.sin(i)+d*Math.cos(i)<0}function du(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),i=parseInt(t[2],16),r=parseInt(t[3],16);return`rgba(${o}, ${i}, ${r}, ${n})`}function eo(e,n){return!n||n<=0?e:Math.round(e/n)*n}function pu(e){if(e.length===0)return[0,0,0];let n=1/0,t=1/0,o=1/0,i=-1/0,r=-1/0,s=-1/0;for(let c of e)for(let l of c.vertices)l[0]<n&&(n=l[0]),l[0]>i&&(i=l[0]),l[1]<t&&(t=l[1]),l[1]>r&&(r=l[1]),l[2]<o&&(o=l[2]),l[2]>s&&(s=l[2]);return Number.isFinite(n)?[(n+i)/2,(t+r)/2,(o+s)/2]:[0,0,0]}function Er(e){if(e.length===0)return vs;let n=1/0,t=1/0,o=1/0,i=-1/0,r=-1/0,s=-1/0;for(let l of e)for(let d of l.vertices)d[0]<n&&(n=d[0]),d[0]>i&&(i=d[0]),d[1]<t&&(t=d[1]),d[1]>r&&(r=d[1]),d[2]<o&&(o=d[2]),d[2]>s&&(s=d[2]);return Number.isFinite(n)?Math.max(i-n,r-t,s-o)*Zt*tu:vs}function mu(e){let{cssAxis:n,sign:t,shaftLengthCss:o,wrapper:i,target:r,startClientX:s,startClientY:c,translationSnap:l,onAxisDelta:d,onMouseDown:p,onMouseUp:y,onDraggingChanged:g}=e,b=o,x=[0,0,0];x[n]=t;let v=i.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)`,i.appendChild(v);let h=i.getBoundingClientRect(),C=v.getBoundingClientRect();i.removeChild(v);let R=(C.left-h.left)/b,I=(C.top-h.top)/b,z=R*R+I*I;if(z<As)return;p?.(),g?.(!0);let D=q=>{let M=q.clientX-s,V=q.clientY-c,B=(M*R+V*I)/z;B=eo(B,l),d(B,x)},X=()=>{window.removeEventListener("pointermove",D),window.removeEventListener("pointerup",X),window.removeEventListener("pointercancel",X);let q=M=>{M.stopPropagation(),M.stopImmediatePropagation()};window.addEventListener("click",q,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",q,!0),0),y?.(),g?.(!1)};window.addEventListener("pointermove",D),window.addEventListener("pointerup",X),window.addEventListener("pointercancel",X)}function fu(e){let{axisA:n,axisB:t,probeDistanceCss:o,wrapper:i,startClientX:r,startClientY:s,translationSnap:c,onPlaneDelta:l,onMouseDown:d,onMouseUp:p,onDraggingChanged:y}=e,g=[0,0,0];g[n]=1;let b=[0,0,0];b[t]=1;function x(z){let D=i.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(${z[0]*o}px, ${z[1]*o}px, ${z[2]*o}px)`,i.appendChild(D);let X=i.getBoundingClientRect(),q=D.getBoundingClientRect();return i.removeChild(D),{x:(q.left-X.left)/o,y:(q.top-X.top)/o}}let v=x(g),h=x(b),C=v.x*h.y-h.x*v.y;if(Math.abs(C)<As)return;d?.(),y?.(!0);let R=z=>{let D=z.clientX-r,X=z.clientY-s,q=(h.y*D-h.x*X)/C,M=(-v.y*D+v.x*X)/C;q=eo(q,c),M=eo(M,c),l(q,M,g,b)},I=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",I),window.removeEventListener("pointercancel",I);let z=D=>{D.stopPropagation(),D.stopImmediatePropagation()};window.addEventListener("click",z,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",z,!0),0),p?.(),y?.(!1)};window.addEventListener("pointermove",R),window.addEventListener("pointerup",I),window.addEventListener("pointercancel",I)}function gu(e){let{cssAxis:n,wrapper:t,target:o,startClientX:i,startClientY:r,rotationSnap:s,onAngleDelta:c,onMouseDown:l,onMouseUp:d,onDraggingChanged:p}=e,y=t.getBoundingClientRect(),g=y.left,b=y.top,x=Math.atan2(r-b,i-g),v=0;l?.(),p?.(!0);let h=R=>{let I=Math.atan2(R.clientY-b,R.clientX-g),z=I-x;z>Math.PI?z-=2*Math.PI:z<-Math.PI&&(z+=2*Math.PI),v+=z,x=I;let D=v*180/Math.PI;D=eo(D,s),c(D)},C=()=>{window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",C),window.removeEventListener("pointercancel",C);let R=I=>{I.stopPropagation(),I.stopImmediatePropagation()};window.addEventListener("click",R,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener("click",R,!0),0),d?.(),p?.(!1)};window.addEventListener("pointermove",h),window.addEventListener("pointerup",C),window.addEventListener("pointercancel",C)}function to(e,n={}){let t=null,o=n.mode??"translate",i=n.size??1,r={...n},s=new Map,c=null,l=null,d=[0,0,0];function p(){if(!t)return[0,0,0];let P=t.transform.position??[0,0,0],L=t.transform.rotation??[0,0,0],u=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,m=Sr(d,L[0],L[1],L[2]);return[P[0]+u*m[0],P[1]+u*m[1],P[2]+u*m[2]]}function y(P){return l===P?uu:c===P?cu:lu}function g(){for(let[P,L]of s){let u=b(L.spec,y(P));L.handle.setPolygons(u,{recomputeAutoCenter:!1})}}function b(P,L){let m=Er(t?.polygons??[])*i,A=m/Zt,k=du(P.color,L);if(P.kind==="arrow"){let w=e.camera.state,K=Tr(P.cssAxis,P.sign,w.rotX??65,w.rotY??45);return Xc({axis:ct[P.cssAxis],sign:P.sign,shaftLength:A,shaftHalfThickness:A*nu,headLength:A*ou,headHalfThickness:A*ru,color:k,shaft:!K})}if(P.kind==="plane"){let w=e.camera.state,K=w.rotX??65,J=w.rotY??45,ee=ct[P.perpAxis],he=(ee+1)%3,Q=(ee+2)%3,fe=ct[he],be=ct[Q],Pe=Tr(fe,1,K,J)?-1:1,Xe=Tr(be,1,K,J)?-1:1,Le=A*au;return Zc({axis:ee,size:A*su,offset:[Pe*Le,Xe*Le],color:k})}let Y=m*iu/Zt*Cr;return eu({axis:ct[P.cssAxis],outerRadius:Y,color:k})}function x(P){return P.kind==="arrow"?"polycss-transform-arrow":P.kind==="plane"?"polycss-transform-plane":"polycss-transform-ring"}function v(){if(o==="translate"){let P=Cs.map(u=>({kind:"arrow",key:u.key,cssAxis:u.cssAxis,sign:u.sign,color:u.color})),L=Es.map(u=>({kind:"plane",key:u.key,perpAxis:u.perpAxis,axisA:u.axisA,axisB:u.axisB,color:u.color}));return[...P,...L]}return o==="rotate"?Ts.map(P=>({kind:"ring",key:P.key,cssAxis:P.cssAxis,color:P.color})):[]}function h(){if(C(),!t)return;let P={x:r.showX!==!1,y:r.showY!==!1,z:r.showZ!==!1};function L(m){if(m.kind==="arrow"){let N=m.key.replace("-","")[0];return P[N]}if(m.kind==="ring")return P[m.key];let A=["x","y","z"][m.axisA],k=["x","y","z"][m.axisB];return P[A]&&P[k]}let u=p();for(let m of v()){if(!L(m))continue;let A=b(m,y(m.key)),k=e.add({polygons:A,objectUrls:[],warnings:[],dispose:()=>{}},{excludeFromAutoCenter:!0,id:`__poly-gizmo-${m.key}`,position:u}),N=x(m);if(k.element.classList.add("polycss-transform-gizmo",N,`${N}--${m.key}`),m.kind==="ring"){let Y=(1-Ss)/Cr,w=(1+Ss)/Cr;k.element.style.setProperty("--ring-inner-ratio",`${Y}`),k.element.style.setProperty("--ring-outer-ratio",`${w}`)}s.set(m.key,{handle:k,spec:m})}}function C(){for(let{handle:P}of s.values())P.remove();s.clear(),c=null,l=null}function R(){if(!t)return;let P=p();for(let{handle:L}of s.values())L.setTransform({position:P})}function I(){t&&(s.size===0?h():R())}function z(P){if(t=P,!P){d=[0,0,0],C();return}d=pu(P.polygons),C(),h()}function D(){z(null)}function X(P){P!==o&&(o=P,t&&(C(),h()))}function q(P,L,u){if(!t||!M)return;let m=u[P.cssAxis],A=ct[P.cssAxis],k=L*m/Zt,N=M.slice();N[A]=M[A]+k,t.setTransform({position:N}),R(),r.onObjectChange?.({object:t,position:N}),r.onChange?.()}let M=null,V=null,B=P=>{if(!t||r.enabled===!1)return;let L={x:r.showX!==!1,y:r.showY!==!1,z:r.showZ!==!1};if(o==="translate"){for(let u of Es){let m=["x","y","z"][u.axisA],A=["x","y","z"][u.axisB];if(!L[m]||!L[A])continue;let k=s.get(u.key);if(k&&qt(k.handle.element,P.clientX,P.clientY)){P.preventDefault(),P.stopPropagation(),l=u.key,g(),M=(t.transform.position??[0,0,0]).slice(),fu({axisA:u.axisA,axisB:u.axisB,probeDistanceCss:Er(t.polygons)*i,wrapper:k.handle.element,target:t,startClientX:P.clientX,startClientY:P.clientY,translationSnap:r.translationSnap??null,onPlaneDelta:(N,Y,w,K)=>{if(!t||!M)return;let J=w[u.axisA],ee=K[u.axisB],he=ct[u.axisA],Q=ct[u.axisB],fe=M.slice();fe[he]+=N*J/Zt,fe[Q]+=Y*ee/Zt,t.setTransform({position:fe}),R(),r.onObjectChange?.({object:t,position:fe}),r.onChange?.()},onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:N=>{N||(l=null,M=null,g()),r.onDraggingChanged?.(N)}});return}}for(let u of Cs){let m=u.key.replace("-","")[0];if(!L[m])continue;let A=s.get(u.key);if(A&&qt(A.handle.element,P.clientX,P.clientY)){P.preventDefault(),P.stopPropagation(),l=u.key,g(),M=(t.transform.position??[0,0,0]).slice(),mu({cssAxis:u.cssAxis,sign:u.sign,shaftLengthCss:Er(t.polygons)*i,wrapper:A.handle.element,target:t,startClientX:P.clientX,startClientY:P.clientY,translationSnap:r.translationSnap??null,onAxisDelta:(k,N)=>q(u,k,N),onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:k=>{k||(l=null,M=null,g()),r.onDraggingChanged?.(k)}});return}}}else if(o==="rotate")for(let u of Ts){if(!L[u.key])continue;let m=s.get(u.key);if(m&&qt(m.handle.element,P.clientX,P.clientY)){P.preventDefault(),P.stopPropagation(),l=u.key,g(),V=(t.transform.rotation??[0,0,0]).slice(),M=(t.transform.position??[0,0,0]).slice(),gu({cssAxis:u.cssAxis,wrapper:m.handle.element,target:t,startClientX:P.clientX,startClientY:P.clientY,rotationSnap:r.rotationSnap??null,onAngleDelta:A=>{if(!t||!V||!M)return;let k=ct[u.cssAxis],N=[0,0,0];N[k]=1;let Y=-A*Math.PI/180,w=Kc(V),K=Qc(N,Y),J=qc(Jc(K,w)),ee=typeof t.transform.scale=="number"?t.transform.scale:t.transform.scale?.[0]??1,he=Sr(d,V[0],V[1],V[2]),Q=Sr(d,J[0],J[1],J[2]),fe=[M[0]+ee*(he[0]-Q[0]),M[1]+ee*(he[1]-Q[1]),M[2]+ee*(he[2]-Q[2])];t.setTransform({rotation:J,position:fe}),R(),r.onObjectChange?.({object:t,rotation:J,position:fe}),r.onChange?.()},onMouseDown:r.onMouseDown,onMouseUp:r.onMouseUp,onDraggingChanged:A=>{A||(l=null,V=null,M=null,g(),t?.rebakeAtlas()),r.onDraggingChanged?.(A)}});return}}};e.host.addEventListener("pointerdown",B,{capture:!0});let F=P=>{if(!t||l||r.enabled===!1)return;let L=null;for(let[u,m]of s)if(qt(m.handle.element,P.clientX,P.clientY)){L=u;break}L!==c&&(c=L,g())};e.host.addEventListener("pointermove",F);function re(){e.host.removeEventListener("pointerdown",B,{capture:!0}),e.host.removeEventListener("pointermove",F),C()}return{attach:z,detach:D,setMode:X,update:I,destroy:re}}var hu=typeof HTMLElement<"u"?HTMLElement:class{},yu=["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 Ye(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function bu(e){return e==="false"?!1:Ye(e)}function Ar(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 xu(e){if(e==="baked"||e==="dynamic")return e}function Pu(e){return e==="auto"?"auto":Ye(e)}function vu(e){if(e==="canonical"||e==="local"||e==="raster")return e}function Su(e){if(e==="auto"||e==="pixelated")return e}function Cu(e){if(e==="auto"||e==="atlas"||e==="image")return e}function Tu(e){if(e==="affine"||e==="projective")return e}function Eu(e){return typeof e.getCamera=="function"}var De=class extends hu{constructor(){super(...arguments);this._scene=null;this._implicitCamera=null}static get observedAttributes(){return[...yu]}getScene(){return this._scene}_findAncestorCamera(){let t=this.parentElement;for(;t;){if(Eu(t)){let o=t.getCamera();if(o)return o}t=t.parentElement}return null}_buildImplicitCamera(){let t=bu(this.getAttribute("perspective")),o=Ye(this.getAttribute("rot-x")),i=Ye(this.getAttribute("rot-y")),r=Ye(this.getAttribute("zoom")),s=Ye(this.getAttribute("distance")),c=Ar(this.getAttribute("target")),l={...o!==void 0?{rotX:o}:{},...i!==void 0?{rotY:i}:{},...r!==void 0?{zoom:r}:{},...s!==void 0?{distance:s}:{},...c!==void 0?{target:c}:{}};return t===!1?st(l):t!==void 0?Pt({...l,perspective:t}):st(l)}_readNonCameraOptions(){let t=this._readDirectionalLight(),o=this._readAmbientLight(),i={};i.textureLighting=xu(this.getAttribute("texture-lighting"))??"baked";let r=Pu(this.getAttribute("texture-quality"));r!==void 0&&(i.textureQuality=r),i.textureLeafSizing=vu(this.getAttribute("texture-leaf-sizing"))??"canonical";let s=Su(this.getAttribute("texture-image-rendering"));s!==void 0&&(i.textureImageRendering=s);let c=Cu(this.getAttribute("texture-backend"));c!==void 0&&(i.textureBackend=c);let l=Tu(this.getAttribute("texture-projection"));return l!==void 0&&(i.textureProjection=l),i.autoCenter=this.hasAttribute("auto-center"),t&&(i.directionalLight=t),o&&(i.ambientLight=o),i}_readDirectionalLight(){let t=Ar(this.getAttribute("directional-direction")),o=this.getAttribute("directional-color")||void 0,i=Ye(this.getAttribute("directional-intensity"));if(!t&&!o&&i===void 0)return;let r={direction:t??[.4,-.7,.59]};return o&&(r.color=o),i!==void 0&&(r.intensity=i),r}_readAmbientLight(){let t=this.getAttribute("ambient-color")||void 0,o=Ye(this.getAttribute("ambient-intensity"));if(!t&&o===void 0)return;let i={};return t&&(i.color=t),o!==void 0&&(i.intensity=o),i}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=Ut(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,i){if(o!==i&&this._scene){if(this._implicitCamera&&["rot-x","rot-y","zoom","distance","target"].includes(t)){let s=Ye(this.getAttribute("rot-x")),c=Ye(this.getAttribute("rot-y")),l=Ye(this.getAttribute("zoom")),d=Ye(this.getAttribute("distance")),p=Ar(this.getAttribute("target"));s!==void 0&&this._implicitCamera.update({rotX:s}),c!==void 0&&this._implicitCamera.update({rotY:c}),l!==void 0&&this._implicitCamera.update({zoom:l}),d!==void 0&&this._implicitCamera.update({distance:d}),p!==void 0&&this._implicitCamera.update({target:p}),this._scene.applyCamera();return}this._scene.setOptions(this._readNonCameraOptions())}}};import{computeSceneBbox as Au,loadMesh as wu}from"@layoutit/polycss-core";var Mu=typeof HTMLElement<"u"?HTMLElement:class{},Lu=["src","mtl","mesh-resolution","position","scale","rotation","auto-center","cast-shadow","receive-shadow","target-size","default-color","palette","include-objects","exclude-objects"];function Pn(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 ws(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Pn(e)}}function wr(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 Ru(e){let n=e.getAttribute("target-size"),t=e.getAttribute("default-color"),o=wr(e.getAttribute("palette")),i=wr(e.getAttribute("include-objects")),r=wr(e.getAttribute("exclude-objects")),s=n!==null?parseFloat(n):NaN,c={};return Number.isFinite(s)&&(c.targetSize=s),t&&(c.defaultColor=t),o&&(c.palette=o),i&&(c.includeObjects=i),r&&(c.excludeObjects=r),Object.keys(c).length>0?c:void 0}function ku(e){return e.closest("poly-scene")??null}function _u(e){if(e.length===0)return e;let n=Au(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,i=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&i===0)return e;let r=s=>[s[0]-t,s[1]-o,s[2]-i];return e.map(s=>({...s,vertices:s.vertices.map(r),...s.textureTriangles?.length?{textureTriangles:s.textureTriangles.map(c=>({...c,vertices:c.vertices.map(r)}))}:null}))}var Qt=class extends Mu{constructor(){super(...arguments);this._handle=null;this._parseResult=null;this._loadToken=0}static get observedAttributes(){return[...Lu]}getMeshHandle(){return this._handle}connectedCallback(){this._maybeLoad()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,i){if(o!==i){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:Pn(this.getAttribute("position")),scale:ws(this.getAttribute("scale")),rotation:Pn(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=ku(this);if(!o)return;let i=++this._loadToken,r=this.getAttribute("mtl")||void 0,c=this.getAttribute("mesh-resolution")==="lossless"?"lossless":void 0,l=Ru(this),d;try{let g=r||c!==void 0||l?{...r?{mtlUrl:r}:{},...c!==void 0?{meshResolution:c}:{},...l?{objOptions:l}:{}}:void 0;d=await wu(t,g)}catch(g){this.dispatchEvent(new CustomEvent("polycss:error",{detail:g,bubbles:!0}));return}if(i!==this._loadToken){try{d.dispose()}catch{}return}let p=o.getScene();if(!p){try{d.dispose()}catch{}return}this.hasAttribute("auto-center")&&(d={...d,polygons:_u(d.polygons)}),this._parseResult=d,this._handle=p.add(d,{position:Pn(this.getAttribute("position")),scale:ws(this.getAttribute("scale")),rotation:Pn(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 vn}from"@layoutit/polycss-core";var Ou=typeof HTMLElement<"u"?HTMLElement:class{},Du=["src","width","height","position","rotation","scale","allow","loading","referrerpolicy","sandbox","title"];function Mr(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 Iu(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Mr(e)}}function Ms(e,n){if(e===null)return n;let t=parseFloat(e);return Number.isFinite(t)?t:n}function Hu(e){let n=e.closest("poly-scene");return n?n.querySelector(".polycss-scene"):null}function Fu(e,n,t,o,i){let r=typeof t=="number"?t:t?.[0]??1,s=typeof t=="number"?t:t?.[1]??1,c=typeof t=="number"?t:t?.[2]??1,l=r!==1||s!==1||c!==1,d=!!n&&(!!n[0]||!!n[1]||!!n[2]),p=(e?.[1]??0)*vn,y=(e?.[0]??0)*vn,g=(e?.[2]??0)*vn,b=[];return b.push(`translate3d(${p}px, ${y}px, ${g}px)`),d&&(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}, ${s}, ${c})`),b.push(`translate(${-o/2}px, ${-i/2}px)`),b.join(" ")}var no=class extends Ou{constructor(){super(...arguments);this._wrapper=null;this._iframe=null}static get observedAttributes(){return[...Du]}getIframeElement(){return this._iframe}connectedCallback(){this._mount()}disconnectedCallback(){this._teardown()}attributeChangedCallback(t,o,i){if(o!==i&&!(!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=Hu(this);if(!t)return;let o=this.ownerDocument;if(!o)return;let i=o.createElement("div");i.className="polycss-iframe",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.transformOrigin="0 0",i.style.transformStyle="preserve-3d";let r=o.createElement("iframe");r.style.display="block",r.style.border="0",r.style.background="#000";let s=this.getAttribute("src");s&&(r.src=s);let c=this.getAttribute("allow");c&&r.setAttribute("allow",c);for(let l of["loading","referrerpolicy","sandbox","title"]){let d=this.getAttribute(l);d!==null&&r.setAttribute(l,d)}i.appendChild(r),t.appendChild(i),this._wrapper=i,this._iframe=r,this._applyGeometry()}_applyGeometry(){if(!this._wrapper||!this._iframe)return;let t=Ms(this.getAttribute("width"),16),o=Ms(this.getAttribute("height"),9),i=t*vn,r=o*vn;this._iframe.style.width=`${i}px`,this._iframe.style.height=`${r}px`;let s=Mr(this.getAttribute("position")),c=Mr(this.getAttribute("rotation")),l=Iu(this.getAttribute("scale"));this._wrapper.style.transform=Fu(s,c,l,i,r)}_teardown(){this._wrapper?.parentNode&&this._wrapper.parentNode.removeChild(this._wrapper),this._wrapper=null,this._iframe=null}};var zu=typeof HTMLElement<"u"?HTMLElement:class{},Bu=["vertices","color","texture","uvs","position","scale","rotation"];function Ls(e){if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Lr(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 Vu(e){if(e){if(!e.includes(",")){let n=parseFloat(e);return Number.isFinite(n)?n:void 0}return Lr(e)}}function Nu(e){return e.closest("poly-scene")??null}var oo=class extends zu{constructor(){super(...arguments);this._handle=null}static get observedAttributes(){return[...Bu]}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,i){o!==i&&(this._tearDown(),this.isConnected&&this._mount())}_tearDown(){if(this._handle){try{this._handle.dispose()}catch{}this._handle=null}}_mount(){let t=Nu(this);if(!t)return;let o=t.getScene();if(!o)return;let i=Ls(this.getAttribute("vertices"));if(!i||!Array.isArray(i)||i.length<3)return;let r=this.getAttribute("color")||void 0,s=this.getAttribute("texture")||void 0,c=Ls(this.getAttribute("uvs"))??void 0,l={};for(let y of Array.from(this.attributes))y.name.startsWith("data-")&&(l[y.name.slice(5)]=y.value);let p={polygons:[{vertices:i,...r!==void 0?{color:r}:{},...s!==void 0?{texture:s}:{},...c!==void 0?{uvs:c}:{},...Object.keys(l).length>0?{data:l}:{}}],objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(p,{position:Lr(this.getAttribute("position")),scale:Vu(this.getAttribute("scale")),rotation:Lr(this.getAttribute("rotation"))})}};function oe(e){if(e==null)return;let n=parseFloat(e);return Number.isFinite(n)?n:void 0}function ro(e){if(!e)return;let n=e.split(",").map(t=>parseFloat(t.trim()));if(!(n.length!==3||n.some(t=>!Number.isFinite(t))))return[n[0],n[1],n[2]]}function Me(e){if(e!==null)return!(e==="false"||e==="0")}function io(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 so(e){if(e==="x"||e==="y")return e}var ju=typeof HTMLElement<"u"?HTMLElement:class{},$u=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],ao=class extends ju{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...$u]}getControls(){return this._controls}_readAnimate(){let t=oe(this.getAttribute("animate-speed")),o=so(this.getAttribute("animate-axis")),i=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}:{},...i!==null?{pauseOnInteraction:Me(i)}:{}}}_readOptions(){let t={},o=Me(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let i=Me(this.getAttribute("wheel"));i!==void 0&&(t.wheel=i),this.hasAttribute("dolly")&&(t.dolly=!0);let r=oe(this.getAttribute("min-distance"));r!==void 0&&(t.minDistance=r);let s=oe(this.getAttribute("max-distance"));s!==void 0&&(t.maxDistance=s);let c=io(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=oe(this.getAttribute("zoom-min")),d=oe(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),d!==void 0&&(t.maxZoom=d),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof De)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._controls=Yn(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,i){o!==i&&this._controls&&this._controls.update(this._readOptions())}};var Wu=typeof HTMLElement<"u"?HTMLElement:class{},Uu=["drag","wheel","dolly","min-distance","max-distance","invert","zoom-min","zoom-max","animate-speed","animate-axis","animate-pause-on-interaction"],lo=class extends Wu{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Uu]}_readAnimate(){let t=oe(this.getAttribute("animate-speed")),o=so(this.getAttribute("animate-axis")),i=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}:{},...i!==null?{pauseOnInteraction:Me(i)}:{}}}_readOptions(){let t={},o=Me(this.getAttribute("drag"));o!==void 0&&(t.drag=o);let i=Me(this.getAttribute("wheel"));i!==void 0&&(t.wheel=i),this.hasAttribute("dolly")&&(t.dolly=!0);let r=oe(this.getAttribute("min-distance"));r!==void 0&&(t.minDistance=r);let s=oe(this.getAttribute("max-distance"));s!==void 0&&(t.maxDistance=s);let c=io(this.getAttribute("invert"));c!==void 0&&(t.invert=c);let l=oe(this.getAttribute("zoom-min")),d=oe(this.getAttribute("zoom-max"));return l!==void 0&&(t.minZoom=l),d!==void 0&&(t.maxZoom=d),t.animate=this._readAnimate()??!1,t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof De)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._controls=Xn(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,i){o!==i&&this._controls&&this._controls.update(this._readOptions())}};var Gu=typeof HTMLElement<"u"?HTMLElement:class{},Yu=["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"],co=class extends Gu{constructor(){super(...arguments);this._controls=null}static get observedAttributes(){return[...Yu]}_readOptions(){let t={},o=Me(this.getAttribute("enabled"));o!==void 0&&(t.enabled=o);let i=Me(this.getAttribute("look-enabled"));i!==void 0&&(t.lookEnabled=i);let r=Me(this.getAttribute("move-enabled"));r!==void 0&&(t.moveEnabled=r);let s=Me(this.getAttribute("jump-enabled"));s!==void 0&&(t.jumpEnabled=s);let c=Me(this.getAttribute("crouch-enabled"));c!==void 0&&(t.crouchEnabled=c);let l=oe(this.getAttribute("look-sensitivity"));if(l!==void 0&&(t.lookSensitivity=l),this.hasAttribute("invert-y")){let C=Me(this.getAttribute("invert-y"));C!==void 0&&(t.invertY=C)}let d=oe(this.getAttribute("move-speed"));d!==void 0&&(t.moveSpeed=d);let p=oe(this.getAttribute("jump-velocity"));p!==void 0&&(t.jumpVelocity=p);let y=oe(this.getAttribute("gravity"));y!==void 0&&(t.gravity=y);let g=oe(this.getAttribute("eye-height"));g!==void 0&&(t.eyeHeight=g);let b=oe(this.getAttribute("crouch-height"));b!==void 0&&(t.crouchHeight=b);let x=oe(this.getAttribute("ground-z"));x!==void 0&&(t.groundZ=x);let v=oe(this.getAttribute("min-pitch"));v!==void 0&&(t.minPitch=v);let h=oe(this.getAttribute("max-pitch"));return h!==void 0&&(t.maxPitch=h),t}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof De)return t;t=t.parentNode}return null}_attach(){if(this._controls)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._controls=qn(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._controls&&(this._controls.destroy(),this._controls=null)}attributeChangedCallback(t,o,i){o!==i&&this._controls&&this._controls.update(this._readOptions())}};var Xu=typeof HTMLElement<"u"?HTMLElement:class{},qu=["perspective","zoom","rot-x","rot-y","target","distance"],uo=class extends Xu{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...qu]}getCamera(){return this._camera}_readOptions(){return{perspective:oe(this.getAttribute("perspective")),zoom:oe(this.getAttribute("zoom")),rotX:oe(this.getAttribute("rot-x")),rotY:oe(this.getAttribute("rot-y")),target:ro(this.getAttribute("target")),distance:oe(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=Pt(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,i){if(o===i||!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 Zu=typeof HTMLElement<"u"?HTMLElement:class{},Qu=["zoom","rot-x","rot-y","target","distance"],Kt=class extends Zu{constructor(){super(...arguments);this._camera=null;this._wrapper=null}static get observedAttributes(){return[...Qu]}getCamera(){return this._camera}_readOptions(){return{zoom:oe(this.getAttribute("zoom")),rotX:oe(this.getAttribute("rot-x")),rotY:oe(this.getAttribute("rot-y")),target:ro(this.getAttribute("target")),distance:oe(this.getAttribute("distance"))}}_mount(){if(this._camera)return;let t=this._readOptions();for(this._camera=st(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,i){if(o===i||!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 po=class extends Kt{};var Ku=typeof HTMLElement<"u"?HTMLElement:class{},Ju=["mode","target","size","enabled"];function Rs(e){if(e==="translate"||e==="rotate")return e}var mo=class extends Ku{constructor(){super(...arguments);this._tc=null}static get observedAttributes(){return[...Ju]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof De)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 i=null;try{i=o.querySelector(`#${t}`)??o.querySelector(t)}catch{i=o.querySelector(`[id="${t}"]`)}return i instanceof Qt?i:null}_readOptions(){let t={},o=Rs(this.getAttribute("mode"));o!==void 0&&(t.mode=o);let i=oe(this.getAttribute("size"));i!==void 0&&(t.size=i);let r=this.getAttribute("enabled");return r!==null&&(t.enabled=r!=="false"&&r!=="0"),t.onObjectChange=s=>{this.dispatchEvent(new CustomEvent("polycss:object-change",{bubbles:!0,detail:{position:s.position,rotation:s.rotation}}))},t}_attach(){if(this._tc)return;let t=this._findScene(),o=t?.getScene();if(!o){if(t){let r=()=>{t.removeEventListener("polycss:scene-ready",r),this._attach()};t.addEventListener("polycss:scene-ready",r)}return}this._tc=to(o,this._readOptions());let i=this._findTargetMesh();if(i){let r=i.getMeshHandle();r&&this._tc.attach(r)}}connectedCallback(){this._attach()}disconnectedCallback(){this._tc&&(this._tc.destroy(),this._tc=null)}attributeChangedCallback(t,o,i){if(o!==i&&this._tc){if(t==="mode"){let r=Rs(i);r&&this._tc.setMode(r)}else if(t==="target"){let r=this._findTargetMesh();this._tc.attach(r?r.getMeshHandle()??null:null)}}}};var ed=typeof HTMLElement<"u"?HTMLElement:class{},td=["multiple","clear-on-miss"],fo=class extends ed{constructor(){super(...arguments);this._selection=null}static get observedAttributes(){return[...td]}_findScene(){let t=this.parentNode;for(;t;){if(t instanceof De)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 i=()=>{t.removeEventListener("polycss:scene-ready",i),this._attach()};t.addEventListener("polycss:scene-ready",i)}return}this._selection=Zn(o,this._readOptions())}connectedCallback(){this._attach()}disconnectedCallback(){this._selection&&(this._selection.destroy(),this._selection=null)}attributeChangedCallback(t,o,i){o!==i&&(this._selection&&(this._selection.destroy(),this._selection=null),this._attach())}};var Rr={quad:0,clippedSolid:0,atlas:0,stableTriangle:0},kr={ready:!0,textureLeafCount:0,readyTextureLeafCount:0,pendingTextureLeafCount:0,atlasTextureLeafCount:0,imageTextureLeafCount:0};function _r(){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 Or(){return{runtimeAtlasUrlCount:0,snapshotAtlasCount:0,snapshotBackgroundCount:0,selfContained:!0}}function go(){return{rootFound:!1,projection:"unknown",perspectiveStyle:"",appliedPerspectiveStyle:""}}var nd={polygonCount:0,mountedPolygonLeafCount:0,shadowLeafCount:0,surfaceLeafCounts:Rr,textureReadiness:kr,textureStats:_r(),snapshotStats:Or(),cameraStats:go(),bucketCount:0};function ho(e){return typeof e=="number"?{polygonCount:e}:e??{}}function Rt(e,n){return e.querySelectorAll(n).length}function ks(e,n){return(Os(e,n)?1:0)+Rt(e,n)}function _s(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 od(e){let n=0,t=e instanceof HTMLElement?e:null;t&&_s(t.getAttribute("style"))&&n++;for(let o of Array.from(e.querySelectorAll("[style]")))o instanceof HTMLElement&&_s(o.getAttribute("style"))&&n++;return n}function Os(e,n){let t=e;return typeof t.matches=="function"&&t.matches(n)}function yo(e,n){if(!n)return[e];let t=[];return Os(e,n)&&t.push(e),t.push(...Array.from(e.querySelectorAll(n))),t}function rd(e){switch(e.toLowerCase()){case"b":return"quad";case"i":return"clippedSolid";case"s":return"atlas";case"u":return"stableTriangle";default:return null}}function id(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 sd(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 ad(e){return e==="orthographic"||e==="perspective"?e:"unknown"}function ld(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 bo(e,n){if(!e)return[];let t=ho(n),o=[];for(let i of yo(e,t.scopeSelector))for(let r of Array.from(i.querySelectorAll("b,i,s,u"))){let s=r,c=rd(s.tagName);if(!c)continue;let l=s.getAttribute("data-polycss-texture-backend")??(c==="atlas"?"atlas":void 0),d=ld(s,l);o.push({element:s,strategy:c,polygonIndex:id(s.getAttribute("data-poly-index")),textureBackend:l,textureReady:d,textureLeafSizing:s.getAttribute("data-polycss-texture-leaf-sizing")??void 0,textureImageRendering:s.getAttribute("data-polycss-texture-image-rendering")??void 0,textureProjection:s.getAttribute("data-polycss-texture-projection")??void 0,textureLeafWidth:Jt(s.getAttribute("data-polycss-texture-leaf-width")),textureLeafHeight:Jt(s.getAttribute("data-polycss-texture-leaf-height")),doubleSided:s.getAttribute("data-polycss-double-sided")==="true"})}return o}function Dr(e,n){let t={...kr};for(let o of bo(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 cd(e,n){let t=_r(),o=!1,i=!1;for(let r of bo(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=i?Math.min(t.minLeafHeight,r.textureLeafHeight):r.textureLeafHeight,t.maxLeafHeight=i?Math.max(t.maxLeafHeight,r.textureLeafHeight):r.textureLeafHeight,i=!0),r.doubleSided&&t.doubleSidedCount++}return t.pendingCount=Math.min(t.pendingCount,t.leafCount),t.ready=t.pendingCount===0,t}function ud(e,n){let t=Or();if(!e)return t;let o=ho(n);for(let i of yo(e,o.scopeSelector))t.runtimeAtlasUrlCount+=od(i),t.snapshotAtlasCount+=ks(i,"[data-polycss-snapshot-atlas]"),t.snapshotBackgroundCount+=ks(i,"[data-polycss-snapshot-bg]");return t.selfContained=t.runtimeAtlasUrlCount===0,t}function dd(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 pd(e,n){if(!e)return go();let t=ho(n),o=null;for(let i of yo(e,t.scopeSelector))if(o=dd(i),o)break;return o?{rootFound:!0,projection:ad(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:sd(o.getAttribute("data-polycss-camera-target"))}:go()}function Ds(e,n){let t=ho(n);if(!e)return{...nd,surfaceLeafCounts:{...Rr},textureReadiness:{...kr},textureStats:_r(),snapshotStats:Or(),cameraStats:go(),polygonCount:t.polygonCount??0};let o=yo(e,t.scopeSelector),i={...Rr},r=0,s=0;for(let l of o)i.quad+=Rt(l,"b"),i.clippedSolid+=Rt(l,"i"),i.atlas+=Rt(l,"s"),i.stableTriangle+=Rt(l,"u"),r+=Rt(l,"q, .polycss-shadow-svg"),s+=Rt(l,".polycss-bucket");let c=i.quad+i.clippedSolid+i.atlas+i.stableTriangle;return{polygonCount:t.polygonCount??c,mountedPolygonLeafCount:c,shadowLeafCount:r,surfaceLeafCounts:i,textureReadiness:Dr(e,t),textureStats:cd(e,t),snapshotStats:ud(e,t),cameraStats:pd(e,t),bucketCount:s}}var vt=class extends Error{constructor(n,t,o){super(t),this.name="PolySceneSnapshotError",this.code=n,this.url=o,Object.setPrototypeOf(this,new.target.prototype)}},md=`
520
+ html,
521
+ body {
522
+ width: 100%;
523
+ height: 100%;
524
+ margin: 0;
525
+ }
526
+
527
+ body {
528
+ position: relative;
529
+ overflow: hidden;
530
+ }
531
+ `,Ir=["b","i","s","u"],fd=["b","i","u"],gd=["--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"],hd=["--clx","--cly","--clz","--shadow-ground-cssz"],yd=["--polycss-atlas-size","--polycss-atlas-width","--polycss-atlas-height","--polycss-atlas-leaf-sizing","--polycss-atlas-url","--polycss-atlas-position","--polycss-atlas-image-size"],bd=["--polycss-atlas-size","--polycss-atlas-width","--polycss-atlas-height","--polycss-atlas-leaf-sizing"];function xd(e){return!!e&&typeof e.querySelector=="function"&&typeof e.cloneNode=="function"}function Pd(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 Cn(e){return[e,...Array.from(e.querySelectorAll("*"))]}function ut(e,n){return e.matches(n)||!!e.querySelector(n)}function Is(e,n){return e.tagName.toLowerCase()===n||!!e.querySelector(n)}function vd(e){let n=Ir.filter(o=>Is(e,o)),t=fd.filter(o=>n.includes(o));return{hasCamera:ut(e,".polycss-camera"),hasScene:ut(e,".polycss-scene"),hasMesh:ut(e,".polycss-mesh"),hasFpvHost:ut(e,".polycss-fpv-host"),hasBucket:ut(e,".polycss-bucket"),hasVoxelMesh:ut(e,".polycss-voxel-mesh"),hasTransformGizmo:ut(e,".polycss-transform-gizmo"),hasTransformRing:ut(e,".polycss-transform-ring"),hasDynamicLighting:ut(e,'.polycss-scene[data-polycss-lighting="dynamic"]'),hasQ:Is(e,"q"),leafTags:n,solidLeafTags:t}}function Sn(e,n=".polycss-scene "){return e.map(t=>`${n}${t}`).join(`,
532
+ `)}function Sd(e){return e.map(n=>`.polycss-scene[data-polycss-lighting="dynamic"] :not(.polycss-bucket) > ${n}`).join(`,
533
+ `)}function Cd(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 Td(e){let n=[Cd(e.hasQ)];return e.hasBucket&&n.push(`
535
+ .polycss-scene[data-polycss-lighting="dynamic"] .polycss-bucket {
536
+ --plam: max(0, calc(
537
+ var(--pnx) * var(--plx) +
538
+ var(--pny) * var(--ply) +
539
+ var(--pnz) * var(--plz)
540
+ ));
541
+ }
542
+ `),e.leafTags.length>0&&n.push(`
543
+ ${Sd(e.leafTags)} {
544
+ --plam: max(0, calc(
545
+ var(--pnx) * var(--plx) +
546
+ var(--pny) * var(--ply) +
547
+ var(--pnz) * var(--plz)
548
+ ));
549
+ }
550
+ `),e.leafTags.includes("s")&&n.push(`
551
+ .polycss-scene[data-polycss-lighting="dynamic"] s {
552
+ contain: strict;
553
+ background-color: rgb(
554
+ calc(255 * (var(--par) * var(--pai)
555
+ + var(--plr) * var(--pli) * var(--plam)))
556
+ calc(255 * (var(--pag) * var(--pai)
557
+ + var(--plg) * var(--pli) * var(--plam)))
558
+ calc(255 * (var(--pab) * var(--pai)
559
+ + var(--plb) * var(--pli) * var(--plam)))
560
+ );
561
+ background-blend-mode: multiply;
562
+ background-image: var(--polycss-atlas-url);
563
+ background-position: var(--polycss-atlas-position);
564
+ background-repeat: no-repeat;
565
+ background-size: var(--polycss-atlas-image-size);
566
+ mask-image: var(--polycss-atlas-url);
567
+ mask-mode: alpha;
568
+ mask-position: var(--polycss-atlas-position);
569
+ mask-repeat: no-repeat;
570
+ mask-size: var(--polycss-atlas-image-size);
571
+ -webkit-mask-image: var(--polycss-atlas-url);
572
+ -webkit-mask-position: var(--polycss-atlas-position);
573
+ -webkit-mask-repeat: no-repeat;
574
+ -webkit-mask-size: var(--polycss-atlas-image-size);
575
+ }
576
+ `),e.solidLeafTags.length>0&&n.push(`
577
+ ${Sn(e.solidLeafTags)} {
578
+ color: rgb(
579
+ calc(255 * var(--psr) * (var(--par) * var(--pai)
580
+ + var(--plr) * var(--pli) * var(--plam)))
581
+ calc(255 * var(--psg) * (var(--pag) * var(--pai)
582
+ + var(--plg) * var(--pli) * var(--plam)))
583
+ calc(255 * var(--psb) * (var(--pab) * var(--pai)
584
+ + var(--plb) * var(--pli) * var(--plam)))
585
+ );
586
+ }
587
+ `),e.hasQ&&n.push(`
588
+ .polycss-scene[data-polycss-lighting="dynamic"] {
589
+ --shadow-proj: matrix3d(
590
+ 1, 0, 0, 0,
591
+ 0, 1, 0, 0,
592
+ calc(-1 * var(--clx) / var(--clz)),
593
+ calc(-1 * var(--cly) / var(--clz)),
594
+ 0.01,
595
+ 0,
596
+ calc(var(--shadow-ground-cssz) * var(--clx) / var(--clz)),
597
+ calc(var(--shadow-ground-cssz) * var(--cly) / var(--clz)),
598
+ calc(var(--shadow-ground-cssz) * 0.99),
599
+ 1
600
+ );
601
+ }
602
+
603
+ .polycss-scene[data-polycss-lighting="dynamic"] q {
604
+ opacity: clamp(0, calc((var(--pnx) * var(--clx) + var(--pny) * var(--cly) + var(--pnz) * var(--clz)) * 10), 1);
605
+ }
606
+ `),n.join(`
607
+ `)}function Ed(e){let n=[md];if(e.hasScene&&n.push(`
608
+ .polycss-scene,
609
+ .polycss-scene *,
610
+ .polycss-scene *::before,
611
+ .polycss-scene *::after {
612
+ box-sizing: border-box;
613
+ }
614
+
615
+ .polycss-scene {
616
+ position: absolute;
617
+ top: 50%;
618
+ left: 50%;
619
+ width: 0;
620
+ height: 0;
621
+ transform-style: preserve-3d;
622
+ }
623
+ `),e.hasCamera&&n.push(`
624
+ .polycss-camera {
625
+ position: relative;
626
+ display: block;
627
+ width: 100%;
628
+ height: 100%;
629
+ }
630
+ `),e.hasFpvHost&&n.push(`
631
+ .polycss-fpv-host {
632
+ perspective: var(--polycss-fpv-perspective, 2000px) !important;
633
+ transform-style: preserve-3d !important;
634
+ }
635
+ `),e.hasMesh&&n.push(`
636
+ .polycss-mesh {
637
+ position: absolute;
638
+ transform-style: preserve-3d;
639
+ }
640
+ `),e.hasBucket&&n.push(`
641
+ .polycss-bucket {
642
+ position: absolute;
643
+ transform-style: preserve-3d;
644
+ }
645
+ `),e.leafTags.length>0&&n.push(`
646
+ ${Sn(e.leafTags)} {
647
+ position: absolute;
648
+ display: block;
649
+ transform-origin: 0 0;
650
+ transform-style: preserve-3d;
651
+ margin: 0;
652
+ padding: 0;
653
+ font: inherit;
654
+ font-weight: normal;
655
+ font-style: normal;
656
+ line-height: 0;
657
+ text-decoration: none;
658
+ backface-visibility: hidden;
659
+ background-repeat: no-repeat;
660
+ }
661
+ `),e.solidLeafTags.length>0&&!e.hasDynamicLighting&&n.push(`
662
+ ${Sn(e.solidLeafTags)} {
663
+ color: currentColor;
664
+ }
665
+ `),e.leafTags.includes("b")&&n.push(`
666
+ .polycss-scene b {
667
+ background: currentColor;
668
+ width: 64px;
669
+ height: 64px;
670
+ }
671
+ `),e.hasVoxelMesh&&n.push(`
672
+ .polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face {
673
+ position: absolute;
674
+ display: block;
675
+ top: 0;
676
+ left: 0;
677
+ width: 0;
678
+ height: 0;
679
+ transform-style: preserve-3d;
680
+ transform-origin: 0 0;
681
+ margin: 0;
682
+ padding: 0;
683
+ font: inherit;
684
+ line-height: 0;
685
+ pointer-events: none;
686
+ }
687
+
688
+ .polycss-mesh.polycss-voxel-mesh > .polycss-voxel-face > b {
689
+ top: 0;
690
+ left: 0;
691
+ width: var(--polycss-voxel-primitive, 1px);
692
+ height: var(--polycss-voxel-primitive, 1px);
693
+ backface-visibility: visible;
694
+ pointer-events: none;
695
+ }
696
+ `),e.leafTags.includes("i")&&n.push(`
697
+ .polycss-scene i {
698
+ width: 16px;
699
+ height: 16px;
700
+ border-color: currentColor;
701
+ }
702
+ `),e.leafTags.includes("s")&&n.push(`
703
+ .polycss-scene s {
704
+ width: 64px;
705
+ height: 64px;
706
+ }
707
+ `),e.leafTags.includes("u")&&n.push(`
708
+ .polycss-scene u {
709
+ width: 0;
710
+ height: 0;
711
+ background: transparent;
712
+ box-sizing: content-box;
713
+ border: 0 solid transparent;
714
+ border-color: transparent transparent currentColor transparent;
715
+ border-width: 0 16px 32px 16px;
716
+ }
717
+
718
+ @supports (corner-top-left-shape: bevel) and (corner-top-right-shape: bevel) {
719
+ .polycss-scene > u,
720
+ .polycss-mesh > u,
721
+ .polycss-bucket > u {
722
+ border-width: 0;
723
+ width: 32px;
724
+ height: 32px;
725
+ background-color: currentColor;
726
+ border-top-left-radius: 50% 100%;
727
+ border-top-right-radius: 50% 100%;
728
+ corner-top-left-shape: bevel;
729
+ corner-top-right-shape: bevel;
730
+ }
731
+
732
+ .polycss-scene > u.polycss-corner-shape-solid,
733
+ .polycss-mesh > u.polycss-corner-shape-solid,
734
+ .polycss-bucket > u.polycss-corner-shape-solid {
735
+ width: 16px;
736
+ height: 16px;
737
+ box-sizing: border-box;
738
+ border: 0;
739
+ background: currentColor;
740
+ border-radius: 0;
741
+ corner-top-left-shape: initial;
742
+ corner-top-right-shape: initial;
743
+ corner-bottom-right-shape: initial;
744
+ corner-bottom-left-shape: initial;
745
+ }
746
+ }
747
+ `),e.hasQ&&n.push(`
748
+ .polycss-scene q {
749
+ position: absolute;
750
+ display: block;
751
+ transform-origin: 0 0;
752
+ transform-style: preserve-3d;
753
+ margin: 0;
754
+ padding: 0;
755
+ font: inherit;
756
+ font-weight: normal;
757
+ font-style: normal;
758
+ line-height: 0;
759
+ text-decoration: none;
760
+ backface-visibility: visible;
761
+ border-color: currentColor;
762
+ pointer-events: none;
763
+ }
764
+
765
+ .polycss-scene q::before,
766
+ .polycss-scene q::after {
767
+ content: none;
768
+ }
769
+ `),e.hasTransformGizmo){let t=e.leafTags.length>0?e.leafTags:Ir;n.push(`
770
+ ${Sn(t,".polycss-mesh.polycss-transform-gizmo ")} {
771
+ backface-visibility: visible;
772
+ transition: color 150ms ease-out, border-color 150ms ease-out, background-color 150ms ease-out;
773
+ }
774
+ `)}if(e.hasTransformRing){let t=e.leafTags.length>0?e.leafTags:Ir;n.push(`
775
+ ${Sn(t,".polycss-mesh.polycss-transform-ring ")} {
776
+ --ring-inner-r: calc(var(--ring-inner-ratio, 0.92) * 50%);
777
+ --ring-outer-r: calc(var(--ring-outer-ratio, 1) * 50%);
778
+ -webkit-mask: radial-gradient(circle at 50% 50%,
779
+ transparent 0%,
780
+ transparent var(--ring-inner-r),
781
+ black var(--ring-inner-r),
782
+ black var(--ring-outer-r),
783
+ transparent var(--ring-outer-r));
784
+ mask: radial-gradient(circle at 50% 50%,
785
+ transparent 0%,
786
+ transparent var(--ring-inner-r),
787
+ black var(--ring-inner-r),
788
+ black var(--ring-outer-r),
789
+ transparent var(--ring-outer-r));
790
+ }
791
+ `)}return e.hasDynamicLighting&&n.push(Td(e)),n.map(t=>t.trim()).filter(Boolean).join(`
792
+
793
+ `)}function Fr(e){let n=e.style;return n&&typeof n.getPropertyValue=="function"?n:null}function Fs(e){let n=e.getAttribute("style");n!==null&&n.trim()===""&&e.removeAttribute("style")}function Ad(e,n){let t=e;for(;t;){let o=Fr(t)?.getPropertyValue(n).trim();if(o)return o;t=t.parentElement}return""}function wd(e,n,t){let o=Cn(e),i=Cn(n);for(let r=0;r<i.length;r++){let s=o[r],c=i[r];if(!s||!c)continue;let l=Fr(c);if(!l)continue;if(c.classList.contains("polycss-mesh")){let p=l.getPropertyValue("--origin").trim();p&&(l.setProperty("transform-origin",p),l.removeProperty("--origin"))}let d=c.tagName.toLowerCase();if(d==="s"){let p=l.getPropertyValue("--polycss-atlas-size").trim(),y=l.getPropertyValue("--polycss-atlas-width").trim()||p,g=l.getPropertyValue("--polycss-atlas-height").trim()||p;if(y&&l.setProperty("width",y),g&&l.setProperty("height",g),t.hasDynamicLighting)for(let b of bd)l.removeProperty(b);else for(let b of yd)l.removeProperty(b)}else if(d==="b"||d==="i"||d==="u"){let p=Ad(s,"--polycss-paint"),y=t.hasDynamicLighting?"":s.ownerDocument.defaultView?.getComputedStyle(s).color;y?l.setProperty("color",y):p&&!l.getPropertyValue("color")&&l.setProperty("color",p)}if(!t.hasDynamicLighting)for(let p of gd)l.removeProperty(p);if(!t.hasQ)for(let p of hd)l.removeProperty(p);l.removeProperty("will-change"),l.removeProperty("--polycss-paint"),Fs(c)}}function Md(e){for(let n of Array.from(e.querySelectorAll("script")))n.remove();for(let n of Cn(e))for(let t of Array.from(n.attributes))t.name.toLowerCase().startsWith("on")&&n.removeAttribute(t.name)}function zs(e){let n=e.trim();return n===""||n.startsWith("#")||/^data:/i.test(n)}function Ld(e,n){return/^data:/i.test(e.trim())?e.trim():Bs(e,n.baseUrl)}function Hs(e){let n=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/i.exec(e);return(n?.[2]??n?.[3]??"").trim()||null}function Rd(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\a ")}function Bs(e,n){try{return new URL(e,n).href}catch{throw new vt("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not resolve asset URL "${e}".`,e)}}function kd(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 _d(e){let n=new Uint8Array(e),t=32768,o="";for(let i=0;i<n.length;i+=t){let r=n.subarray(i,i+t);o+=String.fromCharCode(...r)}return btoa(o)}function Od(e){return/^(blob|filesystem):/i.test(e.trim())}function Dd(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 Id(e){let n=Od(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 Dd(e);throw t}}async function Vs(e,n){if(zs(e))return e;let t=Bs(e,n.baseUrl),o=n.cache.get(t);if(o)return o;let i=(async()=>{try{let r=await Id(t),s=r.type||kd(t),c=_d(await r.arrayBuffer());return`data:${s};base64,${c}`}catch{throw new vt("ASSET_INLINE_FAILED",`exportPolySceneSnapshot: could not inline asset "${t}".`,t)}})();return n.cache.set(t,i),i}async function Hr(e,n){let t=/url\(\s*(?:(["'])(.*?)\1|([^)]*?))\s*\)/gi,o="",i=0,r;for(;(r=t.exec(e))!==null;){o+=e.slice(i,r.index);let s=(r[2]??r[3]??"").trim(),c=await Vs(s,n);o+=zs(s)?r[0]:`url("${c}")`,i=t.lastIndex}return o+e.slice(i)}async function Hd(e,n){for(let t of Cn(e)){let o=t.getAttribute("style");o&&t.setAttribute("style",await Hr(o,n))}for(let t of Array.from(e.querySelectorAll("style")))t.textContent=await Hr(t.textContent??"",n)}function Fd(e){return{position:e.getPropertyValue("background-position").trim(),size:e.getPropertyValue("background-size").trim(),repeat:e.getPropertyValue("background-repeat").trim()}}function zd(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 Bd(e,n){let t=[],o=new Map,i=new Map,r=async l=>{let d=Ld(l,n),p=o.get(d);if(p)return p;let y=`a${o.size}`;return o.set(d,y),i.set(d,await Vs(l,n)),y},s=l=>{for(let[d,p]of o)if(p===l)return i.get(d)??"";return""};for(let l of Cn(e)){let d=Fr(l);if(!d||l.tagName.toLowerCase()!=="s")continue;let p=Hs(d.getPropertyValue("--polycss-atlas-url"));if(p&&!p.startsWith("#")){let v=await r(p),h="data-polycss-snapshot-atlas";l.setAttribute(h,v),d.removeProperty("--polycss-atlas-url"),t.push({attr:h,value:v,property:"--polycss-atlas-url",dataUrl:s(v)})}let y=Hs(d.getPropertyValue("background-image"));if(!y||y.startsWith("#"))continue;let g=await r(y),b="data-polycss-snapshot-bg",x=Fd(d);l.setAttribute(b,g),d.removeProperty("background"),d.removeProperty("background-image"),zd(d,x),t.push({attr:b,value:g,property:"background-image",dataUrl:s(g)}),Fs(l)}let c=new Set;return t.filter(l=>{let d=`${l.attr}|${l.value}|${l.property}`;return c.has(d)?!1:(c.add(d),!0)}).map(l=>`.polycss-scene [${l.attr}="${l.value}"] {
794
+ ${l.property}: url("${Rd(l.dataUrl)}");
795
+ }`).join(`
796
+
797
+ `)}function Vd(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Nd(e){return e.replace(/<\/style/gi,"<\\/style")}function jd(e){return e.baseURI||e.URL||e.defaultView?.location.href||"http://localhost/"}async function Ns(e){if(!xd(e))throw new vt("INVALID_TARGET","exportPolySceneSnapshot: target must be an Element.");let n=Pd(e);if(!n)throw new vt("SCENE_NOT_FOUND","exportPolySceneSnapshot: target is not inside and does not contain a rendered PolyCSS scene.");let t=e.ownerDocument,o={baseUrl:jd(t),cache:new Map},i=n.cloneNode(!0),r=vd(i);wd(n,i,r),Md(i);let s=await Bd(i,o);await Hd(i,o);let c=await Hr([Ed(r),s].filter(Boolean).join(`
798
+
799
+ `),o);return["<!doctype html>","<html>","<head>",'<meta charset="utf-8">',t.title?`<title>${Vd(t.title)}</title>`:"",`<style>${Nd(c)}</style>`,"</head>","<body>",i.outerHTML,"</body>","</html>"].filter(Boolean).join("")}import{boxPolygons as $d,planePolygons as Wd,ringPolygons as Ud,octahedronPolygons as Gd,spherePolygons as Yd,tetrahedronPolygons as Xd,icosahedronPolygons as qd,dodecahedronPolygons as Zd,cylinderPolygons as Qd,conePolygons as Kd,torusPolygons as Jd}from"@layoutit/polycss-core";function Je(e){return{polygons:e,objectUrls:[],warnings:[],dispose:()=>{}}}function js(e={}){return Je($d(e))}function $s(e){return Je(Wd(e))}function Ws(e){return Je(Ud(e))}function Us(e){return Je(Gd(e))}function Gs(e={}){return Je(Yd(e))}function Ys(e={}){return Je(Xd(e))}function Xs(e={}){return Je(qd(e))}function qs(e={}){return Je(Zd(e))}function Zs(e={}){return Je(Qd(e))}function Qs(e={}){return Je(Kd(e))}function Ks(e={}){return Je(Jd(e))}import{boxPolygons as ep,planePolygons as tp,ringPolygons as np,octahedronPolygons as op,spherePolygons as rp,tetrahedronPolygons as ip,icosahedronPolygons as sp,dodecahedronPolygons as ap,cylinderPolygons as lp,conePolygons as cp,torusPolygons as up,computeSceneBbox as dp}from"@layoutit/polycss-core";var pp=typeof HTMLElement<"u"?HTMLElement:class{};function mp(e){return e.closest("poly-scene")??null}function ve(e,n,t){let o=e.getAttribute(n);if(!o)return t;let i=parseFloat(o);return Number.isFinite(i)?i:t}function et(e,n,t){return e.getAttribute(n)??t}function kt(e,n){let t=e.getAttribute(n);if(!t)return;let o=t.split(",").map(i=>parseFloat(i.trim()));if(!(o.length!==3||o.some(i=>!Number.isFinite(i))))return[o[0],o[1],o[2]]}function fp(e){if(e.length===0)return e;let n=dp(e),t=(n.min[0]+n.max[0])/2,o=(n.min[1]+n.max[1])/2,i=(n.min[2]+n.max[2])/2;if(t===0&&o===0&&i===0)return e;let r=s=>[s[0]-t,s[1]-o,s[2]-i];return e.map(s=>({...s,vertices:s.vertices.map(r)}))}var Ve=class extends pp{constructor(){super(...arguments);this._handle=null}connectedCallback(){this._mount()}disconnectedCallback(){this._tearDown()}attributeChangedCallback(t,o,i){if(o!==i&&this._handle){if(t==="position"||t==="scale"||t==="rotation"||t==="cast-shadow"||t==="receive-shadow"){this._handle.setTransform({position:kt(this,"position"),scale:(()=>{let r=this.getAttribute("scale");if(!r)return;if(r.includes(","))return kt(this,"scale");let s=parseFloat(r);return Number.isFinite(s)?s:void 0})(),rotation:kt(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=mp(this);if(!t)return;let o=t.getScene?.();if(!o)return;let i=this.buildPolygons();this.hasAttribute("auto-center")&&(i=fp(i));let r={polygons:i,objectUrls:[],warnings:[],dispose:()=>{}};this._handle=o.add(r,{position:kt(this,"position"),scale:(()=>{let s=this.getAttribute("scale");if(!s)return;if(s.includes(","))return kt(this,"scale");let c=parseFloat(s);return Number.isFinite(c)?c:void 0})(),rotation:kt(this,"rotation"),castShadow:this.hasAttribute("cast-shadow"),receiveShadow:this.hasAttribute("receive-shadow"),excludeFromAutoCenter:this.hasAttribute("exclude-from-auto-center"),merge:!1})}},xo=class extends Ve{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("size"),t=n?parseFloat(n):void 0;return ep({size:t!==void 0&&Number.isFinite(t)?t:void 0,color:et(this,"color")})}},Po=class extends Ve{static get observedAttributes(){return["axis","size","offset","color","auto-center","position","scale","rotation","cast-shadow","receive-shadow"]}buildPolygons(){let n=ve(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("offset"),i=o===null?0:parseFloat(o);return tp({axis:t,size:ve(this,"size",.4),offset:Number.isFinite(i)?i:0,color:et(this,"color")})}},vo=class extends Ve{static get observedAttributes(){return["axis","radius","segments","half-thickness","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=ve(this,"axis",2),t=n===0||n===1||n===2?n:2,o=this.getAttribute("half-thickness");return np({axis:t,radius:ve(this,"radius",50),segments:ve(this,"segments",32),halfThickness:o?parseFloat(o):void 0,color:et(this,"color")})}},So=class extends Ve{static get observedAttributes(){return["size","color","center","auto-center","position","scale","rotation"]}buildPolygons(){return op({center:kt(this,"center")??[0,0,0],size:ve(this,"size",50),color:et(this,"color")})}},Co=class extends Ve{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return ip({size:ve(this,"size",100),color:et(this,"color")})}},To=class extends Ve{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return sp({size:ve(this,"size",100),color:et(this,"color")})}},Eo=class extends Ve{static get observedAttributes(){return["size","color","auto-center","position","scale","rotation"]}buildPolygons(){return ap({size:ve(this,"size",100),color:et(this,"color")})}},Ao=class extends Ve{static get observedAttributes(){return["radius","subdivisions","color","auto-center","position","scale","rotation"]}buildPolygons(){return rp({radius:ve(this,"radius",50),subdivisions:ve(this,"subdivisions",1),color:et(this,"color")})}},wo=class extends Ve{static get observedAttributes(){return["radius","radius-top","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){let n=this.getAttribute("radius-top");return lp({radius:ve(this,"radius",50),radiusTop:n?parseFloat(n):void 0,height:ve(this,"height",100),radialSegments:ve(this,"radial-segments",12),color:et(this,"color")})}},Mo=class extends Ve{static get observedAttributes(){return["radius","height","radial-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return cp({radius:ve(this,"radius",50),height:ve(this,"height",100),radialSegments:ve(this,"radial-segments",12),color:et(this,"color")})}},Lo=class extends Ve{static get observedAttributes(){return["radius","tube","radial-segments","tubular-segments","color","auto-center","position","scale","rotation"]}buildPolygons(){return up({radius:ve(this,"radius",50),tube:ve(this,"tube",15),radialSegments:ve(this,"radial-segments",12),tubularSegments:ve(this,"tubular-segments",16),color:et(this,"color")})}};me(le,Ch);import*as Ch from"@layoutit/polycss-core";import{AmbientLight as Rh,DirectionalLight as kh,Euler as _h,Object3D as Oh,OrthographicCamera as Dh,PerspectiveCamera as Ih,PointLight as Hh,Vector3 as Fh,polyToThreeDirection as zh,polyToThreePoint as Bh,threeToPolyDirection as Vh,threeToPolyPoint as Nh,transformPointToPoly as jh,transformPolygonsToPoly as $h}from"@layoutit/polycss-core/three";import{boxPolygons as Uh,loadMesh as Gh,octahedronPolygons as Yh,planePolygons as Xh,spherePolygons as qh,tetrahedronPolygons as Zh,icosahedronPolygons as Qh,dodecahedronPolygons as Kh,cylinderPolygons as Jh,conePolygons as ey,torusPolygons as ty}from"@layoutit/polycss-core";function wp(e,n={}){return Pt(e.toPolyCameraState(n))}function Mp(e,n={}){return st(e.toPolyCameraState(n))}function wh(e,n){let t=n.camera instanceof Ap?wp(n.camera,n.cameraOptions):Mp(n.camera,n.cameraOptions),{camera:o,cameraOptions:i,polygons:r,meshes:s,...c}=n,l=Ut(e,{...c,textureLighting:c.textureLighting??"baked",camera:t});if(s)for(let d of s)l.add(Js(d.polygons),{merge:!1,...d.transform});else l.add(Js(r??[]),{merge:!1});return l}function Js(e){return{polygons:e,objectUrls:[],warnings:[],dispose(){}}}export{Rh as AmbientLight,kh as DirectionalLight,_h as Euler,Oh as Object3D,Dh as OrthographicCamera,Ih as PerspectiveCamera,Hh as PointLight,Fh as Vector3,Uh as boxPolygons,ey as conePolygons,st as createPolyOrthographicCamera,Mp as createPolyOrthographicCameraFromThree,Pt as createPolyPerspectiveCamera,wp as createPolyPerspectiveCameraFromThree,Ut as createPolyScene,Jh as cylinderPolygons,Kh as dodecahedronPolygons,Qh as icosahedronPolygons,Gh as loadMesh,wh as mountPolyThreeScene,Yh as octahedronPolygons,Xh as planePolygons,zh as polyToThreeDirection,Bh as polyToThreePoint,qh as spherePolygons,Zh as tetrahedronPolygons,Vh as threeToPolyDirection,Nh as threeToPolyPoint,ty as torusPolygons,jh as transformPointToPoly,$h as transformPolygonsToPoly};