Web-based prototype for drawing repeating surface patterns from a single motif. The drawing is made on one tile, and the pattern logic repeats it across the surface. The repetition is based on a set of grid types: square, brick, diamond, mirrored, rotated, hexagonal, triangular and kaleidoscopic layouts. Each type defines a drawing field, a set of copies inside the field and two grid vectors that place the copies side by side. Strokes are grouped in drawing order, and eraser strokes cut white holes into the layers below. The editor shows the tile with its repetitions in grey, and three preview panels show the pattern at different scales in millimetres. Patterns can be stored in a local library, exported as SVG or PNG at a chosen size and resolution, and saved or loaded as a JSON project file. The prototype is intended for design exploration of repeating patterns, for print and textile work, and as a starting point for further pattern tools.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>TURBO:PATTERN v1.0</title>
<style>
*{box-sizing:border-box}
html,body{margin:0;height:100%;background:#fff;color:#111;font:12px/1.4 -apple-system,system-ui,Helvetica,Arial,sans-serif;-webkit-text-size-adjust:100%}
body{touch-action:manipulation}
#app{display:grid;grid-template-columns:260px 1fr 300px;grid-template-areas:"side ed prev";height:100vh;height:100dvh}
#side{grid-area:side;border-right:1px solid #e6e6e6;overflow-y:auto;padding:12px 14px 40px}
#ed{grid-area:ed;display:flex;flex-direction:column;min-width:0;min-height:0}
#prev{grid-area:prev;border-left:1px solid #e6e6e6;overflow-y:auto;padding:12px 14px 30px}
h1{font-size:13px;letter-spacing:.14em;margin:0 0 6px;font-weight:600}
.hdr{margin:14px 0 6px;font-size:10px;letter-spacing:.1em;text-transform:uppercase;color:#999;border-top:1px solid #eee;padding-top:10px}
.hdr.top{border:0;padding-top:0;margin-top:8px}
button,select,input[type=number],input[type=text]{font:inherit;border:1px solid #d8d8d8;background:#fff;color:#111;padding:4px 8px;border-radius:3px}
input[type=number]{width:62px}
button{cursor:pointer}button:hover{background:#f4f4f4}
button.on{background:#111;color:#fff;border-color:#111}
.types{display:grid;grid-template-columns:repeat(3,1fr);gap:5px}
.types button{padding:5px 2px 4px;display:flex;flex-direction:column;align-items:center;gap:3px;font-size:10px;color:#666}
.types canvas{width:44px;height:44px;display:block}
.types button.on{background:#fff;color:#111;border-color:#111;box-shadow:inset 0 0 0 1px #111}
.hint{color:#999;font-size:11px;margin:6px 0}
.row{display:grid;grid-template-columns:1fr 92px 38px;align-items:center;gap:6px;margin:6px 0}
.row label{color:#444}
.row output{text-align:right;color:#888;font-variant-numeric:tabular-nums}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:24px;margin:0;background:transparent;touch-action:pan-y}
input[type=range]::-webkit-slider-runnable-track{height:2px;background:#cfcfcf;border-radius:1px}
input[type=range]::-moz-range-track{height:2px;background:#cfcfcf;border-radius:1px}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:#111;margin-top:-7px;border:0}
input[type=range]::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:#111;border:0}
.chk{display:flex;gap:6px;align-items:center;margin:6px 0;color:#444}
.btns{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}
.ex{display:flex;align-items:center;gap:6px;margin:6px 0;color:#444}.ex label{width:92px}
#name{width:100%}
#bar{display:flex;gap:6px;align-items:center;flex-wrap:wrap;padding:8px 12px;border-bottom:1px solid #eee}
#bar button{padding:5px 12px}
#bar .sep{width:1px;height:24px;background:#e6e6e6;margin:0 4px}
#bar .bs{width:34px;height:30px;padding:0;display:inline-flex;align-items:center;justify-content:center}
#bar .bs i{display:block;border-radius:50%;background:#111}
#bar .bs.on{background:#111}#bar .bs.on i{background:#fff}
#bar .sz{display:flex;align-items:center;gap:6px;color:#444}
#bar .sz input{width:120px}#bar .sz output{width:52px;color:#888;font-variant-numeric:tabular-nums}
#stage{flex:1;min-height:0;display:flex;align-items:center;justify-content:center;padding:10px;overflow:hidden}
#cEd{border:1px solid #e6e6e6;touch-action:none;cursor:none;display:block}
#info{padding:6px 12px;border-top:1px solid #eee;color:#888;font-size:11px;min-height:28px}
.pv{margin:0 0 12px}
.pv canvas{width:100%;aspect-ratio:1;display:block;border:1px solid #e6e6e6}
.pv small{display:flex;justify-content:space-between;color:#888;font-size:11px;margin-bottom:3px}
.pctl{grid-column:1/-1}
.lib{display:grid;grid-template-columns:repeat(3,1fr);gap:5px;margin-top:6px}
.lib .it{position:relative;border:1px solid #e6e6e6;border-radius:3px;cursor:pointer;overflow:hidden;background:#fff}
.lib .it:hover,.lib .it.on{border-color:#111}
.lib img{width:100%;aspect-ratio:1;display:block}
.lib span{display:block;font-size:10px;padding:2px 4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#555}
.lib .x{position:absolute;top:1px;right:1px;background:#fff;color:#999;font-size:11px;line-height:1;padding:2px 4px;border-radius:2px;display:none}
.lib .it:hover .x{display:block}
@media(pointer:coarse){
html,body{font-size:14px}
button,input[type=text],input[type=number]{min-height:40px;font-size:14px}
.row{grid-template-columns:1fr 120px 42px}
input[type=range]{height:34px}
input[type=range]::-webkit-slider-thumb{width:26px;height:26px;margin-top:-12px}
input[type=range]::-moz-range-thumb{width:26px;height:26px}
#bar .bs{width:42px;height:40px}
.lib .x{display:block}
}
@media(max-width:1100px){
#app{grid-template-columns:240px 1fr;grid-template-rows:1fr auto;grid-template-areas:"side ed" "side prev"}
#prev{border-left:0;border-top:1px solid #e6e6e6;display:grid;grid-template-columns:repeat(3,1fr);gap:10px;padding:8px 12px}
#prev .pv{margin:0}#prev .pv canvas{max-height:24vh;width:auto;max-width:100%;margin:0 auto}
#prev .hdr{display:none}
#prev .pctl{display:flex;gap:16px;align-items:center}#prev .pctl .row{flex:1;margin:0}#prev .pctl .chk{margin:0}
}
@media(max-width:720px){
#app{grid-template-columns:1fr;grid-template-rows:auto;grid-template-areas:"ed" "prev" "side";height:auto}
#ed{height:88vh;height:88dvh}
#side{border-right:0;border-top:1px solid #e6e6e6}
}
</style>
</head>
<body>
<div id="app">
<div id="side">
<h1>TURBO:PATTERN v1.0</h1>
<div class="hint" style="margin-top:0">Motiv zeichnen → Rapport wiederholt es.</div>
<div class="hdr top">Rapport</div>
<div class="types" id="types"></div>
<div class="hint" id="tDesc"></div>
<div class="row" id="rAsp"><label>Seitenverhältnis</label><input type="range" min="0.3" max="3" step="0.05" data-k="asp"><output></output></div>
<div class="chk" id="rClip"><input type="checkbox" id="cClip"><label for="cClip">An Spiegelachsen abschneiden</label></div>
<div class="row"><label>Rapportgröße (mm)</label><input type="range" min="4" max="200" step="1" data-k="tile"><output></output></div>
<div class="hint">Skaliert das ganze Muster samt Strichstärken.</div>
<div class="hdr">Zeichenfläche</div>
<div class="row"><label>Zoom</label><input type="range" min="0.5" max="4" step="0.05" data-k="zoom"><output></output></div>
<div class="chk"><input type="checkbox" id="cGrey"><label for="cGrey">Wiederholungen grau zeigen</label></div>
<div class="hdr">Meine Muster</div>
<input type="text" id="name" placeholder="Name">
<div class="btns"><button id="lSave">Speichern</button><button id="lCopy">Als Kopie</button><button id="lNew">Neu</button></div>
<div class="lib" id="lib"></div>
<div class="hdr">Export</div>
<div class="ex"><label>Fläche</label><input type="number" id="ew" min="5" max="2000"> × <input type="number" id="eh" min="5" max="2000"> mm</div>
<div class="ex"><label>PNG-Auflösung</label><input type="number" id="ppm" min="1" max="60"> px/mm</div>
<div class="btns"><button id="xSVG">SVG</button><button id="xPNG">PNG</button></div>
<div class="btns"><button id="pSave">Projekt sichern (.json)</button><button id="pLoad">Laden …</button><input type="file" id="pFile" accept=".json" hidden></div>
<div class="hint">Alles wird automatisch im Browser gespeichert.</div>
</div>
<div id="ed">
<div id="bar">
<button id="tPen" data-tool="pen" class="tb">✎ Stift</button><button id="tEra" data-tool="erase" class="tb">◌ Radierer</button>
<span class="sep"></span>
<span class="sz">Größe <input type="range" min="0.1" max="8" step="0.05" data-k="size"><output></output></span>
<button class="bs" data-v="0.3" title="fein"><i style="width:4px;height:4px"></i></button><button class="bs" data-v="0.8" title="mittel"><i style="width:9px;height:9px"></i></button><button class="bs" data-v="2" title="breit"><i style="width:16px;height:16px"></i></button>
<span class="sep"></span>
<button id="eUndo">↶ Rückgängig</button><button id="eClear">Leeren</button>
</div>
<div id="stage"><canvas id="cEd" width="800" height="800"></canvas></div>
<div id="info"></div>
</div>
<div id="prev">
<div class="hdr top">Vorschau</div>
<div class="pctl">
<div class="row"><label>Maßstab</label><input type="range" min="0.5" max="6" step="0.1" data-k="prev"><output></output></div>
<div class="chk"><input type="checkbox" id="cInv"><label for="cInv">invertiert</label></div>
</div>
<div class="pv"><small><span class="l"></span><span class="r"></span></small><canvas></canvas></div>
<div class="pv"><small><span class="l"></span><span class="r"></span></small><canvas></canvas></div>
<div class="pv"><small><span class="l"></span><span class="r"></span></small><canvas></canvas></div>
</div>
</div>
<script>
'use strict';
const $=s=>document.querySelector(s);
const TAU=Math.PI*2,S3=Math.sqrt(3),HH=S3/2,R=1/S3,DEG=Math.PI/180;
const clone=o=>JSON.parse(JSON.stringify(o));
const fmt=v=>Number(v).toLocaleString('de-DE',{maximumFractionDigits:2});
const uid=()=>'m'+Date.now().toString(36)+Math.random().toString(36).slice(2,5);
const lsGet=k=>{try{return JSON.parse(localStorage.getItem(k))}catch(e){return null}};
const lsSet=(k,v)=>{try{localStorage.setItem(k,JSON.stringify(v))}catch(e){info('Speicher im Browser voll – bitte „Projekt sichern“ nutzen.')}};
const info=t=>{$('#info').textContent=t};
// ---------- Affine Transformationen [a,b,c,d,e,f]: x'=a x + c y + e, y'=b x + d y + f ----------
const I=[1,0,0,1,0,0],MX=[-1,0,0,1,0,0],MY=[1,0,0,-1,0,0],MD=[0,1,1,0,0,0];
const mul=(A,B)=>[A[0]*B[0]+A[2]*B[1],A[1]*B[0]+A[3]*B[1],A[0]*B[2]+A[2]*B[3],A[1]*B[2]+A[3]*B[3],A[0]*B[4]+A[2]*B[5]+A[4],A[1]*B[4]+A[3]*B[5]+A[5]];
const ap=(T,p)=>[T[0]*p[0]+T[2]*p[1]+T[4],T[1]*p[0]+T[3]*p[1]+T[5]];
const inv=T=>{const d=T[0]*T[3]-T[1]*T[2];return[T[3]/d,-T[1]/d,-T[2]/d,T[0]/d,(T[2]*T[5]-T[3]*T[4])/d,(T[1]*T[4]-T[0]*T[5])/d]};
const rot=g=>{const c=Math.cos(g*DEG),s=Math.sin(g*DEG);return[c,s,-s,c,0,0]};
const rots=(n,step)=>Array.from({length:n},(_,k)=>rot(k*step));
const rect=(x0,y0,x1,y1)=>[[x0,y0],[x1,y0],[x1,y1],[x0,y1]];
const hv=k=>[R*Math.cos((30+60*k)*DEG),R*Math.sin((30+60*k)*DEG)];
// ---------- Rapport-Typen: Zeichenfeld (dom), Kopien im Feld (T), Gittervektoren (A,B), Spiegelgrenzen (clip) ----------
const TYPES={
quad:{n:'Quadrat',d:'Einfaches Raster: das Feld wiederholt sich quer und längs. Linien über den Rand laufen nahtlos weiter.',asp:1,
f:a=>({dom:rect(-.5,-a/2,.5,a/2),T:[I],A:[1,0],B:[0,a]})},
brick:{n:'Ziegel',d:'Wie Quadrat, jede Reihe um eine halbe Kachel versetzt.',asp:1,
f:a=>({dom:rect(-.5,-a/2,.5,a/2),T:[I],A:[1,0],B:[.5,a]})},
raute:{n:'Raute',d:'Rautenraster (Diagonalgitter).',asp:1,
f:a=>({dom:[[-.5,0],[0,-a/2],[.5,0],[0,a/2]],T:[I],A:[.5,a/2],B:[.5,-a/2]})},
mirx:{n:'Spiegel',d:'Halbes Feld zeichnen, links/rechts gespiegelt.',asp:1,
f:a=>({dom:rect(0,-a/2,.5,a/2),clip:rect(0,-99,.5,99),T:[I,MX],A:[1,0],B:[0,a]})},
mirxy:{n:'Spiegel 4×',d:'Viertel zeichnen, in beide Richtungen gespiegelt.',asp:1,
f:a=>({dom:rect(0,0,.5,a/2),clip:true,T:[I,MX,MY,mul(MX,MY)],A:[1,0],B:[0,a]})},
rot4:{n:'Drehung 4×',d:'Viertel zeichnen, 4× um die Mitte gedreht (Windrad).',
f:()=>({dom:rect(0,0,.5,.5),T:rots(4,90),A:[1,0],B:[0,1]})},
kal4:{n:'Kaleido 4',d:'Achtel zeichnen – quadratisches Kaleidoskop (8 Kopien).',
f:()=>({dom:[[0,0],[.5,0],[.5,.5]],clip:true,T:rots(4,90).flatMap(r=>[r,mul(r,MD)]),A:[1,0],B:[0,1]})},
hex:{n:'Wabe',d:'Sechseck-Raster: das Wabenfeld wiederholt sich lückenlos.',
f:()=>({dom:[0,1,2,3,4,5].map(hv),T:[I],A:[1,0],B:[.5,HH]})},
rot6:{n:'Wabe 6×',d:'Ein Sechstel zeichnen, 6× um die Wabenmitte gedreht.',
f:()=>({dom:[[0,0],hv(0),hv(1)],T:rots(6,60),A:[1,0],B:[.5,HH]})},
tri2:{n:'Dreieck',d:'Dreiecksraster: jedes zweite Dreieck steht auf dem Kopf.',
f:()=>({dom:[[-.5,-HH/3],[.5,-HH/3],[0,2*HH/3]],T:[I,[-1,0,0,-1,.5,HH/3]],A:[1,0],B:[.5,HH]})},
tri3:{n:'Dreieck ⟷',d:'Dreieck zeichnen, an allen drei Kanten gespiegelt.',
f:()=>({dom:[[0,0],hv(0),hv(1)],clip:true,T:[0,120,240].flatMap(g=>[rot(g),mul(MX,rot(g))]),A:[1,0],B:[.5,HH]})},
kal6:{n:'Kaleido 6',d:'Zwölftel zeichnen – sechseckiges Kaleidoskop (12 Kopien).',
f:()=>({dom:[[0,0],[.5,0],hv(0)],clip:true,T:rots(6,60).flatMap(r=>[r,mul(r,MY)]),A:[1,0],B:[.5,HH]})}
};
const geo=d=>{const t=TYPES[d.type]||TYPES.quad;return t.f(t.asp?d.asp:1)};
// ---------- Zustand ----------
const LS='turbopattern.v1',LSL='turbopattern.lib.v1';
const st={type:'hex',asp:1,tile:20,size:.6,tool:'pen',clip:true,zoom:1,grey:true,prev:1.5,inv:false,ew:100,eh:100,ppm:10,name:'Muster 1',libId:null,strokes:[]};
let lib=[],M=null,undo=[],unsaved=false,saveT=0,prevT=0;
const wU=()=>st.size/st.tile; // Strichstärke = Radierergröße, in Rapport-Einheiten
// ---------- Geometrie-Helfer ----------
function poly(c,pts){c.moveTo(pts[0][0],pts[0][1]);for(let i=1;i<pts.length;i++)c.lineTo(pts[i][0],pts[i][1]);c.closePath()}
function polyBB(P){let a=1e9,b=1e9,c=-1e9,d=-1e9;for(const p of P){a=Math.min(a,p[0]);b=Math.min(b,p[1]);c=Math.max(c,p[0]);d=Math.max(d,p[1])}return[a,b,c,d]}
function tbb(Ts,b){const pts=[];for(const T of Ts)for(const p of[[b[0],b[1]],[b[2],b[1]],[b[0],b[3]],[b[2],b[3]]])pts.push(ap(T,p));return polyBB(pts)}
function strokeTo(c,p){
c.moveTo(p[0][0],p[0][1]);
if(p.length<2){c.lineTo(p[0][0]+1e-5,p[0][1]);return}
for(let i=1;i<p.length-1;i++)c.quadraticCurveTo(p[i][0],p[i][1],(p[i][0]+p[i+1][0])/2,(p[i][1]+p[i+1][1])/2);
c.lineTo(p[p.length-1][0],p[p.length-1][1]);
}
function rawBB_unused(){let a=1e9,b=1e9,c=-1e9,d=-1e9;for(const s of st.strokes){const h=s.w/2;for(const p of s.p){a=Math.min(a,p[0]-h);b=Math.min(b,p[1]-h);c=Math.max(c,p[0]+h);d=Math.max(d,p[1]+h)}}return a<=c?[a,b,c,d]:null}
// Gitterverschiebungen t=iA+jB, für die das Kachel-Rechteck b+t das Sichtfeld schneidet
function offsets(G,b,vx0,vy0,vx1,vy1,max=40000){
const A=G.A,B=G.B,d=A[0]*B[1]-A[1]*B[0],tx0=vx0-b[2],tx1=vx1-b[0],ty0=vy0-b[3],ty1=vy1-b[1];
let i0=1e9,i1=-1e9,j0=1e9,j1=-1e9;
for(const[x,y]of[[tx0,ty0],[tx1,ty0],[tx0,ty1],[tx1,ty1]]){const i=(x*B[1]-y*B[0])/d,j=(A[0]*y-A[1]*x)/d;i0=Math.min(i0,i);i1=Math.max(i1,i);j0=Math.min(j0,j);j1=Math.max(j1,j)}
const o=[],e=1e-9;
for(let j=Math.floor(j0);j<=Math.ceil(j1);j++)for(let i=Math.floor(i0);i<=Math.ceil(i1);i++){
const x=i*A[0]+j*B[0],y=i*A[1]+j*B[1];
if(x>=tx0-e&&x<=tx1+e&&y>=ty0-e&&y<=ty1+e){o.push([x,y]);if(o.length>=max)return o}}
return o;
}
// ---------- Modell: Pfade + Kachel-Bitmap-Cache ----------
// Striche werden in Zeichenreihenfolge zu Ebenen gruppiert: Stift = schwarz auftragen, Radierer = weiß ausstanzen
function makeModel(d){
const G=geo(d),clipP=d.clip&&G.clip?(G.clip===true?G.dom:G.clip):null,layers=[];
let L=null;
for(const s of d.strokes){const e=!!s.e;if(!L||L.e!==e){L={e,groups:new Map(),b:null};layers.push(L)}
let g=L.groups.get(s.w);if(!g)L.groups.set(s.w,g=[]);g.push(s.p);
const h=s.w/2;for(const p of s.p){const b=L.b;if(!b)L.b=[p[0]-h,p[1]-h,p[0]+h,p[1]+h];else{b[0]=Math.min(b[0],p[0]-h);b[1]=Math.min(b[1],p[1]-h);b[2]=Math.max(b[2],p[0]+h);b[3]=Math.max(b[3],p[1]+h)}}}
while(layers.length&&layers[0].e)layers.shift(); // Radieren vor dem ersten Strich hat keine Wirkung
for(const L of layers){
L.raw=[...L.groups];delete L.groups;
L.paths=L.raw.map(([w,arr])=>{const P=new Path2D();for(const p of arr)strokeTo(P,p);return{w,P}});
let b=L.b;L.cb=null;L.cache=new Map();
if(b){if(clipP){const c=polyBB(clipP);b=[Math.max(b[0],c[0]),Math.max(b[1],c[1]),Math.min(b[2],c[2]),Math.min(b[3],c[3])]}
if(b[0]<b[2]&&b[1]<b[3])L.cb=tbb(G.T,b)}}
return{G,clipP,layers,any:layers.some(l=>!l.e&&l.cb)};
}
function drawCell(c,M,L,col){
c.strokeStyle=col;c.lineCap=c.lineJoin='round';
for(const T of M.G.T){c.save();c.transform(...T);if(M.clipP){c.beginPath();poly(c,M.clipP);c.clip()}for(const g of L.paths){c.lineWidth=g.w;c.stroke(g.P)}c.restore()}
}
function cellBmp(M,L,s,col){
const key=s.toFixed(4)+col;let b=L.cache.get(key);if(b)return b;
const cb=L.cb,pad=3,w0=cb[2]-cb[0],h0=cb[3]-cb[1];let bs=s;if(Math.max(w0,h0)*bs>3000)bs=3000/Math.max(w0,h0);
const cv=document.createElement('canvas');cv.width=Math.ceil(w0*bs)+2*pad;cv.height=Math.ceil(h0*bs)+2*pad;
const x=cv.getContext('2d');x.setTransform(bs,0,0,bs,pad-cb[0]*bs,pad-cb[1]*bs);drawCell(x,M,L,col);
b={cv,bs,pad};if(L.cache.size>16)L.cache.clear();L.cache.set(key,b);return b;
}
// Muster stempeln: s = px pro Rapport-Einheit, (ox,oy) = Lage des Ursprungs in px.
// Alle Ebenen nacheinander auf eine transparente Zwischenfläche, Radier-Ebenen per destination-out.
const scratch=document.createElement('canvas');
function paintPattern(c,M,s,ox,oy,W,H,col){
if(!M.any)return;
const tc=W*H>2.5e7?document.createElement('canvas'):scratch;
if(tc.width!==W||tc.height!==H){tc.width=W;tc.height=H}
const x=tc.getContext('2d');x.setTransform(1,0,0,1,0,0);x.globalCompositeOperation='source-over';x.clearRect(0,0,W,H);
for(const L of M.layers){if(!L.cb)continue;
const b=cellBmp(M,L,s,col),k=s/b.bs,cb=L.cb;
x.globalCompositeOperation=L.e?'destination-out':'source-over';
for(const t of offsets(M.G,cb,-ox/s,-oy/s,(W-ox)/s,(H-oy)/s))
x.drawImage(b.cv,ox+(cb[0]+t[0])*s-b.pad*k,oy+(cb[1]+t[1])*s-b.pad*k,b.cv.width*k,b.cv.height*k)}
x.globalCompositeOperation='source-over';
c.save();c.setTransform(1,0,0,1,0,0);c.drawImage(tc,0,0);c.restore();
}
// Bei Spiegel-Rapporten: Punkt in das Zeichenfeld zurückfalten → man kann überall zeichnen
function pointInPoly(u,P){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]>u[1])!==(b[1]>u[1])&&u[0]<(b[0]-a[0])*(u[1]-a[1])/(b[1]-a[1])+a[0])c=!c}return c}
function polyDist(u,P){if(pointInPoly(u,P))return 0;let m=1e9;for(let i=0,j=P.length-1;i<P.length;j=i++)m=Math.min(m,segD2(u,P[j],P[i]));return Math.sqrt(m)}
function foldPt(u,prev){
if(!M.clipP)return u;const G=M.G;
if(G.clip!==true)return[Math.abs(u[0]-Math.round(u[0])),u[1]]; // Spiegel ↔: nur quer falten
const db=polyBB(G.dom);let best=null,bs=1e9;
for(const T of G.T){const Ti=inv(T);for(const t of offsets(G,tbb([T],db),u[0],u[1],u[0],u[1],200)){
const p=ap(Ti,[u[0]-t[0],u[1]-t[1]]);let d=polyDist(p,G.dom);if(d<1e-6)d=0;
const sc=d*1e3+(prev?Math.hypot(p[0]-prev[0],p[1]-prev[1]):Math.hypot(t[0],t[1]));if(sc<bs){bs=sc;best=p}}}
return best||u;
}
// ---------- Editor ----------
const cEd=$('#cEd'),ectx=cEd.getContext('2d'),base=document.createElement('canvas'),bx=base.getContext('2d');
let dirtyBase=true,raf=0,cur=null,curE=false,lastU=null,tmpErase=false;
const GREY='#ababab';
const tool=()=>cur?(curE?'erase':'pen'):tmpErase?'erase':st.tool;
const view=()=>{const W=cEd.width,H=cEd.height;return{s:W/(2.4/st.zoom),ox:W/2,oy:H/2,W,H}};
const dpr=()=>Math.min(2,window.devicePixelRatio||1);
function fitEd(){
const r=$('#stage').getBoundingClientRect(),sz=Math.max(160,Math.floor(Math.min(r.width,r.height)-20)),px=Math.round(sz*dpr());
cEd.style.width=cEd.style.height=sz+'px';
if(cEd.width!==px){cEd.width=cEd.height=base.width=base.height=px;dirtyBase=true}
req();
}
function req(){if(!raf)raf=requestAnimationFrame(renderEd)}
function renderBase(){
const{s,ox,oy,W,H}=view(),c=bx,G=M.G;
c.setTransform(1,0,0,1,0,0);c.fillStyle='#fff';c.fillRect(0,0,W,H);
c.setTransform(s,0,0,s,ox,oy);
c.fillStyle='#f3f3f3';c.beginPath();poly(c,G.dom);c.fill();
// Rapport-Raster
const tb=tbb(G.T,polyBB(G.dom));c.strokeStyle='#e4e4e4';c.lineWidth=1/s;c.beginPath();
for(const t of offsets(G,tb,-ox/s,-oy/s,(W-ox)/s,(H-oy)/s,4000))for(const T of G.T)poly(c,G.dom.map(p=>{const q=ap(T,p);return[q[0]+t[0],q[1]+t[1]]}));
c.stroke();
paintPattern(c,M,s,ox,oy,W,H,st.grey?GREY:'#000');
// Inhalt des Zeichenfelds schwarz
if(st.grey){c.save();c.setTransform(s,0,0,s,ox,oy);c.beginPath();poly(c,G.dom);c.clip();paintPattern(c,M,s,ox,oy,W,H,'#000');c.restore()}
c.setTransform(s,0,0,s,ox,oy);
c.strokeStyle='#777';c.lineWidth=1.5/s;c.setLineDash([5/s,4/s]);c.beginPath();poly(c,G.dom);c.stroke();c.setLineDash([]);
}
function drawLive(c,s,ox,oy,W,H){
const G=M.G,w=wU();let b=null;for(const p of cur){if(!b)b=[p[0],p[1],p[0],p[1]];else{b[0]=Math.min(b[0],p[0]);b[1]=Math.min(b[1],p[1]);b[2]=Math.max(b[2],p[0]);b[3]=Math.max(b[3],p[1])}}
b=[b[0]-w,b[1]-w,b[2]+w,b[3]+w];
const P=new Path2D();strokeTo(P,cur);
for(const t of offsets(G,tbb(G.T,b),-ox/s,-oy/s,(W-ox)/s,(H-oy)/s,4000))G.T.forEach((T,k)=>{
const orig=!k&&Math.abs(t[0])<1e-9&&Math.abs(t[1])<1e-9;
c.save();c.setTransform(s,0,0,s,ox+t[0]*s,oy+t[1]*s);c.transform(...T);
if(M.clipP){c.beginPath();poly(c,M.clipP);c.clip()}
c.lineCap=c.lineJoin='round';c.strokeStyle=curE?'#fff':orig||!st.grey?'#000':GREY;c.lineWidth=w;c.stroke(P);c.restore()});
}
function renderEd(){
raf=0;if(dirtyBase){dirtyBase=false;renderBase()}
const{s,ox,oy,W,H}=view(),c=ectx;
c.setTransform(1,0,0,1,0,0);c.drawImage(base,0,0);
if(cur)drawLive(c,s,ox,oy,W,H);
if(lastU){c.setTransform(1,0,0,1,0,0);const r=Math.max(2,wU()/2*s);c.beginPath();c.arc(ox+lastU[0]*s,oy+lastU[1]*s,r,0,TAU);
c.lineWidth=dpr();if(tool()==='erase'){c.strokeStyle='#888';c.setLineDash([3*dpr(),3*dpr()])}else c.strokeStyle='#111';c.stroke();c.setLineDash([])}
}
const e2u=e=>{const r=cEd.getBoundingClientRect(),{s,ox,oy}=view();return[((e.clientX-r.left)/r.width*cEd.width-ox)/s,((e.clientY-r.top)/r.height*cEd.height-oy)/s]};
function segD2(q,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],l=dx*dx+dy*dy;let t=l?((q[0]-a[0])*dx+(q[1]-a[1])*dy)/l:0;t=Math.max(0,Math.min(1,t));const x=a[0]+t*dx-q[0],y=a[1]+t*dy-q[1];return x*x+y*y}
function simplify(p,d){const o=[p[0]];for(let i=1;i<p.length;i++){const q=o[o.length-1];if(Math.hypot(p[i][0]-q[0],p[i][1]-q[1])>=d||i===p.length-1)o.push(p[i])}return o}
function resample(p,d){if(p.length<2)return p;const o=[p[0]];
for(let i=1;i<p.length;i++){const a=o[o.length-1],b=p[i],n=Math.ceil(Math.hypot(b[0]-a[0],b[1]-a[1])/d);for(let k=1;k<n;k++)o.push([a[0]+(b[0]-a[0])*k/n,a[1]+(b[1]-a[1])*k/n]);o.push(b)}
return o.map(q=>[Math.round(q[0]*1e5)/1e5,Math.round(q[1]*1e5)/1e5])}
function snap(){undo.push(JSON.stringify(st.strokes));if(undo.length>60)undo.shift()}
cEd.addEventListener('contextmenu',e=>e.preventDefault());
cEd.addEventListener('pointerdown',e=>{
cEd.setPointerCapture(e.pointerId);tmpErase=e.button===2;curE=tool()==='erase';
const u=e2u(e);lastU=u;cur=[foldPt(u,null)];req()});
cEd.addEventListener('pointermove',e=>{
const evs=(e.getCoalescedEvents&&e.getCoalescedEvents())||[];if(!evs.length)evs.push(e);
lastU=e2u(e);
if(cur){const md=Math.max(.0012,wU()*.12);for(const ev of evs){const q=cur[cur.length-1],u=foldPt(e2u(ev),q);if(Math.hypot(u[0]-q[0],u[1]-q[1])>md)cur.push(u)}}
req()});
function endPointer(){
if(!cur)return;const w=wU(),s={w:Math.round(w*1e6)/1e6,p:resample(simplify(cur,Math.max(.0015,w*.15)),Math.max(.003,w*.5))};
if(curE)s.e=1;
snap();st.strokes.push(s);cur=null;tmpErase=false;changed();
}
cEd.addEventListener('pointerup',endPointer);cEd.addEventListener('pointercancel',endPointer);
cEd.addEventListener('pointerleave',()=>{if(!cur){lastU=null;req()}});
// ---------- Änderungen ----------
function changed(live){
M=makeModel(st);dirtyBase=true;req();unsaved=true;saveSoon();
schedPrev(live?160:0);updInfo();
}
function saveSoon(){clearTimeout(saveT);saveT=setTimeout(()=>lsSet(LS,st),300)}
function doUndo(){const u=undo.pop();if(u===undefined)return;st.strokes=JSON.parse(u);changed()}
// ---------- Vorschau ----------
const PV=[1,3,9];
function schedPrev(d){clearTimeout(prevT);prevT=setTimeout(renderPrev,d)}
function renderPrev(){
document.querySelectorAll('.pv').forEach((el,k)=>{
const cv=el.querySelector('canvas'),W=Math.round(cv.clientWidth*dpr());if(!W)return;
if(cv.width!==W){cv.width=W;cv.height=Math.round(cv.clientHeight*dpr())||W}
const H=cv.height,c=cv.getContext('2d'),rep=st.prev*PV[k],s=W/rep;
c.setTransform(1,0,0,1,0,0);c.fillStyle=st.inv?'#000':'#fff';c.fillRect(0,0,W,H);
paintPattern(c,M,s,W/2,H/2,W,H,st.inv?'#fff':'#000');
el.querySelector('.l').textContent=fmt(Math.round(rep*10)/10)+' Rapporte breit';
el.querySelector('.r').textContent=fmt(Math.round(rep*st.tile))+' mm';
});
}
new ResizeObserver(()=>schedPrev(60)).observe($('#prev'));
new ResizeObserver(fitEd).observe($('#stage'));
// ---------- UI ----------
function typeIcon(cv,k){
const t=TYPES[k],G=t.f(1),c=cv.getContext('2d'),W=cv.width=cv.height=88,s=W/2.3;
c.setTransform(1,0,0,1,0,0);c.clearRect(0,0,W,W);c.setTransform(s,0,0,s,W/2,W/2);
c.fillStyle='#111';c.beginPath();poly(c,G.dom);c.fill();
c.strokeStyle='#bbb';c.lineWidth=1.2/s;c.beginPath();
for(const o of offsets(G,tbb(G.T,polyBB(G.dom)),-1.15,-1.15,1.15,1.15,400))for(const T of G.T)poly(c,G.dom.map(p=>{const q=ap(T,p);return[q[0]+o[0],q[1]+o[1]]}));
c.stroke();
}
function buildTypes(){
const h=$('#types');h.innerHTML='';
for(const k of Object.keys(TYPES)){const b=document.createElement('button');b.dataset.t=k;const cv=document.createElement('canvas');typeIcon(cv,k);b.appendChild(cv);
const sp=document.createElement('span');sp.textContent=TYPES[k].n;b.appendChild(sp);
b.onclick=()=>{st.type=k;syncUI();changed()};h.appendChild(b)}
}
function setTool(t){st.tool=t;syncTools();req();saveSoon()}
function setSize(v){st.size=Math.max(.1,Math.min(8,Math.round(v*100)/100));syncUI();req();saveSoon();updInfo()}
function syncTools(){
document.querySelectorAll('#bar .tb').forEach(b=>b.classList.toggle('on',b.dataset.tool===st.tool));
document.querySelectorAll('#bar .bs').forEach(b=>b.classList.toggle('on',Math.abs(+b.dataset.v-st.size)<1e-6));
}
function syncUI(){
document.querySelectorAll('input[type=range][data-k]').forEach(inp=>{inp.value=st[inp.dataset.k];inp.nextElementSibling.textContent=fmt(st[inp.dataset.k])+(inp.dataset.k==='size'?' mm':'')});
document.querySelectorAll('#types button').forEach(b=>b.classList.toggle('on',b.dataset.t===st.type));
const t=TYPES[st.type],G=geo(st);
$('#tDesc').textContent=t.d;
$('#rAsp').style.display=t.asp?'':'none';$('#rClip').style.display=G.clip?'':'none';
$('#cClip').checked=st.clip;$('#cGrey').checked=st.grey;$('#cInv').checked=st.inv;
$('#ew').value=st.ew;$('#eh').value=st.eh;$('#ppm').value=st.ppm;$('#name').value=st.name;
syncTools();
}
function updInfo(){
const n=st.strokes.length;
info(`${TYPES[st.type].n} · Rapport ${fmt(st.tile)} mm · Strich/Radierer ${fmt(st.size)} mm · ${n} ${n===1?'Strich':'Striche'} · Radierer = weiße Linie, stanzt aus · Rechtsklick = radieren · B/E Werkzeug · [ ] Größe · ⌘/Strg+Z`);
}
document.querySelectorAll('input[type=range][data-k]').forEach(inp=>{
inp.oninput=()=>{const k=inp.dataset.k;st[k]=+inp.value;inp.nextElementSibling.textContent=fmt(st[k])+(k==='size'?' mm':'');
if(k==='asp')changed();
else if(k==='zoom'){dirtyBase=true;req();saveSoon()}
else if(k==='prev'){schedPrev(0);saveSoon()}
else if(k==='size'){syncTools();req();saveSoon();updInfo()}
else if(k==='tile'){schedPrev(80);req();saveSoon();updInfo()}}});
document.querySelectorAll('#bar .tb').forEach(b=>b.onclick=()=>setTool(b.dataset.tool));
document.querySelectorAll('#bar .bs').forEach(b=>b.onclick=()=>setSize(+b.dataset.v));
$('#cClip').onchange=e=>{st.clip=e.target.checked;changed()};
$('#cGrey').onchange=e=>{st.grey=e.target.checked;dirtyBase=true;req();saveSoon()};
$('#cInv').onchange=e=>{st.inv=e.target.checked;schedPrev(0);saveSoon()};
$('#eUndo').onclick=doUndo;
$('#eClear').onclick=()=>{if(!st.strokes.length)return;snap();st.strokes=[];changed()};
['ew','eh','ppm'].forEach(k=>$('#'+k).onchange=e=>{st[k]=Math.max(1,+e.target.value||1);saveSoon()});
$('#name').oninput=e=>{st.name=e.target.value;saveSoon()};
addEventListener('keydown',e=>{
if(e.target.matches('input,select,textarea'))return;
if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='z'){e.preventDefault();doUndo();return}
if(e.key==='b'||e.key==='p')setTool('pen');else if(e.key==='e')setTool('erase');
else if(e.key==='[')setSize(st.size/1.25);else if(e.key===']')setSize(st.size*1.25)});
// ---------- Meine Muster ----------
function thumb(){const cv=document.createElement('canvas');cv.width=cv.height=120;const c=cv.getContext('2d');c.fillStyle='#fff';c.fillRect(0,0,120,120);paintPattern(c,M,120/2.5,60,60,120,120,'#000');return cv.toDataURL('image/png')}
function libSave(asNew){
if(!st.strokes.length){info('Zeichne zuerst etwas.');return}
const name=($('#name').value||'Muster').trim()||'Muster',data={name,type:st.type,asp:st.asp,clip:st.clip,tile:st.tile,strokes:clone(st.strokes),thumb:thumb()};
let it=!asNew&&st.libId?lib.find(x=>x.id===st.libId):null;
if(it)Object.assign(it,data);else{let n=name,k=2;while(lib.some(x=>x.name===n))n=name+' '+k++;data.name=n;it=Object.assign({id:uid()},data);lib.unshift(it)}
st.libId=it.id;st.name=it.name;$('#name').value=it.name;unsaved=false;lsSet(LSL,lib);saveSoon();renderLib();info('Gespeichert: '+it.name);
}
function libOpen(it){
if(unsaved&&st.strokes.length&&st.libId!==it.id&&!confirm('Ungespeicherte Änderungen verwerfen?'))return;
Object.assign(st,{type:it.type,asp:it.asp??1,clip:it.clip??true,tile:it.tile??st.tile,strokes:clone(it.strokes),libId:it.id,name:it.name});
undo=[];syncUI();changed();unsaved=false;renderLib();
}
function libNew(){
if(unsaved&&st.strokes.length&&!confirm('Ungespeicherte Änderungen verwerfen?'))return;
Object.assign(st,{strokes:[],libId:null,name:'Muster '+(lib.length+1)});undo=[];syncUI();changed();unsaved=false;renderLib();
}
function renderLib(){
const g=$('#lib');g.innerHTML='';
if(!lib.length){g.innerHTML='<div class="hint" style="grid-column:1/-1">Noch keine gespeicherten Muster.</div>';return}
for(const it of lib){const d=document.createElement('div');d.className='it'+(it.id===st.libId?' on':'');d.title=it.name;
d.innerHTML=`<img alt=""><span></span><b class="x" title="löschen">×</b>`;d.querySelector('img').src=it.thumb||'';d.querySelector('span').textContent=it.name;
d.onclick=()=>libOpen(it);
d.querySelector('.x').onclick=ev=>{ev.stopPropagation();if(!confirm(`„${it.name}“ löschen?`))return;lib=lib.filter(x=>x.id!==it.id);if(st.libId===it.id)st.libId=null;lsSet(LSL,lib);renderLib()};
g.appendChild(d)}
}
$('#lSave').onclick=()=>libSave(false);$('#lCopy').onclick=()=>libSave(true);$('#lNew').onclick=libNew;
// ---------- Export ----------
function dl(blob,name){const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(a.href),2000)}
const fname=ext=>(st.name||'muster').trim().replace(/[^\wäöüÄÖÜß\- ]+/g,'').replace(/\s+/g,'_')+'.'+ext;
function pathD(p,f){if(p.length<2)return`M${f(p[0][0])} ${f(p[0][1])}l0.00001 0`;let d=`M${f(p[0][0])} ${f(p[0][1])}`;
for(let i=1;i<p.length-1;i++)d+=`Q${f(p[i][0])} ${f(p[i][1])} ${f((p[i][0]+p[i+1][0])/2)} ${f((p[i][1]+p[i+1][1])/2)}`;
return d+`L${f(p[p.length-1][0])} ${f(p[p.length-1][1])}`}
function toSVG(){
const G=M.G,k=st.tile,W=st.ew,H=st.eh,f=v=>+(+v).toFixed(5),x0=-W/2/k,y0=-H/2/k,x1=W/2/k,y1=H/2/k;
let defs=`<clipPath id="area"><rect width="${W}" height="${H}"/></clipPath>`,body='';
if(M.clipP)defs+=`<clipPath id="cp"><polygon points="${M.clipP.map(p=>f(p[0])+','+f(p[1])).join(' ')}"/></clipPath>`;
M.layers.forEach((L,i)=>{if(!L.cb)return;
defs+=`<g id="m${i}" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round">`+L.raw.map(([w,arr])=>`<path stroke-width="${f(w)}" d="${arr.map(p=>pathD(p,f)).join('')}"/>`).join('')+'</g>';
defs+=`<g id="c${i}">`+G.T.map(T=>`<g transform="matrix(${T.map(f).join(' ')})"><use href="#m${i}" xlink:href="#m${i}"${M.clipP?' clip-path="url(#cp)"':''}/></g>`).join('')+'</g>';
const uses=offsets(G,L.cb,x0,y0,x1,y1,20000).map(t=>`<use href="#c${i}" xlink:href="#c${i}" x="${f(t[0])}" y="${f(t[1])}"/>`).join('');
if(!L.e)body+=uses;
else{defs+=`<mask id="k${i}" maskUnits="userSpaceOnUse" x="${f(x0)}" y="${f(y0)}" width="${f(x1-x0)}" height="${f(y1-y0)}"><rect x="${f(x0)}" y="${f(y0)}" width="${f(x1-x0)}" height="${f(y1-y0)}" fill="#fff"/>${uses}</mask>`;
body=`<g mask="url(#k${i})">${body}</g>`}});
return`<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${W}mm" height="${H}mm" viewBox="0 0 ${W} ${H}"><defs>${defs}</defs><rect width="${W}" height="${H}" fill="#fff"/><g clip-path="url(#area)"><g transform="translate(${W/2} ${H/2}) scale(${k})">${body}</g></g></svg>`;
}
$('#xSVG').onclick=()=>{if(!M.any){info('Noch nichts gezeichnet.');return}dl(new Blob([toSVG()],{type:'image/svg+xml'}),fname('svg'))};
$('#xPNG').onclick=()=>{
if(!M.any){info('Noch nichts gezeichnet.');return}
let ppm=st.ppm;const mx=Math.max(st.ew,st.eh)*ppm;if(mx>8000)ppm*=8000/mx;
const W=Math.round(st.ew*ppm),H=Math.round(st.eh*ppm),cv=document.createElement('canvas');cv.width=W;cv.height=H;
const c=cv.getContext('2d');c.fillStyle='#fff';c.fillRect(0,0,W,H);paintPattern(c,M,st.tile*ppm,W/2,H/2,W,H,'#000');
cv.toBlob(b=>dl(b,fname('png')));if(ppm<st.ppm)info(`PNG auf ${fmt(ppm)} px/mm begrenzt (max. 8000 px).`)};
$('#pSave').onclick=()=>dl(new Blob([JSON.stringify({app:'turbopattern',v:1,state:st,library:lib})],{type:'application/json'}),'turbopattern_projekt.json');
$('#pLoad').onclick=()=>$('#pFile').click();
$('#pFile').onchange=e=>{const fl=e.target.files[0];if(!fl)return;const r=new FileReader();
r.onload=()=>{try{const o=JSON.parse(r.result);if(o.state)Object.assign(st,o.state);
if(Array.isArray(o.library))for(const it of o.library)if(!lib.some(x=>x.id===it.id))lib.push(it);
lsSet(LSL,lib);undo=[];syncUI();changed();renderLib();info('Projekt geladen.')}catch(err){info('Datei konnte nicht gelesen werden.')}};
r.readAsText(fl);e.target.value=''};
// ---------- Start ----------
{const s=lsGet(LS)||lsGet('musterform.v1');if(s&&Array.isArray(s.strokes))Object.assign(st,s);else{
// kleines Startmotiv
const ring=[];for(let i=0;i<=48;i++){const a=TAU*i/48;ring.push([.2*Math.cos(a),.2*Math.sin(a)])}
st.strokes=[{w:.03,p:resample(ring,.015)},{w:.03,p:resample([[0,-.2],[0,-.5]],.015)},{w:.05,p:[[0,0]]}]}
const l=lsGet(LSL)||lsGet('musterform.lib.v1');if(Array.isArray(l))lib=l;
if(!TYPES[st.type])st.type='quad';}
M=makeModel(st);
buildTypes();syncUI();renderLib();updInfo();fitEd();schedPrev(0);
</script>
</body>