Web-based prototype for generating a lattice structure inside a closed 2D shape and viewing it as a 3D mesh. The shape is drawn as a closed Bezier path on a 300 mm square board, and the lattice is built from that outline. Three cell types are available: Voronoi cells from a regularized point set, Delaunay triangles, and an adaptive quadtree grid. Cell size, strut width, rounding, height and rim width can be set as constants or driven by grayscale maps painted with a brush. The material is the union of struts and rim, clipped to the shape, and the result is extracted as contour loops and turned into a mesh with a height field. The prototype shows the structure in a 2D outline view and a shaded 3D view with orbit controls. It can be used for design exploration, teaching, prototyping and 3D printing, and it exports STL and SVG files and saves or loads the full state as JSON.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<title>MAP:LATTICE v0.1</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:#fff;color:#111;font:11px/1.4 "Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;overflow:hidden}
#app{display:grid;grid-template-columns:284px minmax(0,1fr) minmax(0,1fr);grid-template-rows:42px minmax(0,1fr);height:100vh;width:100vw}
header{grid-column:1/4;display:flex;align-items:center;gap:6px;padding:0 12px;border-bottom:1px solid #e4e4e4;background:#fff}
.logo{letter-spacing:.14em;font-size:12px}
.ver{color:#aaa;margin-right:14px}
.sp{flex:1}
#status{color:#888;margin-right:8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:46vw}
button{font:inherit;background:#fff;color:#111;border:1px solid #111;padding:3px 9px;cursor:pointer;border-radius:0}
button:hover{background:#f1f1f1}
button.on{background:#ececec;font-weight:600}
button.ghost{border-color:#cfcfcf}
button.ghost:hover{border-color:#111}
button.sm{padding:1px 6px}
button:disabled{opacity:.35;cursor:default}
select,input[type=number],input[type=text]{font:inherit;border:1px solid #cfcfcf;background:#fff;color:#111;padding:2px 4px;border-radius:0;min-width:0}
select:focus,input:focus{outline:none;border-color:#111}
aside{border-right:1px solid #e4e4e4;overflow:auto;background:#fff}
.grp{padding:10px 12px 11px;border-bottom:1px solid #eee}
.grp h3{margin:0 0 7px;font-size:9.5px;letter-spacing:.09em;text-transform:uppercase;color:#888;font-weight:500}
.row{display:flex;align-items:center;gap:6px;margin:5px 0}
.row>label.k{width:78px;flex:none;color:#666}
.row .num{width:42px;text-align:right;color:#666;flex:none;font-variant-numeric:tabular-nums}
.note{margin:0 0 8px;color:#777;line-height:1.55}
.mut{color:#888}
.seg{display:flex}
.seg button{flex:1;border-right-width:0}
.seg button:last-child{border-right-width:1px}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:16px;background:transparent;margin:0;min-width:0}
input[type=range]::-webkit-slider-runnable-track{height:1px;background:#bbb}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:11px;height:11px;border-radius:50%;background:#fff;border:1px solid #111;margin-top:-5px}
input[type=range]::-moz-range-track{height:1px;background:#bbb}
input[type=range]::-moz-range-thumb{width:9px;height:9px;border-radius:50%;background:#fff;border:1px solid #111}
input[type=range].val::-webkit-slider-runnable-track{height:9px;background:linear-gradient(90deg,#000,#fff);border:1px solid #bbb}
input[type=range].val::-webkit-slider-thumb{margin-top:-3px;width:13px;height:13px}
input[type=range].val::-moz-range-track{height:9px;background:linear-gradient(90deg,#000,#fff);border:1px solid #bbb}
.maps{margin-bottom:6px}
.mrow{display:flex;align-items:center;gap:7px;padding:4px;border:1px solid transparent;cursor:pointer}
.mrow:hover{background:#fafafa}
.mrow.on{border-color:#111}
.mrow canvas{width:40px;height:40px;border:1px solid #ddd;flex:none;background:#fff}
.mrow input{flex:1;border-color:transparent;background:transparent}
.mrow input:hover{border-color:#ddd}
.prm{margin:0 0 10px;padding-bottom:9px;border-bottom:1px dotted #e4e4e4}
.prm:last-child{border-bottom:0;margin-bottom:0}
.ph{display:flex;align-items:center;gap:6px;margin-bottom:2px}
.pl{flex:1;font-weight:600}
.ph select{width:98px}
.pv{display:flex;align-items:center;gap:6px}
.pv .t{width:24px;color:#999;flex:none}
.pv .num{width:34px;text-align:right;color:#666;flex:none;font-variant-numeric:tabular-nums}
#st2d{position:relative;min-width:0;min-height:0;background:#fff;overflow:hidden}
#cv{position:absolute;inset:0;width:100%;height:100%;touch-action:none;display:block}
#hint{position:absolute;left:10px;bottom:8px;color:#999;pointer-events:none;font-variant-numeric:tabular-nums}
#st3d{position:relative;min-width:0;min-height:0;border-left:1px solid #e4e4e4;background:#fff}
#gl{position:absolute;inset:0}
#gl canvas{width:100%;height:100%;display:block}
.tb3{position:absolute;right:10px;top:10px;display:flex;gap:4px}
#empty3{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#bbb;pointer-events:none;letter-spacing:.08em;text-transform:uppercase;font-size:10px}
.ovl{position:absolute;left:0;top:0;right:0;pointer-events:none}
@media (max-width:900px){#app{grid-template-columns:230px 1fr}#st3d{display:none}header{grid-column:1/3}}
</style>
<script>/* Delaunator 5.0.1 (ISC) */!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t="undefined"!=typeof globalThis?globalThis:t||self).Delaunator=i()}(this,(function(){"use strict";const t=11102230246251565e-32,i=134217729,s=(3+8*t)*t;function e(t,i,s,e,n){let h,r,l,o,a=i[0],f=e[0],c=0,u=0;f>a==f>-a?(h=a,a=i[++c]):(h=f,f=e[++u]);let _=0;if(c<t&&u<s)for(f>a==f>-a?(r=a+h,l=h-(r-a),a=i[++c]):(r=f+h,l=h-(r-f),f=e[++u]),h=r,0!==l&&(n[_++]=l);c<t&&u<s;)f>a==f>-a?(r=h+a,o=r-h,l=h-(r-o)+(a-o),a=i[++c]):(r=h+f,o=r-h,l=h-(r-o)+(f-o),f=e[++u]),h=r,0!==l&&(n[_++]=l);for(;c<t;)r=h+a,o=r-h,l=h-(r-o)+(a-o),a=i[++c],h=r,0!==l&&(n[_++]=l);for(;u<s;)r=h+f,o=r-h,l=h-(r-o)+(f-o),f=e[++u],h=r,0!==l&&(n[_++]=l);return 0===h&&0!==_||(n[_++]=h),_}function n(t){return new Float64Array(t)}const h=22204460492503146e-32,r=11093356479670487e-47,l=n(4),o=n(8),a=n(12),f=n(16),c=n(4);function u(t,n,u,_,d,g){const y=(n-g)*(u-d),w=(t-d)*(_-g),b=y-w,A=Math.abs(y+w);return Math.abs(b)>=33306690738754716e-32*A?b:-function(t,n,u,_,d,g,y){let w,b,A,k,M,p,x,S,T,z,U,m,K,L,v,F,P,E;const H=t-d,I=u-d,N=n-g,j=_-g;L=H*j,p=i*H,x=p-(p-H),S=H-x,p=i*j,T=p-(p-j),z=j-T,v=S*z-(L-x*T-S*T-x*z),F=N*I,p=i*N,x=p-(p-N),S=N-x,p=i*I,T=p-(p-I),z=I-T,P=S*z-(F-x*T-S*T-x*z),U=v-P,M=v-U,l[0]=v-(U+M)+(M-P),m=L+U,M=m-L,K=L-(m-M)+(U-M),U=K-F,M=K-U,l[1]=K-(U+M)+(M-F),E=m+U,M=E-m,l[2]=m-(E-M)+(U-M),l[3]=E;let q=function(t,i){let s=i[0];for(let e=1;e<t;e++)s+=i[e];return s}(4,l),D=h*y;if(q>=D||-q>=D)return q;if(M=t-H,w=t-(H+M)+(M-d),M=u-I,A=u-(I+M)+(M-d),M=n-N,b=n-(N+M)+(M-g),M=_-j,k=_-(j+M)+(M-g),0===w&&0===b&&0===A&&0===k)return q;if(D=r*y+s*Math.abs(q),q+=H*k+j*w-(N*A+I*b),q>=D||-q>=D)return q;L=w*j,p=i*w,x=p-(p-w),S=w-x,p=i*j,T=p-(p-j),z=j-T,v=S*z-(L-x*T-S*T-x*z),F=b*I,p=i*b,x=p-(p-b),S=b-x,p=i*I,T=p-(p-I),z=I-T,P=S*z-(F-x*T-S*T-x*z),U=v-P,M=v-U,c[0]=v-(U+M)+(M-P),m=L+U,M=m-L,K=L-(m-M)+(U-M),U=K-F,M=K-U,c[1]=K-(U+M)+(M-F),E=m+U,M=E-m,c[2]=m-(E-M)+(U-M),c[3]=E;const B=e(4,l,4,c,o);L=H*k,p=i*H,x=p-(p-H),S=H-x,p=i*k,T=p-(p-k),z=k-T,v=S*z-(L-x*T-S*T-x*z),F=N*A,p=i*N,x=p-(p-N),S=N-x,p=i*A,T=p-(p-A),z=A-T,P=S*z-(F-x*T-S*T-x*z),U=v-P,M=v-U,c[0]=v-(U+M)+(M-P),m=L+U,M=m-L,K=L-(m-M)+(U-M),U=K-F,M=K-U,c[1]=K-(U+M)+(M-F),E=m+U,M=E-m,c[2]=m-(E-M)+(U-M),c[3]=E;const C=e(B,o,4,c,a);L=w*k,p=i*w,x=p-(p-w),S=w-x,p=i*k,T=p-(p-k),z=k-T,v=S*z-(L-x*T-S*T-x*z),F=b*A,p=i*b,x=p-(p-b),S=b-x,p=i*A,T=p-(p-A),z=A-T,P=S*z-(F-x*T-S*T-x*z),U=v-P,M=v-U,c[0]=v-(U+M)+(M-P),m=L+U,M=m-L,K=L-(m-M)+(U-M),U=K-F,M=K-U,c[1]=K-(U+M)+(M-F),E=m+U,M=E-m,c[2]=m-(E-M)+(U-M),c[3]=E;const G=e(C,a,4,c,f);return f[G-1]}(t,n,u,_,d,g,A)}const _=Math.pow(2,-52),d=new Uint32Array(512);class g{static from(t,i=M,s=p){const e=t.length,n=new Float64Array(2*e);for(let h=0;h<e;h++){const e=t[h];n[2*h]=i(e),n[2*h+1]=s(e)}return new g(n)}constructor(t){const i=t.length>>1;if(i>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const s=Math.max(2*i-5,0);this._triangles=new Uint32Array(3*s),this._halfedges=new Int32Array(3*s),this._hashSize=Math.ceil(Math.sqrt(i)),this._hullPrev=new Uint32Array(i),this._hullNext=new Uint32Array(i),this._hullTri=new Uint32Array(i),this._hullHash=new Int32Array(this._hashSize),this._ids=new Uint32Array(i),this._dists=new Float64Array(i),this.update()}update(){const{coords:t,_hullPrev:i,_hullNext:s,_hullTri:e,_hullHash:n}=this,h=t.length>>1;let r=1/0,l=1/0,o=-1/0,a=-1/0;for(let i=0;i<h;i++){const s=t[2*i],e=t[2*i+1];s<r&&(r=s),e<l&&(l=e),s>o&&(o=s),e>a&&(a=e),this._ids[i]=i}const f=(r+o)/2,c=(l+a)/2;let d,g,w;for(let i=0,s=1/0;i<h;i++){const e=y(f,c,t[2*i],t[2*i+1]);e<s&&(d=i,s=e)}const k=t[2*d],M=t[2*d+1];for(let i=0,s=1/0;i<h;i++){if(i===d)continue;const e=y(k,M,t[2*i],t[2*i+1]);e<s&&e>0&&(g=i,s=e)}let p=t[2*g],x=t[2*g+1],S=1/0;for(let i=0;i<h;i++){if(i===d||i===g)continue;const s=b(k,M,p,x,t[2*i],t[2*i+1]);s<S&&(w=i,S=s)}let T=t[2*w],z=t[2*w+1];if(S===1/0){for(let i=0;i<h;i++)this._dists[i]=t[2*i]-t[0]||t[2*i+1]-t[1];A(this._ids,this._dists,0,h-1);const i=new Uint32Array(h);let s=0;for(let t=0,e=-1/0;t<h;t++){const n=this._ids[t],h=this._dists[n];h>e&&(i[s++]=n,e=h)}return this.hull=i.subarray(0,s),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(u(k,M,p,x,T,z)<0){const t=g,i=p,s=x;g=w,p=T,x=z,w=t,T=i,z=s}const U=function(t,i,s,e,n,h){const r=s-t,l=e-i,o=n-t,a=h-i,f=r*r+l*l,c=o*o+a*a,u=.5/(r*a-l*o);return{x:t+(a*f-l*c)*u,y:i+(r*c-o*f)*u}}(k,M,p,x,T,z);this._cx=U.x,this._cy=U.y;for(let i=0;i<h;i++)this._dists[i]=y(t[2*i],t[2*i+1],U.x,U.y);A(this._ids,this._dists,0,h-1),this._hullStart=d;let m=3;s[d]=i[w]=g,s[g]=i[d]=w,s[w]=i[g]=d,e[d]=0,e[g]=1,e[w]=2,n.fill(-1),n[this._hashKey(k,M)]=d,n[this._hashKey(p,x)]=g,n[this._hashKey(T,z)]=w,this.trianglesLen=0,this._addTriangle(d,g,w,-1,-1,-1);for(let h,r,l=0;l<this._ids.length;l++){const o=this._ids[l],a=t[2*o],f=t[2*o+1];if(l>0&&Math.abs(a-h)<=_&&Math.abs(f-r)<=_)continue;if(h=a,r=f,o===d||o===g||o===w)continue;let c=0;for(let t=0,i=this._hashKey(a,f);t<this._hashSize&&(c=n[(i+t)%this._hashSize],-1===c||c===s[c]);t++);c=i[c];let y,b=c;for(;y=s[b],u(a,f,t[2*b],t[2*b+1],t[2*y],t[2*y+1])>=0;)if(b=y,b===c){b=-1;break}if(-1===b)continue;let A=this._addTriangle(b,o,s[b],-1,-1,e[b]);e[o]=this._legalize(A+2),e[b]=A,m++;let k=s[b];for(;y=s[k],u(a,f,t[2*k],t[2*k+1],t[2*y],t[2*y+1])<0;)A=this._addTriangle(k,o,y,e[o],-1,e[k]),e[o]=this._legalize(A+2),s[k]=k,m--,k=y;if(b===c)for(;y=i[b],u(a,f,t[2*y],t[2*y+1],t[2*b],t[2*b+1])<0;)A=this._addTriangle(y,o,b,-1,e[b],e[y]),this._legalize(A+2),e[y]=A,s[b]=b,m--,b=y;this._hullStart=i[o]=b,s[b]=i[k]=o,s[o]=k,n[this._hashKey(a,f)]=o,n[this._hashKey(t[2*b],t[2*b+1])]=b}this.hull=new Uint32Array(m);for(let t=0,i=this._hullStart;t<m;t++)this.hull[t]=i,i=s[i];this.triangles=this._triangles.subarray(0,this.trianglesLen),this.halfedges=this._halfedges.subarray(0,this.trianglesLen)}_hashKey(t,i){return Math.floor(function(t,i){const s=t/(Math.abs(t)+Math.abs(i));return(i>0?3-s:1+s)/4}(t-this._cx,i-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:i,_halfedges:s,coords:e}=this;let n=0,h=0;for(;;){const r=s[t],l=t-t%3;if(h=l+(t+2)%3,-1===r){if(0===n)break;t=d[--n];continue}const o=r-r%3,a=l+(t+1)%3,f=o+(r+2)%3,c=i[h],u=i[t],_=i[a],g=i[f];if(w(e[2*c],e[2*c+1],e[2*u],e[2*u+1],e[2*_],e[2*_+1],e[2*g],e[2*g+1])){i[t]=g,i[r]=c;const e=s[f];if(-1===e){let i=this._hullStart;do{if(this._hullTri[i]===f){this._hullTri[i]=t;break}i=this._hullPrev[i]}while(i!==this._hullStart)}this._link(t,e),this._link(r,s[h]),this._link(h,f);const l=o+(r+1)%3;n<d.length&&(d[n++]=l)}else{if(0===n)break;t=d[--n]}}return h}_link(t,i){this._halfedges[t]=i,-1!==i&&(this._halfedges[i]=t)}_addTriangle(t,i,s,e,n,h){const r=this.trianglesLen;return this._triangles[r]=t,this._triangles[r+1]=i,this._triangles[r+2]=s,this._link(r,e),this._link(r+1,n),this._link(r+2,h),this.trianglesLen+=3,r}}function y(t,i,s,e){const n=t-s,h=i-e;return n*n+h*h}function w(t,i,s,e,n,h,r,l){const o=t-r,a=i-l,f=s-r,c=e-l,u=n-r,_=h-l,d=f*f+c*c,g=u*u+_*_;return o*(c*g-d*_)-a*(f*g-d*u)+(o*o+a*a)*(f*_-c*u)<0}function b(t,i,s,e,n,h){const r=s-t,l=e-i,o=n-t,a=h-i,f=r*r+l*l,c=o*o+a*a,u=.5/(r*a-l*o),_=(a*f-l*c)*u,d=(r*c-o*f)*u;return _*_+d*d}function A(t,i,s,e){if(e-s<=20)for(let n=s+1;n<=e;n++){const e=t[n],h=i[e];let r=n-1;for(;r>=s&&i[t[r]]>h;)t[r+1]=t[r--];t[r+1]=e}else{let n=s+1,h=e;k(t,s+e>>1,n),i[t[s]]>i[t[e]]&&k(t,s,e),i[t[n]]>i[t[e]]&&k(t,n,e),i[t[s]]>i[t[n]]&&k(t,s,n);const r=t[n],l=i[r];for(;;){do{n++}while(i[t[n]]<l);do{h--}while(i[t[h]]>l);if(h<n)break;k(t,n,h)}t[s+1]=t[h],t[h]=r,e-n+1>=h-s?(A(t,i,n,e),A(t,i,s,h-1)):(A(t,i,s,h-1),A(t,i,n,e))}}function k(t,i,s){const e=t[i];t[i]=t[s],t[s]=e}function M(t){return t[0]}function p(t){return t[1]}return g}));
</script>
<script type="importmap">{"imports":{"three":"https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js","three/addons/":"https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"}}</script>
</head>
<body>
<div id="app">
<header>
<b class="logo">MAP:LATTICE</b><span class="ver">v0.1</span>
<nav id="tabs"></nav>
<span class="sp"></span>
<span id="status"></span>
<button id="bSave" class="ghost">Speichern</button>
<button id="bLoad" class="ghost">Laden</button>
<input type="file" id="fLoad" accept=".json,application/json" hidden>
</header>
<aside id="panel"></aside>
<main id="st2d"><canvas id="cv"></canvas><div id="hint"></div></main>
<section id="st3d"><div id="gl"></div><div class="tb3"><button id="bView" class="ghost">Ansicht</button><button id="bTop" class="ghost">Oben</button></div><div id="empty3">Form schließen → Struktur erscheint hier</div></section>
</div>
<script type="module">
import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';
// <core>
/* =====================================================================
KERN (DOM-frei): Bezier-Form · Maps · Parameter · Zellen · SDF · Mesh
Welt-Einheit = mm, y zeigt auf dem Bildschirm nach unten.
===================================================================== */
const BOARD=300, HALF=BOARD/2, MN=320, CELL=BOARD/MN;
const clamp=(v,a,b)=>v<a?a:v>b?b:v, lerp=(a,b,t)=>a+(b-a)*t;
const MAXCELLS=12000;
/* ---- Maps: Float-Raster 0..1 (schwarz..weiß) über die Arbeitsfläche ---- */
let maps=[], nextMapId=1;
function newMap(name){
const m={id:nextMapId++,name:'',data:new Float32Array(MN*MN).fill(0.5),dirty:true,cv:null,thumb:null};
m.name=name||('Map '+m.id); maps.push(m); return m;
}
const mapById=id=>maps.find(m=>m.id===id)||null;
function sampleMap(m,x,y){
const gx=clamp((x+HALF)/CELL-0.5,0,MN-1.001), gy=clamp((y+HALF)/CELL-0.5,0,MN-1.001);
const ix=gx|0, iy=gy|0, fx=gx-ix, fy=gy-iy, d=m.data, i=iy*MN+ix;
return (d[i]*(1-fx)+d[i+1]*fx)*(1-fy)+(d[i+MN]*(1-fx)+d[i+MN+1]*fx)*fy;
}
/* ---- Parameter: konstant oder per Map zwischen min..max (weiß = max) ---- */
const PARAMS={
size: {label:'Zellgröße', lo:2.5,hi:40, step:.1, src:null,val:10, min:6, max:16, inv:false},
strut: {label:'Stegbreite',lo:.3, hi:8, step:.05,src:null,val:1.6,min:.8, max:3, inv:false},
round: {label:'Rundung', lo:0, hi:12, step:.1, src:null,val:2.5,min:.5, max:6, inv:false},
height:{label:'Höhe', lo:.4, hi:15, step:.1, src:null,val:3, min:1.5,max:6, inv:false},
rim: {label:'Rand', lo:0, hi:12, step:.1, src:null,val:1.6,min:1, max:4, inv:false},
};
const ST={type:'voronoi',reg:0.6,seed:7,angle:0,tri:false,quality:0.4,live:true};
function evalParam(p,x,y){
if(p.src==null) return p.val;
const m=mapById(p.src); if(!m) return p.val;
let t=sampleMap(m,x,y); if(p.inv) t=1-t;
return p.min+(p.max-p.min)*t;
}
function paramRange(p){
if(p.src==null||!mapById(p.src)) return [p.val,p.val];
return [Math.min(p.min,p.max),Math.max(p.min,p.max)];
}
function paramField(p,g){
const a=new Float32Array(g.nx*g.ny), m=p.src==null?null:mapById(p.src);
if(!m){a.fill(p.val);return a;}
for(let iy=0,k=0;iy<g.ny;iy++){const y=g.y0+iy*g.res; for(let ix=0;ix<g.nx;ix++,k++){a[k]=evalParam(p,g.x0+ix*g.res,y);}}
return a;
}
/* ---- Form: geschlossener Bezier-Pfad ---- */
let shape={pts:[],closed:false};
let poly=[]; // geflattetes Polygon [[x,y],…]
function bezPt(a,b,t){
const u=1-t,c1x=a.x+a.ox,c1y=a.y+a.oy,c2x=b.x+b.ix,c2y=b.y+b.iy;
const w0=u*u*u,w1=3*u*u*t,w2=3*u*t*t,w3=t*t*t;
return [w0*a.x+w1*c1x+w2*c2x+w3*b.x, w0*a.y+w1*c1y+w2*c2y+w3*b.y];
}
function flattenShape(sh,n=18){
const P=sh.pts,N=P.length,out=[]; if(N<2) return P.map(p=>[p.x,p.y]);
const segs=sh.closed?N:N-1;
for(let i=0;i<segs;i++){
const a=P[i],b=P[(i+1)%N];
const straight=!a.ox&&!a.oy&&!b.ix&&!b.iy, steps=straight?1:n;
for(let k=0;k<steps;k++) out.push(bezPt(a,b,k/steps));
}
if(!sh.closed) out.push([P[N-1].x,P[N-1].y]);
return out;
}
function polyArea(P){let a=0;for(let i=0,n=P.length;i<n;i++){const p=P[i],q=P[(i+1)%n];a+=p[0]*q[1]-q[0]*p[1];}return a/2;}
function bboxOf(P){let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9;for(const p of P){if(p[0]<x0)x0=p[0];if(p[0]>x1)x1=p[0];if(p[1]<y0)y0=p[1];if(p[1]>y1)y1=p[1];}return{x0,y0,x1,y1};}
function pipPoly(P,x,y){let c=false;for(let i=0,j=P.length-1;i<P.length;j=i++){const a=P[i],b=P[j];if((a[1]>y)!==(b[1]>y)&&x<(b[0]-a[0])*(y-a[1])/(b[1]-a[1])+a[0])c=!c;}return c;}
/* ---- Zufall ---- */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
/* ---- Distanzfeld der Form (positiv innen), exakt im Band um die Kontur ---- */
function shapeSDF(P,g,band){
const {x0,y0,nx,ny,res}=g,N=nx*ny,n=P.length;
const dist=new Float32Array(N).fill(band), inside=new Uint8Array(N), xs=[];
for(let iy=0;iy<ny;iy++){
const y=y0+iy*res; xs.length=0;
for(let i=0;i<n;i++){const a=P[i],b=P[(i+1)%n]; if((a[1]<=y)!==(b[1]<=y)) xs.push(a[0]+(y-a[1])/(b[1]-a[1])*(b[0]-a[0]));}
xs.sort((p,q)=>p-q);
for(let k=0;k+1<xs.length;k+=2){
const i0=Math.max(0,Math.ceil((xs[k]-x0)/res)), i1=Math.min(nx-1,Math.floor((xs[k+1]-x0)/res));
for(let ix=i0;ix<=i1;ix++) inside[iy*nx+ix]=1;
}
}
for(let i=0;i<n;i++){
const a=P[i],b=P[(i+1)%n],ex=b[0]-a[0],ey=b[1]-a[1],l2=ex*ex+ey*ey||1e-12;
const ia=Math.max(0,Math.floor((Math.min(a[0],b[0])-band-x0)/res)), ib=Math.min(nx-1,Math.ceil((Math.max(a[0],b[0])+band-x0)/res));
const ja=Math.max(0,Math.floor((Math.min(a[1],b[1])-band-y0)/res)), jb=Math.min(ny-1,Math.ceil((Math.max(a[1],b[1])+band-y0)/res));
for(let iy=ja;iy<=jb;iy++){const y=y0+iy*res;
for(let ix=ia;ix<=ib;ix++){
const x=x0+ix*res; let t=((x-a[0])*ex+(y-a[1])*ey)/l2; t=t<0?0:t>1?1:t;
const dx=x-(a[0]+t*ex),dy=y-(a[1]+t*ey),d=Math.sqrt(dx*dx+dy*dy),k=iy*nx+ix;
if(d<dist[k]) dist[k]=d;
}}
}
for(let i=0;i<N;i++) if(!inside[i]) dist[i]=-dist[i];
return dist;
}
/* ---- Punktverteilung: Poisson-Disk mit variablem Radius (Bridson) ---- */
function poissonSeeds(dom,hf,rng){
const RF=0.85; let hmin=1e9,hmax=0; const sx=24;
for(let j=0;j<=sx;j++)for(let i=0;i<=sx;i++){const h=hf(lerp(dom.x0,dom.x1,i/sx),lerp(dom.y0,dom.y1,j/sx));if(h<hmin)hmin=h;if(h>hmax)hmax=h;}
const rmin=hmin*RF,rmax=hmax*RF,cs=rmin/Math.SQRT2;
const gw=Math.ceil((dom.x1-dom.x0)/cs)+1, gh=Math.ceil((dom.y1-dom.y0)/cs)+1;
const grid=new Int32Array(gw*gh).fill(-1), X=[],Y=[],R=[],act=[];
const ok=(x,y,r)=>{
if(x<dom.x0||x>dom.x1||y<dom.y0||y>dom.y1) return false;
const gi=((x-dom.x0)/cs)|0,gj=((y-dom.y0)/cs)|0,w=Math.ceil((r+rmax)/2/cs);
for(let j=Math.max(0,gj-w);j<=Math.min(gh-1,gj+w);j++)for(let i=Math.max(0,gi-w);i<=Math.min(gw-1,gi+w);i++){
const q=grid[j*gw+i]; if(q<0)continue; const dx=X[q]-x,dy=Y[q]-y,rr=(r+R[q])*0.5; if(dx*dx+dy*dy<rr*rr) return false;
} return true;
};
const add=(x,y,r)=>{const id=X.length;X.push(x);Y.push(y);R.push(r);grid[(((y-dom.y0)/cs)|0)*gw+(((x-dom.x0)/cs)|0)]=id;act.push(id);};
{const x=lerp(dom.x0,dom.x1,rng()),y=lerp(dom.y0,dom.y1,rng());add(x,y,hf(x,y)*RF);}
while(act.length){
const ai=(rng()*act.length)|0,id=act[ai]; let found=false;
for(let k=0;k<30;k++){
const a=rng()*6.283185307,d=R[id]*(1+rng()),x=X[id]+Math.cos(a)*d,y=Y[id]+Math.sin(a)*d,r=hf(x,y)*RF;
if(ok(x,y,r)){add(x,y,r);found=true;break;}
}
if(!found){act[ai]=act[act.length-1];act.pop();}
}
const P=new Float64Array(X.length*2); for(let i=0;i<X.length;i++){P[2*i]=X[i];P[2*i+1]=Y[i];}
return P;
}
/* ---- Regularisieren (DistMesh-Prinzip): Kanten sollen die Zielgröße h(x) haben ---- */
function distmesh(P,dom,hf,iters){
const n=P.length/2,hp=new Float64Array(n);
for(let it=0;it<iters;it++){
const del=new Delaunator(P),T=del.triangles,H=del.halfedges,ea=[],eb=[];
for(let e=0;e<T.length;e++) if(e<H[e]||H[e]===-1){ea.push(T[e]);eb.push(T[e%3===2?e-2:e+1]);}
for(let i=0;i<n;i++) hp[i]=hf(P[2*i],P[2*i+1]);
const m=ea.length,L=new Float64Array(m),h0=new Float64Array(m); let sL=0,sH=0;
for(let k=0;k<m;k++){const a=ea[k],b=eb[k];L[k]=Math.hypot(P[2*a]-P[2*b],P[2*a+1]-P[2*b+1]);h0[k]=0.5*(hp[a]+hp[b]);sL+=L[k]*L[k];sH+=h0[k]*h0[k];}
const sc=1.2*Math.sqrt(sL/sH),F=new Float64Array(2*n);
for(let k=0;k<m;k++){
const a=ea[k],b=eb[k],f=Math.max(h0[k]*sc-L[k],0)/(L[k]||1);
const fx=f*(P[2*a]-P[2*b]),fy=f*(P[2*a+1]-P[2*b+1]);
F[2*a]+=fx;F[2*a+1]+=fy;F[2*b]-=fx;F[2*b+1]-=fy;
}
for(let i=0;i<n;i++){P[2*i]=clamp(P[2*i]+0.2*F[2*i],dom.x0,dom.x1);P[2*i+1]=clamp(P[2*i+1]+0.2*F[2*i+1],dom.y0,dom.y1);}
}
}
/* ---- Weiches Minimum der Kantenabstände = gerundete Zellecken ---- */
const D=new Float64Array(96);
function softmin(cnt,kk){
let dm=D[0]; for(let i=1;i<cnt;i++) if(D[i]<dm) dm=D[i];
if(kk<0.02) return dm;
let s=0; for(let i=0;i<cnt;i++) s+=Math.exp((dm-D[i])/kk);
return dm-kk*Math.log(s);
}
const RK=0.42; // Rundungsradius → Glättungsbreite des Softmin
/* ---- Zelltyp 1: Voronoi — Zelle = Schnitt der Bisektoren zu den Delaunay-Nachbarn ---- */
function holeVoronoi(g,P,fW,fR){
const n=P.length/2,del=new Delaunator(P),T=del.triangles,H=del.halfedges;
const adj=Array.from({length:n},()=>[]);
for(let e=0;e<T.length;e++) if(e<H[e]||H[e]===-1){const a=T[e],b=T[e%3===2?e-2:e+1];adj[a].push(b);adj[b].push(a);}
const start=new Int32Array(n+1); let tot=0; for(let i=0;i<n;i++){start[i]=tot;tot+=adj[i].length;} start[n]=tot;
const nb=new Int32Array(tot),EN=new Float64Array(tot*3);
for(let i=0;i<n;i++){let k=start[i];for(const j of adj[i]){
const dx=P[2*j]-P[2*i],dy=P[2*j+1]-P[2*i+1],l=Math.hypot(dx,dy)||1e-9,nx=dx/l,ny=dy/l;
nb[k]=j;EN[3*k]=nx;EN[3*k+1]=ny;EN[3*k+2]=nx*(P[2*i]+P[2*j])/2+ny*(P[2*i+1]+P[2*j+1])/2;k++;}}
const out=new Float32Array(g.nx*g.ny); let cur=0,cur0=0;
for(let iy=0;iy<g.ny;iy++){
const y=g.y0+iy*g.res; cur=cur0;
for(let ix=0;ix<g.nx;ix++){
const x=g.x0+ix*g.res; let d=(P[2*cur]-x)**2+(P[2*cur+1]-y)**2;
for(;;){let best=cur,bd=d;for(let k=start[cur];k<start[cur+1];k++){const j=nb[k],dj=(P[2*j]-x)**2+(P[2*j+1]-y)**2;if(dj<bd){bd=dj;best=j;}} if(best===cur)break;cur=best;d=bd;}
if(ix===0) cur0=cur;
const i=iy*g.nx+ix; let c=0;
for(let k=start[cur];k<start[cur+1];k++) D[c++]=EN[3*k+2]-(EN[3*k]*x+EN[3*k+1]*y);
out[i]=0.5*fW[i]-softmin(c,fR[i]*RK);
}
}
return out;
}
/* ---- Zelltyp 2: Delaunay — Zelle = Dreieck ---- */
function holeDelaunay(g,P,fW,fR){
const del=new Delaunator(P),T=del.triangles,nt=T.length/3,TE=new Float64Array(nt*9);
const cellOf=new Int32Array(g.nx*g.ny).fill(-1);
for(let t=0;t<nt;t++){
const v=[T[3*t],T[3*t+1],T[3*t+2]],ax=[],ay=[];
for(const i of v){ax.push(P[2*i]);ay.push(P[2*i+1]);}
const sg=((ax[1]-ax[0])*(ay[2]-ay[0])-(ay[1]-ay[0])*(ax[2]-ax[0]))>0?1:-1;
for(let e=0;e<3;e++){
const a=e,b=(e+1)%3,dx=ax[b]-ax[a],dy=ay[b]-ay[a],l=Math.hypot(dx,dy)||1e-9;
const nx=sg*dy/l,ny=-sg*dx/l; // nach außen
TE[9*t+3*e]=nx;TE[9*t+3*e+1]=ny;TE[9*t+3*e+2]=nx*ax[a]+ny*ay[a];
}
const bx0=Math.max(0,Math.floor((Math.min(...ax)-g.x0)/g.res)),bx1=Math.min(g.nx-1,Math.ceil((Math.max(...ax)-g.x0)/g.res));
const by0=Math.max(0,Math.floor((Math.min(...ay)-g.y0)/g.res)),by1=Math.min(g.ny-1,Math.ceil((Math.max(...ay)-g.y0)/g.res));
for(let iy=by0;iy<=by1;iy++){const y=g.y0+iy*g.res;for(let ix=bx0;ix<=bx1;ix++){const x=g.x0+ix*g.res;
if(TE[9*t+2]-(TE[9*t]*x+TE[9*t+1]*y)>=-1e-7&&TE[9*t+5]-(TE[9*t+3]*x+TE[9*t+4]*y)>=-1e-7&&TE[9*t+8]-(TE[9*t+6]*x+TE[9*t+7]*y)>=-1e-7) cellOf[iy*g.nx+ix]=t;}}
}
const out=new Float32Array(g.nx*g.ny);
for(let iy=0,i=0;iy<g.ny;iy++){const y=g.y0+iy*g.res;for(let ix=0;ix<g.nx;ix++,i++){
const t=cellOf[i]; if(t<0){out[i]=-1e3;continue;} const x=g.x0+ix*g.res;
for(let e=0;e<3;e++) D[e]=TE[9*t+3*e+2]-(TE[9*t+3*e]*x+TE[9*t+3*e+1]*y);
out[i]=0.5*fW[i]-softmin(3,fR[i]*RK);
}}
return out;
}
/* ---- Zelltyp 3: Gitter — adaptives Quadtree (Quadrate, optional Diagonale) ---- */
function holeQuad(g,fW,fR,hf,hs,dom){
const ang=ST.angle*Math.PI/180,c=Math.cos(ang),s=Math.sin(ang),SQ=Math.SQRT1_2;
const [hlo,hhi]=paramRange(PARAMS.size),smin=hlo*hs,S=hhi*hs;
let umin=1e9,umax=-1e9,vmin=1e9,vmax=-1e9;
for(const [x,y] of [[dom.x0,dom.y0],[dom.x1,dom.y0],[dom.x0,dom.y1],[dom.x1,dom.y1]]){const u=c*x+s*y,v=-s*x+c*y;umin=Math.min(umin,u);umax=Math.max(umax,u);vmin=Math.min(vmin,v);vmax=Math.max(vmax,v);}
const I0=Math.floor(umin/S),I1=Math.floor(umax/S),J0=Math.floor(vmin/S),J1=Math.floor(vmax/S),W=I1-I0+1;
let leaves=0;
const mk=(x,y,sz,d)=>{const nd={x,y,s:sz,k:null};const cu=x+sz/2,cv=y+sz/2,t=hf(c*cu-s*cv,s*cu+c*cv);
if(sz>t*1.3&&sz*0.5>=smin*0.8&&d<7){const h=sz/2;nd.k=[mk(x,y,h,d+1),mk(x+h,y,h,d+1),mk(x,y+h,h,d+1),mk(x+h,y+h,h,d+1)];}else leaves++;return nd;};
const roots=[]; for(let j=J0;j<=J1;j++)for(let i=I0;i<=I1;i++) roots.push(mk(i*S,j*S,S,0));
const out=new Float32Array(g.nx*g.ny);
for(let iy=0,i=0;iy<g.ny;iy++){const y=g.y0+iy*g.res;for(let ix=0;ix<g.nx;ix++,i++){
const x=g.x0+ix*g.res,u=c*x+s*y,v=-s*x+c*y;
let nd=roots[(Math.floor(v/S)-J0)*W+(Math.floor(u/S)-I0)];
while(nd.k){const h=nd.s/2;nd=nd.k[(u>=nd.x+h?1:0)+(v>=nd.y+h?2:0)];}
const du0=u-nd.x,du1=nd.x+nd.s-u,dv0=v-nd.y,dv1=nd.y+nd.s-v; let cnt;
if(ST.tri){const t=du0-dv0; if(t>0){D[0]=dv0;D[1]=du1;D[2]=t*SQ;}else{D[0]=dv1;D[1]=du0;D[2]=-t*SQ;} cnt=3;}
else{D[0]=du0;D[1]=du1;D[2]=dv0;D[3]=dv1;cnt=4;}
out[i]=0.5*fW[i]-softmin(cnt,fR[i]*RK);
}}
return {field:out,cells:leaves};
}
/* ---- Marching Squares: Material (F>0) links der Laufrichtung ---- */
const MSTBL=[[],[0,3],[1,0],[1,3],[2,1],null,[2,0],[2,3],[3,2],[0,2],null,[1,2],[3,1],[0,1],[3,0],[]];
function marching(F,g){
const {nx,ny,x0,y0,res}=g,NH=nx*ny,next=new Int32Array(2*NH).fill(-1),px=new Float32Array(2*NH),py=new Float32Array(2*NH);
for(let j=0;j<ny;j++)for(let i=0;i<nx;i++){
const a=F[j*nx+i];
if(i<nx-1){const b=F[j*nx+i+1];if((a>0)!==(b>0)){const t=a/(a-b),id=j*nx+i;px[id]=x0+(i+t)*res;py[id]=y0+j*res;}}
if(j<ny-1){const b=F[(j+1)*nx+i];if((a>0)!==(b>0)){const t=a/(a-b),id=NH+j*nx+i;px[id]=x0+i*res;py[id]=y0+(j+t)*res;}}
}
const E=[0,0,0,0];
for(let j=0;j<ny-1;j++)for(let i=0;i<nx-1;i++){
const v0=F[j*nx+i],v1=F[j*nx+i+1],v2=F[(j+1)*nx+i+1],v3=F[(j+1)*nx+i];
const idx=(v0>0?1:0)|(v1>0?2:0)|(v2>0?4:0)|(v3>0?8:0); if(idx===0||idx===15) continue;
E[0]=j*nx+i; E[1]=NH+j*nx+i+1; E[2]=(j+1)*nx+i; E[3]=NH+j*nx+i;
let seg=MSTBL[idx];
if(!seg){const cen=(v0+v1+v2+v3)>0; seg=idx===5?(cen?[0,1,2,3]:[0,3,2,1]):(cen?[3,0,1,2]:[1,0,3,2]);}
for(let k=0;k<seg.length;k+=2) next[E[seg[k]]]=E[seg[k+1]];
}
const loops=[],seen=new Uint8Array(2*NH);
for(let e0=0;e0<2*NH;e0++){
if(next[e0]<0||seen[e0]) continue;
const pts=[]; let e=e0;
do{seen[e]=1;pts.push(px[e],py[e]);e=next[e];}while(e>=0&&e!==e0&&!seen[e]);
if(e===e0&&pts.length>=6) loops.push(Float32Array.from(pts));
}
return loops;
}
function loopArea(p){let a=0;const n=p.length/2;for(let i=0,j=n-1;i<n;j=i++)a+=p[2*j]*p[2*i+1]-p[2*i]*p[2*j+1];return a/2;}
function rdpClosed(p,eps){
const n=p.length/2; if(n<10) return p;
let far=0,fd=0; for(let i=1;i<n;i++){const d=(p[2*i]-p[0])**2+(p[2*i+1]-p[1])**2;if(d>fd){fd=d;far=i;}}
const keep=new Uint8Array(n); keep[0]=1; keep[far]=1;
const stack=[[0,far],[far,n]];
while(stack.length){
const [a,b]=stack.pop(); if(b-a<2) continue;
const ax=p[2*a],ay=p[2*a+1],bi=b%n,bx=p[2*bi],by=p[2*bi+1],ex=bx-ax,ey=by-ay,l=Math.hypot(ex,ey)||1e-9;
let md=-1,mi=-1;
for(let i=a+1;i<b;i++){const d=Math.abs((p[2*i]-ax)*ey-(p[2*i+1]-ay)*ex)/l;if(d>md){md=d;mi=i;}}
if(md>eps){keep[mi]=1;stack.push([a,mi],[mi,b]);}
}
const o=[]; for(let i=0;i<n;i++) if(keep[i]) o.push(p[2*i],p[2*i+1]);
return Float32Array.from(o);
}
/* ---- Mesh: Deckel/Boden per Earcut, Wände glatt, Höhe aus der Höhen-Map ---- */
class Vbuf{constructor(){this.a=new Float32Array(1<<17);this.n=0;}
push(x,y,z){if(this.n+3>this.a.length){const b=new Float32Array(this.a.length*2);b.set(this.a);this.a=b;}this.a[this.n++]=x;this.a[this.n++]=y;this.a[this.n++]=z;}
done(){return this.a.slice(0,this.n);}}
const heightAt=(x,y)=>evalParam(PARAMS.height,x,y);
function pipFlat(p,x,y){let c=false;const n=p.length/2;for(let i=0,j=n-1;i<n;j=i++){const ay=p[2*i+1],by=p[2*j+1];if((ay>y)!==(by>y)&&x<(p[2*j]-p[2*i])*(y-ay)/(by-ay)+p[2*i])c=!c;}return c;}
function buildMesh(loops){
const pos=new Vbuf(),nor=new Vbuf(),outers=[],holes=[];
for(const L of loops) (L.area>0?outers:holes).push(L);
for(const o of outers){o.holes=[];o.bb=bboxFlat(o.pts);}
for(const hl of holes){
const x=hl.pts[0],y=hl.pts[1]; let best=null;
for(const o of outers){if(x<o.bb[0]||x>o.bb[2]||y<o.bb[1]||y>o.bb[3])continue;if(!pipFlat(o.pts,x,y))continue;if(!best||o.area<best.area)best=o;}
if(best) best.holes.push(hl);
}
const V2=(p)=>{const a=[];for(let i=0;i<p.length;i+=2)a.push(new THREE.Vector2(p[i],p[i+1]));return a;};
for(const o of outers){
const cont=V2(o.pts),hl=o.holes.map(h=>V2(h.pts)),faces=THREE.ShapeUtils.triangulateShape(cont,hl),all=cont.concat(...hl);
const hz=all.map(v=>heightAt(v.x,v.y));
for(const f of faces){
let [i,j,k]=f; const A=all[i],B=all[j],C=all[k];
const cr=(B.x-A.x)*(C.y-A.y)-(B.y-A.y)*(C.x-A.x);
if(cr>0){const t=j;j=k;k=t;} // Deckel: Normale +Y
for(const q of [i,j,k]){pos.push(all[q].x,hz[q],all[q].y);nor.push(0,1,0);}
for(const q of [i,k,j]){pos.push(all[q].x,0,all[q].y);nor.push(0,-1,0);} // Boden
}
}
for(const L of loops){
const p=L.pts,n=p.length/2,hz=new Float32Array(n),wn=new Float32Array(2*n);
for(let i=0;i<n;i++) hz[i]=heightAt(p[2*i],p[2*i+1]);
const en=new Float32Array(2*n); // Kantennormalen (nach außen = rechts der Laufrichtung)
for(let i=0;i<n;i++){const j=(i+1)%n,dx=p[2*j]-p[2*i],dy=p[2*j+1]-p[2*i+1],l=Math.hypot(dx,dy)||1e-9;en[2*i]=dy/l;en[2*i+1]=-dx/l;}
for(let i=0;i<n;i++){const k=(i+n-1)%n,x=en[2*i]+en[2*k],y=en[2*i+1]+en[2*k+1],l=Math.hypot(x,y)||1;wn[2*i]=x/l;wn[2*i+1]=y/l;}
for(let i=0;i<n;i++){
const j=(i+1)%n,xi=p[2*i],yi=p[2*i+1],xj=p[2*j],yj=p[2*j+1];
const Q=[[xi,hz[i],yi,wn[2*i],wn[2*i+1]],[xj,hz[j],yj,wn[2*j],wn[2*j+1]],[xj,0,yj,wn[2*j],wn[2*j+1]],[xi,0,yi,wn[2*i],wn[2*i+1]]];
for(const tri of [[0,1,2],[0,2,3]]){
let [a,b,c]=tri; const A=Q[a],B=Q[b],C=Q[c];
const ux=B[0]-A[0],uy=B[1]-A[1],uz=B[2]-A[2],vx=C[0]-A[0],vy=C[1]-A[1],vz=C[2]-A[2];
const cx=uy*vz-uz*vy,cz=ux*vy-uy*vx;
if(cx*en[2*i]+cz*en[2*i+1]<0){const t=b;b=c;c=t;}
for(const q of [a,b,c]){pos.push(Q[q][0],Q[q][1],Q[q][2]);nor.push(Q[q][3],0,Q[q][4]);}
}
}
}
return {pos:pos.done(),nor:nor.done()};
}
function bboxFlat(p){let x0=1e9,y0=1e9,x1=-1e9,y1=-1e9;for(let i=0;i<p.length;i+=2){if(p[i]<x0)x0=p[i];if(p[i]>x1)x1=p[i];if(p[i+1]<y0)y0=p[i+1];if(p[i+1]>y1)y1=p[i+1];}return[x0,y0,x1,y1];}
/* ---- Gesamte Pipeline ---- */
function computeStructure(){
const t0=performance.now(),notes=[];
const bb=bboxOf(poly); let res=ST.quality; const margin=2.5; let nx,ny;
for(;;){nx=Math.ceil((bb.x1-bb.x0+2*margin)/res)+1;ny=Math.ceil((bb.y1-bb.y0+2*margin)/res)+1;if(nx*ny<=1.4e6)break;res*=1.25;}
if(res>ST.quality+1e-6) notes.push('Raster gröber ('+res.toFixed(2)+' mm)');
const g={x0:bb.x0-margin,y0:bb.y0-margin,nx,ny,res};
const fW=paramField(PARAMS.strut,g),fR=paramField(PARAMS.round,g),fH=paramField(PARAMS.height,g),fRim=paramField(PARAMS.rim,g);
const band=Math.max(paramRange(PARAMS.rim)[1],0)+2.5, sh=shapeSDF(poly,g,band);
// Zellgrößen-Funktion + Zellzahl begrenzen
const [,hhi]=paramRange(PARAMS.size),pad=1.6*hhi+3;
const dom={x0:bb.x0-pad,x1:bb.x1+pad,y0:bb.y0-pad,y1:bb.y1+pad};
let est=0;const ns=40,ca=(dom.x1-dom.x0)*(dom.y1-dom.y0)/(ns*ns);
for(let j=0;j<ns;j++)for(let i=0;i<ns;i++){const h=evalParam(PARAMS.size,lerp(dom.x0,dom.x1,(i+.5)/ns),lerp(dom.y0,dom.y1,(j+.5)/ns));est+=ca/((ST.type==='gitter'?1:0.866)*h*h);}
let hs=1; if(est>MAXCELLS){hs=Math.sqrt(est/MAXCELLS);notes.push('Zellgröße ×'+hs.toFixed(2)+' (zu viele Zellen)');}
const hf=(x,y)=>evalParam(PARAMS.size,x,y)*hs;
let hole,cells=0;
if(ST.type==='gitter'){const r=holeQuad(g,fW,fR,hf,hs,dom);hole=r.field;cells=r.cells;}
else{
const P=poissonSeeds(dom,hf,mulberry32(ST.seed|0)),it=Math.round(ST.reg*30);
if(it>0) distmesh(P,dom,hf,it);
for(let i=0;i<P.length;i+=2) if(pipPoly(poly,P[i],P[i+1])) cells++;
hole=ST.type==='voronoi'?holeVoronoi(g,P,fW,fR):holeDelaunay(g,P,fW,fR);
}
// Material = Stege ∪ Rand, begrenzt auf die Form (glatte Vereinigung = Verrundung an den Übergängen)
const F=new Float32Array(nx*ny); let area=0,vol=0;
for(let i=0;i<F.length;i++){
const a=hole[i],b=fRim[i]-sh[i],k=Math.max(0.3,fR[i]*0.5),hh=Math.max(k-Math.abs(a-b),0)/k;
const u=Math.max(a,b)+hh*hh*k*0.25; F[i]=Math.min(sh[i],u);
if(F[i]>0){area+=1;vol+=fH[i];}
}
for(let ix=0;ix<nx;ix++){F[ix]=-1;F[(ny-1)*nx+ix]=-1;} for(let iy=0;iy<ny;iy++){F[iy*nx]=-1;F[iy*nx+nx-1]=-1;}
const raw=marching(F,g),loops=[];
for(const l of raw){const p=rdpClosed(l,0.02);loops.push({pts:p,area:loopArea(p)});}
const mesh=buildMesh(loops),r2=res*res;
return {loops,mesh,stats:{cells,area:area*r2,vol:vol*r2,tris:mesh.pos.length/9,loops:loops.length,ms:Math.round(performance.now()-t0),notes}};
}
// </core>
/* =====================================================================
UI
===================================================================== */
const $=s=>document.querySelector(s);
function E(tag,props={},...kids){
const e=document.createElement(tag);
for(const k in props){const v=props[k];
if(k==='class')e.className=v;else if(k==='text')e.textContent=v;else if(k==='html')e.innerHTML=v;
else if(k==='val'||k==='checked'||k==='disabled')continue;else if(k.startsWith('on'))e.addEventListener(k.slice(2),v);else e.setAttribute(k,v);}
for(const c of kids.flat()) if(c!=null) e.append(c);
if('val' in props) e.value=props.val; if('checked' in props) e.checked=props.checked; if('disabled' in props) e.disabled=props.disabled;
return e;
}
const fmt=(v,d=1)=>(+v).toFixed(d);
let tab='form', ovl=null, activeMap=null, spaceDown=false, sel=-1, drag=null;
const view={s:2,ox:300,oy:300}, mouse={x:0,y:0,in:false};
const BR={size:22,hard:0.1,flow:0.22,val:1,mode:'paint'};
let S=null; // letztes Strukturergebnis {loops,mesh,stats,path}
const cv=$('#cv'),ctx=cv.getContext('2d'); let dpr=1;
/* ---------- Status / Build-Steuerung ---------- */
function status(t){$('#status').textContent=t||'';}
let buildTimer=0,building=false,pending=false;
function scheduleBuild(delay=220,force=false){
clearTimeout(buildTimer);
if(!force&&!ST.live){status('Eingaben geändert – „Berechnen“ drücken');return;}
buildTimer=setTimeout(()=>build(),delay);
}
async function build(){
if(building){pending=true;return;}
if(!shape.closed||poly.length<3){S=null;clearMesh();showStats();requestDraw();return;}
building=true; status('berechne …'); await new Promise(r=>setTimeout(r,20));
try{
const r=computeStructure(); const p=new Path2D();
for(const L of r.loops){const a=L.pts;p.moveTo(a[0],a[1]);for(let i=2;i<a.length;i+=2)p.lineTo(a[i],a[i+1]);p.closePath();}
r.path=p; S=r; applyMesh(r.mesh); showStats();
const s=r.stats; status(s.cells+' Zellen · '+Math.round(s.tris/1000)+'k Dreiecke · '+s.ms+' ms'+(s.notes.length?' · '+s.notes.join(', '):''));
}catch(e){console.error(e);status('Fehler: '+e.message);}
building=false; requestDraw();
if(pending){pending=false;scheduleBuild(30);}
}
function showStats(){
const el=$('#stats'); if(!el) return;
if(!S){el.textContent='—';return;}
const s=S.stats,cm3=s.vol/1000;
el.innerHTML='Zellen ≈ '+s.cells+'<br>Fläche '+fmt(s.area/100,1)+' cm² · Volumen '+fmt(cm3,2)+' cm³<br>Gewicht ≈ '+fmt(cm3*1.2,1)+' g <span class="mut">(TPU ~1,2 g/cm³)</span><br>'+Math.round(s.tris/1000)+'k Dreiecke · '+s.loops+' Konturen';
}
/* ---------- Form-Daten ---------- */
function shapeChanged(buildNow){
poly=shape.closed?flattenShape(shape):[];
const d=$('#dims'); if(d){ if(shape.closed){const b=bboxOf(poly);d.textContent='Maße: '+fmt(b.x1-b.x0,1)+' × '+fmt(b.y1-b.y0,1)+' mm';}else d.textContent=shape.pts.length?shape.pts.length+' Punkte – offen':'noch keine Form'; }
requestDraw(); if(buildNow) scheduleBuild(120);
}
function autoHandle(i){
const P=shape.pts,N=P.length,p=P[i],a=P[(i-1+N)%N],b=P[(i+1)%N];
const pa=(!shape.closed&&i===0)?p:a, pb=(!shape.closed&&i===N-1)?p:b;
const tx=(pb.x-pa.x)/6,ty=(pb.y-pa.y)/6; p.ox=tx;p.oy=ty;p.ix=-tx;p.iy=-ty;p.mode='smooth';
}
function setAnchors(arr){
shape.pts=arr.map(([x,y])=>({x,y,ix:0,iy:0,ox:0,oy:0,mode:'smooth'})); shape.closed=true;
shape.pts.forEach((_,i)=>autoHandle(i)); sel=-1; shapeChanged(true); fitView(); renderPanel();
}
function presetCircle(){const a=[];for(let i=0;i<8;i++){const t=i/8*Math.PI*2;a.push([Math.cos(t)*45,Math.sin(t)*45]);}setAnchors(a);}
function presetBlob(){const a=[],n=7;for(let i=0;i<n;i++){const t=i/n*Math.PI*2,r=34+Math.random()*22;a.push([Math.cos(t)*r*1.15,Math.sin(t)*r]);}setAnchors(a);}
function presetSole(){setAnchors([[-6,-125],[28,-112],[44,-75],[46,-40],[36,0],[33,50],[32,95],[10,125],[-18,118],[-32,90],[-30,40],[-22,0],[-32,-40],[-40,-70],[-30,-108]]);}
function insertPoint(i,t){
const P=shape.pts,N=P.length,a=P[i],b=P[(i+1)%N];
const c1=[a.x+a.ox,a.y+a.oy],c2=[b.x+b.ix,b.y+b.iy],L=(p,q,u)=>[p[0]+(q[0]-p[0])*u,p[1]+(q[1]-p[1])*u];
const A=L([a.x,a.y],c1,t),B=L(c1,c2,t),C=L(c2,[b.x,b.y],t),Dd=L(A,B,t),Ee=L(B,C,t),Q=L(Dd,Ee,t);
a.ox=A[0]-a.x;a.oy=A[1]-a.y;b.ix=C[0]-b.x;b.iy=C[1]-b.y;
P.splice(i+1,0,{x:Q[0],y:Q[1],ix:Dd[0]-Q[0],iy:Dd[1]-Q[1],ox:Ee[0]-Q[0],oy:Ee[1]-Q[1],mode:'smooth'});
sel=i+1; shapeChanged(true);
}
function hitCurve(p,tol){
const P=shape.pts,N=P.length,segs=shape.closed?N:N-1; let best=null;
for(let i=0;i<segs;i++){const a=P[i],b=P[(i+1)%N];for(let k=0;k<=24;k++){const t=k/24,q=bezPt(a,b,t),d=Math.hypot(q[0]-p.x,q[1]-p.y);if(d<tol&&(!best||d<best.d))best={i,t,d};}}
return best;
}
function hitAnchor(p,tol){const P=shape.pts;for(let i=P.length-1;i>=0;i--)if(Math.hypot(P[i].x-p.x,P[i].y-p.y)<tol)return i;return -1;}
function moveHandle(pt,which,wx,wy,free){
const hx=wx-pt.x,hy=wy-pt.y,m=Math.hypot(hx,hy)||1;
if(which==='out'){pt.ox=hx;pt.oy=hy;if(free)pt.mode='free';else if(pt.mode==='smooth'){const l=Math.hypot(pt.ix,pt.iy);pt.ix=-hx/m*l;pt.iy=-hy/m*l;}}
else{pt.ix=hx;pt.iy=hy;if(free)pt.mode='free';else if(pt.mode==='smooth'){const l=Math.hypot(pt.ox,pt.oy);pt.ox=-hx/m*l;pt.oy=-hy/m*l;}}
}
/* ---------- Ansicht ---------- */
function toWorld(ev){const r=cv.getBoundingClientRect();return{x:(ev.clientX-r.left-view.ox)/view.s,y:(ev.clientY-r.top-view.oy)/view.s};}
function fitView(){
const w=cv.clientWidth,h=cv.clientHeight; if(!w||!h) return;
let b=poly.length?bboxOf(poly):(shape.pts.length?bboxOf(shape.pts.map(p=>[p.x,p.y])):{x0:-110,x1:110,y0:-110,y1:110});
const bw=Math.max(b.x1-b.x0,40),bh=Math.max(b.y1-b.y0,40),pad=70;
view.s=clamp(Math.min((w-pad*2)/bw,(h-pad*2)/bh),0.6,40);
view.ox=w/2-(b.x0+b.x1)/2*view.s; view.oy=h/2-(b.y0+b.y1)/2*view.s; requestDraw();
}
function resize2D(){
dpr=Math.min(window.devicePixelRatio||1,2);
const w=cv.clientWidth,h=cv.clientHeight; cv.width=Math.max(1,w*dpr); cv.height=Math.max(1,h*dpr); requestDraw();
}
let drawQ=false;
function requestDraw(){if(!drawQ){drawQ=true;requestAnimationFrame(()=>{drawQ=false;draw2D();});}}
/* ---------- Map-Bilder ---------- */
function mapCanvas(m){
if(!m.cv){m.cv=document.createElement('canvas');m.cv.width=m.cv.height=MN;m.dirty=true;}
if(m.dirty){
const c=m.cv.getContext('2d'),im=c.createImageData(MN,MN),d=m.data,o=im.data;
for(let i=0,k=0;i<d.length;i++,k+=4){const v=Math.round(clamp(d[i],0,1)*255);o[k]=o[k+1]=o[k+2]=v;o[k+3]=255;}
c.putImageData(im,0,0); m.dirty=false;
}
return m.cv;
}
function drawThumb(m){
if(!m.thumb) return; const c=m.thumb.getContext('2d'),W=m.thumb.width;
c.clearRect(0,0,W,W); c.fillStyle='#fff'; c.fillRect(0,0,W,W);
const sc=W/BOARD; c.save(); c.scale(sc,sc); c.translate(HALF,HALF);
c.imageSmoothingEnabled=true; c.drawImage(mapCanvas(m),-HALF,-HALF,BOARD,BOARD);
if(shape.closed){c.lineWidth=1.2/sc;c.strokeStyle='#111';tracePath(c);c.stroke();}
c.restore();
}
function curMap(){return mapById(activeMap)||null;}
/* ---------- 2D Zeichnen ---------- */
function tracePath(c){
const P=shape.pts,N=P.length; if(!N) return; c.beginPath(); c.moveTo(P[0].x,P[0].y);
const segs=shape.closed?N:N-1;
for(let i=0;i<segs;i++){const a=P[i],b=P[(i+1)%N];
if(!a.ox&&!a.oy&&!b.ix&&!b.iy)c.lineTo(b.x,b.y);else c.bezierCurveTo(a.x+a.ox,a.y+a.oy,b.x+b.ix,b.y+b.iy,b.x,b.y);}
if(shape.closed) c.closePath();
}
function draw2D(){
const w=cv.width/dpr,h=cv.height/dpr,s=view.s;
ctx.setTransform(dpr,0,0,dpr,0,0); ctx.fillStyle='#fff'; ctx.fillRect(0,0,w,h);
ctx.save(); ctx.translate(view.ox,view.oy); ctx.scale(s,s);
const lw=px=>px/s, x0=-view.ox/s,x1=(w-view.ox)/s,y0=-view.oy/s,y1=(h-view.oy)/s;
// Raster
const step=s>=2.2?10:50; ctx.lineWidth=lw(1);
for(let x=Math.ceil(Math.max(x0,-HALF)/step)*step;x<=Math.min(x1,HALF);x+=step){ctx.strokeStyle=x%50===0?'#e9e9e9':'#f4f4f4';ctx.beginPath();ctx.moveTo(x,Math.max(y0,-HALF));ctx.lineTo(x,Math.min(y1,HALF));ctx.stroke();}
for(let y=Math.ceil(Math.max(y0,-HALF)/step)*step;y<=Math.min(y1,HALF);y+=step){ctx.strokeStyle=y%50===0?'#e9e9e9':'#f4f4f4';ctx.beginPath();ctx.moveTo(Math.max(x0,-HALF),y);ctx.lineTo(Math.min(x1,HALF),y);ctx.stroke();}
ctx.strokeStyle='#ddd'; ctx.strokeRect(-HALF,-HALF,BOARD,BOARD);
// Map unter der Form
const showMap=(tab==='maps'&&curMap())?curMap():(tab==='struct'&&ovl!=null?mapById(ovl):null);
if(showMap){
ctx.save(); if(shape.closed){tracePath(ctx);ctx.clip();}
if(tab==='struct') ctx.globalAlpha=0.55;
ctx.imageSmoothingEnabled=true; ctx.drawImage(mapCanvas(showMap),-HALF,-HALF,BOARD,BOARD); ctx.restore();
}
// Struktur
if(tab==='struct'&&S&&S.path){ctx.fillStyle=showMap?'rgba(255,255,255,.0)':'#e9e9e9';ctx.fill(S.path,'evenodd');ctx.strokeStyle='#111';ctx.lineWidth=lw(0.9);ctx.stroke(S.path);}
// Kontur der Form
if(shape.pts.length>1){
tracePath(ctx); ctx.lineWidth=lw(tab==='form'?1.6:1); ctx.strokeStyle='#111'; ctx.setLineDash(tab==='struct'?[lw(4),lw(3)]:[]); ctx.stroke(); ctx.setLineDash([]);
if(tab==='form'&&shape.closed){ctx.fillStyle='rgba(0,0,0,.025)';ctx.fill();}
}
// Pen-UI
if(tab==='form'){
const P=shape.pts,hs=7/s;
if(!shape.closed&&P.length&&mouse.in&&!drag){const l=P[P.length-1];ctx.beginPath();ctx.moveTo(l.x,l.y);
if(l.ox||l.oy)ctx.bezierCurveTo(l.x+l.ox,l.y+l.oy,mouse.x,mouse.y,mouse.x,mouse.y);else ctx.lineTo(mouse.x,mouse.y);
ctx.strokeStyle='#999';ctx.lineWidth=lw(1);ctx.setLineDash([lw(4),lw(3)]);ctx.stroke();ctx.setLineDash([]);}
const showH=i=>i===sel||(drag&&drag.pt===P[i]);
for(let i=0;i<P.length;i++){const p=P[i];
if(showH(i)){ctx.lineWidth=lw(1);ctx.strokeStyle='#888';
for(const [hx,hy] of [[p.ix,p.iy],[p.ox,p.oy]]){if(!hx&&!hy)continue;ctx.beginPath();ctx.moveTo(p.x,p.y);ctx.lineTo(p.x+hx,p.y+hy);ctx.stroke();ctx.beginPath();ctx.arc(p.x+hx,p.y+hy,3.2/s,0,6.3);ctx.fillStyle='#fff';ctx.fill();ctx.stroke();}}
ctx.beginPath();
if(p.mode==='corner')ctx.rect(p.x-hs/2,p.y-hs/2,hs,hs);else ctx.arc(p.x,p.y,hs/1.7,0,6.3);
ctx.fillStyle=i===sel?'#111':'#fff';ctx.fill();ctx.strokeStyle='#111';ctx.lineWidth=lw(1.2);ctx.stroke();
}
if(!shape.closed&&P.length>=3){ctx.beginPath();ctx.arc(P[0].x,P[0].y,11/s,0,6.3);ctx.strokeStyle='#bbb';ctx.lineWidth=lw(1);ctx.stroke();}
}
// Pinsel-Cursor
if(tab==='maps'&&mouse.in&&!spaceDown){
ctx.lineWidth=lw(1);ctx.strokeStyle='#111';ctx.beginPath();ctx.arc(mouse.x,mouse.y,BR.size,0,6.3);ctx.stroke();
ctx.strokeStyle='#999';ctx.beginPath();ctx.arc(mouse.x,mouse.y,BR.size*BR.hard,0,6.3);ctx.stroke();
}
ctx.restore();
$('#hint').textContent=mouse.in?('x '+fmt(mouse.x,1)+' y '+fmt(mouse.y,1)+' mm'):'';
}
/* ---------- Airbrush ---------- */
const falloff=t=>{const h=BR.hard;if(t<=h)return 1;const u=(1-t)/(1-h);return u*u*(3-2*u);};
function stamp(x,y,mul=1){
const m=curMap(); if(!m) return;
const R=BR.size,d=m.data;
const i0=Math.max(0,Math.floor((x-R+HALF)/CELL)),i1=Math.min(MN-1,Math.ceil((x+R+HALF)/CELL));
const j0=Math.max(0,Math.floor((y-R+HALF)/CELL)),j1=Math.min(MN-1,Math.ceil((y+R+HALF)/CELL));
const f=BR.flow*mul;
if(BR.mode==='paint'){
for(let j=j0;j<=j1;j++){const cy=-HALF+(j+.5)*CELL;for(let i=i0;i<=i1;i++){const cx=-HALF+(i+.5)*CELL,t=Math.hypot(cx-x,cy-y)/R;if(t>=1)continue;const k=falloff(t)*f,id=j*MN+i;d[id]+=(BR.val-d[id])*k;}}
}else{
const a0=Math.max(0,i0-1),a1=Math.min(MN-1,i1+1),b0=Math.max(0,j0-1),b1=Math.min(MN-1,j1+1),W=a1-a0+1,tmp=new Float32Array(W*(b1-b0+1));
for(let j=b0;j<=b1;j++)for(let i=a0;i<=a1;i++)tmp[(j-b0)*W+(i-a0)]=d[j*MN+i];
for(let j=j0;j<=j1;j++){const cy=-HALF+(j+.5)*CELL;for(let i=i0;i<=i1;i++){const cx=-HALF+(i+.5)*CELL,t=Math.hypot(cx-x,cy-y)/R;if(t>=1)continue;
let sum=0,c=0;for(let dj=-1;dj<=1;dj++)for(let di=-1;di<=1;di++){const ii=i+di,jj=j+dj;if(ii<a0||ii>a1||jj<b0||jj>b1)continue;sum+=tmp[(jj-b0)*W+(ii-a0)];c++;}
const id=j*MN+i;d[id]+=(sum/c-d[id])*Math.min(1,falloff(t)*f*2);}}
}
m.dirty=true; requestDraw();
}
let lastP=null,lastMoveT=0,lastPress=1;
function strokeTo(p,press){
const dx=p.x-lastP.x,dy=p.y-lastP.y,L=Math.hypot(dx,dy),sp=Math.max(0.6,BR.size*0.12);
if(L<sp) return; const n=Math.floor(L/sp);
for(let k=1;k<=n;k++) stamp(lastP.x+dx/L*sp*k,lastP.y+dy/L*sp*k,press);
lastP={x:lastP.x+dx/L*sp*n,y:lastP.y+dy/L*sp*n};
}
function mapEdited(){const m=curMap();if(m)drawThumb(m);scheduleBuild(180);}
function mapOp(op){
const m=curMap(); if(!m) return; const d=m.data;
if(op==='fill')d.fill(BR.val);
else if(op==='invert')for(let i=0;i<d.length;i++)d[i]=1-d[i];
else if(op==='blur'){const t=Float32Array.from(d);for(let j=0;j<MN;j++)for(let i=0;i<MN;i++){let s=0,c=0;for(let dj=-2;dj<=2;dj++)for(let di=-2;di<=2;di++){const ii=i+di,jj=j+dj;if(ii<0||jj<0||ii>=MN||jj>=MN)continue;s+=t[jj*MN+ii];c++;}d[j*MN+i]=s/c;}}
m.dirty=true; mapEdited(); requestDraw();
}
/* ---------- Eingaben 2D ---------- */
cv.addEventListener('contextmenu',e=>e.preventDefault());
cv.addEventListener('pointerdown',ev=>{
cv.setPointerCapture(ev.pointerId); const p=toWorld(ev);
if(ev.button===1||ev.button===2||spaceDown){drag={type:'pan',sx:ev.clientX,sy:ev.clientY,ox:view.ox,oy:view.oy};return;}
if(ev.button!==0) return;
if(tab==='form') formDown(p,ev);
else if(tab==='maps'){
if(ev.altKey){const m=curMap();if(m){BR.val=sampleMap(m,p.x,p.y);renderPanel();}return;}
if(!curMap()) return; drag={type:'paint'}; lastP=p; lastMoveT=performance.now(); lastPress=ev.pointerType==='pen'?Math.max(0.1,ev.pressure*1.6):1; stamp(p.x,p.y,lastPress);
}else drag={type:'pan',sx:ev.clientX,sy:ev.clientY,ox:view.ox,oy:view.oy};
});
function formDown(p,ev){
const tol=8/view.s,P=shape.pts;
if(!shape.closed){
if(P.length>=3&&Math.hypot(p.x-P[0].x,p.y-P[0].y)<tol*1.5){shape.closed=true;sel=0;shapeChanged(true);renderPanel();return;}
const pt={x:p.x,y:p.y,ix:0,iy:0,ox:0,oy:0,mode:'corner'}; P.push(pt); sel=P.length-1;
drag={type:'newpt',pt,sx:ev.clientX,sy:ev.clientY}; shapeChanged(false); return;
}
if(sel>=0){const q=P[sel];
for(const wh of ['out','in']){const hx=wh==='out'?q.ox:q.ix,hy=wh==='out'?q.oy:q.iy;if((hx||hy)&&Math.hypot(q.x+hx-p.x,q.y+hy-p.y)<tol){drag={type:'handle',pt:q,which:wh};return;}}}
const i=hitAnchor(p,tol);
if(i>=0){sel=i;drag={type:'anchor',pt:P[i],dx:P[i].x-p.x,dy:P[i].y-p.y};requestDraw();return;}
sel=-1; drag={type:'pan',sx:ev.clientX,sy:ev.clientY,ox:view.ox,oy:view.oy}; requestDraw();
}
cv.addEventListener('pointermove',ev=>{
const p=toWorld(ev); mouse.x=p.x;mouse.y=p.y;mouse.in=true;
if(!drag){requestDraw();return;}
if(drag.type==='pan'){view.ox=drag.ox+ev.clientX-drag.sx;view.oy=drag.oy+ev.clientY-drag.sy;requestDraw();}
else if(drag.type==='paint'){lastMoveT=performance.now();strokeTo(p,lastPress);}
else if(drag.type==='newpt'){
if(Math.hypot(ev.clientX-drag.sx,ev.clientY-drag.sy)>3){const q=drag.pt;q.mode='smooth';q.ox=p.x-q.x;q.oy=p.y-q.y;q.ix=-q.ox;q.iy=-q.oy;shapeChanged(false);}
}
else if(drag.type==='handle'){moveHandle(drag.pt,drag.which,p.x,p.y,ev.shiftKey);shapeChanged(false);}
else if(drag.type==='anchor'){drag.pt.x=p.x+drag.dx;drag.pt.y=p.y+drag.dy;shapeChanged(false);}
});
cv.addEventListener('pointerleave',()=>{mouse.in=false;requestDraw();});
cv.addEventListener('pointerup',()=>{
const d=drag; drag=null; if(!d) return;
if(d.type==='paint') mapEdited();
else if(d.type==='newpt'||d.type==='handle'||d.type==='anchor'){if(shape.closed)shapeChanged(true);else shapeChanged(false);}
requestDraw();
});
cv.addEventListener('dblclick',ev=>{
if(tab!=='form'||!shape.closed) return; const p=toWorld(ev),tol=8/view.s,i=hitAnchor(p,tol);
if(i>=0){const q=shape.pts[i];if(q.mode==='corner')autoHandle(i);else{q.ix=q.iy=q.ox=q.oy=0;q.mode='corner';}sel=i;shapeChanged(true);return;}
const c=hitCurve(p,tol); if(c) insertPoint(c.i,c.t);
});
cv.addEventListener('wheel',ev=>{
ev.preventDefault(); const r=cv.getBoundingClientRect(),mx=ev.clientX-r.left,my=ev.clientY-r.top;
const f=Math.exp(-ev.deltaY*0.0016),ns=clamp(view.s*f,0.5,60),k=ns/view.s;
view.ox=mx-(mx-view.ox)*k; view.oy=my-(my-view.oy)*k; view.s=ns; requestDraw();
},{passive:false});
window.addEventListener('keydown',ev=>{
if(/INPUT|SELECT|TEXTAREA/.test(document.activeElement.tagName)&&document.activeElement.type!=='range') return;
if(ev.code==='Space'){spaceDown=true;cv.style.cursor='grab';ev.preventDefault();}
if(tab==='form'){
if((ev.key==='Delete'||ev.key==='Backspace')){
if(!shape.closed&&shape.pts.length){shape.pts.pop();sel=shape.pts.length-1;shapeChanged(false);}
else if(shape.closed&&sel>=0&&shape.pts.length>3){shape.pts.splice(sel,1);sel=-1;shapeChanged(true);}
ev.preventDefault();
}
if(ev.key==='Enter'&&!shape.closed&&shape.pts.length>=3){shape.closed=true;sel=0;shapeChanged(true);renderPanel();}
}
if(tab==='maps'){
if(ev.key==='[')BR.size=Math.max(2,BR.size*0.88);
if(ev.key===']')BR.size=Math.min(90,BR.size/0.88);
if(ev.key.toLowerCase()==='x'){BR.val=1-BR.val;}
if('[]x'.includes(ev.key.toLowerCase())){renderPanel();requestDraw();}
}
});
window.addEventListener('keyup',ev=>{if(ev.code==='Space'){spaceDown=false;cv.style.cursor='';}});
// Airbrush baut sich auf, solange der Stift gehalten wird
setInterval(()=>{if(drag&&drag.type==='paint'&&performance.now()-lastMoveT>40){stamp(lastP.x,lastP.y,0.35*lastPress);}},33);
/* ---------- Panel ---------- */
function btn(text,onclick,cls='ghost'){return E('button',{class:cls,text,onclick});}
function grp(title,...kids){return E('div',{class:'grp'},E('h3',{text:title}),...kids);}
function row(label,...c){return E('div',{class:'row'},label?E('label',{class:'k',text:label}):null,...c);}
function sl(label,min,max,step,get,set,f=v=>fmt(v,2),cls=''){
const num=E('span',{class:'num',text:f(get())}),r=E('input',{type:'range',min,max,step,class:cls}); r.value=get();
r.addEventListener('input',()=>{const v=parseFloat(r.value);set(v);num.textContent=f(v);});
return row(label,r,num);
}
function seg(opts,cur,on){return E('div',{class:'seg'},opts.map(([v,t])=>E('button',{class:v===cur?'on':'',text:t,onclick:()=>on(v)})));}
function renderPanel(){const p=$('#panel');p.innerHTML='';if(tab==='form')panelForm(p);else if(tab==='maps')panelMaps(p);else panelStruct(p);shapeChanged(false);if(tab==='struct')showStats();}
function panelForm(p){
p.append(
grp('1 · Geschlossene Form',
E('p',{class:'note',html:'<b>Klick</b> setzt Punkt · <b>Klick + Ziehen</b> zieht Bezier-Griffe<br>Klick auf den ersten Punkt schließt (oder <b>Enter</b>)<br><b>Doppelklick</b> auf Punkt: rund ↔ eckig · auf Kurve: Punkt einfügen<br><b>Shift</b> beim Griff: Griffe frei · <b>Entf</b> löscht Punkt<br>Verschieben: Leertaste oder rechte Maustaste · Zoom: Mausrad'}),
row('',btn('Neu',()=>{shape={pts:[],closed:false};sel=-1;S=null;clearMesh();shapeChanged(false);renderPanel();}),btn('Schließen',()=>{if(shape.pts.length>=3){shape.closed=true;sel=0;shapeChanged(true);renderPanel();}}),btn('Ansicht ⌖',fitView)),
E('div',{id:'dims',class:'mut'})),
grp('Vorlagen',row('',btn('Kreis',presetCircle),btn('Blob',presetBlob),btn('Sohle',presetSole))));
}
function panelMaps(p){
const list=E('div',{class:'maps'});
for(const m of maps){
const th=E('canvas',{width:80,height:80}); m.thumb=th;
const nm=E('input',{type:'text',val:m.name}); nm.addEventListener('input',()=>{m.name=nm.value;});
nm.addEventListener('change',()=>{renderPanel();});
const del=E('button',{class:'ghost sm',text:'×',title:'Map löschen',onclick:ev=>{ev.stopPropagation();deleteMap(m.id);}});
list.append(E('div',{class:'mrow'+(m.id===activeMap?' on':''),onclick:()=>{activeMap=m.id;renderPanel();requestDraw();}},th,nm,del));
setTimeout(()=>drawThumb(m),0);
}
p.append(grp('2 · Maps (Vertex-Paint)',list,row('',btn('+ Map',()=>{if(maps.length>=8)return;const m=newMap();activeMap=m.id;renderPanel();requestDraw();})),
E('p',{class:'note',html:'Weiß = Maximum, Schwarz = Minimum des zugewiesenen Parameters (Tab 3).<br><b>Alt+Klick</b> nimmt Wert auf · <b>X</b> tauscht Schwarz/Weiß · <b>[ ]</b> Pinselgröße<br>Halten baut die Farbe wie bei einer Airbrush auf.'})));
p.append(grp('Pinsel',
row('',seg([['paint','Malen'],['blur','Verwischen']],BR.mode,v=>{BR.mode=v;renderPanel();})),
sl('Größe',2,90,1,()=>BR.size,v=>{BR.size=v;requestDraw();},v=>fmt(v,0)+' mm'),
sl('Weichheit',0,0.95,.01,()=>1-BR.hard,v=>{BR.hard=1-v;requestDraw();},v=>Math.round(v*100)+'%'),
sl('Fluss',.02,1,.01,()=>BR.flow,v=>{BR.flow=v;},v=>Math.round(v*100)+'%'),
BR.mode==='paint'?sl('Wert',0,1,.01,()=>BR.val,v=>{BR.val=v;},v=>fmt(v,2),'val'):null));
p.append(grp('Aktive Map',row('',btn('Füllen',()=>mapOp('fill')),btn('Invertieren',()=>mapOp('invert')),btn('Glätten',()=>mapOp('blur')))));
}
function deleteMap(id){
maps=maps.filter(m=>m.id!==id); for(const k in PARAMS) if(PARAMS[k].src===id) PARAMS[k].src=null;
if(ovl===id) ovl=null; if(activeMap===id) activeMap=maps[0]?maps[0].id:null; renderPanel(); requestDraw(); scheduleBuild(100);
}
function paramRow(key){
const P=PARAMS[key],wrap=E('div',{class:'prm'});
const sel=E('select',{},E('option',{value:'',text:'konstant'}),maps.map(m=>E('option',{value:m.id,text:m.name})));
sel.value=P.src==null?'':String(P.src);
sel.addEventListener('change',()=>{P.src=sel.value===''?null:+sel.value;renderPanel();scheduleBuild(80);});
const head=E('div',{class:'ph'},E('span',{class:'pl',text:P.label+' (mm)'}),sel);
const hasMap=P.src!=null&&mapById(P.src);
if(hasMap) head.append(E('button',{class:'ghost sm'+(P.inv?' on':''),text:'⇅',title:'Invertieren: Weiß = Minimum',onclick:()=>{P.inv=!P.inv;renderPanel();scheduleBuild(80);}}));
wrap.append(head);
const one=(t,get,set)=>{const n=E('span',{class:'num',text:fmt(get(),2)}),r=E('input',{type:'range',min:P.lo,max:P.hi,step:P.step});r.value=get();
r.addEventListener('input',()=>{set(parseFloat(r.value));n.textContent=fmt(get(),2);scheduleBuild();});return E('div',{class:'pv'},E('span',{class:'t',text:t}),r,n);};
if(hasMap){wrap.append(one('min',()=>P.min,v=>P.min=v),one('max',()=>P.max,v=>P.max=v));}
else wrap.append(one('',()=>P.val,v=>P.val=v));
return wrap;
}
function panelStruct(p){
const g1=grp('3 · Struktur',
seg([['voronoi','Voronoi'],['delaunay','Delaunay'],['gitter','Gitter']],ST.type,v=>{ST.type=v;renderPanel();scheduleBuild(60);}));
if(ST.type==='gitter'){
g1.append(sl('Winkel',0,90,1,()=>ST.angle,v=>{ST.angle=v;scheduleBuild();},v=>fmt(v,0)+'°'),
row('Dreiecke',Object.assign(E('input',{type:'checkbox',checked:ST.tri,onchange:ev=>{ST.tri=ev.target.checked;scheduleBuild(60);}}))));
}else{
g1.append(sl('Regelmäßig',0,1,.01,()=>ST.reg,v=>{ST.reg=v;scheduleBuild();},v=>Math.round(v*100)+'%'),
row('Zufall',E('input',{type:'number',val:ST.seed,min:0,step:1,style:'width:64px',onchange:ev=>{ST.seed=parseInt(ev.target.value)||0;scheduleBuild(60);}}),
btn('↻ neu',()=>{ST.seed=Math.floor(Math.random()*9999);renderPanel();scheduleBuild(60);})));
}
const g2=grp('Parameter ← Maps'); for(const k of ['size','strut','round','height','rim']) g2.append(paramRow(k));
const ovs=E('select',{},E('option',{value:'',text:'–'}),maps.map(m=>E('option',{value:m.id,text:m.name}))); ovs.value=ovl==null?'':String(ovl);
ovs.addEventListener('change',()=>{ovl=ovs.value===''?null:+ovs.value;requestDraw();});
const qsel=E('select',{onchange:ev=>{ST.quality=parseFloat(ev.target.value);scheduleBuild(60);}},[[.6,'grob 0,6 mm'],[.4,'mittel 0,4 mm'],[.25,'fein 0,25 mm']].map(([v,t])=>E('option',{value:v,text:t}))); qsel.value=String(ST.quality);
const g3=grp('Berechnung',
row('Qualität',qsel),
row('Live',E('input',{type:'checkbox',checked:ST.live,onchange:ev=>{ST.live=ev.target.checked;if(ST.live)scheduleBuild(60);}}),btn('Berechnen',()=>scheduleBuild(0,true),'')),
row('Map-Overlay',ovs));
const g4=grp('Export',row('',btn('STL',exportSTL),btn('SVG (2D)',exportSVG)),E('p',{class:'note mut',text:'STL: Z nach oben, Maße in mm.'}));
const g5=grp('Info',E('div',{id:'stats',class:'mut'}));
p.append(g1,g2,g3,g4,g5);
}
/* ---------- 3D ---------- */
const glEl=$('#gl'),renderer=new THREE.WebGLRenderer({antialias:true});
renderer.setPixelRatio(Math.min(window.devicePixelRatio||1,2)); renderer.shadowMap.enabled=true; renderer.shadowMap.type=THREE.PCFSoftShadowMap;
glEl.append(renderer.domElement);
const scene=new THREE.Scene(); scene.background=new THREE.Color(0xffffff);
const camera=new THREE.PerspectiveCamera(32,1,1,4000);
const controls=new OrbitControls(camera,renderer.domElement); controls.addEventListener('change',render3);
scene.add(new THREE.HemisphereLight(0xffffff,0xe4e4e4,1.15));
const sun=new THREE.DirectionalLight(0xffffff,1.9); sun.position.set(-140,300,180); sun.castShadow=true;
sun.shadow.mapSize.set(2048,2048); Object.assign(sun.shadow.camera,{left:-230,right:230,top:230,bottom:-230,near:10,far:900}); sun.shadow.camera.updateProjectionMatrix(); sun.shadow.bias=-0.0004; sun.shadow.normalBias=0.25; sun.shadow.radius=4;
scene.add(sun);
const ground=new THREE.Mesh(new THREE.PlaneGeometry(2000,2000),new THREE.ShadowMaterial({opacity:0.14})); ground.rotation.x=-Math.PI/2; ground.position.y=-0.05; ground.receiveShadow=true; scene.add(ground);
const mat=new THREE.MeshStandardMaterial({color:0xf3f3f1,roughness:0.62,metalness:0,side:THREE.DoubleSide});
let mesh=null,meshBox=null,camSet=false;
function render3(){renderer.render(scene,camera);}
function resize3(){const w=glEl.clientWidth,h=glEl.clientHeight;if(!w||!h)return;renderer.setSize(w,h,false);camera.aspect=w/h;camera.updateProjectionMatrix();render3();}
function clearMesh(){if(mesh){scene.remove(mesh);mesh.geometry.dispose();mesh=null;}$('#empty3').style.display='flex';render3();}
function applyMesh(m){
if(mesh){scene.remove(mesh);mesh.geometry.dispose();}
const geo=new THREE.BufferGeometry(); geo.setAttribute('position',new THREE.BufferAttribute(m.pos,3)); geo.setAttribute('normal',new THREE.BufferAttribute(m.nor,3)); geo.computeBoundingBox();
mesh=new THREE.Mesh(geo,mat); mesh.castShadow=true; mesh.receiveShadow=true; scene.add(mesh); meshBox=geo.boundingBox.clone();
$('#empty3').style.display=m.pos.length?'none':'flex';
if(!camSet&&m.pos.length){viewIso();camSet=true;} render3();
}
function viewIso(top=false){
if(!meshBox){return;} const c=meshBox.getCenter(new THREE.Vector3()),sz=meshBox.getSize(new THREE.Vector3()),d=Math.max(sz.x,sz.z,40)*2.6;
controls.target.set(c.x,0,c.z);
if(top) camera.position.set(c.x,d*1.05,c.z+0.01);
else camera.position.set(c.x+d*0.15,d*0.78,c.z+d*0.66);
camera.lookAt(controls.target); controls.update(); render3();
}
$('#bView').onclick=()=>viewIso(false); $('#bTop').onclick=()=>viewIso(true);
/* ---------- Export / Speichern ---------- */
function download(name,blob){const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;document.body.append(a);a.click();setTimeout(()=>{URL.revokeObjectURL(a.href);a.remove();},500);}
function exportSTL(){
if(!S||!S.mesh.pos.length){status('Nichts zu exportieren');return;}
const pos=S.mesh.pos,nt=pos.length/9,buf=new ArrayBuffer(84+nt*50),dv=new DataView(buf);
const hd='MAP:LATTICE STL (mm)'; for(let i=0;i<hd.length;i++)dv.setUint8(i,hd.charCodeAt(i)); dv.setUint32(80,nt,true);
let o=84; const V=[0,0,0,0,0,0,0,0,0];
for(let t=0;t<nt;t++){
for(let k=0;k<3;k++){const X=pos[9*t+3*k],Y=pos[9*t+3*k+1],Z=pos[9*t+3*k+2];V[3*k]=X;V[3*k+1]=-Z;V[3*k+2]=Y;} // three(Y oben) → STL(Z oben)
const ux=V[3]-V[0],uy=V[4]-V[1],uz=V[5]-V[2],vx=V[6]-V[0],vy=V[7]-V[1],vz=V[8]-V[2];
let nx=uy*vz-uz*vy,ny=uz*vx-ux*vz,nz=ux*vy-uy*vx; const l=Math.hypot(nx,ny,nz)||1; nx/=l;ny/=l;nz/=l;
dv.setFloat32(o,nx,true);dv.setFloat32(o+4,ny,true);dv.setFloat32(o+8,nz,true);o+=12;
for(let k=0;k<9;k++){dv.setFloat32(o,V[k],true);o+=4;} dv.setUint16(o,0,true);o+=2;
}
download('map_lattice.stl',new Blob([buf],{type:'model/stl'}));
}
function exportSVG(){
if(!S){status('Nichts zu exportieren');return;}
const b=bboxOf(poly),pad=2,w=b.x1-b.x0+2*pad,h=b.y1-b.y0+2*pad; let d='';
for(const L of S.loops){const a=L.pts;d+='M'+fmt(a[0],3)+' '+fmt(a[1],3);for(let i=2;i<a.length;i+=2)d+='L'+fmt(a[i],3)+' '+fmt(a[i+1],3);d+='Z';}
const svg='<svg xmlns="http://www.w3.org/2000/svg" width="'+fmt(w,2)+'mm" height="'+fmt(h,2)+'mm" viewBox="'+fmt(b.x0-pad,2)+' '+fmt(b.y0-pad,2)+' '+fmt(w,2)+' '+fmt(h,2)+'"><path d="'+d+'" fill="#000" fill-rule="evenodd"/></svg>';
download('map_lattice.svg',new Blob([svg],{type:'image/svg+xml'}));
}
function u8ToB64(u){let s='';for(let i=0;i<u.length;i+=0x8000)s+=String.fromCharCode.apply(null,u.subarray(i,i+0x8000));return btoa(s);}
function b64ToU8(b){const s=atob(b),u=new Uint8Array(s.length);for(let i=0;i<s.length;i++)u[i]=s.charCodeAt(i);return u;}
$('#bSave').onclick=()=>{
const data={v:1,shape,ST,PARAMS,maps:maps.map(m=>({id:m.id,name:m.name,data:u8ToB64(Uint8Array.from(m.data,v=>Math.round(clamp(v,0,1)*255)))}))};
download('map_lattice.json',new Blob([JSON.stringify(data)],{type:'application/json'}));
};
$('#bLoad').onclick=()=>$('#fLoad').click();
$('#fLoad').onchange=async ev=>{
const f=ev.target.files[0]; if(!f) return;
try{
const d=JSON.parse(await f.text()); shape=d.shape; Object.assign(ST,d.ST); for(const k in d.PARAMS) if(PARAMS[k]) Object.assign(PARAMS[k],d.PARAMS[k]);
maps=[]; nextMapId=1; for(const m of d.maps){const n=newMap(m.name);n.id=m.id;const u=b64ToU8(m.data);for(let i=0;i<n.data.length;i++)n.data[i]=u[i]/255;nextMapId=Math.max(nextMapId,m.id+1);}
activeMap=maps[0]?maps[0].id:null; sel=-1; poly=shape.closed?flattenShape(shape):[]; renderPanel(); fitView(); scheduleBuild(60,true);
}catch(e){status('Laden fehlgeschlagen: '+e.message);}
ev.target.value='';
};
/* ---------- Start ---------- */
function buildTabs(){
const nav=$('#tabs'); nav.innerHTML='';
for(const [k,t] of [['form','1 · Form'],['maps','2 · Maps'],['struct','3 · Struktur']]) nav.append(E('button',{class:'ghost'+(tab===k?' on':''),text:t,style:'margin-right:4px',onclick:()=>{tab=k;buildTabs();renderPanel();requestDraw();}}));
}
new ResizeObserver(()=>{resize2D();}).observe($('#st2d'));
new ResizeObserver(()=>{resize3();}).observe(glEl);
newMap('Map 1'); newMap('Map 2'); activeMap=maps[0].id;
buildTabs(); renderPanel(); resize2D(); fitView(); resize3();
window.__ml={get shape(){return shape;},get S(){return S;},ST,PARAMS,maps,presetSole,presetCircle,presetBlob,build,scheduleBuild,stamp,setTab:k=>{tab=k;buildTabs();renderPanel();requestDraw();},BR,renderPanel,get poly(){return poly;}};
</script>
</body>
</html>