BlueGit

timfa timdraw

feat: Linux-aansturing voor de Bachin TA4

Eerste versie van Timdraw: SVG en tekst op A4, met joggen, homing en een voorbeeldloop binnen het gemeten bereik.

timfa Tim Falken · pushed by timfa

Authored 2026-09-29 · 7 weeks ago

Hash
727c743335795b1f2e91d00b321e73c0cd4707a9
17 files changed +4261 −0
.gitignore added +3 −0
@@ -0,0 +1,3 @@
1 __pycache__/
2 *.py[cod]
3 .venv/
@@ -0,0 +1,3 @@
1__pycache__/
2*.py[cod]
3.venv/
requirements.txt added +1 −0
@@ -0,0 +1 @@
1 pyserial>=3.5
@@ -0,0 +1 @@
1pyserial>=3.5
static/app.js added +1052 −0
@@ -0,0 +1,1052 @@
1 const A4W = 210;
2 const A4H = 297;
3 const PEN_MM = 0.4;
4
5 const $ = (id) => document.getElementById(id);
6 const canvas = $("page");
7 const ctx = canvas.getContext("2d");
8
9 let objects = [];
10 let selectedId = null;
11 let clipboard = null;
12 let preview = null;
13 let previewGen = 0;
14 let interacting = false;
15 let zoom = 1;
16 let panX = 0;
17 let panY = 0;
18 let filling = false;
19 let textTimer = 0;
20 let userDisconnected = false;
21 let autoTried = "";
22 const PORT_KEY = "timdraw-port";
23
24 const defaults = {
25 drawLine: true,
26 drawFill: false,
27 hatchAngle: 45,
28 hatchSpacing: 2,
29 crosshatch: false,
30 grayscale: false,
31 graySteps: 5,
32 spacingMin: 0.8,
33 spacingMax: 4,
34 };
35
36 function selected ()
37 {
38 return objects.find((obj) => obj.id === selectedId) || null;
39 }
40
41 let toastTimer = 0;
42
43 function toast (message, hideAfter)
44 {
45 const el = $("toast");
46 clearTimeout(toastTimer);
47 el.hidden = !message;
48 el.textContent = message || "";
49 if (message && hideAfter)
50 {
51 toastTimer = setTimeout(() =>
52 {
53 el.hidden = true;
54 el.textContent = "";
55 }, hideAfter);
56 }
57 }
58
59 async function api (path, body)
60 {
61 const options = body
62 ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
63 : {};
64 const response = await fetch(path, options);
65 const data = await response.json().catch(() => ({}));
66 if (!response.ok) throw new Error(data.error || response.statusText);
67 return data;
68 }
69
70 function readSettings ()
71 {
72 return {
73 drawSpeed: Number($("draw-speed").value),
74 travelSpeed: Number($("travel-speed").value),
75 penUpZ: Number($("pen-up").value),
76 penDownZ: Number($("pen-down").value),
77 dwellMs: Number($("dwell").value),
78 origin: $("origin").value,
79 returnHome: $("return-home").checked,
80 allowOutside: $("allow-outside").checked,
81 };
82 }
83
84 function styleFlags (obj)
85 {
86 if (obj.drawLine != null || obj.drawFill != null)
87 return { drawLine: !!obj.drawLine, drawFill: !!obj.drawFill };
88 if (obj.mode === "fill") return { drawLine: false, drawFill: true };
89 return { drawLine: true, drawFill: false };
90 }
91
92 function styleLabel (obj)
93 {
94 const flags = styleFlags(obj);
95 if (flags.drawLine && flags.drawFill) return "lijn + vulling";
96 if (flags.drawFill) return "vulling";
97 if (flags.drawLine) return "lijn";
98 return "uit";
99 }
100
101 function hatchFromForm ()
102 {
103 return {
104 drawLine: $("prop-line").checked,
105 drawFill: $("prop-fill").checked,
106 hatchAngle: Number($("prop-angle").value),
107 hatchSpacing: Number($("prop-spacing").value),
108 crosshatch: $("prop-cross").checked,
109 grayscale: $("prop-gray").checked,
110 graySteps: Number($("prop-steps").value),
111 spacingMin: Number($("prop-dark").value),
112 spacingMax: Number($("prop-light").value),
113 };
114 }
115
116 function layout ()
117 {
118 const rect = canvas.getBoundingClientRect();
119 const margin = 28;
120 const fit = Math.min((rect.width - margin * 2) / A4W, (rect.height - margin * 2) / A4H);
121 const scale = fit * zoom;
122 return {
123 scale,
124 ox: (rect.width - A4W * scale) / 2 + panX,
125 oy: (rect.height - A4H * scale) / 2 + panY,
126 width: rect.width,
127 height: rect.height,
128 };
129 }
130
131 function mmToPx (x, y)
132 {
133 const view = layout();
134 return [view.ox + x * view.scale, view.oy + (A4H - y) * view.scale];
135 }
136
137 function pxToMm (px, py)
138 {
139 const view = layout();
140 return [(px - view.ox) / view.scale, A4H - (py - view.oy) / view.scale];
141 }
142
143 function objPoint (obj, x, y)
144 {
145 const scale = obj.scale || 1;
146 x *= scale;
147 y *= scale;
148 const angle = (obj.rotation || 0) * Math.PI / 180;
149 const ca = Math.cos(angle);
150 const sa = Math.sin(angle);
151 return [x * ca - y * sa + obj.x, x * sa + y * ca + obj.y];
152 }
153
154 function eachLocal (obj, fn)
155 {
156 for (const stroke of obj.strokes || [])
157 {
158 for (const point of stroke.pts || stroke) fn(point[0], point[1]);
159 }
160 for (const fill of obj.fills || [])
161 {
162 for (const ring of fill.rings || [])
163 {
164 for (const point of ring) fn(point[0], point[1]);
165 }
166 }
167 }
168
169 function bbox (obj)
170 {
171 let minx = Infinity;
172 let miny = Infinity;
173 let maxx = -Infinity;
174 let maxy = -Infinity;
175 eachLocal(obj, (x, y) =>
176 {
177 const point = objPoint(obj, x, y);
178 minx = Math.min(minx, point[0]);
179 miny = Math.min(miny, point[1]);
180 maxx = Math.max(maxx, point[0]);
181 maxy = Math.max(maxy, point[1]);
182 });
183 if (!Number.isFinite(minx))
184 {
185 return { minx: obj.x - 5, miny: obj.y - 5, maxx: obj.x + 5, maxy: obj.y + 5 };
186 }
187 return { minx, miny, maxx, maxy };
188 }
189
190 function resize ()
191 {
192 const rect = canvas.getBoundingClientRect();
193 const dpr = window.devicePixelRatio || 1;
194 canvas.width = Math.max(1, rect.width * dpr);
195 canvas.height = Math.max(1, rect.height * dpr);
196 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
197 draw();
198 }
199
200 function drawSheet (view)
201 {
202 const origin = mmToPx(0, 0);
203 const far = mmToPx(A4W, A4H);
204 const x = Math.min(origin[0], far[0]);
205 const y = Math.min(origin[1], far[1]);
206 const w = Math.abs(far[0] - origin[0]);
207 const h = Math.abs(far[1] - origin[1]);
208 ctx.save();
209 ctx.fillStyle = "rgba(0,0,0,0.35)";
210 ctx.fillRect(x + 8, y + 10, w, h);
211 ctx.fillStyle = "#f6f1e6";
212 ctx.fillRect(x, y, w, h);
213 ctx.strokeStyle = "rgba(80,60,40,0.18)";
214 ctx.lineWidth = 1;
215 ctx.beginPath();
216 for (let i = 10; i < A4W; i += 10)
217 {
218 const a = mmToPx(i, 0);
219 const b = mmToPx(i, A4H);
220 ctx.moveTo(a[0], a[1]);
221 ctx.lineTo(b[0], b[1]);
222 }
223 for (let i = 10; i < A4H; i += 10)
224 {
225 const a = mmToPx(0, i);
226 const b = mmToPx(A4W, i);
227 ctx.moveTo(a[0], a[1]);
228 ctx.lineTo(b[0], b[1]);
229 }
230 ctx.stroke();
231 ctx.strokeStyle = "#2b241e";
232 ctx.lineWidth = 1.5;
233 ctx.strokeRect(x, y, w, h);
234 ctx.fillStyle = "#8a7b6c";
235 ctx.font = "12px Liberation Sans, sans-serif";
236 const originTop = $("origin").value === "top-left";
237 ctx.fillText("0,0", x + 6, originTop ? y + 16 : y + h - 8);
238 ctx.fillText("A4", x + w - 26, originTop ? y + h - 8 : y + 16);
239 ctx.restore();
240 }
241
242 function tracePoly (points)
243 {
244 if (!points.length) return;
245 const first = mmToPx(points[0][0], points[0][1]);
246 ctx.moveTo(first[0], first[1]);
247 for (let i = 1; i < points.length; i++)
248 {
249 const point = mmToPx(points[i][0], points[i][1]);
250 ctx.lineTo(point[0], point[1]);
251 }
252 }
253
254 function drawObject (obj, active)
255 {
256 ctx.save();
257 ctx.lineWidth = active ? 1.6 : 1.15;
258 ctx.strokeStyle = "#1d1a17";
259 ctx.fillStyle = "rgba(224,122,61,0.13)";
260 ctx.lineJoin = "round";
261 ctx.lineCap = "round";
262 ctx.beginPath();
263 for (const fill of obj.fills || [])
264 {
265 for (const ring of fill.rings || [])
266 {
267 const page = ring.map((point) => objPoint(obj, point[0], point[1]));
268 tracePoly(page);
269 ctx.closePath();
270 }
271 }
272 ctx.fill("evenodd");
273 ctx.beginPath();
274 for (const stroke of obj.strokes || [])
275 {
276 const pts = (stroke.pts || stroke).map((point) => objPoint(obj, point[0], point[1]));
277 tracePoly(pts);
278 }
279 ctx.stroke();
280 ctx.restore();
281 }
282
283 function drawPreview ()
284 {
285 ctx.save();
286 ctx.lineCap = "round";
287 ctx.lineJoin = "round";
288 ctx.strokeStyle = "#1d1a17";
289 ctx.lineWidth = 1.15;
290 ctx.beginPath();
291 for (const line of preview.draw || []) tracePoly(line);
292 ctx.stroke();
293 if ($("show-travel").checked)
294 {
295 ctx.strokeStyle = "rgba(176,122,62,0.85)";
296 ctx.setLineDash([4, 4]);
297 ctx.lineWidth = 1;
298 ctx.beginPath();
299 for (const line of preview.travel || []) tracePoly(line);
300 ctx.stroke();
301 }
302 ctx.restore();
303 }
304
305 function drawHandles (obj)
306 {
307 const box = bbox(obj);
308 const corners = [
309 mmToPx(box.minx, box.maxy),
310 mmToPx(box.maxx, box.maxy),
311 mmToPx(box.maxx, box.miny),
312 mmToPx(box.minx, box.miny),
313 ];
314 ctx.save();
315 ctx.strokeStyle = "#e07a3d";
316 ctx.fillStyle = "#fff";
317 ctx.lineWidth = 1.4;
318 ctx.beginPath();
319 corners.forEach((point, index) => index ? ctx.lineTo(point[0], point[1]) : ctx.moveTo(point[0], point[1]));
320 ctx.closePath();
321 ctx.stroke();
322 const top = mmToPx((box.minx + box.maxx) / 2, box.maxy);
323 ctx.beginPath();
324 ctx.moveTo(top[0], top[1]);
325 ctx.lineTo(top[0], top[1] - 22);
326 ctx.stroke();
327 ctx.beginPath();
328 ctx.arc(top[0], top[1] - 22, 5, 0, Math.PI * 2);
329 ctx.fill();
330 ctx.stroke();
331 for (const point of corners)
332 {
333 ctx.fillRect(point[0] - 4, point[1] - 4, 8, 8);
334 ctx.strokeRect(point[0] - 4, point[1] - 4, 8, 8);
335 }
336 ctx.restore();
337 }
338
339 function draw ()
340 {
341 const view = layout();
342 ctx.clearRect(0, 0, view.width, view.height);
343 drawSheet(view);
344 const current = selected();
345 if (preview && !interacting) drawPreview();
346 else objects.forEach((obj) => drawObject(obj, obj === current));
347 if (current) drawHandles(current);
348 }
349
350 function persist ()
351 {
352 localStorage.setItem("timdraw-doc", JSON.stringify({ objects, defaults, settings: readSettings() }));
353 }
354
355 function schedulePreview ()
356 {
357 clearTimeout(schedulePreview.timer);
358 schedulePreview.timer = setTimeout(refreshPreview, 160);
359 }
360
361 async function refreshPreview ()
362 {
363 const gen = ++previewGen;
364 try
365 {
366 const data = await api("/api/preview", { objects, settings: readSettings() });
367 if (gen !== previewGen) return;
368 preview = data;
369 const stats = data.stats || {};
370 const minutes = Math.floor((stats.seconds || 0) / 60);
371 const seconds = Math.round((stats.seconds || 0) % 60);
372 $("stats").textContent = objects.length
373 ? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s`
374 : "";
375 if (data.warnings && data.warnings.length) toast(data.warnings[0]);
376 $("btn-plot").disabled = !!stats.blocked;
377 } catch (error)
378 {
379 toast(error.message);
380 }
381 draw();
382 persist();
383 }
384
385 function renderList ()
386 {
387 const list = $("layers");
388 list.innerHTML = "";
389 objects.forEach((obj) =>
390 {
391 const item = document.createElement("li");
392 const button = document.createElement("button");
393 button.type = "button";
394 button.className = obj.id === selectedId ? "active" : "";
395 button.innerHTML = `<span>${obj.name || "Object"}</span><span class="tag">${styleLabel(obj)}</span>`;
396 button.onclick = () =>
397 {
398 selectedId = obj.id;
399 renderList();
400 fillForm();
401 draw();
402 };
403 item.appendChild(button);
404 list.appendChild(item);
405 });
406 }
407
408 function fillForm ()
409 {
410 const obj = selected() || defaults;
411 filling = true;
412 $("prop-title").textContent = selected() ? (selected().name || "Object") : "Voor nieuwe objecten";
413 const flags = styleFlags(obj);
414 $("prop-line").checked = flags.drawLine;
415 $("prop-fill").checked = flags.drawFill;
416 $("prop-angle").value = obj.hatchAngle;
417 $("prop-spacing").value = obj.hatchSpacing;
418 $("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100)));
419 $("prop-cross").checked = !!obj.crosshatch;
420 $("prop-gray").checked = !!obj.grayscale;
421 $("prop-steps").value = obj.graySteps;
422 $("prop-dark").value = obj.spacingMin;
423 $("prop-light").value = obj.spacingMax;
424 $("gray-props").hidden = !obj.grayscale;
425 $("defaults-hint").hidden = !!selected();
426 const isText = selected() && selected().kind === "text";
427 $("text-props").hidden = !isText;
428 if (isText)
429 {
430 $("prop-text").value = selected().text || "";
431 $("prop-font").value = selected().font || "futural";
432 $("prop-size").value = selected().fontSize || 12;
433 }
434 filling = false;
435 }
436
437 function applyForm ()
438 {
439 if (filling) return;
440 const values = hatchFromForm();
441 const obj = selected();
442 if (obj) Object.assign(obj, values);
443 else Object.assign(defaults, values);
444 $("gray-props").hidden = !values.grayscale;
445 renderList();
446 schedulePreview();
447 }
448
449 function syncPercent (fromPercent)
450 {
451 if (filling) return;
452 if (fromPercent)
453 {
454 const percent = Math.min(100, Math.max(2, Number($("prop-percent").value) || 2));
455 $("prop-spacing").value = (PEN_MM / (percent / 100)).toFixed(2);
456 } else
457 {
458 const spacing = Math.max(0.3, Number($("prop-spacing").value) || 0.3);
459 $("prop-percent").value = Math.round(Math.min(100, (PEN_MM / spacing) * 100));
460 }
461 applyForm();
462 }
463
464 function addObject (geo, name, extra = {})
465 {
466 const grays = [...new Set((geo.fills || []).map((fill) => Math.round(fill.gray * 20)))];
467 const obj = {
468 id: crypto.randomUUID(),
469 name,
470 kind: extra.kind || "svg",
471 x: geo.x,
472 y: geo.y,
473 scale: 1,
474 rotation: 0,
475 strokes: geo.strokes || [],
476 fills: geo.fills || [],
477 ...defaults,
478 grayscale: grays.length > 1 || defaults.grayscale,
479 ...extra,
480 drawLine: extra.drawLine != null ? extra.drawLine : defaults.drawLine,
481 drawFill: extra.drawFill != null ? extra.drawFill : (grays.length > 1 || defaults.drawFill),
482 };
483 objects.push(obj);
484 selectedId = obj.id;
485 renderList();
486 fillForm();
487 if (geo.warnings && geo.warnings.length) toast(geo.warnings.join(" "));
488 schedulePreview();
489 }
490
491 async function importSvgText (svg, name)
492 {
493 const geo = await api("/api/svg", { svg, name });
494 addObject(geo, geo.name || name || "SVG");
495 }
496
497 function cloneSelected (offset)
498 {
499 const obj = selected();
500 if (!obj) return;
501 const copy = structuredClone(obj);
502 copy.id = crypto.randomUUID();
503 copy.x += offset;
504 copy.y += offset;
505 copy.name = `${obj.name} kopie`;
506 objects.push(copy);
507 selectedId = copy.id;
508 renderList();
509 fillForm();
510 schedulePreview();
511 }
512
513 async function rebuildText (obj)
514 {
515 const geo = await api("/api/text", {
516 text: obj.text,
517 font: obj.font,
518 fontSize: obj.fontSize,
519 lineSpacing: 1.4,
520 });
521 obj.strokes = geo.strokes;
522 obj.fills = geo.fills;
523 schedulePreview();
524 draw();
525 }
526
527 function handleAt (px, py)
528 {
529 const obj = selected();
530 if (!obj) return null;
531 const box = bbox(obj);
532 const corners = {
533 nw: mmToPx(box.minx, box.maxy),
534 ne: mmToPx(box.maxx, box.maxy),
535 se: mmToPx(box.maxx, box.miny),
536 sw: mmToPx(box.minx, box.miny),
537 };
538 const top = mmToPx((box.minx + box.maxx) / 2, box.maxy);
539 if (Math.hypot(top[0] - px, top[1] - 22 - py) < 9) return "rot";
540 for (const [name, point] of Object.entries(corners))
541 {
542 if (Math.hypot(point[0] - px, point[1] - py) < 9) return name;
543 }
544 return null;
545 }
546
547 function hitObject (x, y)
548 {
549 const view = layout();
550 const pad = 5 / view.scale;
551 for (let i = objects.length - 1; i >= 0; i--)
552 {
553 const box = bbox(objects[i]);
554 if (x >= box.minx - pad && x <= box.maxx + pad && y >= box.miny - pad && y <= box.maxy + pad) return objects[i];
555 }
556 return null;
557 }
558
559 let drag = null;
560
561 canvas.addEventListener("pointerdown", (event) =>
562 {
563 if (event.button === 1 || event.altKey)
564 {
565 drag = { type: "pan", x: event.clientX, y: event.clientY, panX, panY };
566 canvas.setPointerCapture(event.pointerId);
567 return;
568 }
569 const rect = canvas.getBoundingClientRect();
570 const px = event.clientX - rect.left;
571 const py = event.clientY - rect.top;
572 const handle = handleAt(px, py);
573 const [x, y] = pxToMm(px, py);
574 const obj = selected();
575 if (handle && obj)
576 {
577 const box = bbox(obj);
578 const cx = (box.minx + box.maxx) / 2;
579 const cy = (box.miny + box.maxy) / 2;
580 drag = {
581 type: handle === "rot" ? "rot" : "scale",
582 id: obj.id,
583 cx, cy,
584 startAngle: Math.atan2(y - cy, x - cx),
585 startRot: obj.rotation || 0,
586 startDist: Math.hypot(x - cx, y - cy) || 1,
587 startScale: obj.scale || 1,
588 };
589 } else
590 {
591 const hit = hitObject(x, y);
592 selectedId = hit ? hit.id : null;
593 renderList();
594 fillForm();
595 if (hit) drag = { type: "move", id: hit.id, x, y, ox: hit.x, oy: hit.y };
596 }
597 interacting = !!drag;
598 canvas.setPointerCapture(event.pointerId);
599 draw();
600 });
601
602 canvas.addEventListener("pointermove", (event) =>
603 {
604 if (!drag) return;
605 if (drag.type === "pan")
606 {
607 panX = drag.panX + (event.clientX - drag.x);
608 panY = drag.panY + (event.clientY - drag.y);
609 draw();
610 return;
611 }
612 const rect = canvas.getBoundingClientRect();
613 const [x, y] = pxToMm(event.clientX - rect.left, event.clientY - rect.top);
614 const obj = objects.find((item) => item.id === drag.id);
615 if (!obj) return;
616 if (drag.type === "move")
617 {
618 obj.x = drag.ox + (x - drag.x);
619 obj.y = drag.oy + (y - drag.y);
620 } else if (drag.type === "scale")
621 {
622 const dist = Math.hypot(x - drag.cx, y - drag.cy);
623 obj.scale = Math.max(0.05, Math.min(20, drag.startScale * (dist / drag.startDist)));
624 } else if (drag.type === "rot")
625 {
626 const angle = Math.atan2(y - drag.cy, x - drag.cx);
627 obj.rotation = Math.round(drag.startRot + (angle - drag.startAngle) * 180 / Math.PI);
628 }
629 draw();
630 });
631
632 function endDrag ()
633 {
634 if (drag && drag.type !== "pan") schedulePreview();
635 drag = null;
636 interacting = false;
637 }
638
639 canvas.addEventListener("pointerup", endDrag);
640 canvas.addEventListener("pointercancel", endDrag);
641 canvas.addEventListener("wheel", (event) =>
642 {
643 event.preventDefault();
644 zoom = Math.max(0.35, Math.min(8, zoom * (event.deltaY < 0 ? 1.08 : 0.92)));
645 draw();
646 }, { passive: false });
647
648 window.addEventListener("keydown", (event) =>
649 {
650 const typing = ["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName);
651 if ((event.key === "Delete" || event.key === "Backspace") && !typing)
652 {
653 objects = objects.filter((obj) => obj.id !== selectedId);
654 selectedId = null;
655 renderList();
656 fillForm();
657 schedulePreview();
658 } else if (event.key === "Escape")
659 {
660 selectedId = null;
661 renderList();
662 fillForm();
663 draw();
664 } else if (!typing && (event.key.startsWith("Arrow")))
665 {
666 const obj = selected();
667 if (!obj) return;
668 const step = event.shiftKey ? 0.1 : 1;
669 if (event.key === "ArrowLeft") obj.x -= step;
670 if (event.key === "ArrowRight") obj.x += step;
671 if (event.key === "ArrowUp") obj.y += step;
672 if (event.key === "ArrowDown") obj.y -= step;
673 event.preventDefault();
674 schedulePreview();
675 draw();
676 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c" && !typing)
677 {
678 clipboard = selected() ? structuredClone(selected()) : clipboard;
679 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v" && !typing)
680 {
681 if (!clipboard) return;
682 const copy = structuredClone(clipboard);
683 copy.id = crypto.randomUUID();
684 copy.x += 8;
685 copy.y += 8;
686 objects.push(copy);
687 selectedId = copy.id;
688 renderList();
689 fillForm();
690 schedulePreview();
691 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "d" && !typing)
692 {
693 event.preventDefault();
694 cloneSelected(8);
695 }
696 });
697
698 document.querySelectorAll('#prop-angle,#prop-steps,#prop-dark,#prop-light').forEach((el) => el.addEventListener("input", applyForm));
699 $("prop-spacing").addEventListener("input", () => syncPercent(false));
700 $("prop-percent").addEventListener("input", () => syncPercent(true));
701 $("prop-cross").addEventListener("change", applyForm);
702 $("prop-gray").addEventListener("change", applyForm);
703 $("prop-line").addEventListener("change", applyForm);
704 $("prop-fill").addEventListener("change", applyForm);
705
706 function queueTextRebuild ()
707 {
708 const obj = selected();
709 if (!obj || obj.kind !== "text" || filling) return;
710 obj.text = $("prop-text").value;
711 obj.font = $("prop-font").value;
712 obj.fontSize = Number($("prop-size").value);
713 obj.name = (obj.text || "Tekst").split("\n")[0].slice(0, 28) || "Tekst";
714 clearTimeout(textTimer);
715 textTimer = setTimeout(() => rebuildText(obj).catch((error) => toast(error.message)), 180);
716 renderList();
717 }
718 $("prop-text").addEventListener("input", queueTextRebuild);
719 $("prop-font").addEventListener("change", queueTextRebuild);
720 $("prop-size").addEventListener("input", queueTextRebuild);
721
722 $("btn-import").onclick = () => $("file").click();
723 $("file").onchange = async () =>
724 {
725 const file = $("file").files[0];
726 $("file").value = "";
727 if (!file) return;
728 try
729 {
730 await importSvgText(await file.text(), file.name);
731 } catch (error)
732 {
733 toast(error.message);
734 }
735 };
736
737 $("demos").onchange = async () =>
738 {
739 const name = $("demos").value;
740 if (!name) return;
741 try
742 {
743 const response = await fetch("/api/demos/" + encodeURIComponent(name));
744 if (!response.ok) throw new Error("Voorbeeld niet gevonden");
745 await importSvgText(await response.text(), name);
746 } catch (error)
747 {
748 toast(error.message);
749 }
750 $("demos").value = "";
751 };
752
753 $("btn-text").onclick = async () =>
754 {
755 try
756 {
757 const text = $("new-text").value || "Timdraw";
758 const font = $("new-font").value;
759 const fontSize = Number($("new-size").value) || 12;
760 const geo = await api("/api/text", { text, font, fontSize, lineSpacing: 1.4 });
761 addObject(geo, text.split("\n")[0].slice(0, 28) || "Tekst", {
762 kind: "text", text, font, fontSize, lineSpacing: 1.4, drawLine: true, drawFill: false, grayscale: false,
763 });
764 } catch (error)
765 {
766 toast(error.message);
767 }
768 };
769
770 $("btn-copy").onclick = () => { clipboard = selected() ? structuredClone(selected()) : clipboard; };
771 $("btn-paste").onclick = () =>
772 {
773 if (!clipboard) return;
774 const copy = structuredClone(clipboard);
775 copy.id = crypto.randomUUID();
776 copy.x += 8;
777 copy.y += 8;
778 objects.push(copy);
779 selectedId = copy.id;
780 renderList();
781 fillForm();
782 schedulePreview();
783 };
784 $("btn-dup").onclick = () => cloneSelected(8);
785 $("btn-delete").onclick = () =>
786 {
787 objects = objects.filter((obj) => obj.id !== selectedId);
788 selectedId = null;
789 renderList();
790 fillForm();
791 schedulePreview();
792 };
793 $("btn-front").onclick = () => moveLayer(1);
794 $("btn-back").onclick = () => moveLayer(-1);
795
796 function moveLayer (dir)
797 {
798 const index = objects.findIndex((obj) => obj.id === selectedId);
799 const next = index + dir;
800 if (index < 0 || next < 0 || next >= objects.length) return;
801 const [item] = objects.splice(index, 1);
802 objects.splice(next, 0, item);
803 renderList();
804 schedulePreview();
805 }
806
807 $("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); };
808 $("show-travel").onchange = draw;
809
810 ["draw-speed", "travel-speed", "pen-up", "pen-down", "dwell", "origin", "return-home", "allow-outside"].forEach((id) =>
811 {
812 $(id).addEventListener("change", schedulePreview);
813 });
814
815 async function machineCall (path, body, confirmText)
816 {
817 if (confirmText && !confirm(confirmText)) return;
818 try
819 {
820 toast("");
821 const result = await api(path, body || {});
822 if (result && result.notice) toast(result.notice, 5000);
823 } catch (error)
824 {
825 toast(error.message);
826 $("machine-error").hidden = false;
827 $("machine-error").textContent = error.message;
828 }
829 }
830
831 $("btn-connect").onclick = () =>
832 {
833 if ($("btn-connect").dataset.on === "1")
834 {
835 userDisconnected = true;
836 machineCall("/api/disconnect");
837 }
838 else
839 {
840 userDisconnected = false;
841 autoTried = "";
842 machineCall("/api/connect", { port: $("port").value });
843 }
844 };
845 document.querySelectorAll(".jog button").forEach((button) =>
846 {
847 button.onclick = () =>
848 {
849 const step = Number($("jog-step").value);
850 machineCall("/api/jog", {
851 x: Number(button.dataset.x) * step,
852 y: Number(button.dataset.y) * step,
853 feed: Number($("travel-speed").value),
854 origin: $("origin").value,
855 });
856 };
857 });
858 $("btn-pen-up").onclick = () => machineCall("/api/pen", { down: false, ...readSettings() });
859 $("btn-pen-down").onclick = () => machineCall("/api/pen", { down: true, ...readSettings() });
860 $("btn-unlock").onclick = () => machineCall("/api/unlock");
861 $("btn-home").onclick = () => machineCall("/api/home", {}, "Homen beweegt naar de eindschakelaars. Doorgaan?");
862 $("btn-release").onclick = () => machineCall("/api/release");
863 $("btn-plot").onclick = () => machineCall("/api/plot", { objects, settings: readSettings() });
864 $("btn-trace").onclick = () => machineCall("/api/trace", { objects, settings: readSettings() });
865 $("btn-pause").onclick = async () =>
866 {
867 const path = $("btn-pause").dataset.paused === "1" ? "/api/resume" : "/api/pause";
868 machineCall(path);
869 };
870 $("btn-stop").onclick = () => machineCall("/api/stop");
871 let connectOpen = false;
872
873 $("machine-name").onclick = () =>
874 {
875 connectOpen = true;
876 syncConnectModal();
877 };
878
879 $("connect-close").onclick = () =>
880 {
881 if ($("btn-connect").dataset.on !== "1") return;
882 connectOpen = false;
883 syncConnectModal();
884 };
885
886 $("connect-modal").addEventListener("cancel", (event) =>
887 {
888 if ($("btn-connect").dataset.on !== "1")
889 {
890 event.preventDefault();
891 return;
892 }
893 connectOpen = false;
894 });
895
896 $("connect-modal").addEventListener("click", (event) =>
897 {
898 if (event.target !== $("connect-modal") || $("btn-connect").dataset.on !== "1") return;
899 connectOpen = false;
900 syncConnectModal();
901 });
902
903 function syncConnectModal ()
904 {
905 const modal = $("connect-modal");
906 const connected = $("btn-connect").dataset.on === "1";
907 $("connect-close").hidden = !connected;
908 const show = !connected || connectOpen;
909 if (show && !modal.open) modal.showModal();
910 if (!show && modal.open) modal.close();
911 }
912
913 function paintStatus (status)
914 {
915 const lamp = $("lamp");
916 const state = (status.state || "").toLowerCase();
917 lamp.className = "lamp";
918 if (!status.connected) lamp.classList.add("bad");
919 else if (state.startsWith("run") || state.startsWith("hold") || status.jobActive) lamp.classList.add("busy");
920 else if (state.startsWith("alarm")) lamp.classList.add("bad");
921 else lamp.classList.add("on");
922 $("machine-state").textContent = status.connecting
923 ? "Verbinden…"
924 : (status.connected ? (status.state || "Verbonden") : "Niet verbonden");
925 $("firmware").textContent = status.firmware || "";
926 $("btn-connect").textContent = status.connected ? "Verbreek" : (status.connecting ? "Verbinden…" : "Verbinden");
927 $("btn-connect").dataset.on = status.connected ? "1" : "0";
928 if (!status.connected) connectOpen = false;
929 syncConnectModal();
930 if (status.localUrl)
931 {
932 $("local-url").href = status.localUrl;
933 $("local-url").textContent = status.localUrl.replace(/^https?:\/\//, "").replace(/\/$/, "");
934 }
935 $("btn-pause").textContent = status.jobPaused ? "Verder" : "Pauze";
936 $("btn-pause").dataset.paused = status.jobPaused ? "1" : "0";
937 const w = status.wpos || [0, 0, 0];
938 $("position").textContent = status.connected
939 ? `X ${w[0].toFixed(2)} Y ${w[1].toFixed(2)} Z ${w[2].toFixed(2)}`
940 : "X — Y — Z —";
941 if (status.error)
942 {
943 $("machine-error").hidden = false;
944 $("machine-error").textContent = status.error;
945 } else if (status.connected)
946 {
947 $("machine-error").hidden = true;
948 }
949 if (!drag)
950 {
951 const ports = status.ports || [];
952 const current = $("port").value;
953 const remembered = status.lastPort || localStorage.getItem(PORT_KEY) || "";
954 const preferred = (status.connected && status.port) || remembered;
955 if ($("port").dataset.list !== ports.join(","))
956 {
957 $("port").innerHTML = ports.map((port) => `<option value="${port}">${portLabel(port)}</option>`).join("")
958 || "<option value=''>—</option>";
959 if (current && ports.includes(current)) $("port").value = current;
960 else if (preferred && ports.includes(preferred)) $("port").value = preferred;
961 else if (status.port && ports.includes(status.port)) $("port").value = status.port;
962 $("port").dataset.list = ports.join(",");
963 }
964 if (status.connected && status.port) localStorage.setItem(PORT_KEY, status.port);
965 }
966 const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0);
967 $("bar").style.width = `${Math.round((progress || 0) * 100)}%`;
968 if (status.message && status.jobActive) toast(status.message);
969 }
970
971 function portLabel (port)
972 {
973 return String(port).split("/").pop()
974 .replace(/^usb-/, "")
975 .replace(/-if\d+-port\d+$/, "")
976 .replaceAll("_", " ");
977 }
978
979 async function maybeAutoConnect (status)
980 {
981 if (userDisconnected || status.connected || status.connecting) return;
982 const port = status.lastPort || localStorage.getItem(PORT_KEY) || "";
983 if (!port || !(status.ports || []).includes(port) || autoTried === port) return;
984 autoTried = port;
985 try
986 {
987 await api("/api/connect", { port });
988 } catch (error)
989 {
990 toast(error.message);
991 $("machine-error").hidden = false;
992 $("machine-error").textContent = error.message;
993 }
994 }
995
996 async function poll ()
997 {
998 try
999 {
1000 const status = await api("/api/status");
1001 paintStatus(status);
1002 await maybeAutoConnect(status);
1003 } catch (error)
1004 {
1005 $("machine-error").hidden = false;
1006 $("machine-error").textContent = error.message;
1007 }
1008 }
1009
1010 async function boot ()
1011 {
1012 try
1013 {
1014 const saved = JSON.parse(localStorage.getItem("timdraw-doc") || "null");
1015 if (saved)
1016 {
1017 objects = saved.objects || [];
1018 Object.assign(defaults, saved.defaults || {});
1019 const settings = saved.settings || {};
1020 if (settings.drawSpeed) $("draw-speed").value = settings.drawSpeed;
1021 if (settings.travelSpeed) $("travel-speed").value = settings.travelSpeed;
1022 if (settings.penUpZ != null) $("pen-up").value = settings.penUpZ;
1023 if (settings.penDownZ != null) $("pen-down").value = settings.penDownZ;
1024 if (settings.dwellMs != null) $("dwell").value = settings.dwellMs;
1025 if (localStorage.getItem("timdraw-origin-v2") && settings.origin) $("origin").value = settings.origin;
1026 else $("origin").value = "top-left";
1027 localStorage.setItem("timdraw-origin-v2", "1");
1028 $("return-home").checked = settings.returnHome !== false;
1029 $("allow-outside").checked = !!settings.allowOutside;
1030 }
1031 } catch { /* lege start */ }
1032 fillForm();
1033 renderList();
1034 resize();
1035 schedulePreview();
1036 try
1037 {
1038 const demos = await api("/api/demos");
1039 for (const name of demos.demos || [])
1040 {
1041 const option = document.createElement("option");
1042 option.value = name;
1043 option.textContent = name;
1044 $("demos").appendChild(option);
1045 }
1046 } catch { /* geen demomap */ }
1047 poll();
1048 setInterval(poll, 700);
1049 }
1050
1051 window.addEventListener("resize", resize);
1052 boot();
@@ -0,0 +1,1052 @@
1const A4W = 210;
2const A4H = 297;
3const PEN_MM = 0.4;
4
5const $ = (id) => document.getElementById(id);
6const canvas = $("page");
7const ctx = canvas.getContext("2d");
8
9let objects = [];
10let selectedId = null;
11let clipboard = null;
12let preview = null;
13let previewGen = 0;
14let interacting = false;
15let zoom = 1;
16let panX = 0;
17let panY = 0;
18let filling = false;
19let textTimer = 0;
20let userDisconnected = false;
21let autoTried = "";
22const PORT_KEY = "timdraw-port";
23
24const defaults = {
25 drawLine: true,
26 drawFill: false,
27 hatchAngle: 45,
28 hatchSpacing: 2,
29 crosshatch: false,
30 grayscale: false,
31 graySteps: 5,
32 spacingMin: 0.8,
33 spacingMax: 4,
34};
35
36function selected ()
37{
38 return objects.find((obj) => obj.id === selectedId) || null;
39}
40
41let toastTimer = 0;
42
43function toast (message, hideAfter)
44{
45 const el = $("toast");
46 clearTimeout(toastTimer);
47 el.hidden = !message;
48 el.textContent = message || "";
49 if (message && hideAfter)
50 {
51 toastTimer = setTimeout(() =>
52 {
53 el.hidden = true;
54 el.textContent = "";
55 }, hideAfter);
56 }
57}
58
59async function api (path, body)
60{
61 const options = body
62 ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
63 : {};
64 const response = await fetch(path, options);
65 const data = await response.json().catch(() => ({}));
66 if (!response.ok) throw new Error(data.error || response.statusText);
67 return data;
68}
69
70function readSettings ()
71{
72 return {
73 drawSpeed: Number($("draw-speed").value),
74 travelSpeed: Number($("travel-speed").value),
75 penUpZ: Number($("pen-up").value),
76 penDownZ: Number($("pen-down").value),
77 dwellMs: Number($("dwell").value),
78 origin: $("origin").value,
79 returnHome: $("return-home").checked,
80 allowOutside: $("allow-outside").checked,
81 };
82}
83
84function styleFlags (obj)
85{
86 if (obj.drawLine != null || obj.drawFill != null)
87 return { drawLine: !!obj.drawLine, drawFill: !!obj.drawFill };
88 if (obj.mode === "fill") return { drawLine: false, drawFill: true };
89 return { drawLine: true, drawFill: false };
90}
91
92function styleLabel (obj)
93{
94 const flags = styleFlags(obj);
95 if (flags.drawLine && flags.drawFill) return "lijn + vulling";
96 if (flags.drawFill) return "vulling";
97 if (flags.drawLine) return "lijn";
98 return "uit";
99}
100
101function hatchFromForm ()
102{
103 return {
104 drawLine: $("prop-line").checked,
105 drawFill: $("prop-fill").checked,
106 hatchAngle: Number($("prop-angle").value),
107 hatchSpacing: Number($("prop-spacing").value),
108 crosshatch: $("prop-cross").checked,
109 grayscale: $("prop-gray").checked,
110 graySteps: Number($("prop-steps").value),
111 spacingMin: Number($("prop-dark").value),
112 spacingMax: Number($("prop-light").value),
113 };
114}
115
116function layout ()
117{
118 const rect = canvas.getBoundingClientRect();
119 const margin = 28;
120 const fit = Math.min((rect.width - margin * 2) / A4W, (rect.height - margin * 2) / A4H);
121 const scale = fit * zoom;
122 return {
123 scale,
124 ox: (rect.width - A4W * scale) / 2 + panX,
125 oy: (rect.height - A4H * scale) / 2 + panY,
126 width: rect.width,
127 height: rect.height,
128 };
129}
130
131function mmToPx (x, y)
132{
133 const view = layout();
134 return [view.ox + x * view.scale, view.oy + (A4H - y) * view.scale];
135}
136
137function pxToMm (px, py)
138{
139 const view = layout();
140 return [(px - view.ox) / view.scale, A4H - (py - view.oy) / view.scale];
141}
142
143function objPoint (obj, x, y)
144{
145 const scale = obj.scale || 1;
146 x *= scale;
147 y *= scale;
148 const angle = (obj.rotation || 0) * Math.PI / 180;
149 const ca = Math.cos(angle);
150 const sa = Math.sin(angle);
151 return [x * ca - y * sa + obj.x, x * sa + y * ca + obj.y];
152}
153
154function eachLocal (obj, fn)
155{
156 for (const stroke of obj.strokes || [])
157 {
158 for (const point of stroke.pts || stroke) fn(point[0], point[1]);
159 }
160 for (const fill of obj.fills || [])
161 {
162 for (const ring of fill.rings || [])
163 {
164 for (const point of ring) fn(point[0], point[1]);
165 }
166 }
167}
168
169function bbox (obj)
170{
171 let minx = Infinity;
172 let miny = Infinity;
173 let maxx = -Infinity;
174 let maxy = -Infinity;
175 eachLocal(obj, (x, y) =>
176 {
177 const point = objPoint(obj, x, y);
178 minx = Math.min(minx, point[0]);
179 miny = Math.min(miny, point[1]);
180 maxx = Math.max(maxx, point[0]);
181 maxy = Math.max(maxy, point[1]);
182 });
183 if (!Number.isFinite(minx))
184 {
185 return { minx: obj.x - 5, miny: obj.y - 5, maxx: obj.x + 5, maxy: obj.y + 5 };
186 }
187 return { minx, miny, maxx, maxy };
188}
189
190function resize ()
191{
192 const rect = canvas.getBoundingClientRect();
193 const dpr = window.devicePixelRatio || 1;
194 canvas.width = Math.max(1, rect.width * dpr);
195 canvas.height = Math.max(1, rect.height * dpr);
196 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
197 draw();
198}
199
200function drawSheet (view)
201{
202 const origin = mmToPx(0, 0);
203 const far = mmToPx(A4W, A4H);
204 const x = Math.min(origin[0], far[0]);
205 const y = Math.min(origin[1], far[1]);
206 const w = Math.abs(far[0] - origin[0]);
207 const h = Math.abs(far[1] - origin[1]);
208 ctx.save();
209 ctx.fillStyle = "rgba(0,0,0,0.35)";
210 ctx.fillRect(x + 8, y + 10, w, h);
211 ctx.fillStyle = "#f6f1e6";
212 ctx.fillRect(x, y, w, h);
213 ctx.strokeStyle = "rgba(80,60,40,0.18)";
214 ctx.lineWidth = 1;
215 ctx.beginPath();
216 for (let i = 10; i < A4W; i += 10)
217 {
218 const a = mmToPx(i, 0);
219 const b = mmToPx(i, A4H);
220 ctx.moveTo(a[0], a[1]);
221 ctx.lineTo(b[0], b[1]);
222 }
223 for (let i = 10; i < A4H; i += 10)
224 {
225 const a = mmToPx(0, i);
226 const b = mmToPx(A4W, i);
227 ctx.moveTo(a[0], a[1]);
228 ctx.lineTo(b[0], b[1]);
229 }
230 ctx.stroke();
231 ctx.strokeStyle = "#2b241e";
232 ctx.lineWidth = 1.5;
233 ctx.strokeRect(x, y, w, h);
234 ctx.fillStyle = "#8a7b6c";
235 ctx.font = "12px Liberation Sans, sans-serif";
236 const originTop = $("origin").value === "top-left";
237 ctx.fillText("0,0", x + 6, originTop ? y + 16 : y + h - 8);
238 ctx.fillText("A4", x + w - 26, originTop ? y + h - 8 : y + 16);
239 ctx.restore();
240}
241
242function tracePoly (points)
243{
244 if (!points.length) return;
245 const first = mmToPx(points[0][0], points[0][1]);
246 ctx.moveTo(first[0], first[1]);
247 for (let i = 1; i < points.length; i++)
248 {
249 const point = mmToPx(points[i][0], points[i][1]);
250 ctx.lineTo(point[0], point[1]);
251 }
252}
253
254function drawObject (obj, active)
255{
256 ctx.save();
257 ctx.lineWidth = active ? 1.6 : 1.15;
258 ctx.strokeStyle = "#1d1a17";
259 ctx.fillStyle = "rgba(224,122,61,0.13)";
260 ctx.lineJoin = "round";
261 ctx.lineCap = "round";
262 ctx.beginPath();
263 for (const fill of obj.fills || [])
264 {
265 for (const ring of fill.rings || [])
266 {
267 const page = ring.map((point) => objPoint(obj, point[0], point[1]));
268 tracePoly(page);
269 ctx.closePath();
270 }
271 }
272 ctx.fill("evenodd");
273 ctx.beginPath();
274 for (const stroke of obj.strokes || [])
275 {
276 const pts = (stroke.pts || stroke).map((point) => objPoint(obj, point[0], point[1]));
277 tracePoly(pts);
278 }
279 ctx.stroke();
280 ctx.restore();
281}
282
283function drawPreview ()
284{
285 ctx.save();
286 ctx.lineCap = "round";
287 ctx.lineJoin = "round";
288 ctx.strokeStyle = "#1d1a17";
289 ctx.lineWidth = 1.15;
290 ctx.beginPath();
291 for (const line of preview.draw || []) tracePoly(line);
292 ctx.stroke();
293 if ($("show-travel").checked)
294 {
295 ctx.strokeStyle = "rgba(176,122,62,0.85)";
296 ctx.setLineDash([4, 4]);
297 ctx.lineWidth = 1;
298 ctx.beginPath();
299 for (const line of preview.travel || []) tracePoly(line);
300 ctx.stroke();
301 }
302 ctx.restore();
303}
304
305function drawHandles (obj)
306{
307 const box = bbox(obj);
308 const corners = [
309 mmToPx(box.minx, box.maxy),
310 mmToPx(box.maxx, box.maxy),
311 mmToPx(box.maxx, box.miny),
312 mmToPx(box.minx, box.miny),
313 ];
314 ctx.save();
315 ctx.strokeStyle = "#e07a3d";
316 ctx.fillStyle = "#fff";
317 ctx.lineWidth = 1.4;
318 ctx.beginPath();
319 corners.forEach((point, index) => index ? ctx.lineTo(point[0], point[1]) : ctx.moveTo(point[0], point[1]));
320 ctx.closePath();
321 ctx.stroke();
322 const top = mmToPx((box.minx + box.maxx) / 2, box.maxy);
323 ctx.beginPath();
324 ctx.moveTo(top[0], top[1]);
325 ctx.lineTo(top[0], top[1] - 22);
326 ctx.stroke();
327 ctx.beginPath();
328 ctx.arc(top[0], top[1] - 22, 5, 0, Math.PI * 2);
329 ctx.fill();
330 ctx.stroke();
331 for (const point of corners)
332 {
333 ctx.fillRect(point[0] - 4, point[1] - 4, 8, 8);
334 ctx.strokeRect(point[0] - 4, point[1] - 4, 8, 8);
335 }
336 ctx.restore();
337}
338
339function draw ()
340{
341 const view = layout();
342 ctx.clearRect(0, 0, view.width, view.height);
343 drawSheet(view);
344 const current = selected();
345 if (preview && !interacting) drawPreview();
346 else objects.forEach((obj) => drawObject(obj, obj === current));
347 if (current) drawHandles(current);
348}
349
350function persist ()
351{
352 localStorage.setItem("timdraw-doc", JSON.stringify({ objects, defaults, settings: readSettings() }));
353}
354
355function schedulePreview ()
356{
357 clearTimeout(schedulePreview.timer);
358 schedulePreview.timer = setTimeout(refreshPreview, 160);
359}
360
361async function refreshPreview ()
362{
363 const gen = ++previewGen;
364 try
365 {
366 const data = await api("/api/preview", { objects, settings: readSettings() });
367 if (gen !== previewGen) return;
368 preview = data;
369 const stats = data.stats || {};
370 const minutes = Math.floor((stats.seconds || 0) / 60);
371 const seconds = Math.round((stats.seconds || 0) % 60);
372 $("stats").textContent = objects.length
373 ? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s`
374 : "";
375 if (data.warnings && data.warnings.length) toast(data.warnings[0]);
376 $("btn-plot").disabled = !!stats.blocked;
377 } catch (error)
378 {
379 toast(error.message);
380 }
381 draw();
382 persist();
383}
384
385function renderList ()
386{
387 const list = $("layers");
388 list.innerHTML = "";
389 objects.forEach((obj) =>
390 {
391 const item = document.createElement("li");
392 const button = document.createElement("button");
393 button.type = "button";
394 button.className = obj.id === selectedId ? "active" : "";
395 button.innerHTML = `<span>${obj.name || "Object"}</span><span class="tag">${styleLabel(obj)}</span>`;
396 button.onclick = () =>
397 {
398 selectedId = obj.id;
399 renderList();
400 fillForm();
401 draw();
402 };
403 item.appendChild(button);
404 list.appendChild(item);
405 });
406}
407
408function fillForm ()
409{
410 const obj = selected() || defaults;
411 filling = true;
412 $("prop-title").textContent = selected() ? (selected().name || "Object") : "Voor nieuwe objecten";
413 const flags = styleFlags(obj);
414 $("prop-line").checked = flags.drawLine;
415 $("prop-fill").checked = flags.drawFill;
416 $("prop-angle").value = obj.hatchAngle;
417 $("prop-spacing").value = obj.hatchSpacing;
418 $("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100)));
419 $("prop-cross").checked = !!obj.crosshatch;
420 $("prop-gray").checked = !!obj.grayscale;
421 $("prop-steps").value = obj.graySteps;
422 $("prop-dark").value = obj.spacingMin;
423 $("prop-light").value = obj.spacingMax;
424 $("gray-props").hidden = !obj.grayscale;
425 $("defaults-hint").hidden = !!selected();
426 const isText = selected() && selected().kind === "text";
427 $("text-props").hidden = !isText;
428 if (isText)
429 {
430 $("prop-text").value = selected().text || "";
431 $("prop-font").value = selected().font || "futural";
432 $("prop-size").value = selected().fontSize || 12;
433 }
434 filling = false;
435}
436
437function applyForm ()
438{
439 if (filling) return;
440 const values = hatchFromForm();
441 const obj = selected();
442 if (obj) Object.assign(obj, values);
443 else Object.assign(defaults, values);
444 $("gray-props").hidden = !values.grayscale;
445 renderList();
446 schedulePreview();
447}
448
449function syncPercent (fromPercent)
450{
451 if (filling) return;
452 if (fromPercent)
453 {
454 const percent = Math.min(100, Math.max(2, Number($("prop-percent").value) || 2));
455 $("prop-spacing").value = (PEN_MM / (percent / 100)).toFixed(2);
456 } else
457 {
458 const spacing = Math.max(0.3, Number($("prop-spacing").value) || 0.3);
459 $("prop-percent").value = Math.round(Math.min(100, (PEN_MM / spacing) * 100));
460 }
461 applyForm();
462}
463
464function addObject (geo, name, extra = {})
465{
466 const grays = [...new Set((geo.fills || []).map((fill) => Math.round(fill.gray * 20)))];
467 const obj = {
468 id: crypto.randomUUID(),
469 name,
470 kind: extra.kind || "svg",
471 x: geo.x,
472 y: geo.y,
473 scale: 1,
474 rotation: 0,
475 strokes: geo.strokes || [],
476 fills: geo.fills || [],
477 ...defaults,
478 grayscale: grays.length > 1 || defaults.grayscale,
479 ...extra,
480 drawLine: extra.drawLine != null ? extra.drawLine : defaults.drawLine,
481 drawFill: extra.drawFill != null ? extra.drawFill : (grays.length > 1 || defaults.drawFill),
482 };
483 objects.push(obj);
484 selectedId = obj.id;
485 renderList();
486 fillForm();
487 if (geo.warnings && geo.warnings.length) toast(geo.warnings.join(" "));
488 schedulePreview();
489}
490
491async function importSvgText (svg, name)
492{
493 const geo = await api("/api/svg", { svg, name });
494 addObject(geo, geo.name || name || "SVG");
495}
496
497function cloneSelected (offset)
498{
499 const obj = selected();
500 if (!obj) return;
501 const copy = structuredClone(obj);
502 copy.id = crypto.randomUUID();
503 copy.x += offset;
504 copy.y += offset;
505 copy.name = `${obj.name} kopie`;
506 objects.push(copy);
507 selectedId = copy.id;
508 renderList();
509 fillForm();
510 schedulePreview();
511}
512
513async function rebuildText (obj)
514{
515 const geo = await api("/api/text", {
516 text: obj.text,
517 font: obj.font,
518 fontSize: obj.fontSize,
519 lineSpacing: 1.4,
520 });
521 obj.strokes = geo.strokes;
522 obj.fills = geo.fills;
523 schedulePreview();
524 draw();
525}
526
527function handleAt (px, py)
528{
529 const obj = selected();
530 if (!obj) return null;
531 const box = bbox(obj);
532 const corners = {
533 nw: mmToPx(box.minx, box.maxy),
534 ne: mmToPx(box.maxx, box.maxy),
535 se: mmToPx(box.maxx, box.miny),
536 sw: mmToPx(box.minx, box.miny),
537 };
538 const top = mmToPx((box.minx + box.maxx) / 2, box.maxy);
539 if (Math.hypot(top[0] - px, top[1] - 22 - py) < 9) return "rot";
540 for (const [name, point] of Object.entries(corners))
541 {
542 if (Math.hypot(point[0] - px, point[1] - py) < 9) return name;
543 }
544 return null;
545}
546
547function hitObject (x, y)
548{
549 const view = layout();
550 const pad = 5 / view.scale;
551 for (let i = objects.length - 1; i >= 0; i--)
552 {
553 const box = bbox(objects[i]);
554 if (x >= box.minx - pad && x <= box.maxx + pad && y >= box.miny - pad && y <= box.maxy + pad) return objects[i];
555 }
556 return null;
557}
558
559let drag = null;
560
561canvas.addEventListener("pointerdown", (event) =>
562{
563 if (event.button === 1 || event.altKey)
564 {
565 drag = { type: "pan", x: event.clientX, y: event.clientY, panX, panY };
566 canvas.setPointerCapture(event.pointerId);
567 return;
568 }
569 const rect = canvas.getBoundingClientRect();
570 const px = event.clientX - rect.left;
571 const py = event.clientY - rect.top;
572 const handle = handleAt(px, py);
573 const [x, y] = pxToMm(px, py);
574 const obj = selected();
575 if (handle && obj)
576 {
577 const box = bbox(obj);
578 const cx = (box.minx + box.maxx) / 2;
579 const cy = (box.miny + box.maxy) / 2;
580 drag = {
581 type: handle === "rot" ? "rot" : "scale",
582 id: obj.id,
583 cx, cy,
584 startAngle: Math.atan2(y - cy, x - cx),
585 startRot: obj.rotation || 0,
586 startDist: Math.hypot(x - cx, y - cy) || 1,
587 startScale: obj.scale || 1,
588 };
589 } else
590 {
591 const hit = hitObject(x, y);
592 selectedId = hit ? hit.id : null;
593 renderList();
594 fillForm();
595 if (hit) drag = { type: "move", id: hit.id, x, y, ox: hit.x, oy: hit.y };
596 }
597 interacting = !!drag;
598 canvas.setPointerCapture(event.pointerId);
599 draw();
600});
601
602canvas.addEventListener("pointermove", (event) =>
603{
604 if (!drag) return;
605 if (drag.type === "pan")
606 {
607 panX = drag.panX + (event.clientX - drag.x);
608 panY = drag.panY + (event.clientY - drag.y);
609 draw();
610 return;
611 }
612 const rect = canvas.getBoundingClientRect();
613 const [x, y] = pxToMm(event.clientX - rect.left, event.clientY - rect.top);
614 const obj = objects.find((item) => item.id === drag.id);
615 if (!obj) return;
616 if (drag.type === "move")
617 {
618 obj.x = drag.ox + (x - drag.x);
619 obj.y = drag.oy + (y - drag.y);
620 } else if (drag.type === "scale")
621 {
622 const dist = Math.hypot(x - drag.cx, y - drag.cy);
623 obj.scale = Math.max(0.05, Math.min(20, drag.startScale * (dist / drag.startDist)));
624 } else if (drag.type === "rot")
625 {
626 const angle = Math.atan2(y - drag.cy, x - drag.cx);
627 obj.rotation = Math.round(drag.startRot + (angle - drag.startAngle) * 180 / Math.PI);
628 }
629 draw();
630});
631
632function endDrag ()
633{
634 if (drag && drag.type !== "pan") schedulePreview();
635 drag = null;
636 interacting = false;
637}
638
639canvas.addEventListener("pointerup", endDrag);
640canvas.addEventListener("pointercancel", endDrag);
641canvas.addEventListener("wheel", (event) =>
642{
643 event.preventDefault();
644 zoom = Math.max(0.35, Math.min(8, zoom * (event.deltaY < 0 ? 1.08 : 0.92)));
645 draw();
646}, { passive: false });
647
648window.addEventListener("keydown", (event) =>
649{
650 const typing = ["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName);
651 if ((event.key === "Delete" || event.key === "Backspace") && !typing)
652 {
653 objects = objects.filter((obj) => obj.id !== selectedId);
654 selectedId = null;
655 renderList();
656 fillForm();
657 schedulePreview();
658 } else if (event.key === "Escape")
659 {
660 selectedId = null;
661 renderList();
662 fillForm();
663 draw();
664 } else if (!typing && (event.key.startsWith("Arrow")))
665 {
666 const obj = selected();
667 if (!obj) return;
668 const step = event.shiftKey ? 0.1 : 1;
669 if (event.key === "ArrowLeft") obj.x -= step;
670 if (event.key === "ArrowRight") obj.x += step;
671 if (event.key === "ArrowUp") obj.y += step;
672 if (event.key === "ArrowDown") obj.y -= step;
673 event.preventDefault();
674 schedulePreview();
675 draw();
676 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c" && !typing)
677 {
678 clipboard = selected() ? structuredClone(selected()) : clipboard;
679 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "v" && !typing)
680 {
681 if (!clipboard) return;
682 const copy = structuredClone(clipboard);
683 copy.id = crypto.randomUUID();
684 copy.x += 8;
685 copy.y += 8;
686 objects.push(copy);
687 selectedId = copy.id;
688 renderList();
689 fillForm();
690 schedulePreview();
691 } else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "d" && !typing)
692 {
693 event.preventDefault();
694 cloneSelected(8);
695 }
696});
697
698document.querySelectorAll('#prop-angle,#prop-steps,#prop-dark,#prop-light').forEach((el) => el.addEventListener("input", applyForm));
699$("prop-spacing").addEventListener("input", () => syncPercent(false));
700$("prop-percent").addEventListener("input", () => syncPercent(true));
701$("prop-cross").addEventListener("change", applyForm);
702$("prop-gray").addEventListener("change", applyForm);
703$("prop-line").addEventListener("change", applyForm);
704$("prop-fill").addEventListener("change", applyForm);
705
706function queueTextRebuild ()
707{
708 const obj = selected();
709 if (!obj || obj.kind !== "text" || filling) return;
710 obj.text = $("prop-text").value;
711 obj.font = $("prop-font").value;
712 obj.fontSize = Number($("prop-size").value);
713 obj.name = (obj.text || "Tekst").split("\n")[0].slice(0, 28) || "Tekst";
714 clearTimeout(textTimer);
715 textTimer = setTimeout(() => rebuildText(obj).catch((error) => toast(error.message)), 180);
716 renderList();
717}
718$("prop-text").addEventListener("input", queueTextRebuild);
719$("prop-font").addEventListener("change", queueTextRebuild);
720$("prop-size").addEventListener("input", queueTextRebuild);
721
722$("btn-import").onclick = () => $("file").click();
723$("file").onchange = async () =>
724{
725 const file = $("file").files[0];
726 $("file").value = "";
727 if (!file) return;
728 try
729 {
730 await importSvgText(await file.text(), file.name);
731 } catch (error)
732 {
733 toast(error.message);
734 }
735};
736
737$("demos").onchange = async () =>
738{
739 const name = $("demos").value;
740 if (!name) return;
741 try
742 {
743 const response = await fetch("/api/demos/" + encodeURIComponent(name));
744 if (!response.ok) throw new Error("Voorbeeld niet gevonden");
745 await importSvgText(await response.text(), name);
746 } catch (error)
747 {
748 toast(error.message);
749 }
750 $("demos").value = "";
751};
752
753$("btn-text").onclick = async () =>
754{
755 try
756 {
757 const text = $("new-text").value || "Timdraw";
758 const font = $("new-font").value;
759 const fontSize = Number($("new-size").value) || 12;
760 const geo = await api("/api/text", { text, font, fontSize, lineSpacing: 1.4 });
761 addObject(geo, text.split("\n")[0].slice(0, 28) || "Tekst", {
762 kind: "text", text, font, fontSize, lineSpacing: 1.4, drawLine: true, drawFill: false, grayscale: false,
763 });
764 } catch (error)
765 {
766 toast(error.message);
767 }
768};
769
770$("btn-copy").onclick = () => { clipboard = selected() ? structuredClone(selected()) : clipboard; };
771$("btn-paste").onclick = () =>
772{
773 if (!clipboard) return;
774 const copy = structuredClone(clipboard);
775 copy.id = crypto.randomUUID();
776 copy.x += 8;
777 copy.y += 8;
778 objects.push(copy);
779 selectedId = copy.id;
780 renderList();
781 fillForm();
782 schedulePreview();
783};
784$("btn-dup").onclick = () => cloneSelected(8);
785$("btn-delete").onclick = () =>
786{
787 objects = objects.filter((obj) => obj.id !== selectedId);
788 selectedId = null;
789 renderList();
790 fillForm();
791 schedulePreview();
792};
793$("btn-front").onclick = () => moveLayer(1);
794$("btn-back").onclick = () => moveLayer(-1);
795
796function moveLayer (dir)
797{
798 const index = objects.findIndex((obj) => obj.id === selectedId);
799 const next = index + dir;
800 if (index < 0 || next < 0 || next >= objects.length) return;
801 const [item] = objects.splice(index, 1);
802 objects.splice(next, 0, item);
803 renderList();
804 schedulePreview();
805}
806
807$("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); };
808$("show-travel").onchange = draw;
809
810["draw-speed", "travel-speed", "pen-up", "pen-down", "dwell", "origin", "return-home", "allow-outside"].forEach((id) =>
811{
812 $(id).addEventListener("change", schedulePreview);
813});
814
815async function machineCall (path, body, confirmText)
816{
817 if (confirmText && !confirm(confirmText)) return;
818 try
819 {
820 toast("");
821 const result = await api(path, body || {});
822 if (result && result.notice) toast(result.notice, 5000);
823 } catch (error)
824 {
825 toast(error.message);
826 $("machine-error").hidden = false;
827 $("machine-error").textContent = error.message;
828 }
829}
830
831$("btn-connect").onclick = () =>
832{
833 if ($("btn-connect").dataset.on === "1")
834 {
835 userDisconnected = true;
836 machineCall("/api/disconnect");
837 }
838 else
839 {
840 userDisconnected = false;
841 autoTried = "";
842 machineCall("/api/connect", { port: $("port").value });
843 }
844};
845document.querySelectorAll(".jog button").forEach((button) =>
846{
847 button.onclick = () =>
848 {
849 const step = Number($("jog-step").value);
850 machineCall("/api/jog", {
851 x: Number(button.dataset.x) * step,
852 y: Number(button.dataset.y) * step,
853 feed: Number($("travel-speed").value),
854 origin: $("origin").value,
855 });
856 };
857});
858$("btn-pen-up").onclick = () => machineCall("/api/pen", { down: false, ...readSettings() });
859$("btn-pen-down").onclick = () => machineCall("/api/pen", { down: true, ...readSettings() });
860$("btn-unlock").onclick = () => machineCall("/api/unlock");
861$("btn-home").onclick = () => machineCall("/api/home", {}, "Homen beweegt naar de eindschakelaars. Doorgaan?");
862$("btn-release").onclick = () => machineCall("/api/release");
863$("btn-plot").onclick = () => machineCall("/api/plot", { objects, settings: readSettings() });
864$("btn-trace").onclick = () => machineCall("/api/trace", { objects, settings: readSettings() });
865$("btn-pause").onclick = async () =>
866{
867 const path = $("btn-pause").dataset.paused === "1" ? "/api/resume" : "/api/pause";
868 machineCall(path);
869};
870$("btn-stop").onclick = () => machineCall("/api/stop");
871let connectOpen = false;
872
873$("machine-name").onclick = () =>
874{
875 connectOpen = true;
876 syncConnectModal();
877};
878
879$("connect-close").onclick = () =>
880{
881 if ($("btn-connect").dataset.on !== "1") return;
882 connectOpen = false;
883 syncConnectModal();
884};
885
886$("connect-modal").addEventListener("cancel", (event) =>
887{
888 if ($("btn-connect").dataset.on !== "1")
889 {
890 event.preventDefault();
891 return;
892 }
893 connectOpen = false;
894});
895
896$("connect-modal").addEventListener("click", (event) =>
897{
898 if (event.target !== $("connect-modal") || $("btn-connect").dataset.on !== "1") return;
899 connectOpen = false;
900 syncConnectModal();
901});
902
903function syncConnectModal ()
904{
905 const modal = $("connect-modal");
906 const connected = $("btn-connect").dataset.on === "1";
907 $("connect-close").hidden = !connected;
908 const show = !connected || connectOpen;
909 if (show && !modal.open) modal.showModal();
910 if (!show && modal.open) modal.close();
911}
912
913function paintStatus (status)
914{
915 const lamp = $("lamp");
916 const state = (status.state || "").toLowerCase();
917 lamp.className = "lamp";
918 if (!status.connected) lamp.classList.add("bad");
919 else if (state.startsWith("run") || state.startsWith("hold") || status.jobActive) lamp.classList.add("busy");
920 else if (state.startsWith("alarm")) lamp.classList.add("bad");
921 else lamp.classList.add("on");
922 $("machine-state").textContent = status.connecting
923 ? "Verbinden…"
924 : (status.connected ? (status.state || "Verbonden") : "Niet verbonden");
925 $("firmware").textContent = status.firmware || "";
926 $("btn-connect").textContent = status.connected ? "Verbreek" : (status.connecting ? "Verbinden…" : "Verbinden");
927 $("btn-connect").dataset.on = status.connected ? "1" : "0";
928 if (!status.connected) connectOpen = false;
929 syncConnectModal();
930 if (status.localUrl)
931 {
932 $("local-url").href = status.localUrl;
933 $("local-url").textContent = status.localUrl.replace(/^https?:\/\//, "").replace(/\/$/, "");
934 }
935 $("btn-pause").textContent = status.jobPaused ? "Verder" : "Pauze";
936 $("btn-pause").dataset.paused = status.jobPaused ? "1" : "0";
937 const w = status.wpos || [0, 0, 0];
938 $("position").textContent = status.connected
939 ? `X ${w[0].toFixed(2)} Y ${w[1].toFixed(2)} Z ${w[2].toFixed(2)}`
940 : "X — Y — Z —";
941 if (status.error)
942 {
943 $("machine-error").hidden = false;
944 $("machine-error").textContent = status.error;
945 } else if (status.connected)
946 {
947 $("machine-error").hidden = true;
948 }
949 if (!drag)
950 {
951 const ports = status.ports || [];
952 const current = $("port").value;
953 const remembered = status.lastPort || localStorage.getItem(PORT_KEY) || "";
954 const preferred = (status.connected && status.port) || remembered;
955 if ($("port").dataset.list !== ports.join(","))
956 {
957 $("port").innerHTML = ports.map((port) => `<option value="${port}">${portLabel(port)}</option>`).join("")
958 || "<option value=''>—</option>";
959 if (current && ports.includes(current)) $("port").value = current;
960 else if (preferred && ports.includes(preferred)) $("port").value = preferred;
961 else if (status.port && ports.includes(status.port)) $("port").value = status.port;
962 $("port").dataset.list = ports.join(",");
963 }
964 if (status.connected && status.port) localStorage.setItem(PORT_KEY, status.port);
965 }
966 const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0);
967 $("bar").style.width = `${Math.round((progress || 0) * 100)}%`;
968 if (status.message && status.jobActive) toast(status.message);
969}
970
971function portLabel (port)
972{
973 return String(port).split("/").pop()
974 .replace(/^usb-/, "")
975 .replace(/-if\d+-port\d+$/, "")
976 .replaceAll("_", " ");
977}
978
979async function maybeAutoConnect (status)
980{
981 if (userDisconnected || status.connected || status.connecting) return;
982 const port = status.lastPort || localStorage.getItem(PORT_KEY) || "";
983 if (!port || !(status.ports || []).includes(port) || autoTried === port) return;
984 autoTried = port;
985 try
986 {
987 await api("/api/connect", { port });
988 } catch (error)
989 {
990 toast(error.message);
991 $("machine-error").hidden = false;
992 $("machine-error").textContent = error.message;
993 }
994}
995
996async function poll ()
997{
998 try
999 {
1000 const status = await api("/api/status");
1001 paintStatus(status);
1002 await maybeAutoConnect(status);
1003 } catch (error)
1004 {
1005 $("machine-error").hidden = false;
1006 $("machine-error").textContent = error.message;
1007 }
1008}
1009
1010async function boot ()
1011{
1012 try
1013 {
1014 const saved = JSON.parse(localStorage.getItem("timdraw-doc") || "null");
1015 if (saved)
1016 {
1017 objects = saved.objects || [];
1018 Object.assign(defaults, saved.defaults || {});
1019 const settings = saved.settings || {};
1020 if (settings.drawSpeed) $("draw-speed").value = settings.drawSpeed;
1021 if (settings.travelSpeed) $("travel-speed").value = settings.travelSpeed;
1022 if (settings.penUpZ != null) $("pen-up").value = settings.penUpZ;
1023 if (settings.penDownZ != null) $("pen-down").value = settings.penDownZ;
1024 if (settings.dwellMs != null) $("dwell").value = settings.dwellMs;
1025 if (localStorage.getItem("timdraw-origin-v2") && settings.origin) $("origin").value = settings.origin;
1026 else $("origin").value = "top-left";
1027 localStorage.setItem("timdraw-origin-v2", "1");
1028 $("return-home").checked = settings.returnHome !== false;
1029 $("allow-outside").checked = !!settings.allowOutside;
1030 }
1031 } catch { /* lege start */ }
1032 fillForm();
1033 renderList();
1034 resize();
1035 schedulePreview();
1036 try
1037 {
1038 const demos = await api("/api/demos");
1039 for (const name of demos.demos || [])
1040 {
1041 const option = document.createElement("option");
1042 option.value = name;
1043 option.textContent = name;
1044 $("demos").appendChild(option);
1045 }
1046 } catch { /* geen demomap */ }
1047 poll();
1048 setInterval(poll, 700);
1049}
1050
1051window.addEventListener("resize", resize);
1052boot();
static/index.html added +218 −0
@@ -0,0 +1,218 @@
1 <!DOCTYPE html>
2 <html lang="nl">
3
4 <head>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 <title>Timdraw</title>
8 <link rel="stylesheet" href="/static/style.css">
9 </head>
10
11 <body>
12 <header>
13 <div class="brand">
14 <strong>Timdraw</strong>
15 <button id="machine-name" type="button" class="machine-name">
16 <span id="lamp" class="lamp"></span>
17 Bachin TA4
18 </button>
19 <a id="local-url" href="http://127.0.0.1:8765/">127.0.0.1:8765</a>
20 </div>
21 <p id="toast" class="toast" hidden></p>
22 <div class="header-actions">
23 <button id="btn-fit" type="button">Passend</button>
24 <label class="check"><input id="show-travel" type="checkbox"> Verplaatsingen</label>
25 </div>
26 </header>
27 <div class="layout">
28 <aside class="panel left">
29 <section>
30 <h2>Tekening</h2>
31 <div class="row">
32 <button id="btn-import" type="button" class="primary">Importeer SVG</button>
33 <input id="file" type="file" accept=".svg,image/svg+xml" hidden>
34 </div>
35 <label class="field">Voorbeeld uit Bachin
36 <select id="demos">
37 <option value="">—</option>
38 </select>
39 </label>
40 </section>
41 <section>
42 <h2>Tekst</h2>
43 <textarea id="new-text" rows="3" placeholder="Tekst op één lijn per regel"></textarea>
44 <div class="split">
45 <label class="field">Font
46 <select id="new-font">
47 <option value="futural">Sans</option>
48 <option value="rowmans">Romein</option>
49 <option value="scripts">Handschrift</option>
50 </select>
51 </label>
52 <label class="field">Hoogte mm
53 <input id="new-size" type="number" min="2" max="80" step="0.5" value="12">
54 </label>
55 </div>
56 <button id="btn-text" type="button">Plaats tekst</button>
57 </section>
58 <section>
59 <h2>Objecten</h2>
60 <ul id="layers"></ul>
61 <div class="row wrap">
62 <button id="btn-copy" type="button">Kopieer</button>
63 <button id="btn-paste" type="button">Plak</button>
64 <button id="btn-dup" type="button">Dupliceer</button>
65 <button id="btn-delete" type="button">Wis</button>
66 <button id="btn-back" type="button">Achter</button>
67 <button id="btn-front" type="button">Voor</button>
68 </div>
69 <p class="hint">Slepen verplaatst. Hoeken schalen. Het handvat boven het kader draait. Delete wist, Ctrl+C /
70 Ctrl+V kopieert.</p>
71 </section>
72 </aside>
73 <main>
74 <canvas id="page"></canvas>
75 </main>
76 <aside class="panel right">
77 <section>
78 <h2 id="prop-title">Eigenschappen</h2>
79 <div id="text-props" hidden>
80 <label class="field">Tekst
81 <textarea id="prop-text" rows="3"></textarea>
82 </label>
83 <div class="split">
84 <label class="field">Font
85 <select id="prop-font">
86 <option value="futural">Sans</option>
87 <option value="rowmans">Romein</option>
88 <option value="scripts">Handschrift</option>
89 </select>
90 </label>
91 <label class="field">Hoogte mm
92 <input id="prop-size" type="number" min="2" max="80" step="0.5">
93 </label>
94 </div>
95 </div>
96 <div class="modes">
97 <label class="check"><input id="prop-line" type="checkbox" checked> Lijn</label>
98 <label class="check"><input id="prop-fill" type="checkbox"> Vulling</label>
99 </div>
100 <p class="hint">Lijn tekent de paden zelf. Vulling zet er een arcering in. Allebei aan tekent de contour en de
101 arcering.</p>
102 <div class="split">
103 <label class="field">Hoek °
104 <input id="prop-angle" type="number" min="-180" max="180" step="1" value="45">
105 </label>
106 <label class="field">Lijnafstand mm
107 <input id="prop-spacing" type="number" min="0.3" max="30" step="0.1" value="2">
108 </label>
109 </div>
110 <label class="field">Vulpercentage
111 <input id="prop-percent" type="number" min="2" max="100" step="1" value="20">
112 </label>
113 <label class="check"><input id="prop-cross" type="checkbox"> Crosshatch</label>
114 <label class="check"><input id="prop-gray" type="checkbox"> Grijswaarden</label>
115 <div id="gray-props">
116 <label class="field">Tredes
117 <input id="prop-steps" type="number" min="2" max="16" step="1" value="5">
118 </label>
119 <div class="split">
120 <label class="field">Donker mm
121 <input id="prop-dark" type="number" min="0.3" max="20" step="0.1" value="0.8">
122 </label>
123 <label class="field">Licht mm
124 <input id="prop-light" type="number" min="0.4" max="40" step="0.1" value="4">
125 </label>
126 </div>
127 <p class="hint">Donkerder wordt krapper gearceerd. Lichter krijgt meer afstand. Bijna-wit slaat Timdraw over.
128 </p>
129 </div>
130 <p id="defaults-hint" class="hint">Zonder selectie gelden deze waarden voor het volgende import- of tekstobject.
131 </p>
132 </section>
133 <section>
134 <h2>Machine</h2>
135 <p id="machine-error" class="error" hidden></p>
136 <p id="position" class="mono">X — &nbsp; Y — &nbsp; Z —</p>
137 <div class="jog">
138 <button type="button" data-x="0" data-y="1">↑</button>
139 <div class="jog-mid">
140 <button type="button" data-x="-1" data-y="0">←</button>
141 <select id="jog-step">
142 <option value="1">1 mm</option>
143 <option value="10" selected>10 mm</option>
144 <option value="50">50 mm</option>
145 </select>
146 <button type="button" data-x="1" data-y="0">→</button>
147 </div>
148 <button type="button" data-x="0" data-y="-1">↓</button>
149 </div>
150 <div class="row wrap">
151 <button id="btn-pen-up" type="button">Pen omhoog</button>
152 <button id="btn-pen-down" type="button">Pen omlaag</button>
153 <button id="btn-unlock" type="button">Ontgrendel</button>
154 <button id="btn-home" type="button">Home</button>
155 <button id="btn-release" type="button">Assen los</button>
156 </div>
157 <div class="split">
158 <label class="field">Tekensnelheid
159 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
160 </label>
161 <label class="field">Verplaatsing
162 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
163 </label>
164 </div>
165 <div class="split">
166 <label class="field">Pen omhoog Z
167 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
168 </label>
169 <label class="field">Pen omlaag Z
170 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
171 </label>
172 </div>
173 <label class="field">Pauze na pen ms
174 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
175 </label>
176 <label class="field">Nulpunt
177 <select id="origin">
178 <option value="top-left" selected>Linksboven</option>
179 <option value="bottom-left">Linksonder</option>
180 </select>
181 </label>
182 <label class="check"><input id="return-home" type="checkbox" checked> Terug naar nulpunt</label>
183 <label class="check"><input id="allow-outside" type="checkbox"> Toch buiten A4 sturen</label>
184 <p id="stats" class="hint"></p>
185 <div class="progress">
186 <div id="bar"></div>
187 </div>
188 <div class="row">
189 <button id="btn-plot" type="button" class="primary">Teken</button>
190 <button id="btn-pause" type="button">Pauze</button>
191 <button id="btn-stop" type="button">Stop</button>
192 <button id="btn-trace" type="button">Voorbeeld</button>
193 </div>
194 <p class="hint">Na homing ligt het nulpunt linksboven. X loopt naar rechts tot 200 mm. Y omhoog is positief,
195 dus het blad loopt naar beneden tot −297 mm. Pen omhoog is Z 0, pen omlaag Z 5. Verplaatsingen gaan met G1,
196 zodat de snelheid echt geldt.
197 </p>
198 </section>
199 </aside>
200 </div>
201 <dialog id="connect-modal" class="connect-modal">
202 <h2>Machine</h2>
203 <p id="machine-state">Niet verbonden</p>
204 <p id="firmware" class="hint"></p>
205 <div class="split">
206 <label class="field">Poort
207 <select id="port"></select>
208 </label>
209 <button id="btn-connect" type="button" class="primary">Verbinden</button>
210 </div>
211 <div class="row">
212 <button id="connect-close" type="button">Sluiten</button>
213 </div>
214 </dialog>
215 <script src="/static/app.js"></script>
216 </body>
217
218 </html>
@@ -0,0 +1,218 @@
1<!DOCTYPE html>
2<html lang="nl">
3
4<head>
5 <meta charset="utf-8">
6 <meta name="viewport" content="width=device-width, initial-scale=1">
7 <title>Timdraw</title>
8 <link rel="stylesheet" href="/static/style.css">
9</head>
10
11<body>
12 <header>
13 <div class="brand">
14 <strong>Timdraw</strong>
15 <button id="machine-name" type="button" class="machine-name">
16 <span id="lamp" class="lamp"></span>
17 Bachin TA4
18 </button>
19 <a id="local-url" href="http://127.0.0.1:8765/">127.0.0.1:8765</a>
20 </div>
21 <p id="toast" class="toast" hidden></p>
22 <div class="header-actions">
23 <button id="btn-fit" type="button">Passend</button>
24 <label class="check"><input id="show-travel" type="checkbox"> Verplaatsingen</label>
25 </div>
26 </header>
27 <div class="layout">
28 <aside class="panel left">
29 <section>
30 <h2>Tekening</h2>
31 <div class="row">
32 <button id="btn-import" type="button" class="primary">Importeer SVG</button>
33 <input id="file" type="file" accept=".svg,image/svg+xml" hidden>
34 </div>
35 <label class="field">Voorbeeld uit Bachin
36 <select id="demos">
37 <option value="">—</option>
38 </select>
39 </label>
40 </section>
41 <section>
42 <h2>Tekst</h2>
43 <textarea id="new-text" rows="3" placeholder="Tekst op één lijn per regel"></textarea>
44 <div class="split">
45 <label class="field">Font
46 <select id="new-font">
47 <option value="futural">Sans</option>
48 <option value="rowmans">Romein</option>
49 <option value="scripts">Handschrift</option>
50 </select>
51 </label>
52 <label class="field">Hoogte mm
53 <input id="new-size" type="number" min="2" max="80" step="0.5" value="12">
54 </label>
55 </div>
56 <button id="btn-text" type="button">Plaats tekst</button>
57 </section>
58 <section>
59 <h2>Objecten</h2>
60 <ul id="layers"></ul>
61 <div class="row wrap">
62 <button id="btn-copy" type="button">Kopieer</button>
63 <button id="btn-paste" type="button">Plak</button>
64 <button id="btn-dup" type="button">Dupliceer</button>
65 <button id="btn-delete" type="button">Wis</button>
66 <button id="btn-back" type="button">Achter</button>
67 <button id="btn-front" type="button">Voor</button>
68 </div>
69 <p class="hint">Slepen verplaatst. Hoeken schalen. Het handvat boven het kader draait. Delete wist, Ctrl+C /
70 Ctrl+V kopieert.</p>
71 </section>
72 </aside>
73 <main>
74 <canvas id="page"></canvas>
75 </main>
76 <aside class="panel right">
77 <section>
78 <h2 id="prop-title">Eigenschappen</h2>
79 <div id="text-props" hidden>
80 <label class="field">Tekst
81 <textarea id="prop-text" rows="3"></textarea>
82 </label>
83 <div class="split">
84 <label class="field">Font
85 <select id="prop-font">
86 <option value="futural">Sans</option>
87 <option value="rowmans">Romein</option>
88 <option value="scripts">Handschrift</option>
89 </select>
90 </label>
91 <label class="field">Hoogte mm
92 <input id="prop-size" type="number" min="2" max="80" step="0.5">
93 </label>
94 </div>
95 </div>
96 <div class="modes">
97 <label class="check"><input id="prop-line" type="checkbox" checked> Lijn</label>
98 <label class="check"><input id="prop-fill" type="checkbox"> Vulling</label>
99 </div>
100 <p class="hint">Lijn tekent de paden zelf. Vulling zet er een arcering in. Allebei aan tekent de contour en de
101 arcering.</p>
102 <div class="split">
103 <label class="field">Hoek °
104 <input id="prop-angle" type="number" min="-180" max="180" step="1" value="45">
105 </label>
106 <label class="field">Lijnafstand mm
107 <input id="prop-spacing" type="number" min="0.3" max="30" step="0.1" value="2">
108 </label>
109 </div>
110 <label class="field">Vulpercentage
111 <input id="prop-percent" type="number" min="2" max="100" step="1" value="20">
112 </label>
113 <label class="check"><input id="prop-cross" type="checkbox"> Crosshatch</label>
114 <label class="check"><input id="prop-gray" type="checkbox"> Grijswaarden</label>
115 <div id="gray-props">
116 <label class="field">Tredes
117 <input id="prop-steps" type="number" min="2" max="16" step="1" value="5">
118 </label>
119 <div class="split">
120 <label class="field">Donker mm
121 <input id="prop-dark" type="number" min="0.3" max="20" step="0.1" value="0.8">
122 </label>
123 <label class="field">Licht mm
124 <input id="prop-light" type="number" min="0.4" max="40" step="0.1" value="4">
125 </label>
126 </div>
127 <p class="hint">Donkerder wordt krapper gearceerd. Lichter krijgt meer afstand. Bijna-wit slaat Timdraw over.
128 </p>
129 </div>
130 <p id="defaults-hint" class="hint">Zonder selectie gelden deze waarden voor het volgende import- of tekstobject.
131 </p>
132 </section>
133 <section>
134 <h2>Machine</h2>
135 <p id="machine-error" class="error" hidden></p>
136 <p id="position" class="mono">X — &nbsp; Y — &nbsp; Z —</p>
137 <div class="jog">
138 <button type="button" data-x="0" data-y="1">↑</button>
139 <div class="jog-mid">
140 <button type="button" data-x="-1" data-y="0">←</button>
141 <select id="jog-step">
142 <option value="1">1 mm</option>
143 <option value="10" selected>10 mm</option>
144 <option value="50">50 mm</option>
145 </select>
146 <button type="button" data-x="1" data-y="0">→</button>
147 </div>
148 <button type="button" data-x="0" data-y="-1">↓</button>
149 </div>
150 <div class="row wrap">
151 <button id="btn-pen-up" type="button">Pen omhoog</button>
152 <button id="btn-pen-down" type="button">Pen omlaag</button>
153 <button id="btn-unlock" type="button">Ontgrendel</button>
154 <button id="btn-home" type="button">Home</button>
155 <button id="btn-release" type="button">Assen los</button>
156 </div>
157 <div class="split">
158 <label class="field">Tekensnelheid
159 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
160 </label>
161 <label class="field">Verplaatsing
162 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
163 </label>
164 </div>
165 <div class="split">
166 <label class="field">Pen omhoog Z
167 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
168 </label>
169 <label class="field">Pen omlaag Z
170 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
171 </label>
172 </div>
173 <label class="field">Pauze na pen ms
174 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
175 </label>
176 <label class="field">Nulpunt
177 <select id="origin">
178 <option value="top-left" selected>Linksboven</option>
179 <option value="bottom-left">Linksonder</option>
180 </select>
181 </label>
182 <label class="check"><input id="return-home" type="checkbox" checked> Terug naar nulpunt</label>
183 <label class="check"><input id="allow-outside" type="checkbox"> Toch buiten A4 sturen</label>
184 <p id="stats" class="hint"></p>
185 <div class="progress">
186 <div id="bar"></div>
187 </div>
188 <div class="row">
189 <button id="btn-plot" type="button" class="primary">Teken</button>
190 <button id="btn-pause" type="button">Pauze</button>
191 <button id="btn-stop" type="button">Stop</button>
192 <button id="btn-trace" type="button">Voorbeeld</button>
193 </div>
194 <p class="hint">Na homing ligt het nulpunt linksboven. X loopt naar rechts tot 200 mm. Y omhoog is positief,
195 dus het blad loopt naar beneden tot −297 mm. Pen omhoog is Z 0, pen omlaag Z 5. Verplaatsingen gaan met G1,
196 zodat de snelheid echt geldt.
197 </p>
198 </section>
199 </aside>
200 </div>
201 <dialog id="connect-modal" class="connect-modal">
202 <h2>Machine</h2>
203 <p id="machine-state">Niet verbonden</p>
204 <p id="firmware" class="hint"></p>
205 <div class="split">
206 <label class="field">Poort
207 <select id="port"></select>
208 </label>
209 <button id="btn-connect" type="button" class="primary">Verbinden</button>
210 </div>
211 <div class="row">
212 <button id="connect-close" type="button">Sluiten</button>
213 </div>
214 </dialog>
215 <script src="/static/app.js"></script>
216</body>
217
218</html>
static/style.css added +379 −0
@@ -0,0 +1,379 @@
1 :root {
2 --bg: #241f1b;
3 --panel: #312b26;
4 --panel-2: #3a342e;
5 --ink: #f3ece3;
6 --muted: #b3a79b;
7 --line: #5a5148;
8 --accent: #e07a3d;
9 --accent-ink: #2a140c;
10 --paper: #f6f1e6;
11 --danger: #e07a72;
12 --ok: #7dcea0;
13 color-scheme: dark;
14 font-family: "Liberation Sans", "Source Sans 3", sans-serif;
15 }
16
17 * {
18 box-sizing: border-box;
19 }
20
21 html,
22 body {
23 margin: 0;
24 height: 100%;
25 background: var(--bg);
26 color: var(--ink);
27 }
28
29 body {
30 display: flex;
31 flex-direction: column;
32 min-height: 100%;
33 }
34
35 button,
36 input,
37 select,
38 textarea {
39 font: inherit;
40 color: inherit;
41 }
42
43 button,
44 select,
45 input,
46 textarea {
47 background: var(--panel-2);
48 border: 1px solid var(--line);
49 border-radius: 6px;
50 padding: 0.4rem 0.55rem;
51 }
52
53 button {
54 cursor: pointer;
55 }
56
57 button:hover {
58 border-color: #8a7d70;
59 }
60
61 button.primary {
62 background: var(--accent);
63 color: var(--accent-ink);
64 border-color: transparent;
65 font-weight: 650;
66 }
67
68 button:disabled {
69 opacity: 0.45;
70 cursor: default;
71 }
72
73 textarea {
74 width: 100%;
75 resize: vertical;
76 }
77
78 header {
79 display: flex;
80 align-items: center;
81 gap: 1rem;
82 padding: 0.65rem 1rem;
83 border-bottom: 1px solid var(--line);
84 }
85
86 .brand {
87 display: flex;
88 flex-direction: column;
89 min-width: 11rem;
90 }
91
92 .brand span,
93 .hint,
94 .mono {
95 color: var(--muted);
96 }
97
98 .brand a {
99 color: var(--accent);
100 font-size: 0.82rem;
101 text-decoration: none;
102 }
103
104 .machine-name {
105 display: inline-flex;
106 align-items: center;
107 gap: 0.45rem;
108 width: fit-content;
109 margin: 0.15rem 0;
110 padding: 0.1rem 0.15rem;
111 background: transparent;
112 border: none;
113 color: var(--ink);
114 font-weight: 650;
115 }
116
117 .machine-name:hover {
118 color: var(--accent);
119 }
120
121 .connect-modal {
122 background: var(--panel);
123 color: var(--ink);
124 border: 1px solid var(--line);
125 border-radius: 12px;
126 padding: 1rem 1.1rem 1.15rem;
127 width: min(24rem, calc(100vw - 2rem));
128 }
129
130 .connect-modal::backdrop {
131 background: rgba(18, 14, 11, 0.72);
132 }
133
134 .connect-modal h2 {
135 margin: 0 0 0.6rem;
136 }
137
138 .hint {
139 font-size: 0.82rem;
140 line-height: 1.35;
141 margin: 0.35rem 0;
142 }
143
144 .header-actions {
145 margin-left: auto;
146 display: flex;
147 gap: 0.8rem;
148 align-items: center;
149 }
150
151 .toast {
152 margin: 0;
153 padding: 0.35rem 0.7rem;
154 background: #4a3424;
155 border-radius: 999px;
156 color: #f6d7bf;
157 }
158
159 .layout {
160 flex: 1;
161 min-height: 0;
162 display: grid;
163 grid-template-columns: minmax(230px, 270px) minmax(0, 1fr) minmax(250px, 310px);
164 }
165
166 .panel {
167 overflow: auto;
168 padding: 0.8rem 0.9rem 1.4rem;
169 background: var(--panel);
170 }
171
172 .panel.left {
173 border-right: 1px solid var(--line);
174 }
175
176 .panel.right {
177 border-left: 1px solid var(--line);
178 }
179
180 section {
181 margin-bottom: 1.1rem;
182 }
183
184 h2 {
185 margin: 0 0 0.55rem;
186 font-size: 0.78rem;
187 letter-spacing: 0.08em;
188 text-transform: uppercase;
189 color: var(--muted);
190 }
191
192 .row {
193 display: flex;
194 gap: 0.4rem;
195 }
196
197 .row.wrap {
198 flex-wrap: wrap;
199 }
200
201 .row>button,
202 .row>.primary {
203 flex: 1;
204 }
205
206 .split {
207 display: grid;
208 grid-template-columns: 1fr 1fr;
209 gap: 0.45rem;
210 }
211
212 .field {
213 display: flex;
214 flex-direction: column;
215 gap: 0.2rem;
216 font-size: 0.82rem;
217 color: var(--muted);
218 margin: 0.35rem 0;
219 }
220
221 .field input,
222 .field select,
223 .field textarea {
224 color: var(--ink);
225 }
226
227 .check {
228 display: flex;
229 gap: 0.45rem;
230 align-items: center;
231 margin: 0.3rem 0;
232 font-size: 0.92rem;
233 }
234
235 .modes {
236 display: flex;
237 gap: 1rem;
238 margin-top: 0.3rem;
239 }
240
241 #layers {
242 list-style: none;
243 margin: 0 0 0.5rem;
244 padding: 0;
245 max-height: 180px;
246 overflow: auto;
247 }
248
249 #layers button {
250 width: 100%;
251 text-align: left;
252 background: transparent;
253 border: 0;
254 padding: 0.35rem 0.45rem;
255 border-radius: 6px;
256 display: flex;
257 justify-content: space-between;
258 gap: 0.5rem;
259 }
260
261 #layers button.active {
262 background: #4a3428;
263 }
264
265 #layers .tag {
266 color: var(--muted);
267 font-size: 0.75rem;
268 }
269
270 main {
271 position: relative;
272 min-width: 0;
273 background: #1a1613;
274 }
275
276 canvas {
277 width: 100%;
278 height: 100%;
279 display: block;
280 cursor: default;
281 }
282
283 .status-line {
284 display: flex;
285 align-items: center;
286 gap: 0.5rem;
287 font-weight: 650;
288 }
289
290 .lamp {
291 width: 0.7rem;
292 height: 0.7rem;
293 border-radius: 50%;
294 background: #6d645c;
295 display: inline-block;
296 }
297
298 .lamp.on {
299 background: var(--ok);
300 }
301
302 .lamp.busy {
303 background: var(--accent);
304 }
305
306 .lamp.bad {
307 background: var(--danger);
308 }
309
310 .error {
311 color: var(--danger);
312 margin: 0.3rem 0;
313 white-space: pre-wrap;
314 }
315
316 .mono {
317 font-family: "Liberation Mono", ui-monospace, monospace;
318 }
319
320 .jog {
321 display: grid;
322 justify-items: center;
323 gap: 0.3rem;
324 margin: 0.4rem 0 0.6rem;
325 }
326
327 .jog-mid {
328 display: flex;
329 gap: 0.3rem;
330 align-items: center;
331 }
332
333 .jog button {
334 width: 2.4rem;
335 height: 2.2rem;
336 }
337
338 .progress {
339 height: 6px;
340 background: #1a1613;
341 border-radius: 99px;
342 overflow: hidden;
343 margin: 0.4rem 0;
344 }
345
346 #bar {
347 height: 100%;
348 width: 0;
349 background: var(--accent);
350 }
351
352 #gray-props[hidden],
353 #text-props[hidden] {
354 display: none;
355 }
356
357 @media (max-width: 860px) {
358 body {
359 height: auto;
360 min-height: 100%;
361 overflow: auto;
362 }
363
364 .layout {
365 display: flex;
366 flex-direction: column;
367 height: auto;
368 flex: none;
369 }
370
371 .panel {
372 overflow: visible;
373 }
374
375 main {
376 height: 70vh;
377 flex: none;
378 }
379 }
@@ -0,0 +1,379 @@
1:root {
2 --bg: #241f1b;
3 --panel: #312b26;
4 --panel-2: #3a342e;
5 --ink: #f3ece3;
6 --muted: #b3a79b;
7 --line: #5a5148;
8 --accent: #e07a3d;
9 --accent-ink: #2a140c;
10 --paper: #f6f1e6;
11 --danger: #e07a72;
12 --ok: #7dcea0;
13 color-scheme: dark;
14 font-family: "Liberation Sans", "Source Sans 3", sans-serif;
15}
16
17* {
18 box-sizing: border-box;
19}
20
21html,
22body {
23 margin: 0;
24 height: 100%;
25 background: var(--bg);
26 color: var(--ink);
27}
28
29body {
30 display: flex;
31 flex-direction: column;
32 min-height: 100%;
33}
34
35button,
36input,
37select,
38textarea {
39 font: inherit;
40 color: inherit;
41}
42
43button,
44select,
45input,
46textarea {
47 background: var(--panel-2);
48 border: 1px solid var(--line);
49 border-radius: 6px;
50 padding: 0.4rem 0.55rem;
51}
52
53button {
54 cursor: pointer;
55}
56
57button:hover {
58 border-color: #8a7d70;
59}
60
61button.primary {
62 background: var(--accent);
63 color: var(--accent-ink);
64 border-color: transparent;
65 font-weight: 650;
66}
67
68button:disabled {
69 opacity: 0.45;
70 cursor: default;
71}
72
73textarea {
74 width: 100%;
75 resize: vertical;
76}
77
78header {
79 display: flex;
80 align-items: center;
81 gap: 1rem;
82 padding: 0.65rem 1rem;
83 border-bottom: 1px solid var(--line);
84}
85
86.brand {
87 display: flex;
88 flex-direction: column;
89 min-width: 11rem;
90}
91
92.brand span,
93.hint,
94.mono {
95 color: var(--muted);
96}
97
98.brand a {
99 color: var(--accent);
100 font-size: 0.82rem;
101 text-decoration: none;
102}
103
104.machine-name {
105 display: inline-flex;
106 align-items: center;
107 gap: 0.45rem;
108 width: fit-content;
109 margin: 0.15rem 0;
110 padding: 0.1rem 0.15rem;
111 background: transparent;
112 border: none;
113 color: var(--ink);
114 font-weight: 650;
115}
116
117.machine-name:hover {
118 color: var(--accent);
119}
120
121.connect-modal {
122 background: var(--panel);
123 color: var(--ink);
124 border: 1px solid var(--line);
125 border-radius: 12px;
126 padding: 1rem 1.1rem 1.15rem;
127 width: min(24rem, calc(100vw - 2rem));
128}
129
130.connect-modal::backdrop {
131 background: rgba(18, 14, 11, 0.72);
132}
133
134.connect-modal h2 {
135 margin: 0 0 0.6rem;
136}
137
138.hint {
139 font-size: 0.82rem;
140 line-height: 1.35;
141 margin: 0.35rem 0;
142}
143
144.header-actions {
145 margin-left: auto;
146 display: flex;
147 gap: 0.8rem;
148 align-items: center;
149}
150
151.toast {
152 margin: 0;
153 padding: 0.35rem 0.7rem;
154 background: #4a3424;
155 border-radius: 999px;
156 color: #f6d7bf;
157}
158
159.layout {
160 flex: 1;
161 min-height: 0;
162 display: grid;
163 grid-template-columns: minmax(230px, 270px) minmax(0, 1fr) minmax(250px, 310px);
164}
165
166.panel {
167 overflow: auto;
168 padding: 0.8rem 0.9rem 1.4rem;
169 background: var(--panel);
170}
171
172.panel.left {
173 border-right: 1px solid var(--line);
174}
175
176.panel.right {
177 border-left: 1px solid var(--line);
178}
179
180section {
181 margin-bottom: 1.1rem;
182}
183
184h2 {
185 margin: 0 0 0.55rem;
186 font-size: 0.78rem;
187 letter-spacing: 0.08em;
188 text-transform: uppercase;
189 color: var(--muted);
190}
191
192.row {
193 display: flex;
194 gap: 0.4rem;
195}
196
197.row.wrap {
198 flex-wrap: wrap;
199}
200
201.row>button,
202.row>.primary {
203 flex: 1;
204}
205
206.split {
207 display: grid;
208 grid-template-columns: 1fr 1fr;
209 gap: 0.45rem;
210}
211
212.field {
213 display: flex;
214 flex-direction: column;
215 gap: 0.2rem;
216 font-size: 0.82rem;
217 color: var(--muted);
218 margin: 0.35rem 0;
219}
220
221.field input,
222.field select,
223.field textarea {
224 color: var(--ink);
225}
226
227.check {
228 display: flex;
229 gap: 0.45rem;
230 align-items: center;
231 margin: 0.3rem 0;
232 font-size: 0.92rem;
233}
234
235.modes {
236 display: flex;
237 gap: 1rem;
238 margin-top: 0.3rem;
239}
240
241#layers {
242 list-style: none;
243 margin: 0 0 0.5rem;
244 padding: 0;
245 max-height: 180px;
246 overflow: auto;
247}
248
249#layers button {
250 width: 100%;
251 text-align: left;
252 background: transparent;
253 border: 0;
254 padding: 0.35rem 0.45rem;
255 border-radius: 6px;
256 display: flex;
257 justify-content: space-between;
258 gap: 0.5rem;
259}
260
261#layers button.active {
262 background: #4a3428;
263}
264
265#layers .tag {
266 color: var(--muted);
267 font-size: 0.75rem;
268}
269
270main {
271 position: relative;
272 min-width: 0;
273 background: #1a1613;
274}
275
276canvas {
277 width: 100%;
278 height: 100%;
279 display: block;
280 cursor: default;
281}
282
283.status-line {
284 display: flex;
285 align-items: center;
286 gap: 0.5rem;
287 font-weight: 650;
288}
289
290.lamp {
291 width: 0.7rem;
292 height: 0.7rem;
293 border-radius: 50%;
294 background: #6d645c;
295 display: inline-block;
296}
297
298.lamp.on {
299 background: var(--ok);
300}
301
302.lamp.busy {
303 background: var(--accent);
304}
305
306.lamp.bad {
307 background: var(--danger);
308}
309
310.error {
311 color: var(--danger);
312 margin: 0.3rem 0;
313 white-space: pre-wrap;
314}
315
316.mono {
317 font-family: "Liberation Mono", ui-monospace, monospace;
318}
319
320.jog {
321 display: grid;
322 justify-items: center;
323 gap: 0.3rem;
324 margin: 0.4rem 0 0.6rem;
325}
326
327.jog-mid {
328 display: flex;
329 gap: 0.3rem;
330 align-items: center;
331}
332
333.jog button {
334 width: 2.4rem;
335 height: 2.2rem;
336}
337
338.progress {
339 height: 6px;
340 background: #1a1613;
341 border-radius: 99px;
342 overflow: hidden;
343 margin: 0.4rem 0;
344}
345
346#bar {
347 height: 100%;
348 width: 0;
349 background: var(--accent);
350}
351
352#gray-props[hidden],
353#text-props[hidden] {
354 display: none;
355}
356
357@media (max-width: 860px) {
358 body {
359 height: auto;
360 min-height: 100%;
361 overflow: auto;
362 }
363
364 .layout {
365 display: flex;
366 flex-direction: column;
367 height: auto;
368 flex: none;
369 }
370
371 .panel {
372 overflow: visible;
373 }
374
375 main {
376 height: 70vh;
377 flex: none;
378 }
379}
timdraw/__init__.py added +1 −0
@@ -0,0 +1 @@
1 """Timdraw: A4-plotter voor de Bachin TA4 (GRBL) onder Linux."""
@@ -0,0 +1 @@
1"""Timdraw: A4-plotter voor de Bachin TA4 (GRBL) onder Linux."""
timdraw/__main__.py added +3 −0
@@ -0,0 +1,3 @@
1 from timdraw.server import main
2
3 main()
@@ -0,0 +1,3 @@
1from timdraw.server import main
2
3main()
timdraw/font.py added +65 −0
@@ -0,0 +1,65 @@
1 """Enkel-lijn-tekst uit de publieke Hershey-fonts (futural, rowmans, scripts)."""
2
3 from __future__ import annotations
4
5 import json
6 from functools import lru_cache
7 from pathlib import Path
8
9 from timdraw.geom import bounds
10
11 # Hershey-Y loopt omlaag. Baseline van de kapitalen ligt op y=9, top op y=-12.
12 _BASELINE = 9.0
13 _CAP_UNITS = 21.0
14
15 FONTS = {
16 "futural": "Sans",
17 "rowmans": "Romein",
18 "scripts": "Handschrift",
19 }
20
21
22 @lru_cache(maxsize=1)
23 def _data() -> dict:
24 path = Path(__file__).with_name("hershey.json")
25 return json.loads(path.read_text(encoding="utf-8"))
26
27
28 def render_text(text: str, font: str = "futural", size_mm: float = 12.0, line_spacing: float = 1.4) -> dict:
29 fonts = _data()
30 if font not in fonts:
31 font = "futural"
32 glyphs = fonts[font]
33 size = max(2.0, min(80.0, float(size_mm)))
34 spacing = max(1.0, min(3.0, float(line_spacing)))
35 scale = size / _CAP_UNITS
36 lines = (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
37 strokes: list[list[list[float]]] = []
38 cursor_y = 0.0
39 for line in lines:
40 cursor_x = 0.0
41 for ch in line:
42 index = ord(ch) - 32
43 if index < 0 or index >= len(glyphs):
44 cursor_x += size * 0.45
45 continue
46 glyph = glyphs[index]
47 left = float(glyph["l"])
48 right = float(glyph["r"])
49 for path in glyph["p"]:
50 pts = []
51 for x, y in path:
52 px = (float(x) - left) * scale + cursor_x
53 py = (-float(y) + _BASELINE) * scale + cursor_y
54 pts.append([px, py])
55 if len(pts) >= 2:
56 strokes.append(pts)
57 cursor_x += (right - left) * scale
58 cursor_y -= size * spacing
59 box = bounds(strokes)
60 if box is None:
61 return {"strokes": [], "fills": [], "x": 105.0, "y": 148.5}
62 minx, miny, maxx, maxy = box
63 cx, cy = (minx + maxx) / 2, (miny + maxy) / 2
64 centered = [[[x - cx, y - cy] for x, y in pts] for pts in strokes]
65 return {"strokes": centered, "fills": [], "x": 105.0, "y": 160.0}
@@ -0,0 +1,65 @@
1"""Enkel-lijn-tekst uit de publieke Hershey-fonts (futural, rowmans, scripts)."""
2
3from __future__ import annotations
4
5import json
6from functools import lru_cache
7from pathlib import Path
8
9from timdraw.geom import bounds
10
11# Hershey-Y loopt omlaag. Baseline van de kapitalen ligt op y=9, top op y=-12.
12_BASELINE = 9.0
13_CAP_UNITS = 21.0
14
15FONTS = {
16 "futural": "Sans",
17 "rowmans": "Romein",
18 "scripts": "Handschrift",
19}
20
21
22@lru_cache(maxsize=1)
23def _data() -> dict:
24 path = Path(__file__).with_name("hershey.json")
25 return json.loads(path.read_text(encoding="utf-8"))
26
27
28def render_text(text: str, font: str = "futural", size_mm: float = 12.0, line_spacing: float = 1.4) -> dict:
29 fonts = _data()
30 if font not in fonts:
31 font = "futural"
32 glyphs = fonts[font]
33 size = max(2.0, min(80.0, float(size_mm)))
34 spacing = max(1.0, min(3.0, float(line_spacing)))
35 scale = size / _CAP_UNITS
36 lines = (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
37 strokes: list[list[list[float]]] = []
38 cursor_y = 0.0
39 for line in lines:
40 cursor_x = 0.0
41 for ch in line:
42 index = ord(ch) - 32
43 if index < 0 or index >= len(glyphs):
44 cursor_x += size * 0.45
45 continue
46 glyph = glyphs[index]
47 left = float(glyph["l"])
48 right = float(glyph["r"])
49 for path in glyph["p"]:
50 pts = []
51 for x, y in path:
52 px = (float(x) - left) * scale + cursor_x
53 py = (-float(y) + _BASELINE) * scale + cursor_y
54 pts.append([px, py])
55 if len(pts) >= 2:
56 strokes.append(pts)
57 cursor_x += (right - left) * scale
58 cursor_y -= size * spacing
59 box = bounds(strokes)
60 if box is None:
61 return {"strokes": [], "fills": [], "x": 105.0, "y": 148.5}
62 minx, miny, maxx, maxy = box
63 cx, cy = (minx + maxx) / 2, (miny + maxy) / 2
64 centered = [[[x - cx, y - cy] for x, y in pts] for pts in strokes]
65 return {"strokes": centered, "fills": [], "x": 105.0, "y": 160.0}
timdraw/gcode.py added +333 −0
@@ -0,0 +1,333 @@
1 """Van tekening naar GRBL-paden. Reizen gaat met G1, omdat GRBL 1.1 de voeding op G0 negeert."""
2
3 from __future__ import annotations
4
5 from timdraw.geom import (
6 A4_H,
7 A4_W,
8 Point,
9 Polyline,
10 dedupe,
11 dist,
12 fit_arcs,
13 is_closed,
14 length_of,
15 transform_point,
16 )
17 from timdraw.hatch import hatch, spacing_for_gray
18
19
20 def _draw_flags(obj: dict) -> tuple[bool, bool]:
21 if "drawLine" in obj or "drawFill" in obj:
22 return bool(obj.get("drawLine")), bool(obj.get("drawFill"))
23 if obj.get("mode") == "fill":
24 return False, True
25 return True, False
26
27
28 def _clamp(value: float, low: float, high: float) -> float:
29 return max(low, min(high, value))
30
31
32 # Bereik na homing, met het nulpunt linksboven. De papierbreedte is 210, de wagen haalt 200.
33 BED_W = 200.0
34 BED_H = 297.0
35
36
37 def _page_point(x: float, y: float, origin_top: bool) -> Point:
38 # Editor-Y loopt omhoog vanaf de onderkant. Na homing is (0, 0) linksboven.
39 # Machine-Y positief is omhoog, voorbij die hoek. Het blad ligt daarom in
40 # negatieve Y, tot -297 mm.
41 machine_y = (y - A4_H) if origin_top else y
42 if abs(x) < 1e-9:
43 x = 0.0
44 if abs(machine_y) < 1e-9:
45 machine_y = 0.0
46 return x, machine_y
47
48
49 def _orient(pts: Polyline, pos: Point) -> tuple[Polyline, float]:
50 """Kies beginpunt en richting zodat de reis vanaf pos zo kort mogelijk is."""
51 if len(pts) > 2 and dist(pts[0], pts[-1]) <= 0.05:
52 body = pts[:-1]
53 start_at = min(range(len(body)), key=lambda index: dist(pos, body[index]))
54 rotated = body[start_at:] + body[:start_at]
55 rotated.append(rotated[0])
56 return rotated, dist(pos, rotated[0])
57 if dist(pos, pts[-1]) < dist(pos, pts[0]):
58 flipped = list(reversed(pts))
59 return flipped, dist(pos, flipped[0])
60 return pts, dist(pos, pts[0])
61
62
63 def _order_paths(paths: list[Polyline], start: Point) -> list[Polyline]:
64 """Teken aansluitende lijnen in één beweging, anders telkens de dichtstbijzijnde."""
65 remaining = [list(pts) for pts in paths if len(pts) >= 2]
66 ordered: list[Polyline] = []
67 pos = start
68 while remaining:
69 best = 0
70 best_path = remaining[0]
71 best_dist = float("inf")
72 for index, pts in enumerate(remaining):
73 oriented, gap = _orient(pts, pos)
74 if gap < best_dist:
75 best = index
76 best_path = oriented
77 best_dist = gap
78 remaining.pop(best)
79 ordered.append(best_path)
80 pos = best_path[-1]
81 return ordered
82
83
84 def _stroke_points(stroke) -> Polyline:
85 raw = stroke["pts"] if isinstance(stroke, dict) else stroke
86 return [(float(p[0]), float(p[1])) for p in raw]
87
88
89 def _signed_area(pts: Polyline) -> float:
90 return sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(pts, pts[1:])) / 2
91
92
93 def _point_in_poly(x: float, y: float, poly: Polyline) -> bool:
94 inside = False
95 count = len(poly)
96 if count >= 2 and dist(poly[0], poly[-1]) < 0.05:
97 count -= 1
98 if count < 3:
99 return False
100 previous = count - 1
101 for index in range(count):
102 xi, yi = poly[index]
103 xj, yj = poly[previous]
104 if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / ((yj - yi) or 1e-15) + xi:
105 inside = not inside
106 previous = index
107 return inside
108
109
110 def _outer_paths(strokes: list, fills: list) -> list[Polyline]:
111 """Buitenste contouren. Gaten en lijnen binnen een vorm vallen weg."""
112 plain: list[Polyline] = []
113 from_fill: list[Polyline] = []
114 for stroke in strokes:
115 pts = _stroke_points(stroke)
116 if len(pts) < 2:
117 continue
118 if isinstance(stroke, dict) and stroke.get("fromFill"):
119 from_fill.append(pts)
120 else:
121 plain.append(pts)
122 chosen = plain or from_fill
123 if not chosen:
124 for fill in fills:
125 for ring in fill.get("rings") or []:
126 pts = _stroke_points(ring)
127 if len(pts) >= 2:
128 chosen.append(pts)
129 closed = [pts for pts in chosen if is_closed(pts)]
130 outer: list[Polyline] = []
131 for pts in chosen:
132 probe = pts[len(pts) // 2]
133 area = abs(_signed_area(pts))
134 nested = False
135 for other in closed:
136 if other is pts:
137 continue
138 if abs(_signed_area(other)) <= max(area, 1e-6) * 1.02:
139 continue
140 if _point_in_poly(probe[0], probe[1], other):
141 nested = True
142 break
143 if not nested:
144 outer.append(pts)
145 return outer
146
147
148 def plan(objects: list[dict], settings: dict | None = None) -> dict:
149 settings = settings or {}
150 draw_speed = _clamp(float(settings.get("drawSpeed", 3000)), 50, 6000)
151 travel_speed = _clamp(float(settings.get("travelSpeed", 5000)), 50, 6000)
152 pen_up = _clamp(float(settings.get("penUpZ", 0)), 0, 12)
153 pen_down = _clamp(float(settings.get("penDownZ", 5)), 0, 12)
154 dwell = _clamp(float(settings.get("dwellMs", 120)), 0, 2000) / 1000.0
155 origin_top = settings.get("origin") == "top-left"
156 return_home = bool(settings.get("returnHome", True))
157 allow_outside = bool(settings.get("allowOutside", False))
158 trace = bool(settings.get("trace"))
159
160 draw: list[Polyline] = []
161 warnings: list[str] = []
162 for obj in objects:
163 if obj.get("hidden"):
164 continue
165 want_line, want_fill = _draw_flags(obj)
166 strokes = obj.get("strokes") or []
167 fills = obj.get("fills") or []
168 angle = float(obj.get("hatchAngle", 45) or 0)
169 spacing = _clamp(float(obj.get("hatchSpacing", 2) or 2), 0.3, 30)
170 cross = bool(obj.get("crosshatch"))
171 use_gray = bool(obj.get("grayscale"))
172 steps = int(obj.get("graySteps", 5) or 5)
173 dark = _clamp(float(obj.get("spacingMin", spacing) or spacing), 0.3, 30)
174 light = _clamp(float(obj.get("spacingMax", max(spacing * 3, dark + 0.4)) or spacing), 0.3, 40)
175 if light < dark:
176 dark, light = light, dark
177
178 def mapped(pts: Polyline) -> Polyline:
179 return [transform_point(x, y, obj) for x, y in pts]
180
181 if trace:
182 for pts in _outer_paths(strokes, fills):
183 if len(pts) >= 2:
184 draw.append(mapped(pts))
185 continue
186
187 def add_hatch(rings: list[Polyline], gap: float, rule: str) -> None:
188 lines = hatch(rings, angle, gap, rule)
189 if cross:
190 lines += hatch(rings, angle + 90, gap, rule)
191 draw.extend(lines)
192
193 if want_fill and fills:
194 for fill in fills:
195 rings = [mapped(_stroke_points(ring)) for ring in fill.get("rings") or []]
196 gap = spacing
197 if use_gray:
198 gap = spacing_for_gray(float(fill.get("gray", 0) or 0), steps, dark, light)
199 add_hatch(rings, gap, fill.get("rule") or "evenodd")
200 if not want_line:
201 for stroke in strokes:
202 pts = _stroke_points(stroke)
203 closed = bool(stroke.get("closed")) if isinstance(stroke, dict) else is_closed(pts)
204 from_fill = bool(stroke.get("fromFill")) if isinstance(stroke, dict) else False
205 if from_fill or closed or len(pts) < 2:
206 continue
207 draw.append(mapped(pts))
208 elif want_fill:
209 for stroke in strokes:
210 pts = _stroke_points(stroke)
211 if len(pts) < 2:
212 continue
213 closed = bool(stroke.get("closed")) if isinstance(stroke, dict) else is_closed(pts)
214 if closed:
215 add_hatch([mapped(pts)], spacing, "evenodd")
216 elif not want_line:
217 draw.append(mapped(pts))
218 warnings.append("Open lijnen blijven een lijn, ook als alleen vulling aan staat.")
219 if want_line:
220 for stroke in strokes:
221 pts = _stroke_points(stroke)
222 if len(pts) >= 2:
223 draw.append(mapped(pts))
224
225 # Dubbele waarschuwing maar één keer.
226 warnings = list(dict.fromkeys(warnings))
227 draw = [pts for pts in draw if length_of(pts) >= 0.15]
228 start = (0.0, A4_H if origin_top else 0.0)
229 draw = _order_paths(draw, start)
230 outside = []
231 for pts in draw:
232 for x, y in pts:
233 if x < -0.2 or y < -0.2 or x > A4_W + 0.2 or y > A4_H + 0.2:
234 outside.append((x, y))
235 break
236 if outside and not allow_outside:
237 warnings.append("Een deel valt buiten A4. Zet het op het blad of vink 'toch buiten A4' aan.")
238
239 travel: list[Polyline] = []
240 gcode = ["; Timdraw", "G21", "G90", "G94"]
241 pen_down_state = True
242 draw_mm = 0.0
243 travel_mm = 0.0
244 feed = None
245
246 def set_feed(speed: float) -> str:
247 nonlocal feed
248 if feed == speed:
249 return ""
250 feed = speed
251 return f" F{speed:.0f}"
252
253 def pen(down: bool) -> None:
254 nonlocal pen_down_state, feed
255 if pen_down_state == down:
256 return
257 z = pen_down if down else pen_up
258 if down:
259 gcode.append("$1=255")
260 gcode.append(f"G1 Z{z:.3f} F{travel_speed:.0f}")
261 feed = None
262 if dwell:
263 gcode.append(f"G4 P{dwell:.3f}")
264 pen_down_state = down
265
266 pen(False)
267
268 clipped = False
269
270 def machine_point(x: float, y: float) -> Point:
271 nonlocal clipped
272 mx, my = _page_point(x, y, origin_top)
273 y_min, y_max = (-BED_H, 0.0) if origin_top else (0.0, BED_H)
274 if mx < -0.2 or my < y_min - 0.2 or mx > BED_W + 0.2 or my > y_max + 0.2:
275 clipped = True
276 return min(BED_W, max(0.0, mx)), min(y_max, max(y_min, my))
277
278 page_at: Point | None = None
279
280 for pts in draw:
281 machine = dedupe([machine_point(x, y) for x, y in pts], 0.05)
282 if len(machine) < 2:
283 continue
284 x0, y0 = machine[0]
285 if page_at is None or dist(page_at, pts[0]) > 0.05:
286 if not trace:
287 pen(False)
288 gcode.append(f"G1 X{x0:.3f} Y{y0:.3f}{set_feed(travel_speed)}")
289 if page_at is not None:
290 travel.append([page_at, pts[0]])
291 travel_mm += dist(page_at, pts[0])
292 if trace:
293 speed = travel_speed
294 travel_mm += length_of(machine)
295 else:
296 pen(True)
297 speed = draw_speed
298 draw_mm += length_of(machine)
299 for code, x, y, i_off, j_off in fit_arcs(machine):
300 if code == "G1":
301 gcode.append(f"G1 X{x:.3f} Y{y:.3f}{set_feed(speed)}")
302 else:
303 gcode.append(f"{code} X{x:.3f} Y{y:.3f} I{i_off:.3f} J{j_off:.3f}{set_feed(speed)}")
304 page_at = pts[-1]
305 if not trace:
306 pen(False)
307 home = (0.0, A4_H if origin_top else 0.0)
308 if return_home and page_at is not None and dist(page_at, home) > 0.05:
309 hx, hy = machine_point(home[0], home[1])
310 gcode.append(f"G1 X{hx:.3f} Y{hy:.3f}{set_feed(travel_speed)}")
311 travel.append([page_at, home])
312 travel_mm += dist(page_at, home)
313 gcode.append("G4 P0.1")
314
315 if clipped:
316 warnings.append("Een deel ligt buiten het bereik van de wagen, 200 bij 297 mm, en blijft op de rand.")
317 pen_lifts = sum(1 for line in gcode if line.startswith("G1 Z"))
318 seconds = draw_mm / draw_speed * 60 + travel_mm / travel_speed * 60 + pen_lifts * (dwell + 0.15)
319 blocked = bool(outside) and not allow_outside
320 return {
321 "draw": [[[round(x, 3), round(y, 3)] for x, y in pts] for pts in draw],
322 "travel": [[[round(x, 3), round(y, 3)] for x, y in pts] for pts in travel],
323 "gcode": "\n".join(gcode) + "\n",
324 "warnings": warnings,
325 "stats": {
326 "drawMm": round(draw_mm, 1),
327 "travelMm": round(travel_mm, 1),
328 "seconds": round(seconds, 1),
329 "outside": bool(outside),
330 "blocked": blocked,
331 "lines": len(gcode),
332 },
333 }
@@ -0,0 +1,333 @@
1"""Van tekening naar GRBL-paden. Reizen gaat met G1, omdat GRBL 1.1 de voeding op G0 negeert."""
2
3from __future__ import annotations
4
5from timdraw.geom import (
6 A4_H,
7 A4_W,
8 Point,
9 Polyline,
10 dedupe,
11 dist,
12 fit_arcs,
13 is_closed,
14 length_of,
15 transform_point,
16)
17from timdraw.hatch import hatch, spacing_for_gray
18
19
20def _draw_flags(obj: dict) -> tuple[bool, bool]:
21 if "drawLine" in obj or "drawFill" in obj:
22 return bool(obj.get("drawLine")), bool(obj.get("drawFill"))
23 if obj.get("mode") == "fill":
24 return False, True
25 return True, False
26
27
28def _clamp(value: float, low: float, high: float) -> float:
29 return max(low, min(high, value))
30
31
32# Bereik na homing, met het nulpunt linksboven. De papierbreedte is 210, de wagen haalt 200.
33BED_W = 200.0
34BED_H = 297.0
35
36
37def _page_point(x: float, y: float, origin_top: bool) -> Point:
38 # Editor-Y loopt omhoog vanaf de onderkant. Na homing is (0, 0) linksboven.
39 # Machine-Y positief is omhoog, voorbij die hoek. Het blad ligt daarom in
40 # negatieve Y, tot -297 mm.
41 machine_y = (y - A4_H) if origin_top else y
42 if abs(x) < 1e-9:
43 x = 0.0
44 if abs(machine_y) < 1e-9:
45 machine_y = 0.0
46 return x, machine_y
47
48
49def _orient(pts: Polyline, pos: Point) -> tuple[Polyline, float]:
50 """Kies beginpunt en richting zodat de reis vanaf pos zo kort mogelijk is."""
51 if len(pts) > 2 and dist(pts[0], pts[-1]) <= 0.05:
52 body = pts[:-1]
53 start_at = min(range(len(body)), key=lambda index: dist(pos, body[index]))
54 rotated = body[start_at:] + body[:start_at]
55 rotated.append(rotated[0])
56 return rotated, dist(pos, rotated[0])
57 if dist(pos, pts[-1]) < dist(pos, pts[0]):
58 flipped = list(reversed(pts))
59 return flipped, dist(pos, flipped[0])
60 return pts, dist(pos, pts[0])
61
62
63def _order_paths(paths: list[Polyline], start: Point) -> list[Polyline]:
64 """Teken aansluitende lijnen in één beweging, anders telkens de dichtstbijzijnde."""
65 remaining = [list(pts) for pts in paths if len(pts) >= 2]
66 ordered: list[Polyline] = []
67 pos = start
68 while remaining:
69 best = 0
70 best_path = remaining[0]
71 best_dist = float("inf")
72 for index, pts in enumerate(remaining):
73 oriented, gap = _orient(pts, pos)
74 if gap < best_dist:
75 best = index
76 best_path = oriented
77 best_dist = gap
78 remaining.pop(best)
79 ordered.append(best_path)
80 pos = best_path[-1]
81 return ordered
82
83
84def _stroke_points(stroke) -> Polyline:
85 raw = stroke["pts"] if isinstance(stroke, dict) else stroke
86 return [(float(p[0]), float(p[1])) for p in raw]
87
88
89def _signed_area(pts: Polyline) -> float:
90 return sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(pts, pts[1:])) / 2
91
92
93def _point_in_poly(x: float, y: float, poly: Polyline) -> bool:
94 inside = False
95 count = len(poly)
96 if count >= 2 and dist(poly[0], poly[-1]) < 0.05:
97 count -= 1
98 if count < 3:
99 return False
100 previous = count - 1
101 for index in range(count):
102 xi, yi = poly[index]
103 xj, yj = poly[previous]
104 if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / ((yj - yi) or 1e-15) + xi:
105 inside = not inside
106 previous = index
107 return inside
108
109
110def _outer_paths(strokes: list, fills: list) -> list[Polyline]:
111 """Buitenste contouren. Gaten en lijnen binnen een vorm vallen weg."""
112 plain: list[Polyline] = []
113 from_fill: list[Polyline] = []
114 for stroke in strokes:
115 pts = _stroke_points(stroke)
116 if len(pts) < 2:
117 continue
118 if isinstance(stroke, dict) and stroke.get("fromFill"):
119 from_fill.append(pts)
120 else:
121 plain.append(pts)
122 chosen = plain or from_fill
123 if not chosen:
124 for fill in fills:
125 for ring in fill.get("rings") or []:
126 pts = _stroke_points(ring)
127 if len(pts) >= 2:
128 chosen.append(pts)
129 closed = [pts for pts in chosen if is_closed(pts)]
130 outer: list[Polyline] = []
131 for pts in chosen:
132 probe = pts[len(pts) // 2]
133 area = abs(_signed_area(pts))
134 nested = False
135 for other in closed:
136 if other is pts:
137 continue
138 if abs(_signed_area(other)) <= max(area, 1e-6) * 1.02:
139 continue
140 if _point_in_poly(probe[0], probe[1], other):
141 nested = True
142 break
143 if not nested:
144 outer.append(pts)
145 return outer
146
147
148def plan(objects: list[dict], settings: dict | None = None) -> dict:
149 settings = settings or {}
150 draw_speed = _clamp(float(settings.get("drawSpeed", 3000)), 50, 6000)
151 travel_speed = _clamp(float(settings.get("travelSpeed", 5000)), 50, 6000)
152 pen_up = _clamp(float(settings.get("penUpZ", 0)), 0, 12)
153 pen_down = _clamp(float(settings.get("penDownZ", 5)), 0, 12)
154 dwell = _clamp(float(settings.get("dwellMs", 120)), 0, 2000) / 1000.0
155 origin_top = settings.get("origin") == "top-left"
156 return_home = bool(settings.get("returnHome", True))
157 allow_outside = bool(settings.get("allowOutside", False))
158 trace = bool(settings.get("trace"))
159
160 draw: list[Polyline] = []
161 warnings: list[str] = []
162 for obj in objects:
163 if obj.get("hidden"):
164 continue
165 want_line, want_fill = _draw_flags(obj)
166 strokes = obj.get("strokes") or []
167 fills = obj.get("fills") or []
168 angle = float(obj.get("hatchAngle", 45) or 0)
169 spacing = _clamp(float(obj.get("hatchSpacing", 2) or 2), 0.3, 30)
170 cross = bool(obj.get("crosshatch"))
171 use_gray = bool(obj.get("grayscale"))
172 steps = int(obj.get("graySteps", 5) or 5)
173 dark = _clamp(float(obj.get("spacingMin", spacing) or spacing), 0.3, 30)
174 light = _clamp(float(obj.get("spacingMax", max(spacing * 3, dark + 0.4)) or spacing), 0.3, 40)
175 if light < dark:
176 dark, light = light, dark
177
178 def mapped(pts: Polyline) -> Polyline:
179 return [transform_point(x, y, obj) for x, y in pts]
180
181 if trace:
182 for pts in _outer_paths(strokes, fills):
183 if len(pts) >= 2:
184 draw.append(mapped(pts))
185 continue
186
187 def add_hatch(rings: list[Polyline], gap: float, rule: str) -> None:
188 lines = hatch(rings, angle, gap, rule)
189 if cross:
190 lines += hatch(rings, angle + 90, gap, rule)
191 draw.extend(lines)
192
193 if want_fill and fills:
194 for fill in fills:
195 rings = [mapped(_stroke_points(ring)) for ring in fill.get("rings") or []]
196 gap = spacing
197 if use_gray:
198 gap = spacing_for_gray(float(fill.get("gray", 0) or 0), steps, dark, light)
199 add_hatch(rings, gap, fill.get("rule") or "evenodd")
200 if not want_line:
201 for stroke in strokes:
202 pts = _stroke_points(stroke)
203 closed = bool(stroke.get("closed")) if isinstance(stroke, dict) else is_closed(pts)
204 from_fill = bool(stroke.get("fromFill")) if isinstance(stroke, dict) else False
205 if from_fill or closed or len(pts) < 2:
206 continue
207 draw.append(mapped(pts))
208 elif want_fill:
209 for stroke in strokes:
210 pts = _stroke_points(stroke)
211 if len(pts) < 2:
212 continue
213 closed = bool(stroke.get("closed")) if isinstance(stroke, dict) else is_closed(pts)
214 if closed:
215 add_hatch([mapped(pts)], spacing, "evenodd")
216 elif not want_line:
217 draw.append(mapped(pts))
218 warnings.append("Open lijnen blijven een lijn, ook als alleen vulling aan staat.")
219 if want_line:
220 for stroke in strokes:
221 pts = _stroke_points(stroke)
222 if len(pts) >= 2:
223 draw.append(mapped(pts))
224
225 # Dubbele waarschuwing maar één keer.
226 warnings = list(dict.fromkeys(warnings))
227 draw = [pts for pts in draw if length_of(pts) >= 0.15]
228 start = (0.0, A4_H if origin_top else 0.0)
229 draw = _order_paths(draw, start)
230 outside = []
231 for pts in draw:
232 for x, y in pts:
233 if x < -0.2 or y < -0.2 or x > A4_W + 0.2 or y > A4_H + 0.2:
234 outside.append((x, y))
235 break
236 if outside and not allow_outside:
237 warnings.append("Een deel valt buiten A4. Zet het op het blad of vink 'toch buiten A4' aan.")
238
239 travel: list[Polyline] = []
240 gcode = ["; Timdraw", "G21", "G90", "G94"]
241 pen_down_state = True
242 draw_mm = 0.0
243 travel_mm = 0.0
244 feed = None
245
246 def set_feed(speed: float) -> str:
247 nonlocal feed
248 if feed == speed:
249 return ""
250 feed = speed
251 return f" F{speed:.0f}"
252
253 def pen(down: bool) -> None:
254 nonlocal pen_down_state, feed
255 if pen_down_state == down:
256 return
257 z = pen_down if down else pen_up
258 if down:
259 gcode.append("$1=255")
260 gcode.append(f"G1 Z{z:.3f} F{travel_speed:.0f}")
261 feed = None
262 if dwell:
263 gcode.append(f"G4 P{dwell:.3f}")
264 pen_down_state = down
265
266 pen(False)
267
268 clipped = False
269
270 def machine_point(x: float, y: float) -> Point:
271 nonlocal clipped
272 mx, my = _page_point(x, y, origin_top)
273 y_min, y_max = (-BED_H, 0.0) if origin_top else (0.0, BED_H)
274 if mx < -0.2 or my < y_min - 0.2 or mx > BED_W + 0.2 or my > y_max + 0.2:
275 clipped = True
276 return min(BED_W, max(0.0, mx)), min(y_max, max(y_min, my))
277
278 page_at: Point | None = None
279
280 for pts in draw:
281 machine = dedupe([machine_point(x, y) for x, y in pts], 0.05)
282 if len(machine) < 2:
283 continue
284 x0, y0 = machine[0]
285 if page_at is None or dist(page_at, pts[0]) > 0.05:
286 if not trace:
287 pen(False)
288 gcode.append(f"G1 X{x0:.3f} Y{y0:.3f}{set_feed(travel_speed)}")
289 if page_at is not None:
290 travel.append([page_at, pts[0]])
291 travel_mm += dist(page_at, pts[0])
292 if trace:
293 speed = travel_speed
294 travel_mm += length_of(machine)
295 else:
296 pen(True)
297 speed = draw_speed
298 draw_mm += length_of(machine)
299 for code, x, y, i_off, j_off in fit_arcs(machine):
300 if code == "G1":
301 gcode.append(f"G1 X{x:.3f} Y{y:.3f}{set_feed(speed)}")
302 else:
303 gcode.append(f"{code} X{x:.3f} Y{y:.3f} I{i_off:.3f} J{j_off:.3f}{set_feed(speed)}")
304 page_at = pts[-1]
305 if not trace:
306 pen(False)
307 home = (0.0, A4_H if origin_top else 0.0)
308 if return_home and page_at is not None and dist(page_at, home) > 0.05:
309 hx, hy = machine_point(home[0], home[1])
310 gcode.append(f"G1 X{hx:.3f} Y{hy:.3f}{set_feed(travel_speed)}")
311 travel.append([page_at, home])
312 travel_mm += dist(page_at, home)
313 gcode.append("G4 P0.1")
314
315 if clipped:
316 warnings.append("Een deel ligt buiten het bereik van de wagen, 200 bij 297 mm, en blijft op de rand.")
317 pen_lifts = sum(1 for line in gcode if line.startswith("G1 Z"))
318 seconds = draw_mm / draw_speed * 60 + travel_mm / travel_speed * 60 + pen_lifts * (dwell + 0.15)
319 blocked = bool(outside) and not allow_outside
320 return {
321 "draw": [[[round(x, 3), round(y, 3)] for x, y in pts] for pts in draw],
322 "travel": [[[round(x, 3), round(y, 3)] for x, y in pts] for pts in travel],
323 "gcode": "\n".join(gcode) + "\n",
324 "warnings": warnings,
325 "stats": {
326 "drawMm": round(draw_mm, 1),
327 "travelMm": round(travel_mm, 1),
328 "seconds": round(seconds, 1),
329 "outside": bool(outside),
330 "blocked": blocked,
331 "lines": len(gcode),
332 },
333 }
timdraw/geom.py added +263 −0
@@ -0,0 +1,263 @@
1 """Kleine meetkunde voor paden, arcering en G-code."""
2
3 from __future__ import annotations
4
5 import math
6
7 Point = tuple[float, float]
8 Polyline = list[Point]
9
10 A4_W = 210.0
11 A4_H = 297.0
12
13
14 def dist(a: Point, b: Point) -> float:
15 return math.hypot(a[0] - b[0], a[1] - b[1])
16
17
18 def length_of(pts: Polyline) -> float:
19 return sum(dist(a, b) for a, b in zip(pts, pts[1:]))
20
21
22 def bounds(polylines: list[Polyline]) -> tuple[float, float, float, float] | None:
23 xs: list[float] = []
24 ys: list[float] = []
25 for poly in polylines:
26 for x, y in poly:
27 xs.append(x)
28 ys.append(y)
29 if not xs:
30 return None
31 return min(xs), min(ys), max(xs), max(ys)
32
33
34 def is_closed(pts: Polyline, tol: float = 0.2) -> bool:
35 return len(pts) >= 3 and dist(pts[0], pts[-1]) <= tol
36
37
38 def dedupe(pts: Polyline, tol: float = 0.01) -> Polyline:
39 if not pts:
40 return []
41 out = [pts[0]]
42 for p in pts[1:]:
43 if dist(out[-1], p) > tol:
44 out.append(p)
45 return out
46
47
48 def _point_line_dist(p: Point, a: Point, b: Point) -> float:
49 ax, ay = a
50 bx, by = b
51 px, py = p
52 dx, dy = bx - ax, by - ay
53 span = dx * dx + dy * dy
54 if span < 1e-12:
55 return dist(p, a)
56 t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / span))
57 return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
58
59
60 def rdp(pts: Polyline, epsilon: float) -> Polyline:
61 if len(pts) < 3:
62 return list(pts)
63 end = len(pts) - 1
64 worst = 0.0
65 index = 0
66 for i in range(1, end):
67 d = _point_line_dist(pts[i], pts[0], pts[end])
68 if d > worst:
69 worst = d
70 index = i
71 if worst > epsilon:
72 left = rdp(pts[: index + 1], epsilon)
73 right = rdp(pts[index:], epsilon)
74 return left[:-1] + right
75 return [pts[0], pts[end]]
76
77
78 def transform_point(x: float, y: float, obj: dict) -> Point:
79 scale = float(obj.get("scale", 1) or 1)
80 x *= scale
81 y *= scale
82 angle = math.radians(float(obj.get("rotation", 0) or 0))
83 ca, sa = math.cos(angle), math.sin(angle)
84 xr = x * ca - y * sa
85 yr = x * sa + y * ca
86 return xr + float(obj.get("x", 0) or 0), yr + float(obj.get("y", 0) or 0)
87
88
89 def flatten_cubic(p0: Point, p1: Point, p2: Point, p3: Point, tol: float) -> Polyline:
90 out: Polyline = []
91
92 def rec(a: Point, b: Point, c: Point, d: Point, depth: int) -> None:
93 if depth > 16 or (
94 _point_line_dist(b, a, d) <= tol and _point_line_dist(c, a, d) <= tol
95 ):
96 out.append(d)
97 return
98 ab = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
99 bc = ((b[0] + c[0]) / 2, (b[1] + c[1]) / 2)
100 cd = ((c[0] + d[0]) / 2, (c[1] + d[1]) / 2)
101 abbc = ((ab[0] + bc[0]) / 2, (ab[1] + bc[1]) / 2)
102 bccd = ((bc[0] + cd[0]) / 2, (bc[1] + cd[1]) / 2)
103 mid = ((abbc[0] + bccd[0]) / 2, (abbc[1] + bccd[1]) / 2)
104 rec(a, ab, abbc, mid, depth + 1)
105 rec(mid, bccd, cd, d, depth + 1)
106
107 rec(p0, p1, p2, p3, 0)
108 return out
109
110
111 def flatten_quad(p0: Point, p1: Point, p2: Point, tol: float) -> Polyline:
112 c1 = (p0[0] + 2 / 3 * (p1[0] - p0[0]), p0[1] + 2 / 3 * (p1[1] - p0[1]))
113 c2 = (p2[0] + 2 / 3 * (p1[0] - p2[0]), p2[1] + 2 / 3 * (p1[1] - p2[1]))
114 return flatten_cubic(p0, c1, c2, p2, tol)
115
116
117 def arc_points(
118 x1: float,
119 y1: float,
120 rx: float,
121 ry: float,
122 phi_deg: float,
123 large: int,
124 sweep: int,
125 x2: float,
126 y2: float,
127 tol: float,
128 ) -> Polyline:
129 if math.hypot(x1 - x2, y1 - y2) < 1e-9:
130 return []
131 if abs(rx) < 1e-9 or abs(ry) < 1e-9:
132 return [(x2, y2)]
133 phi = math.radians(phi_deg % 360.0)
134 cos_p, sin_p = math.cos(phi), math.sin(phi)
135 rx, ry = abs(rx), abs(ry)
136 dx, dy = (x1 - x2) / 2.0, (y1 - y2) / 2.0
137 x1p = cos_p * dx + sin_p * dy
138 y1p = -sin_p * dx + cos_p * dy
139 lam = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
140 if lam > 1:
141 s = math.sqrt(lam)
142 rx *= s
143 ry *= s
144 sign = -1.0 if bool(large) == bool(sweep) else 1.0
145 num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
146 den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
147 coef = sign * math.sqrt(max(0.0, num / den)) if den > 0 else 0.0
148 cxp = coef * (rx * y1p / ry)
149 cyp = coef * (-ry * x1p / rx)
150 cx = cos_p * cxp - sin_p * cyp + (x1 + x2) / 2.0
151 cy = sin_p * cxp + cos_p * cyp + (y1 + y2) / 2.0
152 ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry
153 vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry
154 theta1 = math.atan2(uy, ux)
155 dtheta = math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
156 if sweep == 0 and dtheta > 0:
157 dtheta -= math.tau
158 elif sweep == 1 and dtheta < 0:
159 dtheta += math.tau
160 rmax = max(rx, ry, tol)
161 cos_arg = max(-1.0, min(1.0, 1.0 - tol / rmax))
162 max_step = max(0.04, 2.0 * math.acos(cos_arg))
163 n = max(1, int(math.ceil(abs(dtheta) / max_step)))
164 pts: Polyline = []
165 for i in range(1, n + 1):
166 t = theta1 + dtheta * i / n
167 ct, st = math.cos(t), math.sin(t)
168 x = cos_p * rx * ct - sin_p * ry * st + cx
169 y = sin_p * rx * ct + cos_p * ry * st + cy
170 pts.append((x, y))
171 return pts
172
173
174 def _turn(a: Point, b: Point, c: Point) -> float:
175 v1 = (b[0] - a[0], b[1] - a[1])
176 v2 = (c[0] - b[0], c[1] - b[1])
177 n1 = math.hypot(*v1)
178 n2 = math.hypot(*v2)
179 if n1 < 1e-9 or n2 < 1e-9:
180 return math.pi
181 return math.atan2(v1[0] * v2[1] - v1[1] * v2[0], v1[0] * v2[0] + v1[1] * v2[1])
182
183
184 def _circle(a: Point, b: Point, c: Point) -> tuple[float, float, float] | None:
185 ax, ay = a
186 bx, by = b
187 cx, cy = c
188 det = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
189 if abs(det) < 1e-8:
190 return None
191 a2 = ax * ax + ay * ay
192 b2 = bx * bx + by * by
193 c2 = cx * cx + cy * cy
194 ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / det
195 uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / det
196 return ux, uy, math.hypot(ax - ux, ay - uy)
197
198
199 def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float] | None:
200 """Eén cirkelboog als alle punten erop liggen. G2 is met de klok mee."""
201 if len(pts) < 3:
202 return None
203 circ = _circle(pts[0], pts[len(pts) // 2], pts[-1])
204 if circ is None:
205 return None
206 cx, cy, radius = circ
207 if radius < 0.4 or radius > 5000:
208 return None
209 for point in pts:
210 if abs(math.hypot(point[0] - cx, point[1] - cy) - radius) > tol:
211 return None
212 previous = math.atan2(pts[0][1] - cy, pts[0][0] - cx)
213 direction = 0
214 sweep = 0.0
215 for point in pts[1:]:
216 angle = math.atan2(point[1] - cy, point[0] - cx)
217 step = angle - previous
218 while step > math.pi:
219 step -= math.tau
220 while step < -math.pi:
221 step += math.tau
222 if abs(step) < 1e-6:
223 return None
224 if direction == 0:
225 direction = 1 if step > 0 else -1
226 elif step * direction < -0.02:
227 return None
228 previous += step
229 sweep += step
230 if abs(sweep) < 0.08 or abs(sweep) > 5.5:
231 return None
232 code = "G3" if sweep > 0 else "G2"
233 return code, pts[-1][0], pts[-1][1], cx - pts[0][0], cy - pts[0][1]
234
235
236 def fit_arcs(pts: Polyline, tol: float = 0.08) -> list[tuple[str, float, float, float, float]]:
237 """Vervang een kromme van korte lijntjes door G2/G3, zodat GRBL niet op elke knik afremt."""
238 moves: list[tuple[str, float, float, float, float]] = []
239 index = 0
240 last = len(pts) - 1
241 while index < last:
242 best_end = None
243 best_arc = None
244 for end in range(index + 2, min(last, index + 48) + 1):
245 if abs(_turn(pts[end - 2], pts[end - 1], pts[end])) > 0.45:
246 break
247 arc = _try_arc(pts[index : end + 1], tol)
248 if arc is None:
249 break
250 best_end = end
251 best_arc = arc
252 if best_arc is not None and best_end is not None:
253 moves.append(best_arc)
254 index = best_end
255 continue
256 end = index + 1
257 while end < last:
258 if any(_point_line_dist(pts[k], pts[index], pts[end + 1]) > tol for k in range(index + 1, end + 1)):
259 break
260 end += 1
261 moves.append(("G1", pts[end][0], pts[end][1], 0.0, 0.0))
262 index = end
263 return moves
@@ -0,0 +1,263 @@
1"""Kleine meetkunde voor paden, arcering en G-code."""
2
3from __future__ import annotations
4
5import math
6
7Point = tuple[float, float]
8Polyline = list[Point]
9
10A4_W = 210.0
11A4_H = 297.0
12
13
14def dist(a: Point, b: Point) -> float:
15 return math.hypot(a[0] - b[0], a[1] - b[1])
16
17
18def length_of(pts: Polyline) -> float:
19 return sum(dist(a, b) for a, b in zip(pts, pts[1:]))
20
21
22def bounds(polylines: list[Polyline]) -> tuple[float, float, float, float] | None:
23 xs: list[float] = []
24 ys: list[float] = []
25 for poly in polylines:
26 for x, y in poly:
27 xs.append(x)
28 ys.append(y)
29 if not xs:
30 return None
31 return min(xs), min(ys), max(xs), max(ys)
32
33
34def is_closed(pts: Polyline, tol: float = 0.2) -> bool:
35 return len(pts) >= 3 and dist(pts[0], pts[-1]) <= tol
36
37
38def dedupe(pts: Polyline, tol: float = 0.01) -> Polyline:
39 if not pts:
40 return []
41 out = [pts[0]]
42 for p in pts[1:]:
43 if dist(out[-1], p) > tol:
44 out.append(p)
45 return out
46
47
48def _point_line_dist(p: Point, a: Point, b: Point) -> float:
49 ax, ay = a
50 bx, by = b
51 px, py = p
52 dx, dy = bx - ax, by - ay
53 span = dx * dx + dy * dy
54 if span < 1e-12:
55 return dist(p, a)
56 t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / span))
57 return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
58
59
60def rdp(pts: Polyline, epsilon: float) -> Polyline:
61 if len(pts) < 3:
62 return list(pts)
63 end = len(pts) - 1
64 worst = 0.0
65 index = 0
66 for i in range(1, end):
67 d = _point_line_dist(pts[i], pts[0], pts[end])
68 if d > worst:
69 worst = d
70 index = i
71 if worst > epsilon:
72 left = rdp(pts[: index + 1], epsilon)
73 right = rdp(pts[index:], epsilon)
74 return left[:-1] + right
75 return [pts[0], pts[end]]
76
77
78def transform_point(x: float, y: float, obj: dict) -> Point:
79 scale = float(obj.get("scale", 1) or 1)
80 x *= scale
81 y *= scale
82 angle = math.radians(float(obj.get("rotation", 0) or 0))
83 ca, sa = math.cos(angle), math.sin(angle)
84 xr = x * ca - y * sa
85 yr = x * sa + y * ca
86 return xr + float(obj.get("x", 0) or 0), yr + float(obj.get("y", 0) or 0)
87
88
89def flatten_cubic(p0: Point, p1: Point, p2: Point, p3: Point, tol: float) -> Polyline:
90 out: Polyline = []
91
92 def rec(a: Point, b: Point, c: Point, d: Point, depth: int) -> None:
93 if depth > 16 or (
94 _point_line_dist(b, a, d) <= tol and _point_line_dist(c, a, d) <= tol
95 ):
96 out.append(d)
97 return
98 ab = ((a[0] + b[0]) / 2, (a[1] + b[1]) / 2)
99 bc = ((b[0] + c[0]) / 2, (b[1] + c[1]) / 2)
100 cd = ((c[0] + d[0]) / 2, (c[1] + d[1]) / 2)
101 abbc = ((ab[0] + bc[0]) / 2, (ab[1] + bc[1]) / 2)
102 bccd = ((bc[0] + cd[0]) / 2, (bc[1] + cd[1]) / 2)
103 mid = ((abbc[0] + bccd[0]) / 2, (abbc[1] + bccd[1]) / 2)
104 rec(a, ab, abbc, mid, depth + 1)
105 rec(mid, bccd, cd, d, depth + 1)
106
107 rec(p0, p1, p2, p3, 0)
108 return out
109
110
111def flatten_quad(p0: Point, p1: Point, p2: Point, tol: float) -> Polyline:
112 c1 = (p0[0] + 2 / 3 * (p1[0] - p0[0]), p0[1] + 2 / 3 * (p1[1] - p0[1]))
113 c2 = (p2[0] + 2 / 3 * (p1[0] - p2[0]), p2[1] + 2 / 3 * (p1[1] - p2[1]))
114 return flatten_cubic(p0, c1, c2, p2, tol)
115
116
117def arc_points(
118 x1: float,
119 y1: float,
120 rx: float,
121 ry: float,
122 phi_deg: float,
123 large: int,
124 sweep: int,
125 x2: float,
126 y2: float,
127 tol: float,
128) -> Polyline:
129 if math.hypot(x1 - x2, y1 - y2) < 1e-9:
130 return []
131 if abs(rx) < 1e-9 or abs(ry) < 1e-9:
132 return [(x2, y2)]
133 phi = math.radians(phi_deg % 360.0)
134 cos_p, sin_p = math.cos(phi), math.sin(phi)
135 rx, ry = abs(rx), abs(ry)
136 dx, dy = (x1 - x2) / 2.0, (y1 - y2) / 2.0
137 x1p = cos_p * dx + sin_p * dy
138 y1p = -sin_p * dx + cos_p * dy
139 lam = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry)
140 if lam > 1:
141 s = math.sqrt(lam)
142 rx *= s
143 ry *= s
144 sign = -1.0 if bool(large) == bool(sweep) else 1.0
145 num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p
146 den = rx * rx * y1p * y1p + ry * ry * x1p * x1p
147 coef = sign * math.sqrt(max(0.0, num / den)) if den > 0 else 0.0
148 cxp = coef * (rx * y1p / ry)
149 cyp = coef * (-ry * x1p / rx)
150 cx = cos_p * cxp - sin_p * cyp + (x1 + x2) / 2.0
151 cy = sin_p * cxp + cos_p * cyp + (y1 + y2) / 2.0
152 ux, uy = (x1p - cxp) / rx, (y1p - cyp) / ry
153 vx, vy = (-x1p - cxp) / rx, (-y1p - cyp) / ry
154 theta1 = math.atan2(uy, ux)
155 dtheta = math.atan2(ux * vy - uy * vx, ux * vx + uy * vy)
156 if sweep == 0 and dtheta > 0:
157 dtheta -= math.tau
158 elif sweep == 1 and dtheta < 0:
159 dtheta += math.tau
160 rmax = max(rx, ry, tol)
161 cos_arg = max(-1.0, min(1.0, 1.0 - tol / rmax))
162 max_step = max(0.04, 2.0 * math.acos(cos_arg))
163 n = max(1, int(math.ceil(abs(dtheta) / max_step)))
164 pts: Polyline = []
165 for i in range(1, n + 1):
166 t = theta1 + dtheta * i / n
167 ct, st = math.cos(t), math.sin(t)
168 x = cos_p * rx * ct - sin_p * ry * st + cx
169 y = sin_p * rx * ct + cos_p * ry * st + cy
170 pts.append((x, y))
171 return pts
172
173
174def _turn(a: Point, b: Point, c: Point) -> float:
175 v1 = (b[0] - a[0], b[1] - a[1])
176 v2 = (c[0] - b[0], c[1] - b[1])
177 n1 = math.hypot(*v1)
178 n2 = math.hypot(*v2)
179 if n1 < 1e-9 or n2 < 1e-9:
180 return math.pi
181 return math.atan2(v1[0] * v2[1] - v1[1] * v2[0], v1[0] * v2[0] + v1[1] * v2[1])
182
183
184def _circle(a: Point, b: Point, c: Point) -> tuple[float, float, float] | None:
185 ax, ay = a
186 bx, by = b
187 cx, cy = c
188 det = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
189 if abs(det) < 1e-8:
190 return None
191 a2 = ax * ax + ay * ay
192 b2 = bx * bx + by * by
193 c2 = cx * cx + cy * cy
194 ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / det
195 uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / det
196 return ux, uy, math.hypot(ax - ux, ay - uy)
197
198
199def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float] | None:
200 """Eén cirkelboog als alle punten erop liggen. G2 is met de klok mee."""
201 if len(pts) < 3:
202 return None
203 circ = _circle(pts[0], pts[len(pts) // 2], pts[-1])
204 if circ is None:
205 return None
206 cx, cy, radius = circ
207 if radius < 0.4 or radius > 5000:
208 return None
209 for point in pts:
210 if abs(math.hypot(point[0] - cx, point[1] - cy) - radius) > tol:
211 return None
212 previous = math.atan2(pts[0][1] - cy, pts[0][0] - cx)
213 direction = 0
214 sweep = 0.0
215 for point in pts[1:]:
216 angle = math.atan2(point[1] - cy, point[0] - cx)
217 step = angle - previous
218 while step > math.pi:
219 step -= math.tau
220 while step < -math.pi:
221 step += math.tau
222 if abs(step) < 1e-6:
223 return None
224 if direction == 0:
225 direction = 1 if step > 0 else -1
226 elif step * direction < -0.02:
227 return None
228 previous += step
229 sweep += step
230 if abs(sweep) < 0.08 or abs(sweep) > 5.5:
231 return None
232 code = "G3" if sweep > 0 else "G2"
233 return code, pts[-1][0], pts[-1][1], cx - pts[0][0], cy - pts[0][1]
234
235
236def fit_arcs(pts: Polyline, tol: float = 0.08) -> list[tuple[str, float, float, float, float]]:
237 """Vervang een kromme van korte lijntjes door G2/G3, zodat GRBL niet op elke knik afremt."""
238 moves: list[tuple[str, float, float, float, float]] = []
239 index = 0
240 last = len(pts) - 1
241 while index < last:
242 best_end = None
243 best_arc = None
244 for end in range(index + 2, min(last, index + 48) + 1):
245 if abs(_turn(pts[end - 2], pts[end - 1], pts[end])) > 0.45:
246 break
247 arc = _try_arc(pts[index : end + 1], tol)
248 if arc is None:
249 break
250 best_end = end
251 best_arc = arc
252 if best_arc is not None and best_end is not None:
253 moves.append(best_arc)
254 index = best_end
255 continue
256 end = index + 1
257 while end < last:
258 if any(_point_line_dist(pts[k], pts[index], pts[end + 1]) > tol for k in range(index + 1, end + 1)):
259 break
260 end += 1
261 moves.append(("G1", pts[end][0], pts[end][1], 0.0, 0.0))
262 index = end
263 return moves
timdraw/grbl.py added +625 −0
@@ -0,0 +1,625 @@
1 """Seriële GRBL 1.1-verbinding voor de Bachin TA4 (CH340, 115200)."""
2
3 from __future__ import annotations
4
5 import glob
6 import json
7 import math
8 import os
9 import threading
10 import time
11 from pathlib import Path
12
13 BED_W = 200.0
14 BED_H = 297.0
15
16 try:
17 import serial
18 from serial.serialutil import SerialException
19 except ImportError: # pragma: no cover
20 serial = None
21 SerialException = OSError
22
23
24 _STATE = Path.home() / ".config" / "timdraw" / "last-device.json"
25
26
27 def _mm(value: float) -> str:
28 rounded = round(value)
29 if abs(value - rounded) < 0.05:
30 return str(int(rounded))
31 return f"{value:.1f}"
32
33
34 def limit_step(
35 x: float, y: float, dx: float, dy: float, origin_top: bool = True
36 ) -> tuple[float, float, str | None]:
37 """Houd de stap op het blad. Linksboven: X 0..200, Y -297..0."""
38 y_min, y_max = (-BED_H, 0.0) if origin_top else (0.0, BED_H)
39 nx = min(BED_W, max(0.0, x + dx))
40 ny = min(y_max, max(y_min, y + dy))
41 adx = nx - x
42 ady = ny - y
43 requested = math.hypot(dx, dy)
44 actual = math.hypot(adx, ady)
45 if requested > 0.05 and actual + 0.05 < requested:
46 return adx, ady, f"{_mm(actual)} van {_mm(requested)} mm bewogen, daarna limiet bereikt"
47 return adx, ady, None
48
49
50 def list_ports() -> list[str]:
51 by_id = sorted(glob.glob("/dev/serial/by-id/*"))
52 if by_id:
53 return by_id
54 return sorted(glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*"))
55
56
57 def load_last_port() -> str:
58 try:
59 port = json.loads(_STATE.read_text(encoding="utf-8")).get("port") or ""
60 except (OSError, json.JSONDecodeError):
61 return ""
62 return str(port)
63
64
65 def save_last_port(port: str) -> None:
66 _STATE.parent.mkdir(parents=True, exist_ok=True)
67 _STATE.write_text(json.dumps({"port": port}), encoding="utf-8")
68
69
70 def resolve_port(preferred: str | None) -> str:
71 ports = list_ports()
72 if preferred and preferred in ports:
73 return preferred
74 if preferred:
75 try:
76 target = os.path.realpath(preferred)
77 except OSError:
78 target = ""
79 for port in ports:
80 try:
81 if os.path.realpath(port) == target:
82 return port
83 except OSError:
84 continue
85 if preferred and os.path.exists(preferred):
86 return preferred
87 return ports[0] if len(ports) == 1 and not preferred else ""
88
89
90 class Machine:
91 def __init__(self) -> None:
92 self._io = threading.Lock()
93 self._state_lock = threading.Lock()
94 self._ser = None
95 self._reader: threading.Thread | None = None
96 self._job: threading.Thread | None = None
97 self._acks: list[str] = []
98 self._ack_event = threading.Event()
99 self._stop = threading.Event()
100 self._pause = threading.Event()
101 self.connected = False
102 self.connecting = False
103 self.auto_enabled = True
104 self.last_port = load_last_port()
105 self.port = ""
106 self._connect_lock = threading.Lock()
107 self._watch_stop = threading.Event()
108 self._watcher: threading.Thread | None = None
109 self.firmware = ""
110 self.state = "disconnected"
111 self.wpos = [0.0, 0.0, 0.0]
112 self.mpos = [0.0, 0.0, 0.0]
113 self.message = "Niet verbonden"
114 self.error = ""
115 self.progress = 0.0
116 self.job_active = False
117 self.job_paused = False
118 self.max_rate = 6000.0
119 self._rx = ""
120
121 def status(self) -> dict:
122 if self.connected and self._ser is not None:
123 self._query()
124 with self._state_lock:
125 return {
126 "connected": self.connected,
127 "connecting": self.connecting,
128 "port": self.port,
129 "lastPort": self.last_port,
130 "localUrl": getattr(self, "local_url", ""),
131 "ports": list_ports(),
132 "firmware": self.firmware,
133 "state": self.state,
134 "wpos": list(self.wpos),
135 "mpos": list(self.mpos),
136 "message": self.message,
137 "error": self.error,
138 "progress": self.progress if self.job_active else None,
139 "jobActive": self.job_active,
140 "jobPaused": self.job_paused,
141 "maxRate": self.max_rate,
142 }
143
144 def start_auto(self) -> None:
145 if self._watcher and self._watcher.is_alive():
146 return
147 self._watch_stop.clear()
148 self._watcher = threading.Thread(target=self._watch_ports, daemon=True)
149 self._watcher.start()
150
151 def stop_auto(self) -> None:
152 self.auto_enabled = False
153 self._watch_stop.set()
154
155 def _watch_ports(self) -> None:
156 absent = True
157 while not self._watch_stop.wait(1.2):
158 if not self.auto_enabled or self.connected or self.connecting:
159 continue
160 if not self.last_port:
161 continue
162 port = resolve_port(self.last_port)
163 if not port:
164 absent = True
165 continue
166 if not absent:
167 continue
168 absent = False
169 try:
170 self.connect(port)
171 except Exception as exc:
172 self.connecting = False
173 self.error = str(exc)
174 self.message = str(exc)
175
176 def connect(self, port: str | None = None) -> None:
177 with self._connect_lock:
178 self._connect(port)
179
180 def _connect(self, port: str | None) -> None:
181 if serial is None:
182 raise RuntimeError("pyserial ontbreekt. Installeer het met: pip install pyserial")
183 port = resolve_port(port or self.last_port or None)
184 if (
185 self.connected
186 and self.port
187 and port
188 and os.path.realpath(self.port) == os.path.realpath(port)
189 ):
190 return
191 self.disconnect()
192 if not port:
193 raise RuntimeError("Geen seriële poort gevonden. Zit de USB-kabel erin?")
194 self.connecting = True
195 try:
196 self._open(port)
197 finally:
198 self.connecting = False
199
200 def _open(self, port: str) -> None:
201 try:
202 ser = serial.Serial()
203 ser.port = port
204 ser.baudrate = 115200
205 ser.timeout = 0.2
206 ser.dtr = False
207 ser.rts = False
208 ser.open()
209 except SerialException as exc:
210 text = str(exc)
211 if "Permission" in text or "toegang" in text.lower() or "denied" in text.lower():
212 raise RuntimeError(
213 f"Geen toegang tot {port}. De poort hoort bij groep uucp. "
214 "Eenmalig in een terminal: sudo usermod -aG uucp $USER "
215 "en daarna uitloggen en opnieuw inloggen."
216 ) from exc
217 raise RuntimeError(f"Kan {port} niet openen: {exc}") from exc
218 self._ser = ser
219 self.port = port
220 self.last_port = port
221 self.connected = True
222 self.auto_enabled = True
223 self.connecting = False
224 self.error = ""
225 self.message = "Verbinden…"
226 try:
227 save_last_port(port)
228 except OSError:
229 pass
230 self._stop.clear()
231 self._reader = threading.Thread(target=self._read_loop, daemon=True)
232 self._reader.start()
233 time.sleep(0.3)
234 self._write_raw(b"\n\n")
235 time.sleep(0.4)
236 self._query()
237 try:
238 self._command("$I", timeout=2)
239 self._command("$$", timeout=2)
240 except Exception as exc:
241 self.message = f"Verbonden, instellingen niet gelezen: {exc}"
242 try:
243 self._hold_motors()
244 except Exception as exc:
245 self.message = f"Verbonden, motoren niet vastgezet: {exc}"
246
247 def _hold_motors(self) -> None:
248 # $1=255 houdt de stappenmotoren bekrachtigd. Bij 254 vallen ze na
249 # een kwart seconde uit en trekt de veer de pen meteen weer omhoog.
250 reply = self._command("$1=255", timeout=3)
251 if reply.startswith("error"):
252 raise RuntimeError(reply)
253
254 def disconnect(self, manual: bool = False) -> None:
255 if manual:
256 self.auto_enabled = False
257 self.stop_job()
258 self.connected = False
259 self.state = "disconnected"
260 self.message = "Niet verbonden"
261 reader = self._reader
262 ser = self._ser
263 self._ser = None
264 self._reader = None
265 if ser is not None:
266 try:
267 ser.close()
268 except Exception:
269 pass
270 if reader is not None and reader.is_alive() and threading.current_thread() is not reader:
271 reader.join(timeout=1)
272
273 def _write_raw(self, data: bytes) -> None:
274 with self._io:
275 if self._ser is not None:
276 self._ser.write(data)
277
278 def _query(self) -> None:
279 if self.connected:
280 self._write_raw(b"?")
281
282 def _read_loop(self) -> None:
283 while self._ser is not None and self.connected:
284 try:
285 chunk = self._ser.read(256)
286 except Exception:
287 break
288 if not chunk:
289 continue
290 self._rx += chunk.decode("utf-8", "replace")
291 while "\n" in self._rx:
292 line, self._rx = self._rx.split("\n", 1)
293 self._handle(line.strip("\r"))
294 self.connected = False
295
296 def _handle(self, line: str) -> None:
297 if not line:
298 return
299 if line.startswith("<") and line.endswith(">"):
300 self._parse_status(line[1:-1])
301 return
302 if line == "ok" or line.startswith("error:"):
303 with self._state_lock:
304 self._acks.append(line)
305 self._ack_event.set()
306 if line.startswith("error:"):
307 self.error = line
308 return
309 if line.startswith("Grbl"):
310 with self._state_lock:
311 self.firmware = line
312 self.message = line
313 return
314 if line.startswith("ALARM") or line.startswith("ALARM:"):
315 with self._state_lock:
316 self.state = "Alarm"
317 self.error = line
318 return
319 if line.startswith("$") and "=" in line:
320 self._parse_setting(line)
321 return
322 if line.startswith("[VER:") or line.startswith("[OPT:"):
323 with self._state_lock:
324 self.firmware = (self.firmware + " " + line).strip()
325
326 def _parse_setting(self, line: str) -> None:
327 try:
328 key, value = line.split("=", 1)
329 number = float(value)
330 except ValueError:
331 return
332 if key in ("$110", "$111"):
333 self.max_rate = min(self.max_rate, number) if self.max_rate else number
334 if key == "$110":
335 self.max_rate = number
336
337 def _parse_status(self, body: str) -> None:
338 parts = body.split("|")
339 state = parts[0]
340 mpos = None
341 wpos = None
342 wco = None
343 for part in parts[1:]:
344 if part.startswith("MPos:"):
345 mpos = [float(v) for v in part[5:].split(",")[:3]]
346 elif part.startswith("WPos:"):
347 wpos = [float(v) for v in part[5:].split(",")[:3]]
348 elif part.startswith("WCO:"):
349 wco = [float(v) for v in part[4:].split(",")[:3]]
350 with self._state_lock:
351 self.state = state
352 if mpos:
353 self.mpos = mpos
354 if wpos:
355 self.wpos = wpos
356 elif mpos and wco:
357 self.wpos = [mpos[i] - wco[i] for i in range(3)]
358 if state.lower().startswith("idle") and not self.job_active:
359 self.message = "Gereed"
360
361 def _command(self, line: str, timeout: float = 15) -> str:
362 if not self.connected or self._ser is None:
363 raise RuntimeError("De machine is niet verbonden.")
364 with self._state_lock:
365 self._acks.clear()
366 self._ack_event.clear()
367 self._write_raw((line.strip() + "\n").encode())
368 deadline = time.time() + timeout
369 while time.time() < deadline:
370 with self._state_lock:
371 if self._acks:
372 return self._acks.pop(0)
373 self._ack_event.wait(0.2)
374 self._ack_event.clear()
375 raise TimeoutError(f"Geen antwoord op {line}")
376
377 def jog(self, dx: float, dy: float, feed: float, origin_top: bool = True) -> str | None:
378 dx = max(-80, min(80, dx))
379 dy = max(-80, min(80, dy))
380 feed = max(50, min(self.max_rate or 6000, feed))
381 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
382 return None
383 self._hold_motors()
384 dx, dy, notice = limit_step(self.wpos[0], self.wpos[1], dx, dy, origin_top)
385 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
386 return notice
387 parts = ["$J=G91 G21"]
388 if abs(dx) >= 1e-6:
389 parts.append(f"X{dx:.3f}")
390 if abs(dy) >= 1e-6:
391 parts.append(f"Y{dy:.3f}")
392 parts.append(f"F{feed:.0f}")
393 reply = self._command(" ".join(parts), timeout=8)
394 self._query()
395 if reply.startswith("error"):
396 raise RuntimeError(reply + " — staat de machine in alarm? Ontgrendel of home eerst.")
397 return notice
398
399 def pen(self, down: bool, up_z: float = 0, down_z: float = 5, feed: float = 5000) -> None:
400 z = down_z if down else up_z
401 z = max(0, min(12, z))
402 feed = max(50, min(self.max_rate or 6000, feed))
403 self._hold_motors()
404 self._command("G21")
405 self._command("G90")
406 reply = self._command(f"G1 Z{z:.3f} F{feed:.0f}", timeout=20)
407 self._query()
408 if reply.startswith("error"):
409 raise RuntimeError(reply)
410
411 def _sync(self, line: str, timeout: float, job: bool) -> None:
412 if job:
413 self._job_line(line, timeout)
414 return
415 reply = self._command(line, timeout=timeout)
416 if reply.startswith("error"):
417 raise RuntimeError(reply)
418
419 def _loosen(self, job: bool) -> None:
420 self._sync("G21", 5, job)
421 self._sync("G91", 5, job)
422 self._sync("$1=0", 5, job)
423 self._sync("G1 X0.050 F500", 15, job)
424 self._wait_until_idle(20)
425 self._sync("G90", 5, job)
426
427 def release_axes(self) -> None:
428 self._stop.clear()
429 try:
430 self._loosen(False)
431 except Exception:
432 try:
433 self._sync("G90", 5, False)
434 except Exception:
435 pass
436 raise
437 self._query()
438
439 def _prepare_home(self, job: bool) -> None:
440 """Laat de assen los zodat de veer de pen optilt, wacht een seconde, en home dan."""
441 try:
442 self._loosen(job)
443 deadline = time.time() + 1.0
444 while time.time() < deadline:
445 if job and self._stop.is_set():
446 break
447 time.sleep(0.05)
448 self._sync("$1=255", 5, job)
449 if job and self._stop.is_set():
450 return
451 self._sync("$H", 120, job)
452 self._sync("G92 X0 Y0", 5, job)
453 except Exception:
454 try:
455 self._sync("G90", 5, job)
456 self._sync("$1=255", 5, job)
457 except Exception:
458 pass
459 raise
460
461 def home(self) -> None:
462 self._stop.clear()
463 self._prepare_home(False)
464 self._query()
465
466 def unlock(self) -> None:
467 reply = self._command("$X", timeout=5)
468 self._query()
469 if reply.startswith("error"):
470 raise RuntimeError(reply)
471
472 def start_job(self, gcode: str) -> None:
473 if self.job_active:
474 raise RuntimeError("Er loopt al een tekening.")
475 lines = []
476 for raw in gcode.splitlines():
477 line = raw.split(";", 1)[0].strip()
478 if line:
479 lines.append(line)
480 if not lines:
481 raise RuntimeError("Er is niets om te tekenen.")
482 self._pause.clear()
483 self._stop.clear()
484 with self._state_lock:
485 self._acks.clear()
486 self._ack_event.clear()
487 self.job_active = True
488 self.job_paused = False
489 self.progress = 0
490 self.error = ""
491 self.message = "Tekenen…"
492 self._job = threading.Thread(target=self._run_job, args=(lines,), daemon=True)
493 self._job.start()
494
495 def pause_job(self) -> None:
496 if not self.job_active:
497 return
498 self._pause.set()
499 self.job_paused = True
500 self._write_raw(b"!")
501 self.message = "Pauze"
502
503 def resume_job(self) -> None:
504 if not self.job_active:
505 return
506 self._pause.clear()
507 self.job_paused = False
508 self._write_raw(b"~")
509 self.message = "Tekenen…"
510
511 def stop_job(self) -> None:
512 self._stop.set()
513 self._pause.clear()
514 if self._ser is not None and (self.job_active or self.state.lower().startswith("run") or self.state.lower().startswith("hold")):
515 self._write_raw(b"!")
516 time.sleep(0.15)
517 self._write_raw(b"\x18")
518 self.job_active = False
519 self.job_paused = False
520 self.progress = 0
521 if self.connected:
522 self.message = "Gestopt"
523
524 def _run_job(self, lines: list[str]) -> None:
525 used = 0
526 pending: list[int] = []
527 sent = 0
528 try:
529 if not self._stop.is_set():
530 self.message = "Homen…"
531 self._prepare_home(True)
532 for line in lines:
533 while self._pause.is_set() and not self._stop.is_set():
534 time.sleep(0.05)
535 if self._stop.is_set():
536 break
537 if line.startswith("$"):
538 while pending and not self._stop.is_set():
539 ack = self._wait_ack(60)
540 used -= pending.pop(0)
541 if ack.startswith("error"):
542 raise RuntimeError(ack)
543 self._wait_until_idle(60)
544 if self._stop.is_set():
545 break
546 self._job_line(line, 5)
547 sent += 1
548 self.progress = sent / len(lines)
549 continue
550 size = len(line) + 1
551 while used + size > 110 and not self._stop.is_set():
552 ack = self._wait_ack(30)
553 if pending:
554 used -= pending.pop(0)
555 if ack.startswith("error"):
556 raise RuntimeError(ack)
557 if self._stop.is_set():
558 break
559 self._write_raw((line + "\n").encode())
560 pending.append(size)
561 used += size
562 sent += 1
563 self.progress = sent / len(lines)
564 while pending and not self._stop.is_set():
565 ack = self._wait_ack(60)
566 pending.pop(0)
567 if ack.startswith("error"):
568 raise RuntimeError(ack)
569 if not self._stop.is_set():
570 self.progress = 1
571 self.message = "Homen…"
572 self._prepare_home(True)
573 if not self._stop.is_set():
574 self.message = "Klaar"
575 except Exception as exc:
576 self.error = str(exc)
577 self.message = str(exc)
578 self._write_raw(b"!")
579 finally:
580 self.job_active = False
581 self.job_paused = False
582 self._query()
583
584 def _job_line(self, line: str, timeout: float) -> None:
585 while self._pause.is_set() and not self._stop.is_set():
586 time.sleep(0.05)
587 if self._stop.is_set():
588 return
589 self._write_raw((line + "\n").encode())
590 ack = self._wait_ack(timeout)
591 if ack.startswith("error"):
592 raise RuntimeError(ack)
593
594 def _wait_until_idle(self, timeout: float) -> None:
595 deadline = time.time() + timeout
596 seen_busy = False
597 idle_since = None
598 while time.time() < deadline:
599 if self._stop.is_set():
600 return
601 self._query()
602 time.sleep(0.05)
603 state = self.state.lower()
604 if state.startswith("alarm"):
605 raise RuntimeError(self.error or "Alarm")
606 if state.startswith(("run", "hold", "jog", "home", "door")):
607 seen_busy = True
608 idle_since = None
609 continue
610 if state.startswith("idle"):
611 if seen_busy or (idle_since is not None and time.time() - idle_since > 0.15):
612 return
613 if idle_since is None:
614 idle_since = time.time()
615 raise TimeoutError("De machine bleef bezig.")
616
617 def _wait_ack(self, timeout: float) -> str:
618 deadline = time.time() + timeout
619 while time.time() < deadline:
620 with self._state_lock:
621 if self._acks:
622 return self._acks.pop(0)
623 self._ack_event.wait(0.2)
624 self._ack_event.clear()
625 raise TimeoutError("De machine antwoordt niet meer.")
@@ -0,0 +1,625 @@
1"""Seriële GRBL 1.1-verbinding voor de Bachin TA4 (CH340, 115200)."""
2
3from __future__ import annotations
4
5import glob
6import json
7import math
8import os
9import threading
10import time
11from pathlib import Path
12
13BED_W = 200.0
14BED_H = 297.0
15
16try:
17 import serial
18 from serial.serialutil import SerialException
19except ImportError: # pragma: no cover
20 serial = None
21 SerialException = OSError
22
23
24_STATE = Path.home() / ".config" / "timdraw" / "last-device.json"
25
26
27def _mm(value: float) -> str:
28 rounded = round(value)
29 if abs(value - rounded) < 0.05:
30 return str(int(rounded))
31 return f"{value:.1f}"
32
33
34def limit_step(
35 x: float, y: float, dx: float, dy: float, origin_top: bool = True
36) -> tuple[float, float, str | None]:
37 """Houd de stap op het blad. Linksboven: X 0..200, Y -297..0."""
38 y_min, y_max = (-BED_H, 0.0) if origin_top else (0.0, BED_H)
39 nx = min(BED_W, max(0.0, x + dx))
40 ny = min(y_max, max(y_min, y + dy))
41 adx = nx - x
42 ady = ny - y
43 requested = math.hypot(dx, dy)
44 actual = math.hypot(adx, ady)
45 if requested > 0.05 and actual + 0.05 < requested:
46 return adx, ady, f"{_mm(actual)} van {_mm(requested)} mm bewogen, daarna limiet bereikt"
47 return adx, ady, None
48
49
50def list_ports() -> list[str]:
51 by_id = sorted(glob.glob("/dev/serial/by-id/*"))
52 if by_id:
53 return by_id
54 return sorted(glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*"))
55
56
57def load_last_port() -> str:
58 try:
59 port = json.loads(_STATE.read_text(encoding="utf-8")).get("port") or ""
60 except (OSError, json.JSONDecodeError):
61 return ""
62 return str(port)
63
64
65def save_last_port(port: str) -> None:
66 _STATE.parent.mkdir(parents=True, exist_ok=True)
67 _STATE.write_text(json.dumps({"port": port}), encoding="utf-8")
68
69
70def resolve_port(preferred: str | None) -> str:
71 ports = list_ports()
72 if preferred and preferred in ports:
73 return preferred
74 if preferred:
75 try:
76 target = os.path.realpath(preferred)
77 except OSError:
78 target = ""
79 for port in ports:
80 try:
81 if os.path.realpath(port) == target:
82 return port
83 except OSError:
84 continue
85 if preferred and os.path.exists(preferred):
86 return preferred
87 return ports[0] if len(ports) == 1 and not preferred else ""
88
89
90class Machine:
91 def __init__(self) -> None:
92 self._io = threading.Lock()
93 self._state_lock = threading.Lock()
94 self._ser = None
95 self._reader: threading.Thread | None = None
96 self._job: threading.Thread | None = None
97 self._acks: list[str] = []
98 self._ack_event = threading.Event()
99 self._stop = threading.Event()
100 self._pause = threading.Event()
101 self.connected = False
102 self.connecting = False
103 self.auto_enabled = True
104 self.last_port = load_last_port()
105 self.port = ""
106 self._connect_lock = threading.Lock()
107 self._watch_stop = threading.Event()
108 self._watcher: threading.Thread | None = None
109 self.firmware = ""
110 self.state = "disconnected"
111 self.wpos = [0.0, 0.0, 0.0]
112 self.mpos = [0.0, 0.0, 0.0]
113 self.message = "Niet verbonden"
114 self.error = ""
115 self.progress = 0.0
116 self.job_active = False
117 self.job_paused = False
118 self.max_rate = 6000.0
119 self._rx = ""
120
121 def status(self) -> dict:
122 if self.connected and self._ser is not None:
123 self._query()
124 with self._state_lock:
125 return {
126 "connected": self.connected,
127 "connecting": self.connecting,
128 "port": self.port,
129 "lastPort": self.last_port,
130 "localUrl": getattr(self, "local_url", ""),
131 "ports": list_ports(),
132 "firmware": self.firmware,
133 "state": self.state,
134 "wpos": list(self.wpos),
135 "mpos": list(self.mpos),
136 "message": self.message,
137 "error": self.error,
138 "progress": self.progress if self.job_active else None,
139 "jobActive": self.job_active,
140 "jobPaused": self.job_paused,
141 "maxRate": self.max_rate,
142 }
143
144 def start_auto(self) -> None:
145 if self._watcher and self._watcher.is_alive():
146 return
147 self._watch_stop.clear()
148 self._watcher = threading.Thread(target=self._watch_ports, daemon=True)
149 self._watcher.start()
150
151 def stop_auto(self) -> None:
152 self.auto_enabled = False
153 self._watch_stop.set()
154
155 def _watch_ports(self) -> None:
156 absent = True
157 while not self._watch_stop.wait(1.2):
158 if not self.auto_enabled or self.connected or self.connecting:
159 continue
160 if not self.last_port:
161 continue
162 port = resolve_port(self.last_port)
163 if not port:
164 absent = True
165 continue
166 if not absent:
167 continue
168 absent = False
169 try:
170 self.connect(port)
171 except Exception as exc:
172 self.connecting = False
173 self.error = str(exc)
174 self.message = str(exc)
175
176 def connect(self, port: str | None = None) -> None:
177 with self._connect_lock:
178 self._connect(port)
179
180 def _connect(self, port: str | None) -> None:
181 if serial is None:
182 raise RuntimeError("pyserial ontbreekt. Installeer het met: pip install pyserial")
183 port = resolve_port(port or self.last_port or None)
184 if (
185 self.connected
186 and self.port
187 and port
188 and os.path.realpath(self.port) == os.path.realpath(port)
189 ):
190 return
191 self.disconnect()
192 if not port:
193 raise RuntimeError("Geen seriële poort gevonden. Zit de USB-kabel erin?")
194 self.connecting = True
195 try:
196 self._open(port)
197 finally:
198 self.connecting = False
199
200 def _open(self, port: str) -> None:
201 try:
202 ser = serial.Serial()
203 ser.port = port
204 ser.baudrate = 115200
205 ser.timeout = 0.2
206 ser.dtr = False
207 ser.rts = False
208 ser.open()
209 except SerialException as exc:
210 text = str(exc)
211 if "Permission" in text or "toegang" in text.lower() or "denied" in text.lower():
212 raise RuntimeError(
213 f"Geen toegang tot {port}. De poort hoort bij groep uucp. "
214 "Eenmalig in een terminal: sudo usermod -aG uucp $USER "
215 "en daarna uitloggen en opnieuw inloggen."
216 ) from exc
217 raise RuntimeError(f"Kan {port} niet openen: {exc}") from exc
218 self._ser = ser
219 self.port = port
220 self.last_port = port
221 self.connected = True
222 self.auto_enabled = True
223 self.connecting = False
224 self.error = ""
225 self.message = "Verbinden…"
226 try:
227 save_last_port(port)
228 except OSError:
229 pass
230 self._stop.clear()
231 self._reader = threading.Thread(target=self._read_loop, daemon=True)
232 self._reader.start()
233 time.sleep(0.3)
234 self._write_raw(b"\n\n")
235 time.sleep(0.4)
236 self._query()
237 try:
238 self._command("$I", timeout=2)
239 self._command("$$", timeout=2)
240 except Exception as exc:
241 self.message = f"Verbonden, instellingen niet gelezen: {exc}"
242 try:
243 self._hold_motors()
244 except Exception as exc:
245 self.message = f"Verbonden, motoren niet vastgezet: {exc}"
246
247 def _hold_motors(self) -> None:
248 # $1=255 houdt de stappenmotoren bekrachtigd. Bij 254 vallen ze na
249 # een kwart seconde uit en trekt de veer de pen meteen weer omhoog.
250 reply = self._command("$1=255", timeout=3)
251 if reply.startswith("error"):
252 raise RuntimeError(reply)
253
254 def disconnect(self, manual: bool = False) -> None:
255 if manual:
256 self.auto_enabled = False
257 self.stop_job()
258 self.connected = False
259 self.state = "disconnected"
260 self.message = "Niet verbonden"
261 reader = self._reader
262 ser = self._ser
263 self._ser = None
264 self._reader = None
265 if ser is not None:
266 try:
267 ser.close()
268 except Exception:
269 pass
270 if reader is not None and reader.is_alive() and threading.current_thread() is not reader:
271 reader.join(timeout=1)
272
273 def _write_raw(self, data: bytes) -> None:
274 with self._io:
275 if self._ser is not None:
276 self._ser.write(data)
277
278 def _query(self) -> None:
279 if self.connected:
280 self._write_raw(b"?")
281
282 def _read_loop(self) -> None:
283 while self._ser is not None and self.connected:
284 try:
285 chunk = self._ser.read(256)
286 except Exception:
287 break
288 if not chunk:
289 continue
290 self._rx += chunk.decode("utf-8", "replace")
291 while "\n" in self._rx:
292 line, self._rx = self._rx.split("\n", 1)
293 self._handle(line.strip("\r"))
294 self.connected = False
295
296 def _handle(self, line: str) -> None:
297 if not line:
298 return
299 if line.startswith("<") and line.endswith(">"):
300 self._parse_status(line[1:-1])
301 return
302 if line == "ok" or line.startswith("error:"):
303 with self._state_lock:
304 self._acks.append(line)
305 self._ack_event.set()
306 if line.startswith("error:"):
307 self.error = line
308 return
309 if line.startswith("Grbl"):
310 with self._state_lock:
311 self.firmware = line
312 self.message = line
313 return
314 if line.startswith("ALARM") or line.startswith("ALARM:"):
315 with self._state_lock:
316 self.state = "Alarm"
317 self.error = line
318 return
319 if line.startswith("$") and "=" in line:
320 self._parse_setting(line)
321 return
322 if line.startswith("[VER:") or line.startswith("[OPT:"):
323 with self._state_lock:
324 self.firmware = (self.firmware + " " + line).strip()
325
326 def _parse_setting(self, line: str) -> None:
327 try:
328 key, value = line.split("=", 1)
329 number = float(value)
330 except ValueError:
331 return
332 if key in ("$110", "$111"):
333 self.max_rate = min(self.max_rate, number) if self.max_rate else number
334 if key == "$110":
335 self.max_rate = number
336
337 def _parse_status(self, body: str) -> None:
338 parts = body.split("|")
339 state = parts[0]
340 mpos = None
341 wpos = None
342 wco = None
343 for part in parts[1:]:
344 if part.startswith("MPos:"):
345 mpos = [float(v) for v in part[5:].split(",")[:3]]
346 elif part.startswith("WPos:"):
347 wpos = [float(v) for v in part[5:].split(",")[:3]]
348 elif part.startswith("WCO:"):
349 wco = [float(v) for v in part[4:].split(",")[:3]]
350 with self._state_lock:
351 self.state = state
352 if mpos:
353 self.mpos = mpos
354 if wpos:
355 self.wpos = wpos
356 elif mpos and wco:
357 self.wpos = [mpos[i] - wco[i] for i in range(3)]
358 if state.lower().startswith("idle") and not self.job_active:
359 self.message = "Gereed"
360
361 def _command(self, line: str, timeout: float = 15) -> str:
362 if not self.connected or self._ser is None:
363 raise RuntimeError("De machine is niet verbonden.")
364 with self._state_lock:
365 self._acks.clear()
366 self._ack_event.clear()
367 self._write_raw((line.strip() + "\n").encode())
368 deadline = time.time() + timeout
369 while time.time() < deadline:
370 with self._state_lock:
371 if self._acks:
372 return self._acks.pop(0)
373 self._ack_event.wait(0.2)
374 self._ack_event.clear()
375 raise TimeoutError(f"Geen antwoord op {line}")
376
377 def jog(self, dx: float, dy: float, feed: float, origin_top: bool = True) -> str | None:
378 dx = max(-80, min(80, dx))
379 dy = max(-80, min(80, dy))
380 feed = max(50, min(self.max_rate or 6000, feed))
381 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
382 return None
383 self._hold_motors()
384 dx, dy, notice = limit_step(self.wpos[0], self.wpos[1], dx, dy, origin_top)
385 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
386 return notice
387 parts = ["$J=G91 G21"]
388 if abs(dx) >= 1e-6:
389 parts.append(f"X{dx:.3f}")
390 if abs(dy) >= 1e-6:
391 parts.append(f"Y{dy:.3f}")
392 parts.append(f"F{feed:.0f}")
393 reply = self._command(" ".join(parts), timeout=8)
394 self._query()
395 if reply.startswith("error"):
396 raise RuntimeError(reply + " — staat de machine in alarm? Ontgrendel of home eerst.")
397 return notice
398
399 def pen(self, down: bool, up_z: float = 0, down_z: float = 5, feed: float = 5000) -> None:
400 z = down_z if down else up_z
401 z = max(0, min(12, z))
402 feed = max(50, min(self.max_rate or 6000, feed))
403 self._hold_motors()
404 self._command("G21")
405 self._command("G90")
406 reply = self._command(f"G1 Z{z:.3f} F{feed:.0f}", timeout=20)
407 self._query()
408 if reply.startswith("error"):
409 raise RuntimeError(reply)
410
411 def _sync(self, line: str, timeout: float, job: bool) -> None:
412 if job:
413 self._job_line(line, timeout)
414 return
415 reply = self._command(line, timeout=timeout)
416 if reply.startswith("error"):
417 raise RuntimeError(reply)
418
419 def _loosen(self, job: bool) -> None:
420 self._sync("G21", 5, job)
421 self._sync("G91", 5, job)
422 self._sync("$1=0", 5, job)
423 self._sync("G1 X0.050 F500", 15, job)
424 self._wait_until_idle(20)
425 self._sync("G90", 5, job)
426
427 def release_axes(self) -> None:
428 self._stop.clear()
429 try:
430 self._loosen(False)
431 except Exception:
432 try:
433 self._sync("G90", 5, False)
434 except Exception:
435 pass
436 raise
437 self._query()
438
439 def _prepare_home(self, job: bool) -> None:
440 """Laat de assen los zodat de veer de pen optilt, wacht een seconde, en home dan."""
441 try:
442 self._loosen(job)
443 deadline = time.time() + 1.0
444 while time.time() < deadline:
445 if job and self._stop.is_set():
446 break
447 time.sleep(0.05)
448 self._sync("$1=255", 5, job)
449 if job and self._stop.is_set():
450 return
451 self._sync("$H", 120, job)
452 self._sync("G92 X0 Y0", 5, job)
453 except Exception:
454 try:
455 self._sync("G90", 5, job)
456 self._sync("$1=255", 5, job)
457 except Exception:
458 pass
459 raise
460
461 def home(self) -> None:
462 self._stop.clear()
463 self._prepare_home(False)
464 self._query()
465
466 def unlock(self) -> None:
467 reply = self._command("$X", timeout=5)
468 self._query()
469 if reply.startswith("error"):
470 raise RuntimeError(reply)
471
472 def start_job(self, gcode: str) -> None:
473 if self.job_active:
474 raise RuntimeError("Er loopt al een tekening.")
475 lines = []
476 for raw in gcode.splitlines():
477 line = raw.split(";", 1)[0].strip()
478 if line:
479 lines.append(line)
480 if not lines:
481 raise RuntimeError("Er is niets om te tekenen.")
482 self._pause.clear()
483 self._stop.clear()
484 with self._state_lock:
485 self._acks.clear()
486 self._ack_event.clear()
487 self.job_active = True
488 self.job_paused = False
489 self.progress = 0
490 self.error = ""
491 self.message = "Tekenen…"
492 self._job = threading.Thread(target=self._run_job, args=(lines,), daemon=True)
493 self._job.start()
494
495 def pause_job(self) -> None:
496 if not self.job_active:
497 return
498 self._pause.set()
499 self.job_paused = True
500 self._write_raw(b"!")
501 self.message = "Pauze"
502
503 def resume_job(self) -> None:
504 if not self.job_active:
505 return
506 self._pause.clear()
507 self.job_paused = False
508 self._write_raw(b"~")
509 self.message = "Tekenen…"
510
511 def stop_job(self) -> None:
512 self._stop.set()
513 self._pause.clear()
514 if self._ser is not None and (self.job_active or self.state.lower().startswith("run") or self.state.lower().startswith("hold")):
515 self._write_raw(b"!")
516 time.sleep(0.15)
517 self._write_raw(b"\x18")
518 self.job_active = False
519 self.job_paused = False
520 self.progress = 0
521 if self.connected:
522 self.message = "Gestopt"
523
524 def _run_job(self, lines: list[str]) -> None:
525 used = 0
526 pending: list[int] = []
527 sent = 0
528 try:
529 if not self._stop.is_set():
530 self.message = "Homen…"
531 self._prepare_home(True)
532 for line in lines:
533 while self._pause.is_set() and not self._stop.is_set():
534 time.sleep(0.05)
535 if self._stop.is_set():
536 break
537 if line.startswith("$"):
538 while pending and not self._stop.is_set():
539 ack = self._wait_ack(60)
540 used -= pending.pop(0)
541 if ack.startswith("error"):
542 raise RuntimeError(ack)
543 self._wait_until_idle(60)
544 if self._stop.is_set():
545 break
546 self._job_line(line, 5)
547 sent += 1
548 self.progress = sent / len(lines)
549 continue
550 size = len(line) + 1
551 while used + size > 110 and not self._stop.is_set():
552 ack = self._wait_ack(30)
553 if pending:
554 used -= pending.pop(0)
555 if ack.startswith("error"):
556 raise RuntimeError(ack)
557 if self._stop.is_set():
558 break
559 self._write_raw((line + "\n").encode())
560 pending.append(size)
561 used += size
562 sent += 1
563 self.progress = sent / len(lines)
564 while pending and not self._stop.is_set():
565 ack = self._wait_ack(60)
566 pending.pop(0)
567 if ack.startswith("error"):
568 raise RuntimeError(ack)
569 if not self._stop.is_set():
570 self.progress = 1
571 self.message = "Homen…"
572 self._prepare_home(True)
573 if not self._stop.is_set():
574 self.message = "Klaar"
575 except Exception as exc:
576 self.error = str(exc)
577 self.message = str(exc)
578 self._write_raw(b"!")
579 finally:
580 self.job_active = False
581 self.job_paused = False
582 self._query()
583
584 def _job_line(self, line: str, timeout: float) -> None:
585 while self._pause.is_set() and not self._stop.is_set():
586 time.sleep(0.05)
587 if self._stop.is_set():
588 return
589 self._write_raw((line + "\n").encode())
590 ack = self._wait_ack(timeout)
591 if ack.startswith("error"):
592 raise RuntimeError(ack)
593
594 def _wait_until_idle(self, timeout: float) -> None:
595 deadline = time.time() + timeout
596 seen_busy = False
597 idle_since = None
598 while time.time() < deadline:
599 if self._stop.is_set():
600 return
601 self._query()
602 time.sleep(0.05)
603 state = self.state.lower()
604 if state.startswith("alarm"):
605 raise RuntimeError(self.error or "Alarm")
606 if state.startswith(("run", "hold", "jog", "home", "door")):
607 seen_busy = True
608 idle_since = None
609 continue
610 if state.startswith("idle"):
611 if seen_busy or (idle_since is not None and time.time() - idle_since > 0.15):
612 return
613 if idle_since is None:
614 idle_since = time.time()
615 raise TimeoutError("De machine bleef bezig.")
616
617 def _wait_ack(self, timeout: float) -> str:
618 deadline = time.time() + timeout
619 while time.time() < deadline:
620 with self._state_lock:
621 if self._acks:
622 return self._acks.pop(0)
623 self._ack_event.wait(0.2)
624 self._ack_event.clear()
625 raise TimeoutError("De machine antwoordt niet meer.")
timdraw/hatch.py added +103 −0
@@ -0,0 +1,103 @@
1 """Arcering: even-odd of nonzero, optioneel crosshatch en grijstinten."""
2
3 from __future__ import annotations
4
5 import math
6
7 from timdraw.geom import Point, Polyline
8
9
10 def _rotate(x: float, y: float, ca: float, sa: float) -> Point:
11 return x * ca - y * sa, x * sa + y * ca
12
13
14 def _segments_at(rings: list[Polyline], y: float, rule: str) -> list[tuple[float, float]]:
15 events: list[tuple[float, int]] = []
16 for ring in rings:
17 count = len(ring)
18 if count < 3:
19 continue
20 for i in range(count):
21 x1, y1 = ring[i]
22 x2, y2 = ring[(i + 1) % count]
23 if y1 == y2:
24 continue
25 if y1 < y2:
26 if not (y1 <= y < y2):
27 continue
28 winding = 1
29 else:
30 if not (y2 <= y < y1):
31 continue
32 winding = -1
33 t = (y - y1) / (y2 - y1)
34 events.append((x1 + t * (x2 - x1), winding))
35 events.sort(key=lambda item: item[0])
36 pairs: list[tuple[float, float]] = []
37 winding = 0
38 parity = 0
39 start: float | None = None
40
41 def inside() -> bool:
42 if rule == "nonzero":
43 return winding != 0
44 return parity % 2 == 1
45
46 for x, delta in events:
47 before = inside()
48 winding += delta
49 parity ^= 1
50 after = inside()
51 if not before and after:
52 start = x
53 elif before and not after and start is not None:
54 if x - start > 0.12:
55 pairs.append((start, x))
56 start = None
57 return pairs
58
59
60 def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd") -> list[Polyline]:
61 spacing = max(0.3, float(spacing))
62 cleaned: list[Polyline] = []
63 for ring in rings:
64 if len(ring) >= 3:
65 pts = list(ring)
66 if pts[0] != pts[-1]:
67 pts = pts + [pts[0]]
68 cleaned.append(pts)
69 if not cleaned:
70 return []
71 angle = math.radians(angle_deg)
72 ca, sa = math.cos(-angle), math.sin(-angle)
73 rotated = [[_rotate(x, y, ca, sa) for x, y in ring] for ring in cleaned]
74 ys = [y for ring in rotated for _, y in ring]
75 y0, y1 = min(ys), max(ys)
76 if y1 - y0 < spacing * 0.5:
77 return []
78 uca, usa = math.cos(angle), math.sin(angle)
79 rows: list[list[tuple[Point, Point]]] = []
80 y = y0 + spacing * 0.5
81 while y < y1 - 1e-6:
82 row = []
83 for x0, x1 in _segments_at(rotated, y, rule):
84 a = _rotate(x0, y, uca, usa)
85 b = _rotate(x1, y, uca, usa)
86 row.append((a, b))
87 if row:
88 rows.append(row)
89 y += spacing
90 lines: list[Polyline] = []
91 for index, row in enumerate(rows):
92 ordered = row
93 if index % 2 == 1:
94 ordered = [(b, a) for a, b in reversed(row)]
95 for a, b in ordered:
96 lines.append([a, b])
97 return lines
98
99
100 def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:
101 steps = max(2, min(16, int(steps)))
102 t = round(max(0.0, min(1.0, gray)) * (steps - 1)) / (steps - 1)
103 return dark + t * (light - dark)
@@ -0,0 +1,103 @@
1"""Arcering: even-odd of nonzero, optioneel crosshatch en grijstinten."""
2
3from __future__ import annotations
4
5import math
6
7from timdraw.geom import Point, Polyline
8
9
10def _rotate(x: float, y: float, ca: float, sa: float) -> Point:
11 return x * ca - y * sa, x * sa + y * ca
12
13
14def _segments_at(rings: list[Polyline], y: float, rule: str) -> list[tuple[float, float]]:
15 events: list[tuple[float, int]] = []
16 for ring in rings:
17 count = len(ring)
18 if count < 3:
19 continue
20 for i in range(count):
21 x1, y1 = ring[i]
22 x2, y2 = ring[(i + 1) % count]
23 if y1 == y2:
24 continue
25 if y1 < y2:
26 if not (y1 <= y < y2):
27 continue
28 winding = 1
29 else:
30 if not (y2 <= y < y1):
31 continue
32 winding = -1
33 t = (y - y1) / (y2 - y1)
34 events.append((x1 + t * (x2 - x1), winding))
35 events.sort(key=lambda item: item[0])
36 pairs: list[tuple[float, float]] = []
37 winding = 0
38 parity = 0
39 start: float | None = None
40
41 def inside() -> bool:
42 if rule == "nonzero":
43 return winding != 0
44 return parity % 2 == 1
45
46 for x, delta in events:
47 before = inside()
48 winding += delta
49 parity ^= 1
50 after = inside()
51 if not before and after:
52 start = x
53 elif before and not after and start is not None:
54 if x - start > 0.12:
55 pairs.append((start, x))
56 start = None
57 return pairs
58
59
60def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd") -> list[Polyline]:
61 spacing = max(0.3, float(spacing))
62 cleaned: list[Polyline] = []
63 for ring in rings:
64 if len(ring) >= 3:
65 pts = list(ring)
66 if pts[0] != pts[-1]:
67 pts = pts + [pts[0]]
68 cleaned.append(pts)
69 if not cleaned:
70 return []
71 angle = math.radians(angle_deg)
72 ca, sa = math.cos(-angle), math.sin(-angle)
73 rotated = [[_rotate(x, y, ca, sa) for x, y in ring] for ring in cleaned]
74 ys = [y for ring in rotated for _, y in ring]
75 y0, y1 = min(ys), max(ys)
76 if y1 - y0 < spacing * 0.5:
77 return []
78 uca, usa = math.cos(angle), math.sin(angle)
79 rows: list[list[tuple[Point, Point]]] = []
80 y = y0 + spacing * 0.5
81 while y < y1 - 1e-6:
82 row = []
83 for x0, x1 in _segments_at(rotated, y, rule):
84 a = _rotate(x0, y, uca, usa)
85 b = _rotate(x1, y, uca, usa)
86 row.append((a, b))
87 if row:
88 rows.append(row)
89 y += spacing
90 lines: list[Polyline] = []
91 for index, row in enumerate(rows):
92 ordered = row
93 if index % 2 == 1:
94 ordered = [(b, a) for a, b in reversed(row)]
95 for a, b in ordered:
96 lines.append([a, b])
97 return lines
98
99
100def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:
101 steps = max(2, min(16, int(steps)))
102 t = round(max(0.0, min(1.0, gray)) * (steps - 1)) / (steps - 1)
103 return dark + t * (light - dark)
timdraw/hershey.json added +1 −0
@@ -0,0 +1 @@
1 {"futural":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":5,"p":[[[0,-12],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-8,"r":8,"p":[[[-4,-12],[-4,-5]],[[4,-12],[4,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":10,"p":[[[-2,-16],[-2,13]],[[2,-16],[2,13]],[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-3],[10,-4],[9,-5],[8,-5],[7,-4],[6,-2],[4,3],[2,6],[0,8],[-2,9],[-6,9],[-8,8],[-9,7],[-10,5],[-10,3],[-9,1],[-8,0],[-1,-4],[0,-5],[1,-7],[1,-9],[0,-11],[-2,-12],[-4,-11],[-5,-9],[-5,-7],[-4,-4],[-2,-1],[3,6],[5,8],[7,9],[9,9],[10,8],[10,7]]]},{"l":-5,"r":5,"p":[[[0,-10],[-1,-11],[0,-12],[1,-11],[1,-9],[0,-7],[-1,-6]]]},{"l":-7,"r":7,"p":[[[4,-16],[2,-14],[0,-11],[-2,-7],[-3,-2],[-3,2],[-2,7],[0,11],[2,14],[4,16]]]},{"l":-7,"r":7,"p":[[[-4,-16],[-2,-14],[0,-11],[2,-7],[3,-2],[3,2],[2,7],[0,11],[-2,14],[-4,16]]]},{"l":-8,"r":8,"p":[[[0,-6],[0,6]],[[-5,-3],[5,3]],[[5,-3],[-5,3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-4,"r":4,"p":[[[1,5],[0,6],[-1,5],[0,4],[1,5],[1,7],[-1,9]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-4,"r":4,"p":[[[0,4],[-1,5],[0,6],[1,5],[0,4]]]},{"l":-11,"r":11,"p":[[[9,-16],[-9,16]]]},{"l":-10,"r":10,"p":[[[-1,-12],[-4,-11],[-6,-8],[-7,-3],[-7,0],[-6,5],[-4,8],[-1,9],[1,9],[4,8],[6,5],[7,0],[7,-3],[6,-8],[4,-11],[1,-12],[-1,-12]]]},{"l":-10,"r":10,"p":[[[-4,-8],[-2,-9],[1,-12],[1,9]]]},{"l":-10,"r":10,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[3,-1],[-7,9],[7,9]]]},{"l":-10,"r":10,"p":[[[-5,-12],[6,-12],[0,-4],[3,-4],[5,-3],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[3,-12],[-7,2],[8,2]],[[3,-12],[3,9]]]},{"l":-10,"r":10,"p":[[[5,-12],[-5,-12],[-6,-3],[-5,-4],[-2,-5],[1,-5],[4,-4],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[6,-9],[5,-11],[2,-12],[0,-12],[-3,-11],[-5,-8],[-6,-3],[-6,2],[-5,6],[-3,8],[0,9],[1,9],[4,8],[6,6],[7,3],[7,2],[6,-1],[4,-3],[1,-4],[0,-4],[-3,-3],[-5,-1],[-6,2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-3,9]],[[-7,-12],[7,-12]]]},{"l":-10,"r":10,"p":[[[-2,-12],[-5,-11],[-6,-9],[-6,-7],[-5,-5],[-3,-4],[1,-3],[4,-2],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-6,7],[-7,5],[-7,2],[-6,0],[-4,-2],[-1,-3],[3,-4],[5,-5],[6,-7],[6,-9],[5,-11],[2,-12],[-2,-12]]]},{"l":-10,"r":10,"p":[[[6,-5],[5,-2],[3,0],[0,1],[-1,1],[-4,0],[-6,-2],[-7,-5],[-7,-6],[-6,-9],[-4,-11],[-1,-12],[0,-12],[3,-11],[5,-9],[6,-5],[6,0],[5,5],[3,8],[0,9],[-2,9],[-5,8],[-6,6]]]},{"l":-4,"r":4,"p":[[[0,-3],[-1,-2],[0,-1],[1,-2],[0,-3]],[[0,4],[-1,5],[0,6],[1,5],[0,4]]]},{"l":-4,"r":4,"p":[[[0,-3],[-1,-2],[0,-1],[1,-2],[0,-3]],[[1,5],[0,6],[-1,5],[0,4],[1,5],[1,7],[-1,9]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-9,"r":9,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[4,-3],[0,-1],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-9,"r":9,"p":[[[0,-12],[-8,9]],[[0,-12],[8,9]],[[-5,2],[5,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2]],[[-7,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-7,9]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[0,-12],[3,-11],[5,-9],[6,-7],[7,-4],[7,1],[6,4],[5,6],[3,8],[0,9],[-7,9]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]],[[-6,9],[7,9]]]},{"l":-10,"r":8,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4],[8,1]],[[3,1],[8,1]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[7,-12],[7,9]],[[-7,-2],[7,-2]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-8,"r":8,"p":[[[4,-12],[4,4],[3,7],[2,8],[0,9],[-2,9],[-4,8],[-5,7],[-6,4],[-6,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[7,-12],[-7,2]],[[-2,-3],[7,9]]]},{"l":-10,"r":7,"p":[[[-6,-12],[-6,9]],[[-6,9],[6,9]]]},{"l":-12,"r":12,"p":[[[-8,-12],[-8,9]],[[-8,-12],[0,9]],[[8,-12],[0,9]],[[8,-12],[8,9]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[-7,-12],[7,9]],[[7,-12],[7,9]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-5],[6,-3],[5,-2],[2,-1],[-7,-1]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]],[[1,5],[7,11]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2],[-7,-2]],[[0,-2],[7,9]]]},{"l":-10,"r":10,"p":[[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,9]],[[-7,-12],[7,-12]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,3],[-6,6],[-4,8],[-1,9],[1,9],[4,8],[6,6],[7,3],[7,-12]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,9]],[[8,-12],[0,9]]]},{"l":-12,"r":12,"p":[[[-10,-12],[-5,9]],[[0,-12],[-5,9]],[[0,-12],[5,9]],[[10,-12],[5,9]]]},{"l":-10,"r":10,"p":[[[-7,-12],[7,9]],[[7,-12],[-7,9]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,-2],[0,9]],[[8,-12],[0,-2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-7,9]],[[-7,-12],[7,-12]],[[-7,9],[7,9]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[0,-14],[-8,0]],[[0,-14],[8,0]]]},{"l":-9,"r":9,"p":[[[-9,16],[9,16]]]},{"l":-4,"r":4,"p":[[[1,-7],[-1,-5],[-1,-3],[0,-2],[1,-3],[0,-4],[-1,-3]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":9,"p":[[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[6,-12],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":9,"p":[[[-6,1],[6,1],[6,-1],[5,-3],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-5,"r":7,"p":[[[5,-12],[3,-12],[1,-11],[0,-8],[0,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,11],[5,14],[4,15],[2,16],[-1,16],[-3,15]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[-5,-12],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-4,"r":4,"p":[[[-1,-12],[0,-11],[1,-12],[0,-13],[-1,-12]],[[0,-5],[0,9]]]},{"l":-5,"r":5,"p":[[[0,-12],[1,-11],[2,-12],[1,-13],[0,-12]],[[1,-5],[1,12],[0,15],[-2,16],[-4,16]]]},{"l":-9,"r":8,"p":[[[-5,-12],[-5,9]],[[5,-5],[-5,5]],[[-1,1],[6,9]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-15,"r":15,"p":[[[-11,-5],[-11,9]],[[-11,-1],[-8,-4],[-6,-5],[-3,-5],[-1,-4],[0,-1],[0,9]],[[0,-1],[3,-4],[5,-5],[8,-5],[10,-4],[11,-1],[11,9]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-9,"r":10,"p":[[[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6],[7,3],[7,1],[6,-2],[4,-4],[2,-5],[-1,-5]]]},{"l":-10,"r":9,"p":[[[-6,-5],[-6,16]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,16]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-7,"r":6,"p":[[[-3,-5],[-3,9]],[[-3,1],[-2,-2],[0,-4],[2,-5],[5,-5]]]},{"l":-8,"r":9,"p":[[[6,-2],[5,-4],[2,-5],[-1,-5],[-4,-4],[-5,-2],[-4,0],[-2,1],[3,2],[5,3],[6,5],[6,6],[5,8],[2,9],[-1,9],[-4,8],[-5,6]]]},{"l":-5,"r":7,"p":[[[0,-12],[0,5],[1,8],[3,9],[5,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,5],[-4,8],[-2,9],[1,9],[3,8],[6,5]],[[6,-5],[6,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9]]]},{"l":-11,"r":11,"p":[[[-8,-5],[-4,9]],[[0,-5],[-4,9]],[[0,-5],[4,9]],[[8,-5],[4,9]]]},{"l":-8,"r":9,"p":[[[-5,-5],[6,9]],[[6,-5],[-5,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9],[-2,13],[-4,15],[-6,16],[-7,16]]]},{"l":-8,"r":9,"p":[[[6,-5],[-5,9]],[[-5,-5],[6,-5]],[[-5,9],[6,9]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-8,"r":8,"p":[[[-8,-12],[-8,9],[-7,9],[-7,-12],[-6,-12],[-6,9],[-5,9],[-5,-12],[-4,-12],[-4,9],[-3,9],[-3,-12],[-2,-12],[-2,9],[-1,9],[-1,-12],[0,-12],[0,9],[1,9],[1,-12],[2,-12],[2,9],[3,9],[3,-12],[4,-12],[4,9],[5,9],[5,-12],[6,-12],[6,9],[7,9],[7,-12],[8,-12],[8,9]]]}],"rowmans":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":5,"p":[[[0,-12],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-8,"r":8,"p":[[[-4,-12],[-4,-5]],[[4,-12],[4,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":10,"p":[[[-2,-16],[-2,13]],[[2,-16],[2,13]],[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-3],[10,-4],[9,-5],[8,-5],[7,-4],[6,-2],[4,3],[2,6],[0,8],[-2,9],[-6,9],[-8,8],[-9,7],[-10,5],[-10,3],[-9,1],[-8,0],[-1,-4],[0,-5],[1,-7],[1,-9],[0,-11],[-2,-12],[-4,-11],[-5,-9],[-5,-7],[-4,-4],[-2,-1],[3,6],[5,8],[7,9],[9,9],[10,8],[10,7]]]},{"l":-5,"r":5,"p":[[[0,-10],[-1,-11],[0,-12],[1,-11],[1,-9],[0,-7],[-1,-6]]]},{"l":-7,"r":7,"p":[[[4,-16],[2,-14],[0,-11],[-2,-7],[-3,-2],[-3,2],[-2,7],[0,11],[2,14],[4,16]]]},{"l":-7,"r":7,"p":[[[-4,-16],[-2,-14],[0,-11],[2,-7],[3,-2],[3,2],[2,7],[0,11],[-2,14],[-4,16]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,0]],[[-5,-9],[5,-3]],[[5,-9],[-5,-3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[1,8],[0,9],[-1,8],[0,7],[1,8],[1,10],[0,12],[-1,13]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-11,"r":11,"p":[[[9,-16],[-9,16]]]},{"l":-10,"r":10,"p":[[[-1,-12],[-4,-11],[-6,-8],[-7,-3],[-7,0],[-6,5],[-4,8],[-1,9],[1,9],[4,8],[6,5],[7,0],[7,-3],[6,-8],[4,-11],[1,-12],[-1,-12]]]},{"l":-10,"r":10,"p":[[[-4,-8],[-2,-9],[1,-12],[1,9]]]},{"l":-10,"r":10,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[3,-1],[-7,9],[7,9]]]},{"l":-10,"r":10,"p":[[[-5,-12],[6,-12],[0,-4],[3,-4],[5,-3],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[3,-12],[-7,2],[8,2]],[[3,-12],[3,9]]]},{"l":-10,"r":10,"p":[[[5,-12],[-5,-12],[-6,-3],[-5,-4],[-2,-5],[1,-5],[4,-4],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[6,-9],[5,-11],[2,-12],[0,-12],[-3,-11],[-5,-8],[-6,-3],[-6,2],[-5,6],[-3,8],[0,9],[1,9],[4,8],[6,6],[7,3],[7,2],[6,-1],[4,-3],[1,-4],[0,-4],[-3,-3],[-5,-1],[-6,2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-3,9]],[[-7,-12],[7,-12]]]},{"l":-10,"r":10,"p":[[[-2,-12],[-5,-11],[-6,-9],[-6,-7],[-5,-5],[-3,-4],[1,-3],[4,-2],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-6,7],[-7,5],[-7,2],[-6,0],[-4,-2],[-1,-3],[3,-4],[5,-5],[6,-7],[6,-9],[5,-11],[2,-12],[-2,-12]]]},{"l":-10,"r":10,"p":[[[6,-5],[5,-2],[3,0],[0,1],[-1,1],[-4,0],[-6,-2],[-7,-5],[-7,-6],[-6,-9],[-4,-11],[-1,-12],[0,-12],[3,-11],[5,-9],[6,-5],[6,0],[5,5],[3,8],[0,9],[-2,9],[-5,8],[-6,6]]]},{"l":-5,"r":5,"p":[[[0,-5],[-1,-4],[0,-3],[1,-4],[0,-5]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-5,"r":5,"p":[[[0,-5],[-1,-4],[0,-3],[1,-4],[0,-5]],[[1,8],[0,9],[-1,8],[0,7],[1,8],[1,10],[0,12],[-1,13]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-9,"r":9,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[4,-3],[0,-1],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-9,"r":9,"p":[[[0,-12],[-8,9]],[[0,-12],[8,9]],[[-5,2],[5,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2]],[[-7,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-7,9]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[0,-12],[3,-11],[5,-9],[6,-7],[7,-4],[7,1],[6,4],[5,6],[3,8],[0,9],[-7,9]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]],[[-6,9],[7,9]]]},{"l":-10,"r":8,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4],[8,1]],[[3,1],[8,1]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[7,-12],[7,9]],[[-7,-2],[7,-2]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-8,"r":8,"p":[[[4,-12],[4,4],[3,7],[2,8],[0,9],[-2,9],[-4,8],[-5,7],[-6,4],[-6,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[7,-12],[-7,2]],[[-2,-3],[7,9]]]},{"l":-10,"r":7,"p":[[[-6,-12],[-6,9]],[[-6,9],[6,9]]]},{"l":-12,"r":12,"p":[[[-8,-12],[-8,9]],[[-8,-12],[0,9]],[[8,-12],[0,9]],[[8,-12],[8,9]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[-7,-12],[7,9]],[[7,-12],[7,9]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-5],[6,-3],[5,-2],[2,-1],[-7,-1]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]],[[1,5],[7,11]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2],[-7,-2]],[[0,-2],[7,9]]]},{"l":-10,"r":10,"p":[[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,9]],[[-7,-12],[7,-12]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,3],[-6,6],[-4,8],[-1,9],[1,9],[4,8],[6,6],[7,3],[7,-12]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,9]],[[8,-12],[0,9]]]},{"l":-12,"r":12,"p":[[[-10,-12],[-5,9]],[[0,-12],[-5,9]],[[0,-12],[5,9]],[[10,-12],[5,9]]]},{"l":-10,"r":10,"p":[[[-7,-12],[7,9]],[[7,-12],[-7,9]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,-2],[0,9]],[[8,-12],[0,-2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-7,9]],[[-7,-12],[7,-12]],[[-7,9],[7,9]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[-2,-6],[0,-9],[2,-6]],[[-5,-3],[0,-8],[5,-3]],[[0,-8],[0,9]]]},{"l":-8,"r":8,"p":[[[-8,11],[8,11]]]},{"l":-5,"r":5,"p":[[[1,-12],[0,-11],[-1,-9],[-1,-7],[0,-6],[1,-7],[0,-8]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":9,"p":[[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[6,-12],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":9,"p":[[[-6,1],[6,1],[6,-1],[5,-3],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-5,"r":7,"p":[[[5,-12],[3,-12],[1,-11],[0,-8],[0,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,11],[5,14],[4,15],[2,16],[-1,16],[-3,15]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[-5,-12],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-4,"r":4,"p":[[[-1,-12],[0,-11],[1,-12],[0,-13],[-1,-12]],[[0,-5],[0,9]]]},{"l":-5,"r":5,"p":[[[0,-12],[1,-11],[2,-12],[1,-13],[0,-12]],[[1,-5],[1,12],[0,15],[-2,16],[-4,16]]]},{"l":-9,"r":8,"p":[[[-5,-12],[-5,9]],[[5,-5],[-5,5]],[[-1,1],[6,9]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-15,"r":15,"p":[[[-11,-5],[-11,9]],[[-11,-1],[-8,-4],[-6,-5],[-3,-5],[-1,-4],[0,-1],[0,9]],[[0,-1],[3,-4],[5,-5],[8,-5],[10,-4],[11,-1],[11,9]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-9,"r":10,"p":[[[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6],[7,3],[7,1],[6,-2],[4,-4],[2,-5],[-1,-5]]]},{"l":-10,"r":9,"p":[[[-6,-5],[-6,16]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,16]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-7,"r":6,"p":[[[-3,-5],[-3,9]],[[-3,1],[-2,-2],[0,-4],[2,-5],[5,-5]]]},{"l":-8,"r":9,"p":[[[6,-2],[5,-4],[2,-5],[-1,-5],[-4,-4],[-5,-2],[-4,0],[-2,1],[3,2],[5,3],[6,5],[6,6],[5,8],[2,9],[-1,9],[-4,8],[-5,6]]]},{"l":-5,"r":7,"p":[[[0,-12],[0,5],[1,8],[3,9],[5,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,5],[-4,8],[-2,9],[1,9],[3,8],[6,5]],[[6,-5],[6,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9]]]},{"l":-11,"r":11,"p":[[[-8,-5],[-4,9]],[[0,-5],[-4,9]],[[0,-5],[4,9]],[[8,-5],[4,9]]]},{"l":-8,"r":9,"p":[[[-5,-5],[6,9]],[[6,-5],[-5,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9],[-2,13],[-4,15],[-6,16],[-7,16]]]},{"l":-8,"r":9,"p":[[[6,-5],[-5,9]],[[-5,-5],[6,-5]],[[-5,9],[6,9]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-7,"r":7,"p":[[[-1,-12],[-3,-11],[-4,-9],[-4,-7],[-3,-5],[-1,-4],[1,-4],[3,-5],[4,-7],[4,-9],[3,-11],[1,-12],[-1,-12]]]}],"scripts":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":6,"p":[[[3,-12],[2,-11],[0,1]],[[3,-11],[0,1]],[[3,-12],[4,-11],[0,1]],[[-2,7],[-3,8],[-2,9],[-1,8],[-2,7]]]},{"l":-9,"r":9,"p":[[[-2,-12],[-4,-5]],[[-1,-12],[-4,-5]],[[7,-12],[5,-5]],[[8,-12],[5,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":11,"p":[[[2,-16],[-6,13]],[[7,-16],[-1,13]],[[8,-8],[7,-7],[8,-6],[9,-7],[9,-8],[8,-10],[7,-11],[4,-12],[0,-12],[-3,-11],[-5,-9],[-5,-7],[-4,-5],[-3,-4],[4,0],[6,2]],[[-5,-7],[-3,-5],[4,-1],[5,0],[6,2],[6,5],[5,7],[4,8],[1,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-4],[9,-3],[10,-2],[11,-3],[11,-4],[10,-5],[9,-5],[7,-4],[5,-2],[0,6],[-2,8],[-4,9],[-7,9],[-10,8],[-11,6],[-11,4],[-10,2],[-9,1],[-7,0],[-2,-2],[0,-3],[2,-5],[3,-7],[3,-9],[2,-11],[0,-12],[-2,-11],[-3,-9],[-3,-6],[-2,0],[-1,3],[1,6],[3,8],[5,9],[7,9],[8,7],[8,6]],[[-7,9],[-9,8],[-10,6],[-10,4],[-9,2],[-8,1],[-2,-2]],[[-3,-6],[-2,-1],[-1,2],[1,5],[3,7],[5,8],[7,8],[8,7]]]},{"l":-5,"r":6,"p":[[[3,-10],[2,-11],[3,-12],[4,-11],[4,-10],[3,-8],[1,-6]]]},{"l":-7,"r":8,"p":[[[8,-16],[4,-13],[1,-10],[-1,-7],[-3,-3],[-4,2],[-4,6],[-3,11],[-2,14],[-1,16]],[[4,-13],[1,-9],[-1,-5],[-2,-2],[-3,3],[-3,8],[-2,13],[-1,16]]]},{"l":-8,"r":7,"p":[[[1,-16],[2,-14],[3,-11],[4,-6],[4,-2],[3,3],[1,7],[-1,10],[-4,13],[-8,16]],[[1,-16],[2,-13],[3,-8],[3,-3],[2,2],[1,5],[-1,9],[-4,13]]]},{"l":-8,"r":9,"p":[[[2,-12],[2,0]],[[-3,-9],[7,-3]],[[7,-9],[-3,-3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-5,"r":6,"p":[[[-2,9],[-3,8],[-2,7],[-1,8],[-1,9],[-2,11],[-4,13]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-11,"r":11,"p":[[[13,-16],[-13,16]]]},{"l":-10,"r":11,"p":[[[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-3],[-7,1],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[6,3],[7,0],[8,-4],[8,-7],[7,-10],[6,-11],[4,-12],[2,-12]],[[2,-12],[0,-11],[-2,-9],[-4,-6],[-5,-3],[-6,1],[-6,4],[-5,7],[-3,9]],[[-1,9],[1,8],[3,6],[5,3],[6,0],[7,-4],[7,-7],[6,-10],[4,-12]]]},{"l":-10,"r":11,"p":[[[2,-8],[-3,9]],[[4,-12],[-2,9]],[[4,-12],[1,-9],[-2,-7],[-4,-6]],[[3,-9],[-1,-7],[-4,-6]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[4,-12],[7,-11],[8,-9],[8,-7],[7,-5],[5,-3],[2,-1],[-2,1],[-5,3],[-7,5],[-9,9]],[[4,-12],[6,-11],[7,-9],[7,-7],[6,-5],[4,-3],[-2,1]],[[-8,7],[-7,6],[-5,6],[0,8],[3,8],[5,7],[6,5]],[[-5,6],[0,9],[3,9],[5,8],[6,5]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[4,-12],[7,-11],[8,-9],[8,-7],[7,-5],[4,-3],[1,-2]],[[4,-12],[6,-11],[7,-9],[7,-7],[6,-5],[4,-3]],[[-1,-2],[1,-2],[4,-1],[5,0],[6,2],[6,5],[5,7],[4,8],[1,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]],[[1,-2],[3,-1],[4,0],[5,2],[5,5],[4,7],[3,8],[1,9]]]},{"l":-10,"r":11,"p":[[[6,-11],[0,9]],[[7,-12],[1,9]],[[7,-12],[-8,3],[8,3]]]},{"l":-10,"r":11,"p":[[[-1,-12],[-6,-2]],[[-1,-12],[9,-12]],[[-1,-11],[4,-11],[9,-12]],[[-6,-2],[-5,-3],[-2,-4],[1,-4],[4,-3],[5,-2],[6,0],[6,3],[5,6],[3,8],[0,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]],[[1,-4],[3,-3],[4,-2],[5,0],[5,3],[4,6],[2,8],[0,9]]]},{"l":-10,"r":11,"p":[[[7,-9],[6,-8],[7,-7],[8,-8],[8,-9],[7,-11],[5,-12],[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-3],[-7,1],[-7,5],[-6,7],[-5,8],[-3,9],[0,9],[3,8],[5,6],[6,4],[6,1],[5,-1],[4,-2],[2,-3],[-1,-3],[-3,-2],[-5,0],[-6,2]],[[2,-12],[0,-11],[-2,-9],[-4,-6],[-5,-3],[-6,1],[-6,6],[-5,8]],[[0,9],[2,8],[4,6],[5,4],[5,0],[4,-2]]]},{"l":-10,"r":11,"p":[[[-4,-12],[-6,-6]],[[9,-12],[8,-9],[6,-6],[1,0],[-1,3],[-2,5],[-3,9]],[[6,-6],[0,0],[-2,3],[-3,5],[-4,9]],[[-5,-9],[-2,-12],[0,-12],[5,-9]],[[-4,-10],[-2,-11],[0,-11],[5,-9],[7,-9],[8,-10],[9,-12]]]},{"l":-10,"r":11,"p":[[[1,-12],[-2,-11],[-3,-10],[-4,-8],[-4,-5],[-3,-3],[-1,-2],[2,-2],[6,-3],[7,-4],[8,-6],[8,-9],[7,-11],[4,-12],[1,-12]],[[1,-12],[-1,-11],[-2,-10],[-3,-8],[-3,-5],[-2,-3],[-1,-2]],[[2,-2],[5,-3],[6,-4],[7,-6],[7,-9],[6,-11],[4,-12]],[[-1,-2],[-5,-1],[-7,1],[-8,3],[-8,6],[-7,8],[-4,9],[0,9],[4,8],[5,7],[6,5],[6,2],[5,0],[4,-1],[2,-2]],[[-1,-2],[-4,-1],[-6,1],[-7,3],[-7,6],[-6,8],[-4,9]],[[0,9],[3,8],[4,7],[5,5],[5,1],[4,-1]]]},{"l":-10,"r":11,"p":[[[7,-5],[6,-3],[4,-1],[2,0],[-1,0],[-3,-1],[-4,-2],[-5,-4],[-5,-7],[-4,-9],[-2,-11],[1,-12],[4,-12],[6,-11],[7,-10],[8,-8],[8,-4],[7,0],[6,3],[4,6],[2,8],[-1,9],[-4,9],[-6,8],[-7,6],[-7,5],[-6,4],[-5,5],[-6,6]],[[-3,-1],[-4,-3],[-4,-7],[-3,-9],[-1,-11],[1,-12]],[[6,-11],[7,-9],[7,-4],[6,0],[5,3],[3,6],[1,8],[-1,9]]]},{"l":-5,"r":6,"p":[[[1,-5],[0,-4],[1,-3],[2,-4],[1,-5]],[[-2,7],[-3,8],[-2,9],[-1,8]]]},{"l":-5,"r":6,"p":[[[1,-5],[0,-4],[1,-3],[2,-4],[1,-5]],[[-2,9],[-3,8],[-2,7],[-1,8],[-1,9],[-2,11],[-4,13]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[5,-12],[8,-11],[9,-9],[9,-7],[8,-5],[7,-4],[1,-2],[-1,-1],[-1,1],[0,2],[2,2]],[[5,-12],[7,-11],[8,-9],[8,-7],[7,-5],[6,-4],[4,-3]],[[-2,7],[-3,8],[-2,9],[-1,8],[-2,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-11,"r":9,"p":[[[-11,9],[-9,8],[-6,5],[-3,1],[1,-6],[4,-12],[4,9],[3,6],[1,3],[-1,1],[-4,-1],[-6,-1],[-7,0],[-7,2],[-6,4],[-4,6],[-1,8],[2,9],[7,9]]]},{"l":-12,"r":11,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[6,-12],[8,-11],[9,-9],[9,-7],[8,-5],[7,-4],[5,-3],[2,-2]],[[1,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[3,9],[0,9],[-2,8],[-3,6]]]},{"l":-10,"r":10,"p":[[[2,-6],[2,-5],[3,-4],[5,-4],[7,-5],[8,-7],[8,-9],[7,-11],[5,-12],[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-4],[-7,0],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[5,4]]]},{"l":-11,"r":12,"p":[[[2,-12],[0,-11],[-1,-9],[-2,-5],[-3,1],[-4,4],[-5,6],[-7,8],[-9,9],[-11,9],[-12,8],[-12,6],[-11,5],[-9,5],[-7,6],[-5,8],[-2,9],[1,9],[4,8],[6,6],[8,2],[9,-3],[9,-7],[8,-10],[7,-11],[5,-12],[2,-12],[0,-10],[0,-8],[1,-5],[3,-2],[5,0],[8,2],[10,3]]]},{"l":-10,"r":10,"p":[[[4,-8],[4,-7],[5,-6],[7,-6],[8,-7],[8,-9],[7,-11],[4,-12],[0,-12],[-3,-11],[-4,-9],[-4,-6],[-3,-4],[-2,-3],[1,-2],[-2,-2],[-5,-1],[-6,0],[-7,2],[-7,5],[-6,7],[-5,8],[-2,9],[1,9],[4,8],[6,6],[7,4]]]},{"l":-10,"r":10,"p":[[[0,-6],[-2,-6],[-4,-7],[-5,-9],[-4,-11],[-1,-12],[2,-12],[6,-11],[9,-11],[11,-12]],[[6,-11],[4,-4],[2,2],[0,6],[-2,8],[-4,9],[-6,9],[-8,8],[-9,6],[-9,4],[-8,3],[-6,3],[-4,4]],[[-1,-2],[8,-2]]]},{"l":-11,"r":12,"p":[[[-11,9],[-9,8],[-5,4],[-2,-1],[-1,-4],[0,-8],[0,-11],[-1,-12],[-2,-12],[-3,-11],[-4,-9],[-4,-6],[-3,-4],[-1,-3],[3,-3],[6,-4],[7,-5],[8,-7],[8,-1],[7,4],[6,6],[4,8],[1,9],[-3,9],[-6,8],[-8,6],[-9,4],[-9,2]]]},{"l":-12,"r":12,"p":[[[-5,-5],[-7,-6],[-8,-8],[-8,-9],[-7,-11],[-5,-12],[-4,-12],[-2,-11],[-1,-9],[-1,-7],[-2,-3],[-4,3],[-6,7],[-8,9],[-10,9],[-11,8],[-11,6]],[[-5,0],[4,-3],[6,-4],[9,-6],[11,-8],[12,-10],[12,-11],[11,-12],[10,-12],[8,-10],[6,-6],[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-9,"r":8,"p":[[[5,4],[3,2],[1,-1],[0,-3],[-1,-6],[-1,-9],[0,-11],[1,-12],[3,-12],[4,-11],[5,-9],[5,-6],[4,-1],[2,4],[1,6],[-1,8],[-3,9],[-5,9],[-7,8],[-8,6],[-8,4],[-7,3],[-5,3],[-3,4]]]},{"l":-8,"r":7,"p":[[[2,12],[0,9],[-2,4],[-3,-2],[-3,-8],[-2,-11],[0,-12],[2,-12],[3,-11],[4,-8],[4,-5],[3,0],[0,9],[-2,15],[-3,18],[-4,20],[-6,21],[-7,20],[-7,18],[-6,15],[-4,12],[-2,10],[1,8],[5,6]]]},{"l":-12,"r":12,"p":[[[-5,-5],[-7,-6],[-8,-8],[-8,-9],[-7,-11],[-5,-12],[-4,-12],[-2,-11],[-1,-9],[-1,-7],[-2,-3],[-4,3],[-6,7],[-8,9],[-10,9],[-11,8],[-11,6]],[[12,-9],[12,-11],[11,-12],[10,-12],[8,-11],[6,-9],[4,-6],[2,-4],[0,-3],[-2,-3]],[[0,-3],[1,-1],[1,6],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-9,"r":10,"p":[[[-5,0],[-3,0],[1,-1],[4,-3],[6,-5],[7,-7],[7,-10],[6,-12],[4,-12],[3,-11],[2,-9],[1,-4],[0,1],[-1,4],[-2,6],[-4,8],[-6,9],[-8,9],[-9,8],[-9,6],[-8,5],[-6,5],[-4,6],[-1,8],[2,9],[4,9],[7,8],[9,6]]]},{"l":-18,"r":15,"p":[[[-13,-5],[-15,-6],[-16,-8],[-16,-9],[-15,-11],[-13,-12],[-12,-12],[-10,-11],[-9,-9],[-9,-7],[-10,-2],[-11,2],[-13,9]],[[-11,2],[-8,-6],[-6,-10],[-5,-11],[-3,-12],[-2,-12],[0,-11],[1,-9],[1,-7],[0,-2],[-1,2],[-3,9]],[[-1,2],[2,-6],[4,-10],[5,-11],[7,-12],[8,-12],[10,-11],[11,-9],[11,-7],[10,-2],[8,5],[8,8],[9,9],[10,9],[12,8],[13,7],[15,4]]]},{"l":-13,"r":11,"p":[[[-8,-5],[-10,-6],[-11,-8],[-11,-9],[-10,-11],[-8,-12],[-7,-12],[-5,-11],[-4,-9],[-4,-7],[-5,-2],[-6,2],[-8,9]],[[-6,2],[-3,-6],[-1,-10],[0,-11],[2,-12],[4,-12],[6,-11],[7,-9],[7,-7],[6,-2],[4,5],[4,8],[5,9],[6,9],[8,8],[9,7],[11,4]]]},{"l":-10,"r":11,"p":[[[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-4],[-7,0],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[6,3],[7,1],[8,-3],[8,-7],[7,-10],[6,-11],[4,-12],[2,-12],[0,-10],[0,-7],[1,-4],[3,-1],[5,1],[8,3],[10,4]]]},{"l":-12,"r":13,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[8,-12],[10,-11],[11,-10],[12,-8],[12,-5],[11,-3],[10,-2],[8,-1],[5,-1],[3,-2],[2,-3]]]},{"l":-10,"r":12,"p":[[[3,-6],[2,-4],[1,-3],[-1,-2],[-3,-2],[-4,-4],[-4,-6],[-3,-9],[-1,-11],[2,-12],[5,-12],[7,-11],[8,-9],[8,-5],[7,-2],[5,1],[1,5],[-2,7],[-4,8],[-7,9],[-9,9],[-10,8],[-10,6],[-9,5],[-7,5],[-5,6],[-2,8],[1,9],[4,9],[7,8],[9,6]]]},{"l":-12,"r":13,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[7,-12],[9,-11],[10,-10],[11,-8],[11,-5],[10,-3],[9,-2],[7,-1],[4,-1],[1,-2],[2,-1],[3,1],[3,6],[4,8],[6,9],[8,8],[9,7],[11,4]]]},{"l":-10,"r":10,"p":[[[-10,9],[-8,8],[-6,6],[-3,2],[-1,-1],[1,-5],[2,-8],[2,-11],[1,-12],[0,-12],[-1,-11],[-2,-9],[-2,-7],[-1,-5],[1,-3],[4,-1],[6,1],[7,3],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-7,6],[-8,4],[-8,2]]]},{"l":-10,"r":9,"p":[[[0,-6],[-2,-6],[-4,-7],[-5,-9],[-4,-11],[-1,-12],[2,-12],[6,-11],[9,-11],[11,-12]],[[6,-11],[4,-4],[2,2],[0,6],[-2,8],[-4,9],[-6,9],[-8,8],[-9,6],[-9,4],[-8,3],[-6,3],[-4,4]]]},{"l":-13,"r":11,"p":[[[-8,-5],[-10,-6],[-11,-8],[-11,-9],[-10,-11],[-8,-12],[-7,-12],[-5,-11],[-4,-9],[-4,-7],[-5,-3],[-6,0],[-7,4],[-7,6],[-6,8],[-4,9],[-2,9],[0,8],[1,7],[3,3],[6,-5],[8,-12]],[[6,-5],[5,-1],[4,5],[4,8],[5,9],[6,9],[8,8],[9,7],[11,4]]]},{"l":-12,"r":11,"p":[[[-7,-5],[-9,-6],[-10,-8],[-10,-9],[-9,-11],[-7,-12],[-6,-12],[-4,-11],[-3,-9],[-3,-7],[-4,-3],[-5,0],[-6,4],[-6,7],[-5,9],[-3,9],[-1,8],[2,5],[4,2],[6,-2],[7,-5],[8,-9],[8,-11],[7,-12],[6,-12],[5,-11],[4,-9],[4,-7],[5,-4],[7,-2],[9,-1]]]},{"l":-15,"r":13,"p":[[[-10,-5],[-12,-6],[-13,-8],[-13,-9],[-12,-11],[-10,-12],[-9,-12],[-7,-11],[-6,-9],[-6,-6],[-7,9]],[[3,-12],[-7,9]],[[3,-12],[1,9]],[[15,-12],[13,-11],[10,-8],[7,-4],[4,2],[1,9]]]},{"l":-12,"r":12,"p":[[[-4,-6],[-6,-6],[-7,-7],[-7,-9],[-6,-11],[-4,-12],[-2,-12],[0,-11],[1,-9],[1,-6],[-1,3],[-1,6],[0,8],[2,9],[4,9],[6,8],[7,6],[7,4],[6,3],[4,3]],[[11,-9],[11,-11],[10,-12],[8,-12],[6,-11],[4,-9],[2,-6],[-2,3],[-4,6],[-6,8],[-8,9],[-10,9],[-11,8],[-11,6]]]},{"l":-12,"r":11,"p":[[[-7,-5],[-9,-6],[-10,-8],[-10,-9],[-9,-11],[-7,-12],[-6,-12],[-4,-11],[-3,-9],[-3,-7],[-4,-3],[-5,0],[-6,4],[-6,6],[-5,8],[-4,9],[-2,9],[0,8],[2,6],[4,3],[5,1],[7,-5]],[[9,-12],[7,-5],[4,5],[2,11],[0,16],[-2,20],[-4,21],[-5,20],[-5,18],[-4,15],[-2,12],[1,9],[4,7],[9,4]]]},{"l":-10,"r":11,"p":[[[3,-6],[2,-4],[1,-3],[-1,-2],[-3,-2],[-4,-4],[-4,-6],[-3,-9],[-1,-11],[2,-12],[5,-12],[7,-11],[8,-9],[8,-5],[7,-2],[5,2],[2,5],[-2,8],[-4,9],[-7,9],[-8,8],[-8,6],[-7,5],[-4,5],[-2,6],[-1,7],[0,9],[0,12],[-1,15],[-2,17],[-4,20],[-6,21],[-7,20],[-7,18],[-6,15],[-4,12],[-1,9],[2,7],[8,4]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[-2,-6],[0,-9],[2,-6]],[[-5,-3],[0,-8],[5,-3]],[[0,-8],[0,9]]]},{"l":-8,"r":8,"p":[[[-8,11],[8,11]]]},{"l":-5,"r":6,"p":[[[4,-12],[2,-10],[1,-8],[1,-7],[2,-6],[3,-7],[2,-8]]]},{"l":-6,"r":10,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,6],[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-5,"r":9,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,2],[-4,8],[-3,9],[-2,9],[0,8],[2,6],[3,3],[3,0],[4,4],[5,5],[7,5],[9,4]]]},{"l":-5,"r":6,"p":[[[2,2],[2,1],[1,0],[-1,0],[-3,1],[-4,2],[-5,4],[-5,6],[-4,8],[-2,9],[1,9],[4,7],[6,4]]]},{"l":-6,"r":10,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,6],[8,-12]],[[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-4,"r":6,"p":[[[-3,7],[-1,6],[0,5],[1,3],[1,1],[0,0],[-1,0],[-3,1],[-4,3],[-4,6],[-3,8],[-1,9],[1,9],[3,8],[4,7],[6,4]]]},{"l":-3,"r":5,"p":[[[-3,4],[1,-1],[3,-4],[4,-6],[5,-9],[5,-11],[4,-12],[2,-11],[1,-9],[-1,-1],[-4,8],[-7,15],[-8,18],[-8,20],[-7,21],[-5,20],[-4,17],[-3,8],[-2,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-6,"r":9,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,7]],[[4,0],[2,7],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[3,9],[6,7],[9,4]]]},{"l":-5,"r":10,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,1],[-5,9]],[[-5,9],[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[3,6],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-2,"r":5,"p":[[[1,-5],[1,-4],[2,-4],[2,-5],[1,-5]],[[-2,4],[0,0],[-2,6],[-2,8],[-1,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-2,"r":5,"p":[[[1,-5],[1,-4],[2,-4],[2,-5],[1,-5]],[[-2,4],[0,0],[-6,18],[-7,20],[-9,21],[-10,20],[-10,18],[-9,15],[-6,12],[-3,10],[-1,9],[2,7],[5,4]]]},{"l":-5,"r":9,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,1],[-5,9]],[[-5,9],[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[2,4],[-1,4]],[[-1,4],[1,5],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-3,"r":5,"p":[[[-3,4],[-1,1],[2,-4],[3,-6],[4,-9],[4,-11],[3,-12],[1,-11],[0,-9],[-1,-5],[-2,2],[-2,8],[-1,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-13,"r":12,"p":[[[-13,4],[-11,1],[-9,0],[-8,1],[-8,2],[-9,6],[-10,9]],[[-9,6],[-8,4],[-6,1],[-4,0],[-2,0],[-1,1],[-1,2],[-2,6],[-3,9]],[[-2,6],[-1,4],[1,1],[3,0],[5,0],[6,1],[6,3],[5,6],[5,8],[6,9],[7,9],[9,8],[10,7],[12,4]]]},{"l":-8,"r":10,"p":[[[-8,4],[-6,1],[-4,0],[-3,1],[-3,2],[-4,6],[-5,9]],[[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[3,6],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-6,"r":8,"p":[[[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,7],[3,5],[3,3],[2,1],[0,0],[-1,1],[-1,3],[0,5],[2,6],[5,6],[7,5],[8,4]]]},{"l":-7,"r":8,"p":[[[-7,4],[-5,1],[-4,-1],[-5,3],[-11,21]],[[-5,3],[-4,1],[-2,0],[0,0],[2,1],[3,3],[3,5],[2,7],[1,8],[-1,9]],[[-5,8],[-3,9],[0,9],[3,8],[5,7],[8,4]]]},{"l":-6,"r":9,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8]],[[4,0],[3,3],[1,8],[-2,15],[-3,18],[-3,20],[-2,21],[0,20],[1,17],[1,10],[3,9],[6,7],[9,4]]]},{"l":-5,"r":8,"p":[[[-5,4],[-3,1],[-2,-1],[-2,1],[1,1],[2,2],[2,4],[1,7],[1,8],[2,9],[3,9],[5,8],[6,7],[8,4]]]},{"l":-4,"r":7,"p":[[[-4,4],[-2,1],[-1,-1],[-1,1],[1,4],[2,6],[2,8],[0,9]],[[-4,8],[-2,9],[2,9],[4,8],[5,7],[7,4]]]},{"l":-3,"r":6,"p":[[[-3,4],[-1,1],[1,-3]],[[4,-12],[-2,6],[-2,8],[-1,9],[1,9],[3,8],[4,7],[6,4]],[[-2,-4],[5,-4]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-6,6],[-6,8],[-5,9],[-3,9],[-1,8],[1,6],[3,3]],[[4,0],[2,6],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-5,5],[-5,8],[-4,9],[-3,9],[0,8],[2,6],[3,3],[3,0]],[[3,0],[4,4],[5,5],[7,5],[9,4]]]},{"l":-9,"r":12,"p":[[[-6,0],[-8,2],[-9,5],[-9,7],[-8,9],[-6,9],[-4,8],[-2,6]],[[0,0],[-2,6],[-2,8],[-1,9],[1,9],[3,8],[5,6],[6,3],[6,0]],[[6,0],[7,4],[8,5],[10,5],[12,4]]]},{"l":-8,"r":8,"p":[[[-8,4],[-6,1],[-4,0],[-2,0],[-1,1],[-1,8],[0,9],[3,9],[6,7],[8,4]],[[5,1],[4,0],[2,0],[1,1],[-3,8],[-4,9],[-6,9],[-7,8]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-6,6],[-6,8],[-5,9],[-3,9],[-1,8],[1,6],[3,3]],[[4,0],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[3,9],[6,7],[9,4]]]},{"l":-6,"r":8,"p":[[[-6,4],[-4,1],[-2,0],[0,0],[2,2],[2,4],[1,6],[-1,8],[-4,9],[-2,10],[-1,12],[-1,15],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[5,7],[8,4]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-7,"r":7,"p":[[[-1,-12],[-3,-11],[-4,-9],[-4,-7],[-3,-5],[-1,-4],[1,-4],[3,-5],[4,-7],[4,-9],[3,-11],[1,-12],[-1,-12]]]}]}
@@ -0,0 +1 @@
1{"futural":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":5,"p":[[[0,-12],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-8,"r":8,"p":[[[-4,-12],[-4,-5]],[[4,-12],[4,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":10,"p":[[[-2,-16],[-2,13]],[[2,-16],[2,13]],[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-3],[10,-4],[9,-5],[8,-5],[7,-4],[6,-2],[4,3],[2,6],[0,8],[-2,9],[-6,9],[-8,8],[-9,7],[-10,5],[-10,3],[-9,1],[-8,0],[-1,-4],[0,-5],[1,-7],[1,-9],[0,-11],[-2,-12],[-4,-11],[-5,-9],[-5,-7],[-4,-4],[-2,-1],[3,6],[5,8],[7,9],[9,9],[10,8],[10,7]]]},{"l":-5,"r":5,"p":[[[0,-10],[-1,-11],[0,-12],[1,-11],[1,-9],[0,-7],[-1,-6]]]},{"l":-7,"r":7,"p":[[[4,-16],[2,-14],[0,-11],[-2,-7],[-3,-2],[-3,2],[-2,7],[0,11],[2,14],[4,16]]]},{"l":-7,"r":7,"p":[[[-4,-16],[-2,-14],[0,-11],[2,-7],[3,-2],[3,2],[2,7],[0,11],[-2,14],[-4,16]]]},{"l":-8,"r":8,"p":[[[0,-6],[0,6]],[[-5,-3],[5,3]],[[5,-3],[-5,3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-4,"r":4,"p":[[[1,5],[0,6],[-1,5],[0,4],[1,5],[1,7],[-1,9]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-4,"r":4,"p":[[[0,4],[-1,5],[0,6],[1,5],[0,4]]]},{"l":-11,"r":11,"p":[[[9,-16],[-9,16]]]},{"l":-10,"r":10,"p":[[[-1,-12],[-4,-11],[-6,-8],[-7,-3],[-7,0],[-6,5],[-4,8],[-1,9],[1,9],[4,8],[6,5],[7,0],[7,-3],[6,-8],[4,-11],[1,-12],[-1,-12]]]},{"l":-10,"r":10,"p":[[[-4,-8],[-2,-9],[1,-12],[1,9]]]},{"l":-10,"r":10,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[3,-1],[-7,9],[7,9]]]},{"l":-10,"r":10,"p":[[[-5,-12],[6,-12],[0,-4],[3,-4],[5,-3],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[3,-12],[-7,2],[8,2]],[[3,-12],[3,9]]]},{"l":-10,"r":10,"p":[[[5,-12],[-5,-12],[-6,-3],[-5,-4],[-2,-5],[1,-5],[4,-4],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[6,-9],[5,-11],[2,-12],[0,-12],[-3,-11],[-5,-8],[-6,-3],[-6,2],[-5,6],[-3,8],[0,9],[1,9],[4,8],[6,6],[7,3],[7,2],[6,-1],[4,-3],[1,-4],[0,-4],[-3,-3],[-5,-1],[-6,2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-3,9]],[[-7,-12],[7,-12]]]},{"l":-10,"r":10,"p":[[[-2,-12],[-5,-11],[-6,-9],[-6,-7],[-5,-5],[-3,-4],[1,-3],[4,-2],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-6,7],[-7,5],[-7,2],[-6,0],[-4,-2],[-1,-3],[3,-4],[5,-5],[6,-7],[6,-9],[5,-11],[2,-12],[-2,-12]]]},{"l":-10,"r":10,"p":[[[6,-5],[5,-2],[3,0],[0,1],[-1,1],[-4,0],[-6,-2],[-7,-5],[-7,-6],[-6,-9],[-4,-11],[-1,-12],[0,-12],[3,-11],[5,-9],[6,-5],[6,0],[5,5],[3,8],[0,9],[-2,9],[-5,8],[-6,6]]]},{"l":-4,"r":4,"p":[[[0,-3],[-1,-2],[0,-1],[1,-2],[0,-3]],[[0,4],[-1,5],[0,6],[1,5],[0,4]]]},{"l":-4,"r":4,"p":[[[0,-3],[-1,-2],[0,-1],[1,-2],[0,-3]],[[1,5],[0,6],[-1,5],[0,4],[1,5],[1,7],[-1,9]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-9,"r":9,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[4,-3],[0,-1],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-9,"r":9,"p":[[[0,-12],[-8,9]],[[0,-12],[8,9]],[[-5,2],[5,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2]],[[-7,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-7,9]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[0,-12],[3,-11],[5,-9],[6,-7],[7,-4],[7,1],[6,4],[5,6],[3,8],[0,9],[-7,9]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]],[[-6,9],[7,9]]]},{"l":-10,"r":8,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4],[8,1]],[[3,1],[8,1]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[7,-12],[7,9]],[[-7,-2],[7,-2]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-8,"r":8,"p":[[[4,-12],[4,4],[3,7],[2,8],[0,9],[-2,9],[-4,8],[-5,7],[-6,4],[-6,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[7,-12],[-7,2]],[[-2,-3],[7,9]]]},{"l":-10,"r":7,"p":[[[-6,-12],[-6,9]],[[-6,9],[6,9]]]},{"l":-12,"r":12,"p":[[[-8,-12],[-8,9]],[[-8,-12],[0,9]],[[8,-12],[0,9]],[[8,-12],[8,9]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[-7,-12],[7,9]],[[7,-12],[7,9]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-5],[6,-3],[5,-2],[2,-1],[-7,-1]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]],[[1,5],[7,11]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2],[-7,-2]],[[0,-2],[7,9]]]},{"l":-10,"r":10,"p":[[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,9]],[[-7,-12],[7,-12]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,3],[-6,6],[-4,8],[-1,9],[1,9],[4,8],[6,6],[7,3],[7,-12]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,9]],[[8,-12],[0,9]]]},{"l":-12,"r":12,"p":[[[-10,-12],[-5,9]],[[0,-12],[-5,9]],[[0,-12],[5,9]],[[10,-12],[5,9]]]},{"l":-10,"r":10,"p":[[[-7,-12],[7,9]],[[7,-12],[-7,9]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,-2],[0,9]],[[8,-12],[0,-2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-7,9]],[[-7,-12],[7,-12]],[[-7,9],[7,9]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[0,-14],[-8,0]],[[0,-14],[8,0]]]},{"l":-9,"r":9,"p":[[[-9,16],[9,16]]]},{"l":-4,"r":4,"p":[[[1,-7],[-1,-5],[-1,-3],[0,-2],[1,-3],[0,-4],[-1,-3]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":9,"p":[[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[6,-12],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":9,"p":[[[-6,1],[6,1],[6,-1],[5,-3],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-5,"r":7,"p":[[[5,-12],[3,-12],[1,-11],[0,-8],[0,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,11],[5,14],[4,15],[2,16],[-1,16],[-3,15]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[-5,-12],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-4,"r":4,"p":[[[-1,-12],[0,-11],[1,-12],[0,-13],[-1,-12]],[[0,-5],[0,9]]]},{"l":-5,"r":5,"p":[[[0,-12],[1,-11],[2,-12],[1,-13],[0,-12]],[[1,-5],[1,12],[0,15],[-2,16],[-4,16]]]},{"l":-9,"r":8,"p":[[[-5,-12],[-5,9]],[[5,-5],[-5,5]],[[-1,1],[6,9]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-15,"r":15,"p":[[[-11,-5],[-11,9]],[[-11,-1],[-8,-4],[-6,-5],[-3,-5],[-1,-4],[0,-1],[0,9]],[[0,-1],[3,-4],[5,-5],[8,-5],[10,-4],[11,-1],[11,9]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-9,"r":10,"p":[[[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6],[7,3],[7,1],[6,-2],[4,-4],[2,-5],[-1,-5]]]},{"l":-10,"r":9,"p":[[[-6,-5],[-6,16]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,16]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-7,"r":6,"p":[[[-3,-5],[-3,9]],[[-3,1],[-2,-2],[0,-4],[2,-5],[5,-5]]]},{"l":-8,"r":9,"p":[[[6,-2],[5,-4],[2,-5],[-1,-5],[-4,-4],[-5,-2],[-4,0],[-2,1],[3,2],[5,3],[6,5],[6,6],[5,8],[2,9],[-1,9],[-4,8],[-5,6]]]},{"l":-5,"r":7,"p":[[[0,-12],[0,5],[1,8],[3,9],[5,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,5],[-4,8],[-2,9],[1,9],[3,8],[6,5]],[[6,-5],[6,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9]]]},{"l":-11,"r":11,"p":[[[-8,-5],[-4,9]],[[0,-5],[-4,9]],[[0,-5],[4,9]],[[8,-5],[4,9]]]},{"l":-8,"r":9,"p":[[[-5,-5],[6,9]],[[6,-5],[-5,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9],[-2,13],[-4,15],[-6,16],[-7,16]]]},{"l":-8,"r":9,"p":[[[6,-5],[-5,9]],[[-5,-5],[6,-5]],[[-5,9],[6,9]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-8,"r":8,"p":[[[-8,-12],[-8,9],[-7,9],[-7,-12],[-6,-12],[-6,9],[-5,9],[-5,-12],[-4,-12],[-4,9],[-3,9],[-3,-12],[-2,-12],[-2,9],[-1,9],[-1,-12],[0,-12],[0,9],[1,9],[1,-12],[2,-12],[2,9],[3,9],[3,-12],[4,-12],[4,9],[5,9],[5,-12],[6,-12],[6,9],[7,9],[7,-12],[8,-12],[8,9]]]}],"rowmans":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":5,"p":[[[0,-12],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-8,"r":8,"p":[[[-4,-12],[-4,-5]],[[4,-12],[4,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":10,"p":[[[-2,-16],[-2,13]],[[2,-16],[2,13]],[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-3],[10,-4],[9,-5],[8,-5],[7,-4],[6,-2],[4,3],[2,6],[0,8],[-2,9],[-6,9],[-8,8],[-9,7],[-10,5],[-10,3],[-9,1],[-8,0],[-1,-4],[0,-5],[1,-7],[1,-9],[0,-11],[-2,-12],[-4,-11],[-5,-9],[-5,-7],[-4,-4],[-2,-1],[3,6],[5,8],[7,9],[9,9],[10,8],[10,7]]]},{"l":-5,"r":5,"p":[[[0,-10],[-1,-11],[0,-12],[1,-11],[1,-9],[0,-7],[-1,-6]]]},{"l":-7,"r":7,"p":[[[4,-16],[2,-14],[0,-11],[-2,-7],[-3,-2],[-3,2],[-2,7],[0,11],[2,14],[4,16]]]},{"l":-7,"r":7,"p":[[[-4,-16],[-2,-14],[0,-11],[2,-7],[3,-2],[3,2],[2,7],[0,11],[-2,14],[-4,16]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,0]],[[-5,-9],[5,-3]],[[5,-9],[-5,-3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[1,8],[0,9],[-1,8],[0,7],[1,8],[1,10],[0,12],[-1,13]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-11,"r":11,"p":[[[9,-16],[-9,16]]]},{"l":-10,"r":10,"p":[[[-1,-12],[-4,-11],[-6,-8],[-7,-3],[-7,0],[-6,5],[-4,8],[-1,9],[1,9],[4,8],[6,5],[7,0],[7,-3],[6,-8],[4,-11],[1,-12],[-1,-12]]]},{"l":-10,"r":10,"p":[[[-4,-8],[-2,-9],[1,-12],[1,9]]]},{"l":-10,"r":10,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[3,-1],[-7,9],[7,9]]]},{"l":-10,"r":10,"p":[[[-5,-12],[6,-12],[0,-4],[3,-4],[5,-3],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[3,-12],[-7,2],[8,2]],[[3,-12],[3,9]]]},{"l":-10,"r":10,"p":[[[5,-12],[-5,-12],[-6,-3],[-5,-4],[-2,-5],[1,-5],[4,-4],[6,-2],[7,1],[7,3],[6,6],[4,8],[1,9],[-2,9],[-5,8],[-6,7],[-7,5]]]},{"l":-10,"r":10,"p":[[[6,-9],[5,-11],[2,-12],[0,-12],[-3,-11],[-5,-8],[-6,-3],[-6,2],[-5,6],[-3,8],[0,9],[1,9],[4,8],[6,6],[7,3],[7,2],[6,-1],[4,-3],[1,-4],[0,-4],[-3,-3],[-5,-1],[-6,2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-3,9]],[[-7,-12],[7,-12]]]},{"l":-10,"r":10,"p":[[[-2,-12],[-5,-11],[-6,-9],[-6,-7],[-5,-5],[-3,-4],[1,-3],[4,-2],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-6,7],[-7,5],[-7,2],[-6,0],[-4,-2],[-1,-3],[3,-4],[5,-5],[6,-7],[6,-9],[5,-11],[2,-12],[-2,-12]]]},{"l":-10,"r":10,"p":[[[6,-5],[5,-2],[3,0],[0,1],[-1,1],[-4,0],[-6,-2],[-7,-5],[-7,-6],[-6,-9],[-4,-11],[-1,-12],[0,-12],[3,-11],[5,-9],[6,-5],[6,0],[5,5],[3,8],[0,9],[-2,9],[-5,8],[-6,6]]]},{"l":-5,"r":5,"p":[[[0,-5],[-1,-4],[0,-3],[1,-4],[0,-5]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-5,"r":5,"p":[[[0,-5],[-1,-4],[0,-3],[1,-4],[0,-5]],[[1,8],[0,9],[-1,8],[0,7],[1,8],[1,10],[0,12],[-1,13]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-9,"r":9,"p":[[[-6,-7],[-6,-8],[-5,-10],[-4,-11],[-2,-12],[2,-12],[4,-11],[5,-10],[6,-8],[6,-6],[5,-4],[4,-3],[0,-1],[0,2]],[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-9,"r":9,"p":[[[0,-12],[-8,9]],[[0,-12],[8,9]],[[-5,2],[5,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2]],[[-7,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[2,9],[-7,9]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[0,-12],[3,-11],[5,-9],[6,-7],[7,-4],[7,1],[6,4],[5,6],[3,8],[0,9],[-7,9]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]],[[-6,9],[7,9]]]},{"l":-10,"r":8,"p":[[[-6,-12],[-6,9]],[[-6,-12],[7,-12]],[[-6,-2],[2,-2]]]},{"l":-10,"r":11,"p":[[[8,-7],[7,-9],[5,-11],[3,-12],[-1,-12],[-3,-11],[-5,-9],[-6,-7],[-7,-4],[-7,1],[-6,4],[-5,6],[-3,8],[-1,9],[3,9],[5,8],[7,6],[8,4],[8,1]],[[3,1],[8,1]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[7,-12],[7,9]],[[-7,-2],[7,-2]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-8,"r":8,"p":[[[4,-12],[4,4],[3,7],[2,8],[0,9],[-2,9],[-4,8],[-5,7],[-6,4],[-6,2]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[7,-12],[-7,2]],[[-2,-3],[7,9]]]},{"l":-10,"r":7,"p":[[[-6,-12],[-6,9]],[[-6,9],[6,9]]]},{"l":-12,"r":12,"p":[[[-8,-12],[-8,9]],[[-8,-12],[0,9]],[[8,-12],[0,9]],[[8,-12],[8,9]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,9]],[[-7,-12],[7,9]],[[7,-12],[7,9]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-5],[6,-3],[5,-2],[2,-1],[-7,-1]]]},{"l":-11,"r":11,"p":[[[-2,-12],[-4,-11],[-6,-9],[-7,-7],[-8,-4],[-8,1],[-7,4],[-6,6],[-4,8],[-2,9],[2,9],[4,8],[6,6],[7,4],[8,1],[8,-4],[7,-7],[6,-9],[4,-11],[2,-12],[-2,-12]],[[1,5],[7,11]]]},{"l":-11,"r":10,"p":[[[-7,-12],[-7,9]],[[-7,-12],[2,-12],[5,-11],[6,-10],[7,-8],[7,-6],[6,-4],[5,-3],[2,-2],[-7,-2]],[[0,-2],[7,9]]]},{"l":-10,"r":10,"p":[[[7,-9],[5,-11],[2,-12],[-2,-12],[-5,-11],[-7,-9],[-7,-7],[-6,-5],[-5,-4],[-3,-3],[3,-1],[5,0],[6,1],[7,3],[7,6],[5,8],[2,9],[-2,9],[-5,8],[-7,6]]]},{"l":-8,"r":8,"p":[[[0,-12],[0,9]],[[-7,-12],[7,-12]]]},{"l":-11,"r":11,"p":[[[-7,-12],[-7,3],[-6,6],[-4,8],[-1,9],[1,9],[4,8],[6,6],[7,3],[7,-12]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,9]],[[8,-12],[0,9]]]},{"l":-12,"r":12,"p":[[[-10,-12],[-5,9]],[[0,-12],[-5,9]],[[0,-12],[5,9]],[[10,-12],[5,9]]]},{"l":-10,"r":10,"p":[[[-7,-12],[7,9]],[[7,-12],[-7,9]]]},{"l":-9,"r":9,"p":[[[-8,-12],[0,-2],[0,9]],[[8,-12],[0,-2]]]},{"l":-10,"r":10,"p":[[[7,-12],[-7,9]],[[-7,-12],[7,-12]],[[-7,9],[7,9]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[-2,-6],[0,-9],[2,-6]],[[-5,-3],[0,-8],[5,-3]],[[0,-8],[0,9]]]},{"l":-8,"r":8,"p":[[[-8,11],[8,11]]]},{"l":-5,"r":5,"p":[[[1,-12],[0,-11],[-1,-9],[-1,-7],[0,-6],[1,-7],[0,-8]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-10,"r":9,"p":[[[-6,-12],[-6,9]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":9,"p":[[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[6,-12],[6,9]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":9,"p":[[[-6,1],[6,1],[6,-1],[5,-3],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-5,"r":7,"p":[[[5,-12],[3,-12],[1,-11],[0,-8],[0,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,11],[5,14],[4,15],[2,16],[-1,16],[-3,15]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-9,"r":10,"p":[[[-5,-12],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-4,"r":4,"p":[[[-1,-12],[0,-11],[1,-12],[0,-13],[-1,-12]],[[0,-5],[0,9]]]},{"l":-5,"r":5,"p":[[[0,-12],[1,-11],[2,-12],[1,-13],[0,-12]],[[1,-5],[1,12],[0,15],[-2,16],[-4,16]]]},{"l":-9,"r":8,"p":[[[-5,-12],[-5,9]],[[5,-5],[-5,5]],[[-1,1],[6,9]]]},{"l":-4,"r":4,"p":[[[0,-12],[0,9]]]},{"l":-15,"r":15,"p":[[[-11,-5],[-11,9]],[[-11,-1],[-8,-4],[-6,-5],[-3,-5],[-1,-4],[0,-1],[0,9]],[[0,-1],[3,-4],[5,-5],[8,-5],[10,-4],[11,-1],[11,9]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,9]],[[-5,-1],[-2,-4],[0,-5],[3,-5],[5,-4],[6,-1],[6,9]]]},{"l":-9,"r":10,"p":[[[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6],[7,3],[7,1],[6,-2],[4,-4],[2,-5],[-1,-5]]]},{"l":-10,"r":9,"p":[[[-6,-5],[-6,16]],[[-6,-2],[-4,-4],[-2,-5],[1,-5],[3,-4],[5,-2],[6,1],[6,3],[5,6],[3,8],[1,9],[-2,9],[-4,8],[-6,6]]]},{"l":-9,"r":10,"p":[[[6,-5],[6,16]],[[6,-2],[4,-4],[2,-5],[-1,-5],[-3,-4],[-5,-2],[-6,1],[-6,3],[-5,6],[-3,8],[-1,9],[2,9],[4,8],[6,6]]]},{"l":-7,"r":6,"p":[[[-3,-5],[-3,9]],[[-3,1],[-2,-2],[0,-4],[2,-5],[5,-5]]]},{"l":-8,"r":9,"p":[[[6,-2],[5,-4],[2,-5],[-1,-5],[-4,-4],[-5,-2],[-4,0],[-2,1],[3,2],[5,3],[6,5],[6,6],[5,8],[2,9],[-1,9],[-4,8],[-5,6]]]},{"l":-5,"r":7,"p":[[[0,-12],[0,5],[1,8],[3,9],[5,9]],[[-3,-5],[4,-5]]]},{"l":-9,"r":10,"p":[[[-5,-5],[-5,5],[-4,8],[-2,9],[1,9],[3,8],[6,5]],[[6,-5],[6,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9]]]},{"l":-11,"r":11,"p":[[[-8,-5],[-4,9]],[[0,-5],[-4,9]],[[0,-5],[4,9]],[[8,-5],[4,9]]]},{"l":-8,"r":9,"p":[[[-5,-5],[6,9]],[[6,-5],[-5,9]]]},{"l":-8,"r":8,"p":[[[-6,-5],[0,9]],[[6,-5],[0,9],[-2,13],[-4,15],[-6,16],[-7,16]]]},{"l":-8,"r":9,"p":[[[6,-5],[-5,9]],[[-5,-5],[6,-5]],[[-5,9],[6,9]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-7,"r":7,"p":[[[-1,-12],[-3,-11],[-4,-9],[-4,-7],[-3,-5],[-1,-4],[1,-4],[3,-5],[4,-7],[4,-9],[3,-11],[1,-12],[-1,-12]]]}],"scripts":[{"l":-8,"r":8,"p":[]},{"l":-5,"r":6,"p":[[[3,-12],[2,-11],[0,1]],[[3,-11],[0,1]],[[3,-12],[4,-11],[0,1]],[[-2,7],[-3,8],[-2,9],[-1,8],[-2,7]]]},{"l":-9,"r":9,"p":[[[-2,-12],[-4,-5]],[[-1,-12],[-4,-5]],[[7,-12],[5,-5]],[[8,-12],[5,-5]]]},{"l":-10,"r":11,"p":[[[1,-16],[-6,16]],[[7,-16],[0,16]],[[-6,-3],[8,-3]],[[-7,3],[7,3]]]},{"l":-10,"r":11,"p":[[[2,-16],[-6,13]],[[7,-16],[-1,13]],[[8,-8],[7,-7],[8,-6],[9,-7],[9,-8],[8,-10],[7,-11],[4,-12],[0,-12],[-3,-11],[-5,-9],[-5,-7],[-4,-5],[-3,-4],[4,0],[6,2]],[[-5,-7],[-3,-5],[4,-1],[5,0],[6,2],[6,5],[5,7],[4,8],[1,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]]]},{"l":-12,"r":12,"p":[[[9,-12],[-9,9]],[[-4,-12],[-2,-10],[-2,-8],[-3,-6],[-5,-5],[-7,-5],[-9,-7],[-9,-9],[-8,-11],[-6,-12],[-4,-12],[-2,-11],[1,-10],[4,-10],[7,-11],[9,-12]],[[5,2],[3,3],[2,5],[2,7],[4,9],[6,9],[8,8],[9,6],[9,4],[7,2],[5,2]]]},{"l":-13,"r":13,"p":[[[10,-4],[9,-3],[10,-2],[11,-3],[11,-4],[10,-5],[9,-5],[7,-4],[5,-2],[0,6],[-2,8],[-4,9],[-7,9],[-10,8],[-11,6],[-11,4],[-10,2],[-9,1],[-7,0],[-2,-2],[0,-3],[2,-5],[3,-7],[3,-9],[2,-11],[0,-12],[-2,-11],[-3,-9],[-3,-6],[-2,0],[-1,3],[1,6],[3,8],[5,9],[7,9],[8,7],[8,6]],[[-7,9],[-9,8],[-10,6],[-10,4],[-9,2],[-8,1],[-2,-2]],[[-3,-6],[-2,-1],[-1,2],[1,5],[3,7],[5,8],[7,8],[8,7]]]},{"l":-5,"r":6,"p":[[[3,-10],[2,-11],[3,-12],[4,-11],[4,-10],[3,-8],[1,-6]]]},{"l":-7,"r":8,"p":[[[8,-16],[4,-13],[1,-10],[-1,-7],[-3,-3],[-4,2],[-4,6],[-3,11],[-2,14],[-1,16]],[[4,-13],[1,-9],[-1,-5],[-2,-2],[-3,3],[-3,8],[-2,13],[-1,16]]]},{"l":-8,"r":7,"p":[[[1,-16],[2,-14],[3,-11],[4,-6],[4,-2],[3,3],[1,7],[-1,10],[-4,13],[-8,16]],[[1,-16],[2,-13],[3,-8],[3,-3],[2,2],[1,5],[-1,9],[-4,13]]]},{"l":-8,"r":9,"p":[[[2,-12],[2,0]],[[-3,-9],[7,-3]],[[7,-9],[-3,-3]]]},{"l":-13,"r":13,"p":[[[0,-9],[0,9]],[[-9,0],[9,0]]]},{"l":-5,"r":6,"p":[[[-2,9],[-3,8],[-2,7],[-1,8],[-1,9],[-2,11],[-4,13]]]},{"l":-13,"r":13,"p":[[[-9,0],[9,0]]]},{"l":-5,"r":5,"p":[[[0,7],[-1,8],[0,9],[1,8],[0,7]]]},{"l":-11,"r":11,"p":[[[13,-16],[-13,16]]]},{"l":-10,"r":11,"p":[[[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-3],[-7,1],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[6,3],[7,0],[8,-4],[8,-7],[7,-10],[6,-11],[4,-12],[2,-12]],[[2,-12],[0,-11],[-2,-9],[-4,-6],[-5,-3],[-6,1],[-6,4],[-5,7],[-3,9]],[[-1,9],[1,8],[3,6],[5,3],[6,0],[7,-4],[7,-7],[6,-10],[4,-12]]]},{"l":-10,"r":11,"p":[[[2,-8],[-3,9]],[[4,-12],[-2,9]],[[4,-12],[1,-9],[-2,-7],[-4,-6]],[[3,-9],[-1,-7],[-4,-6]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[4,-12],[7,-11],[8,-9],[8,-7],[7,-5],[5,-3],[2,-1],[-2,1],[-5,3],[-7,5],[-9,9]],[[4,-12],[6,-11],[7,-9],[7,-7],[6,-5],[4,-3],[-2,1]],[[-8,7],[-7,6],[-5,6],[0,8],[3,8],[5,7],[6,5]],[[-5,6],[0,9],[3,9],[5,8],[6,5]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[4,-12],[7,-11],[8,-9],[8,-7],[7,-5],[4,-3],[1,-2]],[[4,-12],[6,-11],[7,-9],[7,-7],[6,-5],[4,-3]],[[-1,-2],[1,-2],[4,-1],[5,0],[6,2],[6,5],[5,7],[4,8],[1,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]],[[1,-2],[3,-1],[4,0],[5,2],[5,5],[4,7],[3,8],[1,9]]]},{"l":-10,"r":11,"p":[[[6,-11],[0,9]],[[7,-12],[1,9]],[[7,-12],[-8,3],[8,3]]]},{"l":-10,"r":11,"p":[[[-1,-12],[-6,-2]],[[-1,-12],[9,-12]],[[-1,-11],[4,-11],[9,-12]],[[-6,-2],[-5,-3],[-2,-4],[1,-4],[4,-3],[5,-2],[6,0],[6,3],[5,6],[3,8],[0,9],[-3,9],[-6,8],[-7,7],[-8,5],[-8,4],[-7,3],[-6,4],[-7,5]],[[1,-4],[3,-3],[4,-2],[5,0],[5,3],[4,6],[2,8],[0,9]]]},{"l":-10,"r":11,"p":[[[7,-9],[6,-8],[7,-7],[8,-8],[8,-9],[7,-11],[5,-12],[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-3],[-7,1],[-7,5],[-6,7],[-5,8],[-3,9],[0,9],[3,8],[5,6],[6,4],[6,1],[5,-1],[4,-2],[2,-3],[-1,-3],[-3,-2],[-5,0],[-6,2]],[[2,-12],[0,-11],[-2,-9],[-4,-6],[-5,-3],[-6,1],[-6,6],[-5,8]],[[0,9],[2,8],[4,6],[5,4],[5,0],[4,-2]]]},{"l":-10,"r":11,"p":[[[-4,-12],[-6,-6]],[[9,-12],[8,-9],[6,-6],[1,0],[-1,3],[-2,5],[-3,9]],[[6,-6],[0,0],[-2,3],[-3,5],[-4,9]],[[-5,-9],[-2,-12],[0,-12],[5,-9]],[[-4,-10],[-2,-11],[0,-11],[5,-9],[7,-9],[8,-10],[9,-12]]]},{"l":-10,"r":11,"p":[[[1,-12],[-2,-11],[-3,-10],[-4,-8],[-4,-5],[-3,-3],[-1,-2],[2,-2],[6,-3],[7,-4],[8,-6],[8,-9],[7,-11],[4,-12],[1,-12]],[[1,-12],[-1,-11],[-2,-10],[-3,-8],[-3,-5],[-2,-3],[-1,-2]],[[2,-2],[5,-3],[6,-4],[7,-6],[7,-9],[6,-11],[4,-12]],[[-1,-2],[-5,-1],[-7,1],[-8,3],[-8,6],[-7,8],[-4,9],[0,9],[4,8],[5,7],[6,5],[6,2],[5,0],[4,-1],[2,-2]],[[-1,-2],[-4,-1],[-6,1],[-7,3],[-7,6],[-6,8],[-4,9]],[[0,9],[3,8],[4,7],[5,5],[5,1],[4,-1]]]},{"l":-10,"r":11,"p":[[[7,-5],[6,-3],[4,-1],[2,0],[-1,0],[-3,-1],[-4,-2],[-5,-4],[-5,-7],[-4,-9],[-2,-11],[1,-12],[4,-12],[6,-11],[7,-10],[8,-8],[8,-4],[7,0],[6,3],[4,6],[2,8],[-1,9],[-4,9],[-6,8],[-7,6],[-7,5],[-6,4],[-5,5],[-6,6]],[[-3,-1],[-4,-3],[-4,-7],[-3,-9],[-1,-11],[1,-12]],[[6,-11],[7,-9],[7,-4],[6,0],[5,3],[3,6],[1,8],[-1,9]]]},{"l":-5,"r":6,"p":[[[1,-5],[0,-4],[1,-3],[2,-4],[1,-5]],[[-2,7],[-3,8],[-2,9],[-1,8]]]},{"l":-5,"r":6,"p":[[[1,-5],[0,-4],[1,-3],[2,-4],[1,-5]],[[-2,9],[-3,8],[-2,7],[-1,8],[-1,9],[-2,11],[-4,13]]]},{"l":-12,"r":12,"p":[[[8,-9],[-8,0],[8,9]]]},{"l":-13,"r":13,"p":[[[-9,-3],[9,-3]],[[-9,3],[9,3]]]},{"l":-12,"r":12,"p":[[[-8,-9],[8,0],[-8,9]]]},{"l":-10,"r":11,"p":[[[-3,-8],[-2,-7],[-3,-6],[-4,-7],[-4,-8],[-3,-10],[-2,-11],[1,-12],[5,-12],[8,-11],[9,-9],[9,-7],[8,-5],[7,-4],[1,-2],[-1,-1],[-1,1],[0,2],[2,2]],[[5,-12],[7,-11],[8,-9],[8,-7],[7,-5],[6,-4],[4,-3]],[[-2,7],[-3,8],[-2,9],[-1,8],[-2,7]]]},{"l":-13,"r":14,"p":[[[5,-4],[4,-6],[2,-7],[-1,-7],[-3,-6],[-4,-5],[-5,-2],[-5,1],[-4,3],[-2,4],[1,4],[3,3],[4,1]],[[-1,-7],[-3,-5],[-4,-2],[-4,1],[-3,3],[-2,4]],[[5,-7],[4,1],[4,3],[6,4],[8,4],[10,2],[11,-1],[11,-3],[10,-6],[9,-8],[7,-10],[5,-11],[2,-12],[-1,-12],[-4,-11],[-6,-10],[-8,-8],[-9,-6],[-10,-3],[-10,0],[-9,3],[-8,5],[-6,7],[-4,8],[-1,9],[2,9],[5,8],[7,7],[8,6]],[[6,-7],[5,1],[5,3],[6,4]]]},{"l":-11,"r":9,"p":[[[-11,9],[-9,8],[-6,5],[-3,1],[1,-6],[4,-12],[4,9],[3,6],[1,3],[-1,1],[-4,-1],[-6,-1],[-7,0],[-7,2],[-6,4],[-4,6],[-1,8],[2,9],[7,9]]]},{"l":-12,"r":11,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[6,-12],[8,-11],[9,-9],[9,-7],[8,-5],[7,-4],[5,-3],[2,-2]],[[1,-2],[2,-2],[5,-1],[6,0],[7,2],[7,5],[6,7],[5,8],[3,9],[0,9],[-2,8],[-3,6]]]},{"l":-10,"r":10,"p":[[[2,-6],[2,-5],[3,-4],[5,-4],[7,-5],[8,-7],[8,-9],[7,-11],[5,-12],[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-4],[-7,0],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[5,4]]]},{"l":-11,"r":12,"p":[[[2,-12],[0,-11],[-1,-9],[-2,-5],[-3,1],[-4,4],[-5,6],[-7,8],[-9,9],[-11,9],[-12,8],[-12,6],[-11,5],[-9,5],[-7,6],[-5,8],[-2,9],[1,9],[4,8],[6,6],[8,2],[9,-3],[9,-7],[8,-10],[7,-11],[5,-12],[2,-12],[0,-10],[0,-8],[1,-5],[3,-2],[5,0],[8,2],[10,3]]]},{"l":-10,"r":10,"p":[[[4,-8],[4,-7],[5,-6],[7,-6],[8,-7],[8,-9],[7,-11],[4,-12],[0,-12],[-3,-11],[-4,-9],[-4,-6],[-3,-4],[-2,-3],[1,-2],[-2,-2],[-5,-1],[-6,0],[-7,2],[-7,5],[-6,7],[-5,8],[-2,9],[1,9],[4,8],[6,6],[7,4]]]},{"l":-10,"r":10,"p":[[[0,-6],[-2,-6],[-4,-7],[-5,-9],[-4,-11],[-1,-12],[2,-12],[6,-11],[9,-11],[11,-12]],[[6,-11],[4,-4],[2,2],[0,6],[-2,8],[-4,9],[-6,9],[-8,8],[-9,6],[-9,4],[-8,3],[-6,3],[-4,4]],[[-1,-2],[8,-2]]]},{"l":-11,"r":12,"p":[[[-11,9],[-9,8],[-5,4],[-2,-1],[-1,-4],[0,-8],[0,-11],[-1,-12],[-2,-12],[-3,-11],[-4,-9],[-4,-6],[-3,-4],[-1,-3],[3,-3],[6,-4],[7,-5],[8,-7],[8,-1],[7,4],[6,6],[4,8],[1,9],[-3,9],[-6,8],[-8,6],[-9,4],[-9,2]]]},{"l":-12,"r":12,"p":[[[-5,-5],[-7,-6],[-8,-8],[-8,-9],[-7,-11],[-5,-12],[-4,-12],[-2,-11],[-1,-9],[-1,-7],[-2,-3],[-4,3],[-6,7],[-8,9],[-10,9],[-11,8],[-11,6]],[[-5,0],[4,-3],[6,-4],[9,-6],[11,-8],[12,-10],[12,-11],[11,-12],[10,-12],[8,-10],[6,-6],[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-9,"r":8,"p":[[[5,4],[3,2],[1,-1],[0,-3],[-1,-6],[-1,-9],[0,-11],[1,-12],[3,-12],[4,-11],[5,-9],[5,-6],[4,-1],[2,4],[1,6],[-1,8],[-3,9],[-5,9],[-7,8],[-8,6],[-8,4],[-7,3],[-5,3],[-3,4]]]},{"l":-8,"r":7,"p":[[[2,12],[0,9],[-2,4],[-3,-2],[-3,-8],[-2,-11],[0,-12],[2,-12],[3,-11],[4,-8],[4,-5],[3,0],[0,9],[-2,15],[-3,18],[-4,20],[-6,21],[-7,20],[-7,18],[-6,15],[-4,12],[-2,10],[1,8],[5,6]]]},{"l":-12,"r":12,"p":[[[-5,-5],[-7,-6],[-8,-8],[-8,-9],[-7,-11],[-5,-12],[-4,-12],[-2,-11],[-1,-9],[-1,-7],[-2,-3],[-4,3],[-6,7],[-8,9],[-10,9],[-11,8],[-11,6]],[[12,-9],[12,-11],[11,-12],[10,-12],[8,-11],[6,-9],[4,-6],[2,-4],[0,-3],[-2,-3]],[[0,-3],[1,-1],[1,6],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-9,"r":10,"p":[[[-5,0],[-3,0],[1,-1],[4,-3],[6,-5],[7,-7],[7,-10],[6,-12],[4,-12],[3,-11],[2,-9],[1,-4],[0,1],[-1,4],[-2,6],[-4,8],[-6,9],[-8,9],[-9,8],[-9,6],[-8,5],[-6,5],[-4,6],[-1,8],[2,9],[4,9],[7,8],[9,6]]]},{"l":-18,"r":15,"p":[[[-13,-5],[-15,-6],[-16,-8],[-16,-9],[-15,-11],[-13,-12],[-12,-12],[-10,-11],[-9,-9],[-9,-7],[-10,-2],[-11,2],[-13,9]],[[-11,2],[-8,-6],[-6,-10],[-5,-11],[-3,-12],[-2,-12],[0,-11],[1,-9],[1,-7],[0,-2],[-1,2],[-3,9]],[[-1,2],[2,-6],[4,-10],[5,-11],[7,-12],[8,-12],[10,-11],[11,-9],[11,-7],[10,-2],[8,5],[8,8],[9,9],[10,9],[12,8],[13,7],[15,4]]]},{"l":-13,"r":11,"p":[[[-8,-5],[-10,-6],[-11,-8],[-11,-9],[-10,-11],[-8,-12],[-7,-12],[-5,-11],[-4,-9],[-4,-7],[-5,-2],[-6,2],[-8,9]],[[-6,2],[-3,-6],[-1,-10],[0,-11],[2,-12],[4,-12],[6,-11],[7,-9],[7,-7],[6,-2],[4,5],[4,8],[5,9],[6,9],[8,8],[9,7],[11,4]]]},{"l":-10,"r":11,"p":[[[2,-12],[-1,-11],[-3,-9],[-5,-6],[-6,-4],[-7,0],[-7,4],[-6,7],[-5,8],[-3,9],[-1,9],[2,8],[4,6],[6,3],[7,1],[8,-3],[8,-7],[7,-10],[6,-11],[4,-12],[2,-12],[0,-10],[0,-7],[1,-4],[3,-1],[5,1],[8,3],[10,4]]]},{"l":-12,"r":13,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[8,-12],[10,-11],[11,-10],[12,-8],[12,-5],[11,-3],[10,-2],[8,-1],[5,-1],[3,-2],[2,-3]]]},{"l":-10,"r":12,"p":[[[3,-6],[2,-4],[1,-3],[-1,-2],[-3,-2],[-4,-4],[-4,-6],[-3,-9],[-1,-11],[2,-12],[5,-12],[7,-11],[8,-9],[8,-5],[7,-2],[5,1],[1,5],[-2,7],[-4,8],[-7,9],[-9,9],[-10,8],[-10,6],[-9,5],[-7,5],[-5,6],[-2,8],[1,9],[4,9],[7,8],[9,6]]]},{"l":-12,"r":13,"p":[[[1,-10],[2,-9],[2,-6],[1,-2],[0,1],[-1,3],[-3,6],[-5,8],[-7,9],[-8,9],[-9,8],[-9,5],[-8,0],[-7,-3],[-6,-5],[-4,-8],[-2,-10],[0,-11],[3,-12],[7,-12],[9,-11],[10,-10],[11,-8],[11,-5],[10,-3],[9,-2],[7,-1],[4,-1],[1,-2],[2,-1],[3,1],[3,6],[4,8],[6,9],[8,8],[9,7],[11,4]]]},{"l":-10,"r":10,"p":[[[-10,9],[-8,8],[-6,6],[-3,2],[-1,-1],[1,-5],[2,-8],[2,-11],[1,-12],[0,-12],[-1,-11],[-2,-9],[-2,-7],[-1,-5],[1,-3],[4,-1],[6,1],[7,3],[7,5],[6,7],[5,8],[2,9],[-2,9],[-5,8],[-7,6],[-8,4],[-8,2]]]},{"l":-10,"r":9,"p":[[[0,-6],[-2,-6],[-4,-7],[-5,-9],[-4,-11],[-1,-12],[2,-12],[6,-11],[9,-11],[11,-12]],[[6,-11],[4,-4],[2,2],[0,6],[-2,8],[-4,9],[-6,9],[-8,8],[-9,6],[-9,4],[-8,3],[-6,3],[-4,4]]]},{"l":-13,"r":11,"p":[[[-8,-5],[-10,-6],[-11,-8],[-11,-9],[-10,-11],[-8,-12],[-7,-12],[-5,-11],[-4,-9],[-4,-7],[-5,-3],[-6,0],[-7,4],[-7,6],[-6,8],[-4,9],[-2,9],[0,8],[1,7],[3,3],[6,-5],[8,-12]],[[6,-5],[5,-1],[4,5],[4,8],[5,9],[6,9],[8,8],[9,7],[11,4]]]},{"l":-12,"r":11,"p":[[[-7,-5],[-9,-6],[-10,-8],[-10,-9],[-9,-11],[-7,-12],[-6,-12],[-4,-11],[-3,-9],[-3,-7],[-4,-3],[-5,0],[-6,4],[-6,7],[-5,9],[-3,9],[-1,8],[2,5],[4,2],[6,-2],[7,-5],[8,-9],[8,-11],[7,-12],[6,-12],[5,-11],[4,-9],[4,-7],[5,-4],[7,-2],[9,-1]]]},{"l":-15,"r":13,"p":[[[-10,-5],[-12,-6],[-13,-8],[-13,-9],[-12,-11],[-10,-12],[-9,-12],[-7,-11],[-6,-9],[-6,-6],[-7,9]],[[3,-12],[-7,9]],[[3,-12],[1,9]],[[15,-12],[13,-11],[10,-8],[7,-4],[4,2],[1,9]]]},{"l":-12,"r":12,"p":[[[-4,-6],[-6,-6],[-7,-7],[-7,-9],[-6,-11],[-4,-12],[-2,-12],[0,-11],[1,-9],[1,-6],[-1,3],[-1,6],[0,8],[2,9],[4,9],[6,8],[7,6],[7,4],[6,3],[4,3]],[[11,-9],[11,-11],[10,-12],[8,-12],[6,-11],[4,-9],[2,-6],[-2,3],[-4,6],[-6,8],[-8,9],[-10,9],[-11,8],[-11,6]]]},{"l":-12,"r":11,"p":[[[-7,-5],[-9,-6],[-10,-8],[-10,-9],[-9,-11],[-7,-12],[-6,-12],[-4,-11],[-3,-9],[-3,-7],[-4,-3],[-5,0],[-6,4],[-6,6],[-5,8],[-4,9],[-2,9],[0,8],[2,6],[4,3],[5,1],[7,-5]],[[9,-12],[7,-5],[4,5],[2,11],[0,16],[-2,20],[-4,21],[-5,20],[-5,18],[-4,15],[-2,12],[1,9],[4,7],[9,4]]]},{"l":-10,"r":11,"p":[[[3,-6],[2,-4],[1,-3],[-1,-2],[-3,-2],[-4,-4],[-4,-6],[-3,-9],[-1,-11],[2,-12],[5,-12],[7,-11],[8,-9],[8,-5],[7,-2],[5,2],[2,5],[-2,8],[-4,9],[-7,9],[-8,8],[-8,6],[-7,5],[-4,5],[-2,6],[-1,7],[0,9],[0,12],[-1,15],[-2,17],[-4,20],[-6,21],[-7,20],[-7,18],[-6,15],[-4,12],[-1,9],[2,7],[8,4]]]},{"l":-7,"r":7,"p":[[[-3,-16],[-3,16]],[[-2,-16],[-2,16]],[[-3,-16],[4,-16]],[[-3,16],[4,16]]]},{"l":-7,"r":7,"p":[[[-7,-12],[7,12]]]},{"l":-7,"r":7,"p":[[[2,-16],[2,16]],[[3,-16],[3,16]],[[-4,-16],[3,-16]],[[-4,16],[3,16]]]},{"l":-8,"r":8,"p":[[[-2,-6],[0,-9],[2,-6]],[[-5,-3],[0,-8],[5,-3]],[[0,-8],[0,9]]]},{"l":-8,"r":8,"p":[[[-8,11],[8,11]]]},{"l":-5,"r":6,"p":[[[4,-12],[2,-10],[1,-8],[1,-7],[2,-6],[3,-7],[2,-8]]]},{"l":-6,"r":10,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,6],[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-5,"r":9,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,2],[-4,8],[-3,9],[-2,9],[0,8],[2,6],[3,3],[3,0],[4,4],[5,5],[7,5],[9,4]]]},{"l":-5,"r":6,"p":[[[2,2],[2,1],[1,0],[-1,0],[-3,1],[-4,2],[-5,4],[-5,6],[-4,8],[-2,9],[1,9],[4,7],[6,4]]]},{"l":-6,"r":10,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,6],[8,-12]],[[4,0],[3,5],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-4,"r":6,"p":[[[-3,7],[-1,6],[0,5],[1,3],[1,1],[0,0],[-1,0],[-3,1],[-4,3],[-4,6],[-3,8],[-1,9],[1,9],[3,8],[4,7],[6,4]]]},{"l":-3,"r":5,"p":[[[-3,4],[1,-1],[3,-4],[4,-6],[5,-9],[5,-11],[4,-12],[2,-11],[1,-9],[-1,-1],[-4,8],[-7,15],[-8,18],[-8,20],[-7,21],[-5,20],[-4,17],[-3,8],[-2,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-6,"r":9,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,7]],[[4,0],[2,7],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[3,9],[6,7],[9,4]]]},{"l":-5,"r":10,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,1],[-5,9]],[[-5,9],[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[3,6],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-2,"r":5,"p":[[[1,-5],[1,-4],[2,-4],[2,-5],[1,-5]],[[-2,4],[0,0],[-2,6],[-2,8],[-1,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-2,"r":5,"p":[[[1,-5],[1,-4],[2,-4],[2,-5],[1,-5]],[[-2,4],[0,0],[-6,18],[-7,20],[-9,21],[-10,20],[-10,18],[-9,15],[-6,12],[-3,10],[-1,9],[2,7],[5,4]]]},{"l":-5,"r":9,"p":[[[-5,4],[-3,1],[0,-4],[1,-6],[2,-9],[2,-11],[1,-12],[-1,-11],[-2,-9],[-3,-5],[-4,1],[-5,9]],[[-5,9],[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[2,4],[-1,4]],[[-1,4],[1,5],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-3,"r":5,"p":[[[-3,4],[-1,1],[2,-4],[3,-6],[4,-9],[4,-11],[3,-12],[1,-11],[0,-9],[-1,-5],[-2,2],[-2,8],[-1,9],[0,9],[2,8],[3,7],[5,4]]]},{"l":-13,"r":12,"p":[[[-13,4],[-11,1],[-9,0],[-8,1],[-8,2],[-9,6],[-10,9]],[[-9,6],[-8,4],[-6,1],[-4,0],[-2,0],[-1,1],[-1,2],[-2,6],[-3,9]],[[-2,6],[-1,4],[1,1],[3,0],[5,0],[6,1],[6,3],[5,6],[5,8],[6,9],[7,9],[9,8],[10,7],[12,4]]]},{"l":-8,"r":10,"p":[[[-8,4],[-6,1],[-4,0],[-3,1],[-3,2],[-4,6],[-5,9]],[[-4,6],[-3,4],[-1,1],[1,0],[3,0],[4,1],[4,3],[3,6],[3,8],[4,9],[5,9],[7,8],[8,7],[10,4]]]},{"l":-6,"r":8,"p":[[[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8],[2,7],[3,5],[3,3],[2,1],[0,0],[-1,1],[-1,3],[0,5],[2,6],[5,6],[7,5],[8,4]]]},{"l":-7,"r":8,"p":[[[-7,4],[-5,1],[-4,-1],[-5,3],[-11,21]],[[-5,3],[-4,1],[-2,0],[0,0],[2,1],[3,3],[3,5],[2,7],[1,8],[-1,9]],[[-5,8],[-3,9],[0,9],[3,8],[5,7],[8,4]]]},{"l":-6,"r":9,"p":[[[3,3],[2,1],[0,0],[-2,0],[-4,1],[-5,2],[-6,4],[-6,6],[-5,8],[-3,9],[-1,9],[1,8]],[[4,0],[3,3],[1,8],[-2,15],[-3,18],[-3,20],[-2,21],[0,20],[1,17],[1,10],[3,9],[6,7],[9,4]]]},{"l":-5,"r":8,"p":[[[-5,4],[-3,1],[-2,-1],[-2,1],[1,1],[2,2],[2,4],[1,7],[1,8],[2,9],[3,9],[5,8],[6,7],[8,4]]]},{"l":-4,"r":7,"p":[[[-4,4],[-2,1],[-1,-1],[-1,1],[1,4],[2,6],[2,8],[0,9]],[[-4,8],[-2,9],[2,9],[4,8],[5,7],[7,4]]]},{"l":-3,"r":6,"p":[[[-3,4],[-1,1],[1,-3]],[[4,-12],[-2,6],[-2,8],[-1,9],[1,9],[3,8],[4,7],[6,4]],[[-2,-4],[5,-4]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-6,6],[-6,8],[-5,9],[-3,9],[-1,8],[1,6],[3,3]],[[4,0],[2,6],[2,8],[3,9],[4,9],[6,8],[7,7],[9,4]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-5,5],[-5,8],[-4,9],[-3,9],[0,8],[2,6],[3,3],[3,0]],[[3,0],[4,4],[5,5],[7,5],[9,4]]]},{"l":-9,"r":12,"p":[[[-6,0],[-8,2],[-9,5],[-9,7],[-8,9],[-6,9],[-4,8],[-2,6]],[[0,0],[-2,6],[-2,8],[-1,9],[1,9],[3,8],[5,6],[6,3],[6,0]],[[6,0],[7,4],[8,5],[10,5],[12,4]]]},{"l":-8,"r":8,"p":[[[-8,4],[-6,1],[-4,0],[-2,0],[-1,1],[-1,8],[0,9],[3,9],[6,7],[8,4]],[[5,1],[4,0],[2,0],[1,1],[-3,8],[-4,9],[-6,9],[-7,8]]]},{"l":-6,"r":9,"p":[[[-6,4],[-4,0],[-6,6],[-6,8],[-5,9],[-3,9],[-1,8],[1,6],[3,3]],[[4,0],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[3,9],[6,7],[9,4]]]},{"l":-6,"r":8,"p":[[[-6,4],[-4,1],[-2,0],[0,0],[2,2],[2,4],[1,6],[-1,8],[-4,9],[-2,10],[-1,12],[-1,15],[-2,18],[-3,20],[-5,21],[-6,20],[-6,18],[-5,15],[-2,12],[1,10],[5,7],[8,4]]]},{"l":-7,"r":7,"p":[[[2,-16],[0,-15],[-1,-14],[-2,-12],[-2,-10],[-1,-8],[0,-7],[1,-5],[1,-3],[-1,-1]],[[0,-15],[-1,-13],[-1,-11],[0,-9],[1,-8],[2,-6],[2,-4],[1,-2],[-3,0],[1,2],[2,4],[2,6],[1,8],[0,9],[-1,11],[-1,13],[0,15]],[[-1,1],[1,3],[1,5],[0,7],[-1,8],[-2,10],[-2,12],[-1,14],[0,15],[2,16]]]},{"l":-4,"r":4,"p":[[[0,-16],[0,16]]]},{"l":-7,"r":7,"p":[[[-2,-16],[0,-15],[1,-14],[2,-12],[2,-10],[1,-8],[0,-7],[-1,-5],[-1,-3],[1,-1]],[[0,-15],[1,-13],[1,-11],[0,-9],[-1,-8],[-2,-6],[-2,-4],[-1,-2],[3,0],[-1,2],[-2,4],[-2,6],[-1,8],[0,9],[1,11],[1,13],[0,15]],[[1,1],[-1,3],[-1,5],[0,7],[1,8],[2,10],[2,12],[1,14],[0,15],[-2,16]]]},{"l":-12,"r":12,"p":[[[-9,3],[-9,1],[-8,-2],[-6,-3],[-4,-3],[-2,-2],[2,1],[4,2],[6,2],[8,1],[9,-1]],[[-9,1],[-8,-1],[-6,-2],[-4,-2],[-2,-1],[2,2],[4,3],[6,3],[8,2],[9,-1],[9,-3]]]},{"l":-7,"r":7,"p":[[[-1,-12],[-3,-11],[-4,-9],[-4,-7],[-3,-5],[-1,-4],[1,-4],[3,-5],[4,-7],[4,-9],[3,-11],[1,-12],[-1,-12]]]}]}
timdraw/publish.py added +210 −0
@@ -0,0 +1,210 @@
1 """Maak timdraw.local bereikbaar zolang de server draait.
2
3 Apache op deze machine luistert al op poort 80 en heeft het recht om die poort
4 te binden. Timdraw zet daar een doorverwijzing neer naar zijn eigen poort, en
5 haalt die weg bij het stoppen. De naam zelf wordt via mDNS aangekondigd.
6 timdraw.localhost wijst uit zichzelf naar deze computer, dus die werkt ook
7 zonder extra hosts-regel.
8 """
9
10 from __future__ import annotations
11
12 import subprocess
13 from pathlib import Path
14
15 _APACHE = Path.home() / ".local/state/apache2/httpd.conf"
16 _SNIPPET_DIR = Path.home() / ".local/state/apache2/dynamic"
17 _SNIPPET = _SNIPPET_DIR / "timdraw.conf"
18 _HOSTS = Path("/etc/hosts")
19 _HOSTS_MARK = "# timdraw"
20
21
22 class LocalRoute:
23 def __init__(self, port: int) -> None:
24 self.port = port
25 self.url = f"http://127.0.0.1:{port}/"
26 self._avahi: subprocess.Popen[bytes] | None = None
27 self._hosts_owned = False
28 self._apache = False
29
30 def start(self) -> None:
31 self._hosts_owned = self._add_hosts()
32 self._publish_mdns()
33 self._apache = self._install_apache()
34 if self._apache and (self._hosts_owned or _hosts_has_name()):
35 self.url = "http://timdraw.local/"
36 elif self._apache:
37 self.url = "http://timdraw.localhost/"
38 else:
39 self.url = f"http://127.0.0.1:{self.port}/"
40
41 def stop(self) -> None:
42 self._remove_apache()
43 self._remove_hosts()
44 proc = self._avahi
45 self._avahi = None
46 if proc is not None and proc.poll() is None:
47 proc.terminate()
48 try:
49 proc.wait(timeout=2)
50 except subprocess.TimeoutExpired:
51 proc.kill()
52
53 def _publish_mdns(self) -> None:
54 try:
55 self._avahi = subprocess.Popen(
56 ["avahi-publish-address", "-R", "timdraw.local", "127.0.0.1"],
57 stdout=subprocess.DEVNULL,
58 stderr=subprocess.DEVNULL,
59 )
60 except OSError as exc:
61 print(f"mDNS niet gestart: {exc}")
62
63 def _add_hosts(self) -> bool:
64 try:
65 text = _HOSTS.read_text(encoding="utf-8")
66 except OSError:
67 return False
68 if _hosts_has_name(text):
69 return False
70 line = f"127.0.0.1\ttimdraw.local {_HOSTS_MARK}\n"
71 try:
72 with _HOSTS.open("a", encoding="utf-8") as handle:
73 if text and not text.endswith("\n"):
74 handle.write("\n")
75 handle.write(line)
76 except OSError:
77 return False
78 return True
79
80 def _remove_hosts(self) -> None:
81 if not self._hosts_owned:
82 return
83 try:
84 lines = _HOSTS.read_text(encoding="utf-8").splitlines(keepends=True)
85 kept = [line for line in lines if _HOSTS_MARK not in line]
86 _HOSTS.write_text("".join(kept), encoding="utf-8")
87 except OSError:
88 pass
89 self._hosts_owned = False
90
91 def _install_apache(self) -> bool:
92 if not _APACHE.is_file():
93 return False
94 try:
95 original = _APACHE.read_text(encoding="utf-8")
96 except OSError as exc:
97 print(f"Apache-config niet gelezen: {exc}")
98 return False
99 if "127.0.0.1:80" not in original and "\nListen 80" not in original:
100 return False
101 _SNIPPET_DIR.mkdir(parents=True, exist_ok=True)
102 updated, added_module = _with_modules(original)
103 if updated != original:
104 try:
105 _APACHE.write_text(updated, encoding="utf-8")
106 except OSError as exc:
107 print(f"Apache-config niet geschreven: {exc}")
108 return False
109 if not _apache_ok():
110 _APACHE.write_text(original, encoding="utf-8")
111 print("Apache-config geweigerd, origineel teruggezet.")
112 return False
113 try:
114 _SNIPPET.write_text(_snippet(self.port), encoding="utf-8")
115 except OSError as exc:
116 print(f"Doorverwijzing niet geschreven: {exc}")
117 return False
118 if not _apache_ok():
119 _SNIPPET.unlink(missing_ok=True)
120 print("Doorverwijzing geweigerd door Apache.")
121 return False
122 return _apache_reload(hard=added_module)
123
124 def _remove_apache(self) -> None:
125 if not self._apache:
126 return
127 try:
128 _SNIPPET.unlink(missing_ok=True)
129 except OSError:
130 pass
131 _apache_reload(hard=False)
132 self._apache = False
133
134
135 def _hosts_has_name(text: str | None = None) -> bool:
136 try:
137 body = _HOSTS.read_text(encoding="utf-8") if text is None else text
138 except OSError:
139 return False
140 for line in body.splitlines():
141 if line.lstrip().startswith("#"):
142 continue
143 if "timdraw.local" in line.split():
144 return True
145 return False
146
147
148 def _with_modules(text: str) -> tuple[str, bool]:
149 modules = (
150 "LoadModule proxy_http_module /usr/lib/httpd/modules/mod_proxy_http.so\n",
151 "LoadModule rewrite_module /usr/lib/httpd/modules/mod_rewrite.so\n",
152 )
153 include = "IncludeOptional /home/timfa/.local/state/apache2/dynamic/*.conf\n"
154 missing = [line for line in (*modules, include) if line not in text and line.strip() not in text]
155 # De include-regel vergelijken op de directive, niet op een exacte newline.
156 if "IncludeOptional /home/timfa/.local/state/apache2/dynamic/*.conf" in text:
157 missing = [line for line in missing if not line.startswith("IncludeOptional")]
158 if not missing:
159 return text, False
160 addition = "".join(missing)
161 if not text.endswith("\n"):
162 text += "\n"
163 return text + addition, any(line.startswith("LoadModule") for line in missing)
164
165
166 def _snippet(port: int) -> str:
167 return f"""# Aanwezig zolang Timdraw draait. Wordt bij afsluiten verwijderd.
168 ProxyRequests Off
169 ProxyTimeout 180
170 RewriteEngine On
171 RewriteCond %{{HTTP_HOST}} ^timdraw\\.(local|localhost)(?::[0-9]+)?$ [NC]
172 RewriteRule ^ http://127.0.0.1:{port}%{{REQUEST_URI}} [P,L,QSA]
173 """
174
175
176 def _apache_ok() -> bool:
177 try:
178 result = subprocess.run(
179 ["httpd", "-t", "-f", str(_APACHE)],
180 capture_output=True,
181 text=True,
182 timeout=15,
183 )
184 except (OSError, subprocess.TimeoutExpired) as exc:
185 print(f"Apache-test mislukt: {exc}")
186 return False
187 if result.returncode != 0:
188 detail = (result.stderr or result.stdout).strip()
189 print(f"Apache-test: {detail}")
190 return False
191 return True
192
193
194 def _apache_reload(hard: bool) -> bool:
195 flag = "restart" if hard else "graceful"
196 try:
197 result = subprocess.run(
198 ["httpd", "-k", flag, "-f", str(_APACHE)],
199 capture_output=True,
200 text=True,
201 timeout=20,
202 )
203 except (OSError, subprocess.TimeoutExpired) as exc:
204 print(f"Apache niet herladen: {exc}")
205 return False
206 if result.returncode != 0:
207 detail = (result.stderr or result.stdout).strip()
208 print(f"Apache niet herladen: {detail}")
209 return False
210 return True
@@ -0,0 +1,210 @@
1"""Maak timdraw.local bereikbaar zolang de server draait.
2
3Apache op deze machine luistert al op poort 80 en heeft het recht om die poort
4te binden. Timdraw zet daar een doorverwijzing neer naar zijn eigen poort, en
5haalt die weg bij het stoppen. De naam zelf wordt via mDNS aangekondigd.
6timdraw.localhost wijst uit zichzelf naar deze computer, dus die werkt ook
7zonder extra hosts-regel.
8"""
9
10from __future__ import annotations
11
12import subprocess
13from pathlib import Path
14
15_APACHE = Path.home() / ".local/state/apache2/httpd.conf"
16_SNIPPET_DIR = Path.home() / ".local/state/apache2/dynamic"
17_SNIPPET = _SNIPPET_DIR / "timdraw.conf"
18_HOSTS = Path("/etc/hosts")
19_HOSTS_MARK = "# timdraw"
20
21
22class LocalRoute:
23 def __init__(self, port: int) -> None:
24 self.port = port
25 self.url = f"http://127.0.0.1:{port}/"
26 self._avahi: subprocess.Popen[bytes] | None = None
27 self._hosts_owned = False
28 self._apache = False
29
30 def start(self) -> None:
31 self._hosts_owned = self._add_hosts()
32 self._publish_mdns()
33 self._apache = self._install_apache()
34 if self._apache and (self._hosts_owned or _hosts_has_name()):
35 self.url = "http://timdraw.local/"
36 elif self._apache:
37 self.url = "http://timdraw.localhost/"
38 else:
39 self.url = f"http://127.0.0.1:{self.port}/"
40
41 def stop(self) -> None:
42 self._remove_apache()
43 self._remove_hosts()
44 proc = self._avahi
45 self._avahi = None
46 if proc is not None and proc.poll() is None:
47 proc.terminate()
48 try:
49 proc.wait(timeout=2)
50 except subprocess.TimeoutExpired:
51 proc.kill()
52
53 def _publish_mdns(self) -> None:
54 try:
55 self._avahi = subprocess.Popen(
56 ["avahi-publish-address", "-R", "timdraw.local", "127.0.0.1"],
57 stdout=subprocess.DEVNULL,
58 stderr=subprocess.DEVNULL,
59 )
60 except OSError as exc:
61 print(f"mDNS niet gestart: {exc}")
62
63 def _add_hosts(self) -> bool:
64 try:
65 text = _HOSTS.read_text(encoding="utf-8")
66 except OSError:
67 return False
68 if _hosts_has_name(text):
69 return False
70 line = f"127.0.0.1\ttimdraw.local {_HOSTS_MARK}\n"
71 try:
72 with _HOSTS.open("a", encoding="utf-8") as handle:
73 if text and not text.endswith("\n"):
74 handle.write("\n")
75 handle.write(line)
76 except OSError:
77 return False
78 return True
79
80 def _remove_hosts(self) -> None:
81 if not self._hosts_owned:
82 return
83 try:
84 lines = _HOSTS.read_text(encoding="utf-8").splitlines(keepends=True)
85 kept = [line for line in lines if _HOSTS_MARK not in line]
86 _HOSTS.write_text("".join(kept), encoding="utf-8")
87 except OSError:
88 pass
89 self._hosts_owned = False
90
91 def _install_apache(self) -> bool:
92 if not _APACHE.is_file():
93 return False
94 try:
95 original = _APACHE.read_text(encoding="utf-8")
96 except OSError as exc:
97 print(f"Apache-config niet gelezen: {exc}")
98 return False
99 if "127.0.0.1:80" not in original and "\nListen 80" not in original:
100 return False
101 _SNIPPET_DIR.mkdir(parents=True, exist_ok=True)
102 updated, added_module = _with_modules(original)
103 if updated != original:
104 try:
105 _APACHE.write_text(updated, encoding="utf-8")
106 except OSError as exc:
107 print(f"Apache-config niet geschreven: {exc}")
108 return False
109 if not _apache_ok():
110 _APACHE.write_text(original, encoding="utf-8")
111 print("Apache-config geweigerd, origineel teruggezet.")
112 return False
113 try:
114 _SNIPPET.write_text(_snippet(self.port), encoding="utf-8")
115 except OSError as exc:
116 print(f"Doorverwijzing niet geschreven: {exc}")
117 return False
118 if not _apache_ok():
119 _SNIPPET.unlink(missing_ok=True)
120 print("Doorverwijzing geweigerd door Apache.")
121 return False
122 return _apache_reload(hard=added_module)
123
124 def _remove_apache(self) -> None:
125 if not self._apache:
126 return
127 try:
128 _SNIPPET.unlink(missing_ok=True)
129 except OSError:
130 pass
131 _apache_reload(hard=False)
132 self._apache = False
133
134
135def _hosts_has_name(text: str | None = None) -> bool:
136 try:
137 body = _HOSTS.read_text(encoding="utf-8") if text is None else text
138 except OSError:
139 return False
140 for line in body.splitlines():
141 if line.lstrip().startswith("#"):
142 continue
143 if "timdraw.local" in line.split():
144 return True
145 return False
146
147
148def _with_modules(text: str) -> tuple[str, bool]:
149 modules = (
150 "LoadModule proxy_http_module /usr/lib/httpd/modules/mod_proxy_http.so\n",
151 "LoadModule rewrite_module /usr/lib/httpd/modules/mod_rewrite.so\n",
152 )
153 include = "IncludeOptional /home/timfa/.local/state/apache2/dynamic/*.conf\n"
154 missing = [line for line in (*modules, include) if line not in text and line.strip() not in text]
155 # De include-regel vergelijken op de directive, niet op een exacte newline.
156 if "IncludeOptional /home/timfa/.local/state/apache2/dynamic/*.conf" in text:
157 missing = [line for line in missing if not line.startswith("IncludeOptional")]
158 if not missing:
159 return text, False
160 addition = "".join(missing)
161 if not text.endswith("\n"):
162 text += "\n"
163 return text + addition, any(line.startswith("LoadModule") for line in missing)
164
165
166def _snippet(port: int) -> str:
167 return f"""# Aanwezig zolang Timdraw draait. Wordt bij afsluiten verwijderd.
168ProxyRequests Off
169ProxyTimeout 180
170RewriteEngine On
171RewriteCond %{{HTTP_HOST}} ^timdraw\\.(local|localhost)(?::[0-9]+)?$ [NC]
172RewriteRule ^ http://127.0.0.1:{port}%{{REQUEST_URI}} [P,L,QSA]
173"""
174
175
176def _apache_ok() -> bool:
177 try:
178 result = subprocess.run(
179 ["httpd", "-t", "-f", str(_APACHE)],
180 capture_output=True,
181 text=True,
182 timeout=15,
183 )
184 except (OSError, subprocess.TimeoutExpired) as exc:
185 print(f"Apache-test mislukt: {exc}")
186 return False
187 if result.returncode != 0:
188 detail = (result.stderr or result.stdout).strip()
189 print(f"Apache-test: {detail}")
190 return False
191 return True
192
193
194def _apache_reload(hard: bool) -> bool:
195 flag = "restart" if hard else "graceful"
196 try:
197 result = subprocess.run(
198 ["httpd", "-k", flag, "-f", str(_APACHE)],
199 capture_output=True,
200 text=True,
201 timeout=20,
202 )
203 except (OSError, subprocess.TimeoutExpired) as exc:
204 print(f"Apache niet herladen: {exc}")
205 return False
206 if result.returncode != 0:
207 detail = (result.stderr or result.stdout).strip()
208 print(f"Apache niet herladen: {detail}")
209 return False
210 return True
timdraw/selftest.py added +131 −0
@@ -0,0 +1,131 @@
1 """Controle van SVG, tekst, arcering en G-code, zonder de machine te bewegen."""
2
3 from pathlib import Path
4 import math
5
6 from timdraw.font import render_text
7 from timdraw.gcode import plan
8 from timdraw.grbl import limit_step
9 from timdraw.geom import arc_points, bounds, dist, fit_arcs
10 from timdraw.svgimport import import_svg
11
12 DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
13
14
15 def check(name: str, ok: bool, detail: str = "") -> None:
16 print(("ok " if ok else "FAIL") + " " + name + (f" — {detail}" if detail else ""))
17 if not ok:
18 raise SystemExit(1)
19
20
21 def test_arc() -> None:
22 pts = arc_points(0, 0, 10, 10, 0, 0, 1, 10, 10, 0.05)
23 check("boog eindigt op doel", dist(pts[-1], (10, 10)) < 0.05, str(pts[-1]))
24 mid = pts[len(pts) // 2]
25 # Kwartcirkel: het midden ligt ongeveer 2.9 mm van het koorde-midden (5, 5).
26 bulge = dist(mid, (5, 5))
27 check("boog bolt op", 2.2 < bulge < 3.6, f"{bulge:.2f}")
28
29
30 def test_svg(filename: str, fills: bool) -> None:
31 data = import_svg((DEMO / filename).read_text(encoding="utf-8", errors="replace"))
32 strokes = data["strokes"]
33 check(f"{filename} heeft paden", len(strokes) > 0, f"{len(strokes)} paden, {len(data['fills'])} vlakken")
34 check(f"{filename} vulling", (len(data["fills"]) > 0) is fills, str(len(data["fills"])))
35 placed = [[[p[0] + data["x"], p[1] + data["y"]] for p in stroke["pts"]] for stroke in strokes]
36 box = bounds(placed)
37 check(
38 f"{filename} binnen A4",
39 box[0] > -5 and box[1] > -5 and box[2] < 220 and box[3] < 310,
40 f"centrum {data['x']:.1f},{data['y']:.1f} kader {tuple(round(v, 1) for v in box)}",
41 )
42
43
44 def test_text_and_gcode() -> None:
45 text = render_text("Ag", "futural", 10)
46 check("tekst heeft lijnen", len(text["strokes"]) >= 2, str(len(text["strokes"])))
47 ys = [y for stroke in text["strokes"] for _, y in stroke]
48 check("g daalt onder de basislijn", min(ys) < -0.5, f"min y {min(ys):.2f}")
49 heart = import_svg((DEMO / "Heart.svg").read_text(encoding="utf-8", errors="replace"))
50 obj = {
51 "x": heart["x"], "y": heart["y"], "scale": 1, "rotation": 0, "mode": "fill",
52 "hatchAngle": 45, "hatchSpacing": 2, "crosshatch": True,
53 "strokes": heart["strokes"], "fills": heart["fills"],
54 }
55 planned = plan([obj], {"drawSpeed": 2500, "travelSpeed": 4000, "origin": "bottom-left"})
56 check("g-code bevat G21 en pen", "G21" in planned["gcode"] and "G1 Z5.000" in planned["gcode"])
57 check("vulling maakt arcering", len(planned["draw"]) > len(heart["strokes"]), f"{len(planned['draw'])} lijnen")
58 both = dict(obj)
59 both["drawLine"] = True
60 both["drawFill"] = True
61 both_plan = plan([both], {"drawSpeed": 2500, "travelSpeed": 4000})
62 check("lijn en vulling samen", both_plan["stats"]["drawMm"] > planned["stats"]["drawMm"], str(both_plan["stats"]["drawMm"]))
63 check("niet geblokkeerd", not planned["stats"]["blocked"], str(planned["warnings"]))
64 dolphin = import_svg((DEMO / "Dolphin.svg").read_text(encoding="utf-8", errors="replace"))
65 grays = sorted({fill["gray"] for fill in dolphin["fills"]})
66 check("dolfijn houdt kleurverschil", len(grays) >= 1 and grays[0] < 0.5, str(grays))
67 gray_job = plan([{
68 "x": dolphin["x"], "y": dolphin["y"], "scale": 1, "rotation": 0, "mode": "fill",
69 "hatchAngle": 30, "hatchSpacing": 1.5, "crosshatch": False, "grayscale": True,
70 "graySteps": 4, "spacingMin": 0.8, "spacingMax": 3.5,
71 "strokes": dolphin["strokes"], "fills": dolphin["fills"],
72 }])
73 check("grijswaarden tekenen", gray_job["stats"]["drawMm"] > 100, str(gray_job["stats"]))
74 corner = plan([{
75 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
76 "strokes": [{"pts": [(0, 297), (20, 277)]}],
77 }], {"origin": "top-left", "returnHome": True})
78 check("homehoek blijft X0 Y0", "X0.000 Y0.000" in corner["gcode"], corner["gcode"])
79 check("blad ligt rechts en onder het nulpunt", "X20.000 Y-20.000" in corner["gcode"])
80 check("pen gebruikt verplaatsingssnelheid", "G1 Z5.000 F4000" in planned["gcode"])
81 check("pen omhoog houdt de as vast", "G1 Z0.000" in planned["gcode"] and "$1=25\n" not in planned["gcode"])
82 check("pen omlaag vergrendelt", "$1=255\nG1 Z5.000" in planned["gcode"])
83 linked = plan([{
84 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
85 "strokes": [
86 {"pts": [(100, 100), (120, 100)]},
87 {"pts": [(10, 297), (0, 297)]},
88 {"pts": [(10, 287), (10, 297)]},
89 ],
90 }], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
91 moves = [line for line in linked["gcode"].splitlines() if line.startswith("G1 X")]
92 check("dichtstbijzijnde lijn eerst", moves[0].startswith("G1 X0.000 Y0.000"), " | ".join(moves[:4]))
93 check("aansluitende lijn direct daarna", "X10.000 Y-10.000" in moves[2], " | ".join(moves[:4]))
94 pen_ups = [line for line in linked["gcode"].splitlines() if line.startswith("G1 Z0")]
95 check("geen pen omhoog tussen aansluitende lijnen", len(pen_ups) == 3, str(pen_ups))
96 step_x, step_y, note = limit_step(0, -287, 0, -50)
97 check("vanaf -287 nog 10 mm omlaag", abs(step_y + 10) < 0.01 and abs(step_x) < 0.01, note or "")
98 check("limiettoast", note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
99 step_x, _, note = limit_step(190, -10, 50, 0)
100 check("breedte stopt op 200", abs(step_x - 10) < 0.01 and note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
101 _, step_y, note = limit_step(10, 0, 0, 20)
102 check("niet boven nul", abs(step_y) < 0.01 and note == "0 van 20 mm bewogen, daarna limiet bereikt", note or "")
103 quarter = [
104 (10 * math.cos(i * math.pi / 32), 10 * math.sin(i * math.pi / 32))
105 for i in range(17)
106 ]
107 arcs = fit_arcs(quarter, 0.08)
108 check("kwartcirkel wordt één boog", len(arcs) == 1 and arcs[0][0] == "G3", str(arcs))
109 outer = [(0, 0), (80, 0), (80, 80), (0, 80), (0, 0)]
110 inner = [(30, 30), (50, 30), (50, 50), (30, 50), (30, 30)]
111 traced = plan([{
112 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": True,
113 "strokes": [
114 {"pts": outer, "closed": True},
115 {"pts": inner, "closed": True},
116 ],
117 }], {"origin": "top-left", "trace": True, "returnHome": False})
118 check("voorbeeld laat de pen omhoog", "Z5" not in traced["gcode"], traced["gcode"])
119 check("voorbeeld volgt de buitenkant", "X80.000" in traced["gcode"])
120 arc_lines = [line for line in traced["gcode"].splitlines() if line.startswith(("G2 ", "G3 "))]
121 check("voorbeeld houdt hoeken recht", not arc_lines, " | ".join(arc_lines))
122 check("voorbeeld slaat het gat over", "X50.000" not in traced["gcode"] and "X30.000" not in traced["gcode"])
123
124
125 if __name__ == "__main__":
126 test_arc()
127 test_svg("Heart.svg", False)
128 test_svg("Dolphin.svg", True)
129 test_svg("wiresphere.svg", False)
130 test_text_and_gcode()
131 print("alle controles geslaagd")
@@ -0,0 +1,131 @@
1"""Controle van SVG, tekst, arcering en G-code, zonder de machine te bewegen."""
2
3from pathlib import Path
4import math
5
6from timdraw.font import render_text
7from timdraw.gcode import plan
8from timdraw.grbl import limit_step
9from timdraw.geom import arc_points, bounds, dist, fit_arcs
10from timdraw.svgimport import import_svg
11
12DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
13
14
15def check(name: str, ok: bool, detail: str = "") -> None:
16 print(("ok " if ok else "FAIL") + " " + name + (f" — {detail}" if detail else ""))
17 if not ok:
18 raise SystemExit(1)
19
20
21def test_arc() -> None:
22 pts = arc_points(0, 0, 10, 10, 0, 0, 1, 10, 10, 0.05)
23 check("boog eindigt op doel", dist(pts[-1], (10, 10)) < 0.05, str(pts[-1]))
24 mid = pts[len(pts) // 2]
25 # Kwartcirkel: het midden ligt ongeveer 2.9 mm van het koorde-midden (5, 5).
26 bulge = dist(mid, (5, 5))
27 check("boog bolt op", 2.2 < bulge < 3.6, f"{bulge:.2f}")
28
29
30def test_svg(filename: str, fills: bool) -> None:
31 data = import_svg((DEMO / filename).read_text(encoding="utf-8", errors="replace"))
32 strokes = data["strokes"]
33 check(f"{filename} heeft paden", len(strokes) > 0, f"{len(strokes)} paden, {len(data['fills'])} vlakken")
34 check(f"{filename} vulling", (len(data["fills"]) > 0) is fills, str(len(data["fills"])))
35 placed = [[[p[0] + data["x"], p[1] + data["y"]] for p in stroke["pts"]] for stroke in strokes]
36 box = bounds(placed)
37 check(
38 f"{filename} binnen A4",
39 box[0] > -5 and box[1] > -5 and box[2] < 220 and box[3] < 310,
40 f"centrum {data['x']:.1f},{data['y']:.1f} kader {tuple(round(v, 1) for v in box)}",
41 )
42
43
44def test_text_and_gcode() -> None:
45 text = render_text("Ag", "futural", 10)
46 check("tekst heeft lijnen", len(text["strokes"]) >= 2, str(len(text["strokes"])))
47 ys = [y for stroke in text["strokes"] for _, y in stroke]
48 check("g daalt onder de basislijn", min(ys) < -0.5, f"min y {min(ys):.2f}")
49 heart = import_svg((DEMO / "Heart.svg").read_text(encoding="utf-8", errors="replace"))
50 obj = {
51 "x": heart["x"], "y": heart["y"], "scale": 1, "rotation": 0, "mode": "fill",
52 "hatchAngle": 45, "hatchSpacing": 2, "crosshatch": True,
53 "strokes": heart["strokes"], "fills": heart["fills"],
54 }
55 planned = plan([obj], {"drawSpeed": 2500, "travelSpeed": 4000, "origin": "bottom-left"})
56 check("g-code bevat G21 en pen", "G21" in planned["gcode"] and "G1 Z5.000" in planned["gcode"])
57 check("vulling maakt arcering", len(planned["draw"]) > len(heart["strokes"]), f"{len(planned['draw'])} lijnen")
58 both = dict(obj)
59 both["drawLine"] = True
60 both["drawFill"] = True
61 both_plan = plan([both], {"drawSpeed": 2500, "travelSpeed": 4000})
62 check("lijn en vulling samen", both_plan["stats"]["drawMm"] > planned["stats"]["drawMm"], str(both_plan["stats"]["drawMm"]))
63 check("niet geblokkeerd", not planned["stats"]["blocked"], str(planned["warnings"]))
64 dolphin = import_svg((DEMO / "Dolphin.svg").read_text(encoding="utf-8", errors="replace"))
65 grays = sorted({fill["gray"] for fill in dolphin["fills"]})
66 check("dolfijn houdt kleurverschil", len(grays) >= 1 and grays[0] < 0.5, str(grays))
67 gray_job = plan([{
68 "x": dolphin["x"], "y": dolphin["y"], "scale": 1, "rotation": 0, "mode": "fill",
69 "hatchAngle": 30, "hatchSpacing": 1.5, "crosshatch": False, "grayscale": True,
70 "graySteps": 4, "spacingMin": 0.8, "spacingMax": 3.5,
71 "strokes": dolphin["strokes"], "fills": dolphin["fills"],
72 }])
73 check("grijswaarden tekenen", gray_job["stats"]["drawMm"] > 100, str(gray_job["stats"]))
74 corner = plan([{
75 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
76 "strokes": [{"pts": [(0, 297), (20, 277)]}],
77 }], {"origin": "top-left", "returnHome": True})
78 check("homehoek blijft X0 Y0", "X0.000 Y0.000" in corner["gcode"], corner["gcode"])
79 check("blad ligt rechts en onder het nulpunt", "X20.000 Y-20.000" in corner["gcode"])
80 check("pen gebruikt verplaatsingssnelheid", "G1 Z5.000 F4000" in planned["gcode"])
81 check("pen omhoog houdt de as vast", "G1 Z0.000" in planned["gcode"] and "$1=25\n" not in planned["gcode"])
82 check("pen omlaag vergrendelt", "$1=255\nG1 Z5.000" in planned["gcode"])
83 linked = plan([{
84 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
85 "strokes": [
86 {"pts": [(100, 100), (120, 100)]},
87 {"pts": [(10, 297), (0, 297)]},
88 {"pts": [(10, 287), (10, 297)]},
89 ],
90 }], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
91 moves = [line for line in linked["gcode"].splitlines() if line.startswith("G1 X")]
92 check("dichtstbijzijnde lijn eerst", moves[0].startswith("G1 X0.000 Y0.000"), " | ".join(moves[:4]))
93 check("aansluitende lijn direct daarna", "X10.000 Y-10.000" in moves[2], " | ".join(moves[:4]))
94 pen_ups = [line for line in linked["gcode"].splitlines() if line.startswith("G1 Z0")]
95 check("geen pen omhoog tussen aansluitende lijnen", len(pen_ups) == 3, str(pen_ups))
96 step_x, step_y, note = limit_step(0, -287, 0, -50)
97 check("vanaf -287 nog 10 mm omlaag", abs(step_y + 10) < 0.01 and abs(step_x) < 0.01, note or "")
98 check("limiettoast", note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
99 step_x, _, note = limit_step(190, -10, 50, 0)
100 check("breedte stopt op 200", abs(step_x - 10) < 0.01 and note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
101 _, step_y, note = limit_step(10, 0, 0, 20)
102 check("niet boven nul", abs(step_y) < 0.01 and note == "0 van 20 mm bewogen, daarna limiet bereikt", note or "")
103 quarter = [
104 (10 * math.cos(i * math.pi / 32), 10 * math.sin(i * math.pi / 32))
105 for i in range(17)
106 ]
107 arcs = fit_arcs(quarter, 0.08)
108 check("kwartcirkel wordt één boog", len(arcs) == 1 and arcs[0][0] == "G3", str(arcs))
109 outer = [(0, 0), (80, 0), (80, 80), (0, 80), (0, 0)]
110 inner = [(30, 30), (50, 30), (50, 50), (30, 50), (30, 30)]
111 traced = plan([{
112 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": True,
113 "strokes": [
114 {"pts": outer, "closed": True},
115 {"pts": inner, "closed": True},
116 ],
117 }], {"origin": "top-left", "trace": True, "returnHome": False})
118 check("voorbeeld laat de pen omhoog", "Z5" not in traced["gcode"], traced["gcode"])
119 check("voorbeeld volgt de buitenkant", "X80.000" in traced["gcode"])
120 arc_lines = [line for line in traced["gcode"].splitlines() if line.startswith(("G2 ", "G3 "))]
121 check("voorbeeld houdt hoeken recht", not arc_lines, " | ".join(arc_lines))
122 check("voorbeeld slaat het gat over", "X50.000" not in traced["gcode"] and "X30.000" not in traced["gcode"])
123
124
125if __name__ == "__main__":
126 test_arc()
127 test_svg("Heart.svg", False)
128 test_svg("Dolphin.svg", True)
129 test_svg("wiresphere.svg", False)
130 test_text_and_gcode()
131 print("alle controles geslaagd")
timdraw/server.py added +215 −0
@@ -0,0 +1,215 @@
1 """Lokale webapp voor Timdraw."""
2
3 from __future__ import annotations
4
5 import json
6 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7 from pathlib import Path
8 from urllib.parse import unquote, urlparse
9
10 from timdraw.font import render_text
11 from timdraw.gcode import plan
12 from timdraw.grbl import Machine
13 from timdraw.publish import LocalRoute
14 from timdraw.svgimport import import_svg
15
16 ROOT = Path(__file__).resolve().parent.parent
17 STATIC = ROOT / "static"
18 DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
19 MACHINE = Machine()
20 ROUTE = LocalRoute(8765)
21
22
23 def _demo_file(name: str) -> Path:
24 safe = Path(name).name
25 if safe != name or not safe.lower().endswith(".svg"):
26 raise FileNotFoundError(name)
27 path = DEMO / safe
28 if not path.is_file():
29 raise FileNotFoundError(safe)
30 return path
31
32
33 class Handler(BaseHTTPRequestHandler):
34 protocol_version = "HTTP/1.1"
35
36 def log_message(self, fmt: str, *args) -> None:
37 if args and "/api/status" in str(args[0]):
38 return
39 print(f"[timdraw] {self.address_string()} {fmt % args}")
40
41 def _send(self, code: int, body: bytes, content_type: str) -> None:
42 self.send_response(code)
43 self.send_header("Content-Type", content_type)
44 self.send_header("Content-Length", str(len(body)))
45 self.send_header("Cache-Control", "no-store")
46 self.end_headers()
47 self.wfile.write(body)
48
49 def _json(self, payload: dict, code: int = 200) -> None:
50 self._send(code, json.dumps(payload).encode(), "application/json; charset=utf-8")
51
52 def _error(self, message: str, code: int = 400) -> None:
53 self._json({"error": message}, code)
54
55 def _status(self) -> dict:
56 MACHINE.local_url = ROUTE.url
57 return MACHINE.status()
58
59 def _body(self) -> dict:
60 length = int(self.headers.get("Content-Length") or 0)
61 if length > 20_000_000:
62 raise ValueError("Bestand is te groot")
63 raw = self.rfile.read(length) if length else b"{}"
64 if not raw:
65 return {}
66 data = json.loads(raw.decode("utf-8"))
67 if not isinstance(data, dict):
68 raise ValueError("JSON-object verwacht")
69 return data
70
71 def do_GET(self) -> None:
72 parsed = urlparse(self.path)
73 path = unquote(parsed.path)
74 try:
75 if path in ("/", "/index.html"):
76 self._send(200, (STATIC / "index.html").read_bytes(), "text/html; charset=utf-8")
77 return
78 if path.startswith("/static/"):
79 file = STATIC / path[len("/static/") :]
80 if not file.resolve().is_relative_to(STATIC.resolve()) or not file.is_file():
81 self._error("Niet gevonden", 404)
82 return
83 kind = "text/css; charset=utf-8" if file.suffix == ".css" else "text/javascript; charset=utf-8"
84 self._send(200, file.read_bytes(), kind)
85 return
86 if path == "/api/status":
87 self._json(self._status())
88 return
89 if path == "/api/demos":
90 names = sorted(p.name for p in DEMO.glob("*.svg")) if DEMO.is_dir() else []
91 self._json({"demos": names})
92 return
93 if path.startswith("/api/demos/"):
94 file = _demo_file(path[len("/api/demos/") :])
95 self._send(200, file.read_bytes(), "image/svg+xml; charset=utf-8")
96 return
97 self._error("Niet gevonden", 404)
98 except FileNotFoundError:
99 self._error("Niet gevonden", 404)
100 except Exception as exc:
101 self._error(str(exc), 500)
102
103 def do_POST(self) -> None:
104 path = urlparse(self.path).path
105 try:
106 data = self._body()
107 if path == "/api/svg":
108 result = import_svg(data.get("svg") or "")
109 result["name"] = (data.get("name") or "SVG").rsplit("/", 1)[-1][:80]
110 self._json(result)
111 return
112 if path == "/api/text":
113 result = render_text(
114 data.get("text") or "",
115 data.get("font") or "futural",
116 float(data.get("fontSize") or 12),
117 float(data.get("lineSpacing") or 1.4),
118 )
119 self._json(result)
120 return
121 if path == "/api/preview":
122 self._json(plan(data.get("objects") or [], data.get("settings") or {}))
123 return
124 if path == "/api/connect":
125 MACHINE.connect(data.get("port") or None)
126 self._json(self._status())
127 return
128 if path == "/api/disconnect":
129 MACHINE.disconnect(manual=True)
130 self._json(self._status())
131 return
132 if MACHINE.job_active and path not in ("/api/pause", "/api/resume", "/api/stop"):
133 self._error("Wacht tot de tekening klaar is, of stop hem.", 409)
134 return
135 if path == "/api/plot":
136 planned = plan(data.get("objects") or [], data.get("settings") or {})
137 if planned["stats"]["blocked"]:
138 self._error(planned["warnings"][0] if planned["warnings"] else "Buiten A4", 400)
139 return
140 MACHINE.start_job(planned["gcode"])
141 self._json({"ok": True, "stats": planned["stats"]})
142 return
143 if path == "/api/pause":
144 MACHINE.pause_job()
145 elif path == "/api/resume":
146 MACHINE.resume_job()
147 elif path == "/api/stop":
148 MACHINE.stop_job()
149 elif path == "/api/jog":
150 notice = MACHINE.jog(
151 float(data.get("x") or 0),
152 float(data.get("y") or 0),
153 float(data.get("feed") or 3000),
154 origin_top=(data.get("origin") or "top-left") == "top-left",
155 )
156 payload = self._status()
157 if notice:
158 payload["notice"] = notice
159 self._json(payload)
160 return
161 elif path == "/api/pen":
162 MACHINE.pen(
163 bool(data.get("down")),
164 float(data.get("penUpZ", 0)),
165 float(data.get("penDownZ", 5)),
166 float(data.get("travelSpeed") or 5000),
167 )
168 elif path == "/api/home":
169 MACHINE.home()
170 elif path == "/api/release":
171 MACHINE.release_axes()
172 elif path == "/api/unlock":
173 MACHINE.unlock()
174 elif path == "/api/trace":
175 settings = dict(data.get("settings") or {})
176 settings["trace"] = True
177 planned = plan(data.get("objects") or [], settings)
178 if not planned["draw"]:
179 self._error("Er is niets om te volgen.", 400)
180 return
181 if planned["stats"]["blocked"]:
182 self._error(planned["warnings"][0] if planned["warnings"] else "Buiten A4", 400)
183 return
184 MACHINE.start_job(planned["gcode"])
185 self._json({"ok": True, "stats": planned["stats"]})
186 return
187 else:
188 self._error("Niet gevonden", 404)
189 return
190 self._json(self._status())
191 except json.JSONDecodeError:
192 self._error("Ongeldige JSON")
193 except Exception as exc:
194 self._error(str(exc), 400)
195
196
197 def main() -> None:
198 MACHINE.start_auto()
199 server = ThreadingHTTPServer(("127.0.0.1", 8765), Handler)
200 ROUTE.start()
201 MACHINE.local_url = ROUTE.url
202 print(f"Timdraw staat op {ROUTE.url}")
203 try:
204 server.serve_forever()
205 except KeyboardInterrupt:
206 print("\nStop.")
207 finally:
208 ROUTE.stop()
209 MACHINE.stop_auto()
210 MACHINE.disconnect()
211 server.server_close()
212
213
214 if __name__ == "__main__":
215 main()
@@ -0,0 +1,215 @@
1"""Lokale webapp voor Timdraw."""
2
3from __future__ import annotations
4
5import json
6from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
7from pathlib import Path
8from urllib.parse import unquote, urlparse
9
10from timdraw.font import render_text
11from timdraw.gcode import plan
12from timdraw.grbl import Machine
13from timdraw.publish import LocalRoute
14from timdraw.svgimport import import_svg
15
16ROOT = Path(__file__).resolve().parent.parent
17STATIC = ROOT / "static"
18DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
19MACHINE = Machine()
20ROUTE = LocalRoute(8765)
21
22
23def _demo_file(name: str) -> Path:
24 safe = Path(name).name
25 if safe != name or not safe.lower().endswith(".svg"):
26 raise FileNotFoundError(name)
27 path = DEMO / safe
28 if not path.is_file():
29 raise FileNotFoundError(safe)
30 return path
31
32
33class Handler(BaseHTTPRequestHandler):
34 protocol_version = "HTTP/1.1"
35
36 def log_message(self, fmt: str, *args) -> None:
37 if args and "/api/status" in str(args[0]):
38 return
39 print(f"[timdraw] {self.address_string()} {fmt % args}")
40
41 def _send(self, code: int, body: bytes, content_type: str) -> None:
42 self.send_response(code)
43 self.send_header("Content-Type", content_type)
44 self.send_header("Content-Length", str(len(body)))
45 self.send_header("Cache-Control", "no-store")
46 self.end_headers()
47 self.wfile.write(body)
48
49 def _json(self, payload: dict, code: int = 200) -> None:
50 self._send(code, json.dumps(payload).encode(), "application/json; charset=utf-8")
51
52 def _error(self, message: str, code: int = 400) -> None:
53 self._json({"error": message}, code)
54
55 def _status(self) -> dict:
56 MACHINE.local_url = ROUTE.url
57 return MACHINE.status()
58
59 def _body(self) -> dict:
60 length = int(self.headers.get("Content-Length") or 0)
61 if length > 20_000_000:
62 raise ValueError("Bestand is te groot")
63 raw = self.rfile.read(length) if length else b"{}"
64 if not raw:
65 return {}
66 data = json.loads(raw.decode("utf-8"))
67 if not isinstance(data, dict):
68 raise ValueError("JSON-object verwacht")
69 return data
70
71 def do_GET(self) -> None:
72 parsed = urlparse(self.path)
73 path = unquote(parsed.path)
74 try:
75 if path in ("/", "/index.html"):
76 self._send(200, (STATIC / "index.html").read_bytes(), "text/html; charset=utf-8")
77 return
78 if path.startswith("/static/"):
79 file = STATIC / path[len("/static/") :]
80 if not file.resolve().is_relative_to(STATIC.resolve()) or not file.is_file():
81 self._error("Niet gevonden", 404)
82 return
83 kind = "text/css; charset=utf-8" if file.suffix == ".css" else "text/javascript; charset=utf-8"
84 self._send(200, file.read_bytes(), kind)
85 return
86 if path == "/api/status":
87 self._json(self._status())
88 return
89 if path == "/api/demos":
90 names = sorted(p.name for p in DEMO.glob("*.svg")) if DEMO.is_dir() else []
91 self._json({"demos": names})
92 return
93 if path.startswith("/api/demos/"):
94 file = _demo_file(path[len("/api/demos/") :])
95 self._send(200, file.read_bytes(), "image/svg+xml; charset=utf-8")
96 return
97 self._error("Niet gevonden", 404)
98 except FileNotFoundError:
99 self._error("Niet gevonden", 404)
100 except Exception as exc:
101 self._error(str(exc), 500)
102
103 def do_POST(self) -> None:
104 path = urlparse(self.path).path
105 try:
106 data = self._body()
107 if path == "/api/svg":
108 result = import_svg(data.get("svg") or "")
109 result["name"] = (data.get("name") or "SVG").rsplit("/", 1)[-1][:80]
110 self._json(result)
111 return
112 if path == "/api/text":
113 result = render_text(
114 data.get("text") or "",
115 data.get("font") or "futural",
116 float(data.get("fontSize") or 12),
117 float(data.get("lineSpacing") or 1.4),
118 )
119 self._json(result)
120 return
121 if path == "/api/preview":
122 self._json(plan(data.get("objects") or [], data.get("settings") or {}))
123 return
124 if path == "/api/connect":
125 MACHINE.connect(data.get("port") or None)
126 self._json(self._status())
127 return
128 if path == "/api/disconnect":
129 MACHINE.disconnect(manual=True)
130 self._json(self._status())
131 return
132 if MACHINE.job_active and path not in ("/api/pause", "/api/resume", "/api/stop"):
133 self._error("Wacht tot de tekening klaar is, of stop hem.", 409)
134 return
135 if path == "/api/plot":
136 planned = plan(data.get("objects") or [], data.get("settings") or {})
137 if planned["stats"]["blocked"]:
138 self._error(planned["warnings"][0] if planned["warnings"] else "Buiten A4", 400)
139 return
140 MACHINE.start_job(planned["gcode"])
141 self._json({"ok": True, "stats": planned["stats"]})
142 return
143 if path == "/api/pause":
144 MACHINE.pause_job()
145 elif path == "/api/resume":
146 MACHINE.resume_job()
147 elif path == "/api/stop":
148 MACHINE.stop_job()
149 elif path == "/api/jog":
150 notice = MACHINE.jog(
151 float(data.get("x") or 0),
152 float(data.get("y") or 0),
153 float(data.get("feed") or 3000),
154 origin_top=(data.get("origin") or "top-left") == "top-left",
155 )
156 payload = self._status()
157 if notice:
158 payload["notice"] = notice
159 self._json(payload)
160 return
161 elif path == "/api/pen":
162 MACHINE.pen(
163 bool(data.get("down")),
164 float(data.get("penUpZ", 0)),
165 float(data.get("penDownZ", 5)),
166 float(data.get("travelSpeed") or 5000),
167 )
168 elif path == "/api/home":
169 MACHINE.home()
170 elif path == "/api/release":
171 MACHINE.release_axes()
172 elif path == "/api/unlock":
173 MACHINE.unlock()
174 elif path == "/api/trace":
175 settings = dict(data.get("settings") or {})
176 settings["trace"] = True
177 planned = plan(data.get("objects") or [], settings)
178 if not planned["draw"]:
179 self._error("Er is niets om te volgen.", 400)
180 return
181 if planned["stats"]["blocked"]:
182 self._error(planned["warnings"][0] if planned["warnings"] else "Buiten A4", 400)
183 return
184 MACHINE.start_job(planned["gcode"])
185 self._json({"ok": True, "stats": planned["stats"]})
186 return
187 else:
188 self._error("Niet gevonden", 404)
189 return
190 self._json(self._status())
191 except json.JSONDecodeError:
192 self._error("Ongeldige JSON")
193 except Exception as exc:
194 self._error(str(exc), 400)
195
196
197def main() -> None:
198 MACHINE.start_auto()
199 server = ThreadingHTTPServer(("127.0.0.1", 8765), Handler)
200 ROUTE.start()
201 MACHINE.local_url = ROUTE.url
202 print(f"Timdraw staat op {ROUTE.url}")
203 try:
204 server.serve_forever()
205 except KeyboardInterrupt:
206 print("\nStop.")
207 finally:
208 ROUTE.stop()
209 MACHINE.stop_auto()
210 MACHINE.disconnect()
211 server.server_close()
212
213
214if __name__ == "__main__":
215 main()
timdraw/svgimport.py added +658 −0
@@ -0,0 +1,658 @@
1 """SVG naar millimeter-paden, met Y omhoog en oorsprong linksonder."""
2
3 from __future__ import annotations
4
5 import math
6 import re
7 import xml.etree.ElementTree as ET
8
9 from timdraw.geom import (
10 A4_H,
11 A4_W,
12 Point,
13 Polyline,
14 arc_points,
15 bounds,
16 dedupe,
17 dist,
18 flatten_cubic,
19 flatten_quad,
20 is_closed,
21 rdp,
22 )
23
24 _LENGTH = re.compile(
25 r"^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*(mm|cm|in|pt|pc|px|%)?\s*$"
26 )
27 _TRANSFORM = re.compile(r"([a-zA-Z]+)\s*\(([^)]*)\)")
28 _CSS_RULE = re.compile(r"([^{]+)\{([^}]+)\}")
29 _NUMBER = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
30
31 _NAMED = {
32 "black": (0, 0, 0),
33 "white": (255, 255, 255),
34 "red": (255, 0, 0),
35 "green": (0, 128, 0),
36 "blue": (0, 0, 255),
37 "gray": (128, 128, 128),
38 "grey": (128, 128, 128),
39 "orange": (255, 165, 0),
40 "yellow": (255, 255, 0),
41 }
42
43
44 def _local(tag: str) -> str:
45 return tag.rsplit("}", 1)[-1] if tag else ""
46
47
48 def _parse_length_mm(value: str | None) -> float | None:
49 if not value:
50 return None
51 match = _LENGTH.match(value.strip())
52 if not match:
53 return None
54 number = float(match.group(1))
55 unit = (match.group(2) or "").lower()
56 factors = {"": None, "px": 25.4 / 96, "mm": 1, "cm": 10, "in": 25.4, "pt": 25.4 / 72, "pc": 25.4 / 6}
57 if unit == "%":
58 return None
59 factor = factors.get(unit)
60 if factor is None:
61 return None
62 return number * factor
63
64
65 def _numbers(text: str) -> list[float]:
66 return [float(item) for item in _NUMBER.findall(text or "")]
67
68
69 def _mul(m1: tuple, m2: tuple) -> tuple:
70 a1, b1, c1, d1, e1, f1 = m1
71 a2, b2, c2, d2, e2, f2 = m2
72 return (
73 a1 * a2 + c1 * b2,
74 b1 * a2 + d1 * b2,
75 a1 * c2 + c1 * d2,
76 b1 * c2 + d1 * d2,
77 a1 * e2 + c1 * f2 + e1,
78 b1 * e2 + d1 * f2 + f1,
79 )
80
81
82 def _apply(matrix: tuple, x: float, y: float) -> Point:
83 a, b, c, d, e, f = matrix
84 return a * x + c * y + e, b * x + d * y + f
85
86
87 def _parse_transform(text: str | None) -> tuple:
88 matrix = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
89 if not text:
90 return matrix
91 for name, args in _TRANSFORM.findall(text):
92 vals = _numbers(args)
93 name = name.lower()
94 if name == "matrix" and len(vals) >= 6:
95 part = tuple(vals[:6])
96 elif name == "translate":
97 tx = vals[0] if vals else 0.0
98 ty = vals[1] if len(vals) > 1 else 0.0
99 part = (1.0, 0.0, 0.0, 1.0, tx, ty)
100 elif name == "scale":
101 sx = vals[0] if vals else 1.0
102 sy = vals[1] if len(vals) > 1 else sx
103 part = (sx, 0.0, 0.0, sy, 0.0, 0.0)
104 elif name == "rotate":
105 angle = math.radians(vals[0] if vals else 0.0)
106 ca, sa = math.cos(angle), math.sin(angle)
107 rot = (ca, sa, -sa, ca, 0.0, 0.0)
108 if len(vals) >= 3:
109 tx, ty = vals[1], vals[2]
110 rot = _mul((1, 0, 0, 1, tx, ty), _mul(rot, (1, 0, 0, 1, -tx, -ty)))
111 part = rot
112 elif name == "skewx" and vals:
113 part = (1.0, 0.0, math.tan(math.radians(vals[0])), 1.0, 0.0, 0.0)
114 elif name == "skewy" and vals:
115 part = (1.0, math.tan(math.radians(vals[0])), 0.0, 1.0, 0.0, 0.0)
116 else:
117 continue
118 matrix = _mul(matrix, part)
119 return matrix
120
121
122 def _decls(text: str) -> dict[str, str]:
123 found: dict[str, str] = {}
124 for part in text.split(";"):
125 if ":" not in part:
126 continue
127 key, value = part.split(":", 1)
128 found[key.strip().lower()] = value.strip()
129 return found
130
131
132 def _css(text: str) -> dict[str, dict[str, str]]:
133 text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
134 rules: dict[str, dict[str, str]] = {}
135 for selector, body in _CSS_RULE.findall(text):
136 decl = _decls(body)
137 for item in selector.split(","):
138 item = item.strip()
139 if item.startswith("."):
140 rules.setdefault(item[1:], {}).update(decl)
141 return rules
142
143
144 def _channel(value: str) -> int:
145 value = value.strip()
146 if value.endswith("%"):
147 return max(0, min(255, round(float(value[:-1]) * 2.55)))
148 return max(0, min(255, round(float(value))))
149
150
151 def _color(value: str | None) -> tuple[int, int, int] | None:
152 if not value:
153 return None
154 value = value.strip().lower()
155 if value in ("none", "transparent"):
156 return None
157 if value in _NAMED:
158 return _NAMED[value]
159 if value.startswith("#"):
160 hex_value = value[1:]
161 if len(hex_value) == 3:
162 hex_value = "".join(ch * 2 for ch in hex_value)
163 if len(hex_value) >= 6:
164 return tuple(int(hex_value[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
165 if value.startswith("rgb"):
166 nums = _numbers(value)
167 if len(nums) >= 3:
168 parts = value[value.find("(") + 1 :].split(",")
169 if len(parts) >= 3:
170 return _channel(parts[0]), _channel(parts[1]), _channel(parts[2])
171 return (0, 0, 0)
172
173
174 def _luminance(rgb: tuple[int, int, int]) -> float:
175 def lin(channel: int) -> float:
176 c = channel / 255.0
177 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
178
179 r, g, b = (lin(c) for c in rgb)
180 return 0.2126 * r + 0.7152 * g + 0.0722 * b
181
182
183 def _alpha(style: dict, key: str) -> float:
184 try:
185 own = float(style.get(key, "1"))
186 except ValueError:
187 own = 1.0
188 try:
189 extra = float(style.get("opacity", "1"))
190 except ValueError:
191 extra = 1.0
192 return max(0.0, min(1.0, own * extra))
193
194
195 class _Path:
196 def __init__(self, data: str):
197 self.d = data or ""
198 self.i = 0
199 self.n = len(self.d)
200
201 def _skip(self) -> None:
202 while self.i < self.n and self.d[self.i] in " \t\r\n,":
203 self.i += 1
204
205 def command(self) -> str | None:
206 self._skip()
207 if self.i < self.n and self.d[self.i].isalpha():
208 cmd = self.d[self.i]
209 self.i += 1
210 return cmd
211 return None
212
213 def has_number(self) -> bool:
214 self._skip()
215 if self.i >= self.n:
216 return False
217 ch = self.d[self.i]
218 return ch.isdigit() or ch in "+-."
219
220 def number(self) -> float:
221 self._skip()
222 start = self.i
223 if self.i < self.n and self.d[self.i] in "+-":
224 self.i += 1
225 saw = False
226 while self.i < self.n and self.d[self.i].isdigit():
227 saw = True
228 self.i += 1
229 if self.i < self.n and self.d[self.i] == ".":
230 self.i += 1
231 while self.i < self.n and self.d[self.i].isdigit():
232 saw = True
233 self.i += 1
234 if self.i < self.n and self.d[self.i] in "eE":
235 j = self.i + 1
236 if j < self.n and self.d[j] in "+-":
237 j += 1
238 if j < self.n and self.d[j].isdigit():
239 self.i = j + 1
240 while self.i < self.n and self.d[self.i].isdigit():
241 self.i += 1
242 saw = True
243 if not saw:
244 raise ValueError("getal verwacht in pad")
245 return float(self.d[start : self.i])
246
247 def flag(self) -> int:
248 self._skip()
249 if self.i < self.n and self.d[self.i] in "01":
250 value = self.d[self.i]
251 self.i += 1
252 # 0110 is vlag 0, vlag 1, en daarna een getal
253 return int(value)
254 return 1 if self.number() else 0
255
256
257 def _subpaths(data: str, tol: float) -> list[tuple[Polyline, bool]]:
258 parser = _Path(data)
259 current = (0.0, 0.0)
260 start = (0.0, 0.0)
261 cubic: Point | None = None
262 quad: Point | None = None
263 cmd: str | None = None
264 out: list[tuple[Polyline, bool]] = []
265 pts: Polyline = []
266 closed = False
267
268 def finish() -> None:
269 nonlocal pts, closed
270 cleaned = dedupe(pts)
271 if len(cleaned) >= 2:
272 out.append((cleaned, closed or is_closed(cleaned, 0.15)))
273 pts = []
274 closed = False
275
276 def line_to(point: Point) -> None:
277 nonlocal current, cubic, quad
278 if not pts:
279 pts.append(current)
280 pts.append(point)
281 current = point
282 cubic = None
283 quad = None
284
285 while True:
286 nxt = parser.command()
287 if nxt is None:
288 if cmd is None or not parser.has_number():
289 break
290 else:
291 cmd = nxt
292 if cmd in "Zz":
293 if pts:
294 pts.append(start)
295 closed = True
296 current = start
297 finish()
298 cubic = None
299 quad = None
300 continue
301 if cmd in "Mm":
302 if pts:
303 finish()
304 x, y = parser.number(), parser.number()
305 if cmd == "m":
306 x += current[0]
307 y += current[1]
308 current = (x, y)
309 start = current
310 pts = [current]
311 closed = False
312 cmd = "L" if cmd == "M" else "l"
313 while parser.has_number():
314 x, y = parser.number(), parser.number()
315 if cmd == "l":
316 x += current[0]
317 y += current[1]
318 line_to((x, y))
319 continue
320 if cmd in "Ll":
321 while parser.has_number():
322 x, y = parser.number(), parser.number()
323 if cmd == "l":
324 x += current[0]
325 y += current[1]
326 line_to((x, y))
327 continue
328 if cmd in "Hh":
329 while parser.has_number():
330 x = parser.number()
331 if cmd == "h":
332 x += current[0]
333 line_to((x, current[1]))
334 continue
335 if cmd in "Vv":
336 while parser.has_number():
337 y = parser.number()
338 if cmd == "v":
339 y += current[1]
340 line_to((current[0], y))
341 continue
342 if cmd in "Cc":
343 while parser.has_number():
344 c1 = (parser.number(), parser.number())
345 c2 = (parser.number(), parser.number())
346 end = (parser.number(), parser.number())
347 if cmd == "c":
348 c1 = (c1[0] + current[0], c1[1] + current[1])
349 c2 = (c2[0] + current[0], c2[1] + current[1])
350 end = (end[0] + current[0], end[1] + current[1])
351 if not pts:
352 pts.append(current)
353 extra = flatten_cubic(current, c1, c2, end, tol)
354 pts.extend(extra)
355 current = end
356 cubic = c2
357 quad = None
358 continue
359 if cmd in "Ss":
360 while parser.has_number():
361 c2 = (parser.number(), parser.number())
362 end = (parser.number(), parser.number())
363 if cmd == "s":
364 c2 = (c2[0] + current[0], c2[1] + current[1])
365 end = (end[0] + current[0], end[1] + current[1])
366 c1 = (2 * current[0] - cubic[0], 2 * current[1] - cubic[1]) if cubic else current
367 if not pts:
368 pts.append(current)
369 pts.extend(flatten_cubic(current, c1, c2, end, tol))
370 current = end
371 cubic = c2
372 quad = None
373 continue
374 if cmd in "Qq":
375 while parser.has_number():
376 ctrl = (parser.number(), parser.number())
377 end = (parser.number(), parser.number())
378 if cmd == "q":
379 ctrl = (ctrl[0] + current[0], ctrl[1] + current[1])
380 end = (end[0] + current[0], end[1] + current[1])
381 if not pts:
382 pts.append(current)
383 pts.extend(flatten_quad(current, ctrl, end, tol))
384 current = end
385 quad = ctrl
386 cubic = None
387 continue
388 if cmd in "Tt":
389 while parser.has_number():
390 end = (parser.number(), parser.number())
391 if cmd == "t":
392 end = (end[0] + current[0], end[1] + current[1])
393 ctrl = (2 * current[0] - quad[0], 2 * current[1] - quad[1]) if quad else current
394 if not pts:
395 pts.append(current)
396 pts.extend(flatten_quad(current, ctrl, end, tol))
397 current = end
398 quad = ctrl
399 cubic = None
400 continue
401 if cmd in "Aa":
402 while parser.has_number():
403 rx, ry = parser.number(), parser.number()
404 phi = parser.number()
405 large, sweep = parser.flag(), parser.flag()
406 end = (parser.number(), parser.number())
407 if cmd == "a":
408 end = (end[0] + current[0], end[1] + current[1])
409 if not pts:
410 pts.append(current)
411 pts.extend(arc_points(current[0], current[1], rx, ry, phi, large, sweep, end[0], end[1], tol))
412 current = pts[-1] if pts else end
413 cubic = None
414 quad = None
415 continue
416 raise ValueError(f"onbekend padcommando {cmd}")
417 finish()
418 return out
419
420
421 def _ellipse(cx: float, cy: float, rx: float, ry: float, tol: float) -> Polyline:
422 radius = max(rx, ry, 0.1)
423 steps = max(16, int(math.tau * radius / max(tol * 4, 0.4)))
424 return [
425 (cx + rx * math.cos(math.tau * i / steps), cy + ry * math.sin(math.tau * i / steps))
426 for i in range(steps + 1)
427 ]
428
429
430 def import_svg(text: str, curve_tol: float = 0.08) -> dict:
431 text = text.lstrip("\ufeff")
432 text = re.sub(r"<!DOCTYPE[^>]*>", "", text, count=1, flags=re.I)
433 root = ET.fromstring(text)
434 css: dict[str, dict[str, str]] = {}
435 warnings: list[str] = []
436
437 def collect_css(el: ET.Element) -> None:
438 if _local(el.tag) == "style" and el.text:
439 css.update(_css(el.text))
440 for child in list(el):
441 collect_css(child)
442
443 collect_css(root)
444 width = _parse_length_mm(root.get("width"))
445 height = _parse_length_mm(root.get("height"))
446 view = _numbers(root.get("viewBox") or "")
447 if len(view) == 4 and view[2] > 0 and view[3] > 0:
448 vb_x, vb_y, vb_w, vb_h = view
449 else:
450 vb_x, vb_y = 0.0, 0.0
451 vb_w = width or 210.0
452 vb_h = height or 297.0
453 if width is None:
454 width = vb_w * 25.4 / 96 if vb_w > 400 else vb_w
455 if height is None:
456 height = vb_h * 25.4 / 96 if vb_h > 400 else vb_h
457 if width is None:
458 width = vb_w if vb_w <= 500 else vb_w * 25.4 / 96
459 if height is None:
460 height = vb_h if vb_h <= 500 else vb_h * 25.4 / 96
461 aspect = (root.get("preserveAspectRatio") or "xMidYMid meet").strip()
462 if aspect == "none" or "none" in aspect.split():
463 scale_x = width / vb_w
464 scale_y = height / vb_h
465 origin_x = origin_y = 0.0
466 else:
467 scale = min(width / vb_w, height / vb_h)
468 scale_x = scale_y = scale
469 origin_x = (width - vb_w * scale) / 2
470 origin_y = (height - vb_h * scale) / 2
471
472 strokes: list[dict] = []
473 fills: list[dict] = []
474
475 def to_page(point: Point) -> list[float]:
476 x, y = point
477 px = (x - vb_x) * scale_x + origin_x
478 py = (y - vb_y) * scale_y + origin_y
479 return [round(px, 3), round(height - py, 3)]
480
481 def add_subpaths(subs: list[tuple[Polyline, bool]], style: dict, matrix: tuple) -> None:
482 mapped: list[tuple[Polyline, bool]] = []
483 for pts, closed in subs:
484 page = []
485 for x, y in pts:
486 page.append(tuple(to_page(_apply(matrix, x, y))))
487 page = rdp(dedupe([(float(x), float(y)) for x, y in page], 0.02), 0.06)
488 if len(page) >= 2 and _length(page) >= 0.25:
489 mapped.append((page, closed or is_closed(page, 0.25)))
490 if not mapped:
491 return
492 fill_rgb = _color(style.get("fill"))
493 stroke_rgb = _color(style.get("stroke"))
494 painted = fill_rgb is not None and _alpha(style, "fill-opacity") > 0.04
495 stroke_on = stroke_rgb is not None and _alpha(style, "stroke-opacity") > 0.04
496 gray = 1.0
497 fill_on = painted
498 if painted and fill_rgb is not None:
499 opacity = _alpha(style, "fill-opacity")
500 gray = _luminance(fill_rgb) * opacity + (1 - opacity)
501 if gray >= 0.97:
502 fill_on = False
503 rule = (style.get("fill-rule") or "nonzero").lower()
504 if rule not in ("evenodd", "nonzero"):
505 rule = "nonzero"
506 closed_rings = [pts for pts, closed in mapped if closed]
507 if stroke_on:
508 for pts, closed in mapped:
509 strokes.append({"pts": [[x, y] for x, y in pts], "closed": closed, "fromFill": False})
510 elif painted:
511 for pts in closed_rings:
512 strokes.append({"pts": [[x, y] for x, y in pts], "closed": True, "fromFill": True})
513 if fill_on and closed_rings:
514 fills.append(
515 {
516 "rings": [[[x, y] for x, y in pts] for pts in closed_rings],
517 "gray": round(gray, 4),
518 "rule": rule,
519 }
520 )
521
522 def style_of(el: ET.Element, parent: dict) -> dict:
523 style = dict(parent)
524 for key in ("fill", "stroke", "fill-rule", "fill-opacity", "stroke-opacity", "opacity", "display", "visibility"):
525 if el.get(key) is not None:
526 style[key] = el.get(key)
527 for name in (el.get("class") or "").split():
528 style.update(css.get(name, {}))
529 if el.get("style"):
530 style.update(_decls(el.get("style") or ""))
531 return style
532
533 def walk(el: ET.Element, matrix: tuple, parent: dict) -> None:
534 tag = _local(el.tag)
535 if tag in ("defs", "metadata", "title", "desc", "style", "clippath", "mask", "pattern", "symbol", "marker"):
536 return
537 if tag == "text":
538 if "tekst" not in " ".join(warnings):
539 warnings.append("Tekst in de SVG is overgeslagen. Plaats tekst met de tekstknop, dat is een enkel-lijn-font.")
540 return
541 if tag in ("image", "use"):
542 if tag not in " ".join(warnings):
543 warnings.append("Afbeeldingen en use-verwijzingen in de SVG zijn overgeslagen.")
544 return
545 style = style_of(el, parent)
546 if style.get("display") == "none" or style.get("visibility") == "hidden":
547 return
548 matrix = _mul(matrix, _parse_transform(el.get("transform")))
549 if tag in ("g", "svg", "a"):
550 for child in list(el):
551 walk(child, matrix, style)
552 return
553 try:
554 if tag == "path":
555 add_subpaths(_subpaths(el.get("d") or "", curve_tol), style, matrix)
556 elif tag == "line":
557 subs = [([(float(el.get("x1") or 0), float(el.get("y1") or 0)),
558 (float(el.get("x2") or 0), float(el.get("y2") or 0))], False)]
559 forced = dict(style)
560 if _color(forced.get("stroke")) is None:
561 forced["stroke"] = "#000"
562 forced["fill"] = "none"
563 add_subpaths(subs, forced, matrix)
564 elif tag in ("polyline", "polygon"):
565 nums = _numbers(el.get("points") or "")
566 pts = [(nums[i], nums[i + 1]) for i in range(0, len(nums) - 1, 2)]
567 if tag == "polygon" and pts:
568 pts = pts + [pts[0]]
569 add_subpaths([(pts, tag == "polygon")], style, matrix)
570 elif tag == "rect":
571 x, y = float(el.get("x") or 0), float(el.get("y") or 0)
572 w, h = float(el.get("width") or 0), float(el.get("height") or 0)
573 pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]
574 add_subpaths([(pts, True)], style, matrix)
575 elif tag in ("circle", "ellipse"):
576 cx, cy = float(el.get("cx") or 0), float(el.get("cy") or 0)
577 if tag == "circle":
578 rx = ry = float(el.get("r") or 0)
579 else:
580 rx, ry = float(el.get("rx") or 0), float(el.get("ry") or 0)
581 add_subpaths([(_ellipse(cx, cy, rx, ry, curve_tol), True)], style, matrix)
582 except Exception as exc:
583 warnings.append(f"Een vorm is overgeslagen ({exc}).")
584
585 root_style = style_of(root, {
586 "fill": "#000000",
587 "stroke": "none",
588 "fill-rule": "nonzero",
589 "fill-opacity": "1",
590 "stroke-opacity": "1",
591 "opacity": "1",
592 })
593 for child in list(root):
594 walk(child, (1, 0, 0, 1, 0, 0), root_style)
595
596 _fit(strokes, fills, width, height)
597 return center_geometry({"strokes": strokes, "fills": fills, "warnings": warnings})
598
599
600 def _length(pts: Polyline) -> float:
601 return sum(dist(a, b) for a, b in zip(pts, pts[1:]))
602
603
604 def _fit(strokes: list[dict], fills: list[dict], page_w: float, page_h: float) -> None:
605 if abs(page_w - A4_W) < 3 and abs(page_h - A4_H) < 3:
606 return
607 polys = _all_polys(strokes, fills)
608 box = bounds(polys)
609 if box is None:
610 return
611 minx, miny, maxx, maxy = box
612 bw, bh = maxx - minx, maxy - miny
613 if bw < 1e-6 or bh < 1e-6:
614 return
615 margin = 12.0
616 scale = min((A4_W - 2 * margin) / bw, (A4_H - 2 * margin) / bh)
617 ox = (A4_W - bw * scale) / 2 - minx * scale
618 oy = (A4_H - bh * scale) / 2 - miny * scale
619
620 def map_pt(p: list[float]) -> list[float]:
621 return [round(p[0] * scale + ox, 3), round(p[1] * scale + oy, 3)]
622
623 for stroke in strokes:
624 stroke["pts"] = [map_pt(p) for p in stroke["pts"]]
625 for fill in fills:
626 fill["rings"] = [[map_pt(p) for p in ring] for ring in fill["rings"]]
627
628
629 def _all_polys(strokes: list[dict], fills: list[dict]) -> list[Polyline]:
630 polys: list[Polyline] = []
631 for stroke in strokes:
632 polys.append([(p[0], p[1]) for p in stroke["pts"]])
633 for fill in fills:
634 for ring in fill["rings"]:
635 polys.append([(p[0], p[1]) for p in ring])
636 return polys
637
638
639 def center_geometry(data: dict) -> dict:
640 polys = _all_polys(data.get("strokes") or [], data.get("fills") or [])
641 box = bounds(polys)
642 if box is None:
643 data["x"] = A4_W / 2
644 data["y"] = A4_H / 2
645 return data
646 minx, miny, maxx, maxy = box
647 cx, cy = (minx + maxx) / 2, (miny + maxy) / 2
648
649 def shift(p: list[float]) -> list[float]:
650 return [round(p[0] - cx, 3), round(p[1] - cy, 3)]
651
652 for stroke in data["strokes"]:
653 stroke["pts"] = [shift(p) for p in stroke["pts"]]
654 for fill in data["fills"]:
655 fill["rings"] = [[shift(p) for p in ring] for ring in fill["rings"]]
656 data["x"] = round(cx, 3)
657 data["y"] = round(cy, 3)
658 return data
@@ -0,0 +1,658 @@
1"""SVG naar millimeter-paden, met Y omhoog en oorsprong linksonder."""
2
3from __future__ import annotations
4
5import math
6import re
7import xml.etree.ElementTree as ET
8
9from timdraw.geom import (
10 A4_H,
11 A4_W,
12 Point,
13 Polyline,
14 arc_points,
15 bounds,
16 dedupe,
17 dist,
18 flatten_cubic,
19 flatten_quad,
20 is_closed,
21 rdp,
22)
23
24_LENGTH = re.compile(
25 r"^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)\s*(mm|cm|in|pt|pc|px|%)?\s*$"
26)
27_TRANSFORM = re.compile(r"([a-zA-Z]+)\s*\(([^)]*)\)")
28_CSS_RULE = re.compile(r"([^{]+)\{([^}]+)\}")
29_NUMBER = re.compile(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?")
30
31_NAMED = {
32 "black": (0, 0, 0),
33 "white": (255, 255, 255),
34 "red": (255, 0, 0),
35 "green": (0, 128, 0),
36 "blue": (0, 0, 255),
37 "gray": (128, 128, 128),
38 "grey": (128, 128, 128),
39 "orange": (255, 165, 0),
40 "yellow": (255, 255, 0),
41}
42
43
44def _local(tag: str) -> str:
45 return tag.rsplit("}", 1)[-1] if tag else ""
46
47
48def _parse_length_mm(value: str | None) -> float | None:
49 if not value:
50 return None
51 match = _LENGTH.match(value.strip())
52 if not match:
53 return None
54 number = float(match.group(1))
55 unit = (match.group(2) or "").lower()
56 factors = {"": None, "px": 25.4 / 96, "mm": 1, "cm": 10, "in": 25.4, "pt": 25.4 / 72, "pc": 25.4 / 6}
57 if unit == "%":
58 return None
59 factor = factors.get(unit)
60 if factor is None:
61 return None
62 return number * factor
63
64
65def _numbers(text: str) -> list[float]:
66 return [float(item) for item in _NUMBER.findall(text or "")]
67
68
69def _mul(m1: tuple, m2: tuple) -> tuple:
70 a1, b1, c1, d1, e1, f1 = m1
71 a2, b2, c2, d2, e2, f2 = m2
72 return (
73 a1 * a2 + c1 * b2,
74 b1 * a2 + d1 * b2,
75 a1 * c2 + c1 * d2,
76 b1 * c2 + d1 * d2,
77 a1 * e2 + c1 * f2 + e1,
78 b1 * e2 + d1 * f2 + f1,
79 )
80
81
82def _apply(matrix: tuple, x: float, y: float) -> Point:
83 a, b, c, d, e, f = matrix
84 return a * x + c * y + e, b * x + d * y + f
85
86
87def _parse_transform(text: str | None) -> tuple:
88 matrix = (1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
89 if not text:
90 return matrix
91 for name, args in _TRANSFORM.findall(text):
92 vals = _numbers(args)
93 name = name.lower()
94 if name == "matrix" and len(vals) >= 6:
95 part = tuple(vals[:6])
96 elif name == "translate":
97 tx = vals[0] if vals else 0.0
98 ty = vals[1] if len(vals) > 1 else 0.0
99 part = (1.0, 0.0, 0.0, 1.0, tx, ty)
100 elif name == "scale":
101 sx = vals[0] if vals else 1.0
102 sy = vals[1] if len(vals) > 1 else sx
103 part = (sx, 0.0, 0.0, sy, 0.0, 0.0)
104 elif name == "rotate":
105 angle = math.radians(vals[0] if vals else 0.0)
106 ca, sa = math.cos(angle), math.sin(angle)
107 rot = (ca, sa, -sa, ca, 0.0, 0.0)
108 if len(vals) >= 3:
109 tx, ty = vals[1], vals[2]
110 rot = _mul((1, 0, 0, 1, tx, ty), _mul(rot, (1, 0, 0, 1, -tx, -ty)))
111 part = rot
112 elif name == "skewx" and vals:
113 part = (1.0, 0.0, math.tan(math.radians(vals[0])), 1.0, 0.0, 0.0)
114 elif name == "skewy" and vals:
115 part = (1.0, math.tan(math.radians(vals[0])), 0.0, 1.0, 0.0, 0.0)
116 else:
117 continue
118 matrix = _mul(matrix, part)
119 return matrix
120
121
122def _decls(text: str) -> dict[str, str]:
123 found: dict[str, str] = {}
124 for part in text.split(";"):
125 if ":" not in part:
126 continue
127 key, value = part.split(":", 1)
128 found[key.strip().lower()] = value.strip()
129 return found
130
131
132def _css(text: str) -> dict[str, dict[str, str]]:
133 text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
134 rules: dict[str, dict[str, str]] = {}
135 for selector, body in _CSS_RULE.findall(text):
136 decl = _decls(body)
137 for item in selector.split(","):
138 item = item.strip()
139 if item.startswith("."):
140 rules.setdefault(item[1:], {}).update(decl)
141 return rules
142
143
144def _channel(value: str) -> int:
145 value = value.strip()
146 if value.endswith("%"):
147 return max(0, min(255, round(float(value[:-1]) * 2.55)))
148 return max(0, min(255, round(float(value))))
149
150
151def _color(value: str | None) -> tuple[int, int, int] | None:
152 if not value:
153 return None
154 value = value.strip().lower()
155 if value in ("none", "transparent"):
156 return None
157 if value in _NAMED:
158 return _NAMED[value]
159 if value.startswith("#"):
160 hex_value = value[1:]
161 if len(hex_value) == 3:
162 hex_value = "".join(ch * 2 for ch in hex_value)
163 if len(hex_value) >= 6:
164 return tuple(int(hex_value[i : i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
165 if value.startswith("rgb"):
166 nums = _numbers(value)
167 if len(nums) >= 3:
168 parts = value[value.find("(") + 1 :].split(",")
169 if len(parts) >= 3:
170 return _channel(parts[0]), _channel(parts[1]), _channel(parts[2])
171 return (0, 0, 0)
172
173
174def _luminance(rgb: tuple[int, int, int]) -> float:
175 def lin(channel: int) -> float:
176 c = channel / 255.0
177 return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
178
179 r, g, b = (lin(c) for c in rgb)
180 return 0.2126 * r + 0.7152 * g + 0.0722 * b
181
182
183def _alpha(style: dict, key: str) -> float:
184 try:
185 own = float(style.get(key, "1"))
186 except ValueError:
187 own = 1.0
188 try:
189 extra = float(style.get("opacity", "1"))
190 except ValueError:
191 extra = 1.0
192 return max(0.0, min(1.0, own * extra))
193
194
195class _Path:
196 def __init__(self, data: str):
197 self.d = data or ""
198 self.i = 0
199 self.n = len(self.d)
200
201 def _skip(self) -> None:
202 while self.i < self.n and self.d[self.i] in " \t\r\n,":
203 self.i += 1
204
205 def command(self) -> str | None:
206 self._skip()
207 if self.i < self.n and self.d[self.i].isalpha():
208 cmd = self.d[self.i]
209 self.i += 1
210 return cmd
211 return None
212
213 def has_number(self) -> bool:
214 self._skip()
215 if self.i >= self.n:
216 return False
217 ch = self.d[self.i]
218 return ch.isdigit() or ch in "+-."
219
220 def number(self) -> float:
221 self._skip()
222 start = self.i
223 if self.i < self.n and self.d[self.i] in "+-":
224 self.i += 1
225 saw = False
226 while self.i < self.n and self.d[self.i].isdigit():
227 saw = True
228 self.i += 1
229 if self.i < self.n and self.d[self.i] == ".":
230 self.i += 1
231 while self.i < self.n and self.d[self.i].isdigit():
232 saw = True
233 self.i += 1
234 if self.i < self.n and self.d[self.i] in "eE":
235 j = self.i + 1
236 if j < self.n and self.d[j] in "+-":
237 j += 1
238 if j < self.n and self.d[j].isdigit():
239 self.i = j + 1
240 while self.i < self.n and self.d[self.i].isdigit():
241 self.i += 1
242 saw = True
243 if not saw:
244 raise ValueError("getal verwacht in pad")
245 return float(self.d[start : self.i])
246
247 def flag(self) -> int:
248 self._skip()
249 if self.i < self.n and self.d[self.i] in "01":
250 value = self.d[self.i]
251 self.i += 1
252 # 0110 is vlag 0, vlag 1, en daarna een getal
253 return int(value)
254 return 1 if self.number() else 0
255
256
257def _subpaths(data: str, tol: float) -> list[tuple[Polyline, bool]]:
258 parser = _Path(data)
259 current = (0.0, 0.0)
260 start = (0.0, 0.0)
261 cubic: Point | None = None
262 quad: Point | None = None
263 cmd: str | None = None
264 out: list[tuple[Polyline, bool]] = []
265 pts: Polyline = []
266 closed = False
267
268 def finish() -> None:
269 nonlocal pts, closed
270 cleaned = dedupe(pts)
271 if len(cleaned) >= 2:
272 out.append((cleaned, closed or is_closed(cleaned, 0.15)))
273 pts = []
274 closed = False
275
276 def line_to(point: Point) -> None:
277 nonlocal current, cubic, quad
278 if not pts:
279 pts.append(current)
280 pts.append(point)
281 current = point
282 cubic = None
283 quad = None
284
285 while True:
286 nxt = parser.command()
287 if nxt is None:
288 if cmd is None or not parser.has_number():
289 break
290 else:
291 cmd = nxt
292 if cmd in "Zz":
293 if pts:
294 pts.append(start)
295 closed = True
296 current = start
297 finish()
298 cubic = None
299 quad = None
300 continue
301 if cmd in "Mm":
302 if pts:
303 finish()
304 x, y = parser.number(), parser.number()
305 if cmd == "m":
306 x += current[0]
307 y += current[1]
308 current = (x, y)
309 start = current
310 pts = [current]
311 closed = False
312 cmd = "L" if cmd == "M" else "l"
313 while parser.has_number():
314 x, y = parser.number(), parser.number()
315 if cmd == "l":
316 x += current[0]
317 y += current[1]
318 line_to((x, y))
319 continue
320 if cmd in "Ll":
321 while parser.has_number():
322 x, y = parser.number(), parser.number()
323 if cmd == "l":
324 x += current[0]
325 y += current[1]
326 line_to((x, y))
327 continue
328 if cmd in "Hh":
329 while parser.has_number():
330 x = parser.number()
331 if cmd == "h":
332 x += current[0]
333 line_to((x, current[1]))
334 continue
335 if cmd in "Vv":
336 while parser.has_number():
337 y = parser.number()
338 if cmd == "v":
339 y += current[1]
340 line_to((current[0], y))
341 continue
342 if cmd in "Cc":
343 while parser.has_number():
344 c1 = (parser.number(), parser.number())
345 c2 = (parser.number(), parser.number())
346 end = (parser.number(), parser.number())
347 if cmd == "c":
348 c1 = (c1[0] + current[0], c1[1] + current[1])
349 c2 = (c2[0] + current[0], c2[1] + current[1])
350 end = (end[0] + current[0], end[1] + current[1])
351 if not pts:
352 pts.append(current)
353 extra = flatten_cubic(current, c1, c2, end, tol)
354 pts.extend(extra)
355 current = end
356 cubic = c2
357 quad = None
358 continue
359 if cmd in "Ss":
360 while parser.has_number():
361 c2 = (parser.number(), parser.number())
362 end = (parser.number(), parser.number())
363 if cmd == "s":
364 c2 = (c2[0] + current[0], c2[1] + current[1])
365 end = (end[0] + current[0], end[1] + current[1])
366 c1 = (2 * current[0] - cubic[0], 2 * current[1] - cubic[1]) if cubic else current
367 if not pts:
368 pts.append(current)
369 pts.extend(flatten_cubic(current, c1, c2, end, tol))
370 current = end
371 cubic = c2
372 quad = None
373 continue
374 if cmd in "Qq":
375 while parser.has_number():
376 ctrl = (parser.number(), parser.number())
377 end = (parser.number(), parser.number())
378 if cmd == "q":
379 ctrl = (ctrl[0] + current[0], ctrl[1] + current[1])
380 end = (end[0] + current[0], end[1] + current[1])
381 if not pts:
382 pts.append(current)
383 pts.extend(flatten_quad(current, ctrl, end, tol))
384 current = end
385 quad = ctrl
386 cubic = None
387 continue
388 if cmd in "Tt":
389 while parser.has_number():
390 end = (parser.number(), parser.number())
391 if cmd == "t":
392 end = (end[0] + current[0], end[1] + current[1])
393 ctrl = (2 * current[0] - quad[0], 2 * current[1] - quad[1]) if quad else current
394 if not pts:
395 pts.append(current)
396 pts.extend(flatten_quad(current, ctrl, end, tol))
397 current = end
398 quad = ctrl
399 cubic = None
400 continue
401 if cmd in "Aa":
402 while parser.has_number():
403 rx, ry = parser.number(), parser.number()
404 phi = parser.number()
405 large, sweep = parser.flag(), parser.flag()
406 end = (parser.number(), parser.number())
407 if cmd == "a":
408 end = (end[0] + current[0], end[1] + current[1])
409 if not pts:
410 pts.append(current)
411 pts.extend(arc_points(current[0], current[1], rx, ry, phi, large, sweep, end[0], end[1], tol))
412 current = pts[-1] if pts else end
413 cubic = None
414 quad = None
415 continue
416 raise ValueError(f"onbekend padcommando {cmd}")
417 finish()
418 return out
419
420
421def _ellipse(cx: float, cy: float, rx: float, ry: float, tol: float) -> Polyline:
422 radius = max(rx, ry, 0.1)
423 steps = max(16, int(math.tau * radius / max(tol * 4, 0.4)))
424 return [
425 (cx + rx * math.cos(math.tau * i / steps), cy + ry * math.sin(math.tau * i / steps))
426 for i in range(steps + 1)
427 ]
428
429
430def import_svg(text: str, curve_tol: float = 0.08) -> dict:
431 text = text.lstrip("\ufeff")
432 text = re.sub(r"<!DOCTYPE[^>]*>", "", text, count=1, flags=re.I)
433 root = ET.fromstring(text)
434 css: dict[str, dict[str, str]] = {}
435 warnings: list[str] = []
436
437 def collect_css(el: ET.Element) -> None:
438 if _local(el.tag) == "style" and el.text:
439 css.update(_css(el.text))
440 for child in list(el):
441 collect_css(child)
442
443 collect_css(root)
444 width = _parse_length_mm(root.get("width"))
445 height = _parse_length_mm(root.get("height"))
446 view = _numbers(root.get("viewBox") or "")
447 if len(view) == 4 and view[2] > 0 and view[3] > 0:
448 vb_x, vb_y, vb_w, vb_h = view
449 else:
450 vb_x, vb_y = 0.0, 0.0
451 vb_w = width or 210.0
452 vb_h = height or 297.0
453 if width is None:
454 width = vb_w * 25.4 / 96 if vb_w > 400 else vb_w
455 if height is None:
456 height = vb_h * 25.4 / 96 if vb_h > 400 else vb_h
457 if width is None:
458 width = vb_w if vb_w <= 500 else vb_w * 25.4 / 96
459 if height is None:
460 height = vb_h if vb_h <= 500 else vb_h * 25.4 / 96
461 aspect = (root.get("preserveAspectRatio") or "xMidYMid meet").strip()
462 if aspect == "none" or "none" in aspect.split():
463 scale_x = width / vb_w
464 scale_y = height / vb_h
465 origin_x = origin_y = 0.0
466 else:
467 scale = min(width / vb_w, height / vb_h)
468 scale_x = scale_y = scale
469 origin_x = (width - vb_w * scale) / 2
470 origin_y = (height - vb_h * scale) / 2
471
472 strokes: list[dict] = []
473 fills: list[dict] = []
474
475 def to_page(point: Point) -> list[float]:
476 x, y = point
477 px = (x - vb_x) * scale_x + origin_x
478 py = (y - vb_y) * scale_y + origin_y
479 return [round(px, 3), round(height - py, 3)]
480
481 def add_subpaths(subs: list[tuple[Polyline, bool]], style: dict, matrix: tuple) -> None:
482 mapped: list[tuple[Polyline, bool]] = []
483 for pts, closed in subs:
484 page = []
485 for x, y in pts:
486 page.append(tuple(to_page(_apply(matrix, x, y))))
487 page = rdp(dedupe([(float(x), float(y)) for x, y in page], 0.02), 0.06)
488 if len(page) >= 2 and _length(page) >= 0.25:
489 mapped.append((page, closed or is_closed(page, 0.25)))
490 if not mapped:
491 return
492 fill_rgb = _color(style.get("fill"))
493 stroke_rgb = _color(style.get("stroke"))
494 painted = fill_rgb is not None and _alpha(style, "fill-opacity") > 0.04
495 stroke_on = stroke_rgb is not None and _alpha(style, "stroke-opacity") > 0.04
496 gray = 1.0
497 fill_on = painted
498 if painted and fill_rgb is not None:
499 opacity = _alpha(style, "fill-opacity")
500 gray = _luminance(fill_rgb) * opacity + (1 - opacity)
501 if gray >= 0.97:
502 fill_on = False
503 rule = (style.get("fill-rule") or "nonzero").lower()
504 if rule not in ("evenodd", "nonzero"):
505 rule = "nonzero"
506 closed_rings = [pts for pts, closed in mapped if closed]
507 if stroke_on:
508 for pts, closed in mapped:
509 strokes.append({"pts": [[x, y] for x, y in pts], "closed": closed, "fromFill": False})
510 elif painted:
511 for pts in closed_rings:
512 strokes.append({"pts": [[x, y] for x, y in pts], "closed": True, "fromFill": True})
513 if fill_on and closed_rings:
514 fills.append(
515 {
516 "rings": [[[x, y] for x, y in pts] for pts in closed_rings],
517 "gray": round(gray, 4),
518 "rule": rule,
519 }
520 )
521
522 def style_of(el: ET.Element, parent: dict) -> dict:
523 style = dict(parent)
524 for key in ("fill", "stroke", "fill-rule", "fill-opacity", "stroke-opacity", "opacity", "display", "visibility"):
525 if el.get(key) is not None:
526 style[key] = el.get(key)
527 for name in (el.get("class") or "").split():
528 style.update(css.get(name, {}))
529 if el.get("style"):
530 style.update(_decls(el.get("style") or ""))
531 return style
532
533 def walk(el: ET.Element, matrix: tuple, parent: dict) -> None:
534 tag = _local(el.tag)
535 if tag in ("defs", "metadata", "title", "desc", "style", "clippath", "mask", "pattern", "symbol", "marker"):
536 return
537 if tag == "text":
538 if "tekst" not in " ".join(warnings):
539 warnings.append("Tekst in de SVG is overgeslagen. Plaats tekst met de tekstknop, dat is een enkel-lijn-font.")
540 return
541 if tag in ("image", "use"):
542 if tag not in " ".join(warnings):
543 warnings.append("Afbeeldingen en use-verwijzingen in de SVG zijn overgeslagen.")
544 return
545 style = style_of(el, parent)
546 if style.get("display") == "none" or style.get("visibility") == "hidden":
547 return
548 matrix = _mul(matrix, _parse_transform(el.get("transform")))
549 if tag in ("g", "svg", "a"):
550 for child in list(el):
551 walk(child, matrix, style)
552 return
553 try:
554 if tag == "path":
555 add_subpaths(_subpaths(el.get("d") or "", curve_tol), style, matrix)
556 elif tag == "line":
557 subs = [([(float(el.get("x1") or 0), float(el.get("y1") or 0)),
558 (float(el.get("x2") or 0), float(el.get("y2") or 0))], False)]
559 forced = dict(style)
560 if _color(forced.get("stroke")) is None:
561 forced["stroke"] = "#000"
562 forced["fill"] = "none"
563 add_subpaths(subs, forced, matrix)
564 elif tag in ("polyline", "polygon"):
565 nums = _numbers(el.get("points") or "")
566 pts = [(nums[i], nums[i + 1]) for i in range(0, len(nums) - 1, 2)]
567 if tag == "polygon" and pts:
568 pts = pts + [pts[0]]
569 add_subpaths([(pts, tag == "polygon")], style, matrix)
570 elif tag == "rect":
571 x, y = float(el.get("x") or 0), float(el.get("y") or 0)
572 w, h = float(el.get("width") or 0), float(el.get("height") or 0)
573 pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)]
574 add_subpaths([(pts, True)], style, matrix)
575 elif tag in ("circle", "ellipse"):
576 cx, cy = float(el.get("cx") or 0), float(el.get("cy") or 0)
577 if tag == "circle":
578 rx = ry = float(el.get("r") or 0)
579 else:
580 rx, ry = float(el.get("rx") or 0), float(el.get("ry") or 0)
581 add_subpaths([(_ellipse(cx, cy, rx, ry, curve_tol), True)], style, matrix)
582 except Exception as exc:
583 warnings.append(f"Een vorm is overgeslagen ({exc}).")
584
585 root_style = style_of(root, {
586 "fill": "#000000",
587 "stroke": "none",
588 "fill-rule": "nonzero",
589 "fill-opacity": "1",
590 "stroke-opacity": "1",
591 "opacity": "1",
592 })
593 for child in list(root):
594 walk(child, (1, 0, 0, 1, 0, 0), root_style)
595
596 _fit(strokes, fills, width, height)
597 return center_geometry({"strokes": strokes, "fills": fills, "warnings": warnings})
598
599
600def _length(pts: Polyline) -> float:
601 return sum(dist(a, b) for a, b in zip(pts, pts[1:]))
602
603
604def _fit(strokes: list[dict], fills: list[dict], page_w: float, page_h: float) -> None:
605 if abs(page_w - A4_W) < 3 and abs(page_h - A4_H) < 3:
606 return
607 polys = _all_polys(strokes, fills)
608 box = bounds(polys)
609 if box is None:
610 return
611 minx, miny, maxx, maxy = box
612 bw, bh = maxx - minx, maxy - miny
613 if bw < 1e-6 or bh < 1e-6:
614 return
615 margin = 12.0
616 scale = min((A4_W - 2 * margin) / bw, (A4_H - 2 * margin) / bh)
617 ox = (A4_W - bw * scale) / 2 - minx * scale
618 oy = (A4_H - bh * scale) / 2 - miny * scale
619
620 def map_pt(p: list[float]) -> list[float]:
621 return [round(p[0] * scale + ox, 3), round(p[1] * scale + oy, 3)]
622
623 for stroke in strokes:
624 stroke["pts"] = [map_pt(p) for p in stroke["pts"]]
625 for fill in fills:
626 fill["rings"] = [[map_pt(p) for p in ring] for ring in fill["rings"]]
627
628
629def _all_polys(strokes: list[dict], fills: list[dict]) -> list[Polyline]:
630 polys: list[Polyline] = []
631 for stroke in strokes:
632 polys.append([(p[0], p[1]) for p in stroke["pts"]])
633 for fill in fills:
634 for ring in fill["rings"]:
635 polys.append([(p[0], p[1]) for p in ring])
636 return polys
637
638
639def center_geometry(data: dict) -> dict:
640 polys = _all_polys(data.get("strokes") or [], data.get("fills") or [])
641 box = bounds(polys)
642 if box is None:
643 data["x"] = A4_W / 2
644 data["y"] = A4_H / 2
645 return data
646 minx, miny, maxx, maxy = box
647 cx, cy = (minx + maxx) / 2, (miny + maxy) / 2
648
649 def shift(p: list[float]) -> list[float]:
650 return [round(p[0] - cx, 3), round(p[1] - cy, 3)]
651
652 for stroke in data["strokes"]:
653 stroke["pts"] = [shift(p) for p in stroke["pts"]]
654 for fill in data["fills"]:
655 fill["rings"] = [[shift(p) for p in ring] for ring in fill["rings"]]
656 data["x"] = round(cx, 3)
657 data["y"] = round(cy, 3)
658 return data