feat: zigzag-arcering en overlappende lijnen overslaan
Zigzag laat hatchlijnen schuin aansluiten zodat de pen minder hoeft te tillen. Overlappende lijnen worden geteld en, als de optie aanstaat, maar één keer getekend.
@@ -44,6 +44,7 @@ const defaults = {
44
44
hatchAngle: 45,
45
45
hatchSpacing: 2,
46
46
crosshatch: false,
47
zigzag: false,
47
48
grayscale: false,
48
49
graySteps: 5,
49
50
spacingMin: 0.8,
@@ -94,6 +95,7 @@ function readSettings ()
94
95
dwellMs: Number($("dwell").value),
95
96
origin: $("origin").value,
96
97
perObject: $("per-object").checked,
98
ignoreOverlap: $("ignore-overlap").checked,
97
99
showTravel: $("show-travel").checked,
98
100
jogStep: Number($("jog-step").value),
99
101
};
@@ -124,6 +126,7 @@ function hatchFromForm ()
124
126
hatchAngle: Number($("prop-angle").value),
125
127
hatchSpacing: Number($("prop-spacing").value),
126
128
crosshatch: $("prop-cross").checked,
129
zigzag: $("prop-zigzag").checked,
127
130
grayscale: $("prop-gray").checked,
128
131
graySteps: Number($("prop-steps").value),
129
132
spacingMin: Number($("prop-dark").value),
@@ -600,6 +603,7 @@ function applySaved (saved)
600
603
else $("origin").value = "top-left";
601
604
localStorage.setItem("timdraw-origin-v2", "1");
602
605
$("per-object").checked = !!settings.perObject;
606
$("ignore-overlap").checked = !!settings.ignoreOverlap;
603
607
$("show-travel").checked = !!settings.showTravel;
604
608
if (settings.jogStep) $("jog-step").value = String(settings.jogStep);
605
609
const composer = saved.composer || {};
@@ -633,6 +637,7 @@ async function refreshPreview ()
633
637
? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s`
634
638
: "";
635
639
if (data.warnings && data.warnings.length) toast(data.warnings[0]);
640
showOverlaps(stats.overlaps || 0);
636
641
} catch (error)
637
642
{
638
643
toast(error.message);
@@ -676,6 +681,7 @@ function fillForm ()
676
681
$("prop-spacing").value = obj.hatchSpacing;
677
682
$("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100)));
678
683
$("prop-cross").checked = !!obj.crosshatch;
684
$("prop-zigzag").checked = !!obj.zigzag;
679
685
$("prop-gray").checked = !!obj.grayscale;
680
686
$("prop-steps").value = obj.graySteps;
681
687
$("prop-dark").value = obj.spacingMin;
@@ -959,6 +965,7 @@ document.querySelectorAll('#prop-angle,#prop-steps,#prop-dark,#prop-light').forE
959
965
$("prop-spacing").addEventListener("input", () => syncPercent(false));
960
966
$("prop-percent").addEventListener("input", () => syncPercent(true));
961
967
$("prop-cross").addEventListener("change", applyForm);
968
$("prop-zigzag").addEventListener("change", applyForm);
962
969
$("prop-gray").addEventListener("change", applyForm);
963
970
$("prop-line").addEventListener("change", applyForm);
964
971
$("prop-fill").addEventListener("change", applyForm);
@@ -1104,9 +1111,26 @@ function moveLayer (dir)
1104
1111
schedulePreview();
1105
1112
}
1106
1113
1114
function showOverlaps (count)
1115
{
1116
const label = $("ignore-overlap-label");
1117
const on = $("ignore-overlap").checked;
1118
if (!on && count > 0)
1119
{
1120
label.classList.add("pulse");
1121
label.title = `${count} overlappende lijnen gevonden. Zet 'Overlappende lijnen negeren' aan.`;
1122
}
1123
else
1124
{
1125
label.classList.remove("pulse");
1126
label.title = "";
1127
}
1128
}
1129
1107
1130
$("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); persist(); };
1108
1131
$("show-travel").onchange = () => { draw(); persist(); };
1109
1132
$("per-object").addEventListener("change", schedulePreview);
1133
$("ignore-overlap").addEventListener("change", () => { persist(); schedulePreview(); });
1110
1134
$("jog-step").addEventListener("change", persist);
1111
1135
$("new-text").addEventListener("input", persist);
1112
1136
$("new-font").addEventListener("change", persist);
@@ -44,6 +44,7 @@ const defaults = {44
hatchAngle: 45,44
hatchAngle: 45,45
hatchSpacing: 2,45
hatchSpacing: 2,46
crosshatch: false,46
crosshatch: false,47
zigzag: false,47
grayscale: false,48
grayscale: false,48
graySteps: 5,49
graySteps: 5,49
spacingMin: 0.8,50
spacingMin: 0.8,@@ -94,6 +95,7 @@ function readSettings ()94
dwellMs: Number($("dwell").value),95
dwellMs: Number($("dwell").value),95
origin: $("origin").value,96
origin: $("origin").value,96
perObject: $("per-object").checked,97
perObject: $("per-object").checked,98
ignoreOverlap: $("ignore-overlap").checked,97
showTravel: $("show-travel").checked,99
showTravel: $("show-travel").checked,98
jogStep: Number($("jog-step").value),100
jogStep: Number($("jog-step").value),99
};101
};@@ -124,6 +126,7 @@ function hatchFromForm ()124
hatchAngle: Number($("prop-angle").value),126
hatchAngle: Number($("prop-angle").value),125
hatchSpacing: Number($("prop-spacing").value),127
hatchSpacing: Number($("prop-spacing").value),126
crosshatch: $("prop-cross").checked,128
crosshatch: $("prop-cross").checked,129
zigzag: $("prop-zigzag").checked,127
grayscale: $("prop-gray").checked,130
grayscale: $("prop-gray").checked,128
graySteps: Number($("prop-steps").value),131
graySteps: Number($("prop-steps").value),129
spacingMin: Number($("prop-dark").value),132
spacingMin: Number($("prop-dark").value),@@ -600,6 +603,7 @@ function applySaved (saved)600
else $("origin").value = "top-left";603
else $("origin").value = "top-left";601
localStorage.setItem("timdraw-origin-v2", "1");604
localStorage.setItem("timdraw-origin-v2", "1");602
$("per-object").checked = !!settings.perObject;605
$("per-object").checked = !!settings.perObject;606
$("ignore-overlap").checked = !!settings.ignoreOverlap;603
$("show-travel").checked = !!settings.showTravel;607
$("show-travel").checked = !!settings.showTravel;604
if (settings.jogStep) $("jog-step").value = String(settings.jogStep);608
if (settings.jogStep) $("jog-step").value = String(settings.jogStep);605
const composer = saved.composer || {};609
const composer = saved.composer || {};@@ -633,6 +637,7 @@ async function refreshPreview ()633
? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s`637
? `${stats.drawMm || 0} mm tekenen · ${stats.travelMm || 0} mm reizen · ongeveer ${minutes} min ${seconds} s`634
: "";638
: "";635
if (data.warnings && data.warnings.length) toast(data.warnings[0]);639
if (data.warnings && data.warnings.length) toast(data.warnings[0]);640
showOverlaps(stats.overlaps || 0);636
} catch (error)641
} catch (error)637
{642
{638
toast(error.message);643
toast(error.message);@@ -676,6 +681,7 @@ function fillForm ()676
$("prop-spacing").value = obj.hatchSpacing;681
$("prop-spacing").value = obj.hatchSpacing;677
$("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100)));682
$("prop-percent").value = Math.round(Math.min(100, Math.max(2, (PEN_MM / obj.hatchSpacing) * 100)));678
$("prop-cross").checked = !!obj.crosshatch;683
$("prop-cross").checked = !!obj.crosshatch;684
$("prop-zigzag").checked = !!obj.zigzag;679
$("prop-gray").checked = !!obj.grayscale;685
$("prop-gray").checked = !!obj.grayscale;680
$("prop-steps").value = obj.graySteps;686
$("prop-steps").value = obj.graySteps;681
$("prop-dark").value = obj.spacingMin;687
$("prop-dark").value = obj.spacingMin;@@ -959,6 +965,7 @@ document.querySelectorAll('#prop-angle,#prop-steps,#prop-dark,#prop-light').forE959
$("prop-spacing").addEventListener("input", () => syncPercent(false));965
$("prop-spacing").addEventListener("input", () => syncPercent(false));960
$("prop-percent").addEventListener("input", () => syncPercent(true));966
$("prop-percent").addEventListener("input", () => syncPercent(true));961
$("prop-cross").addEventListener("change", applyForm);967
$("prop-cross").addEventListener("change", applyForm);968
$("prop-zigzag").addEventListener("change", applyForm);962
$("prop-gray").addEventListener("change", applyForm);969
$("prop-gray").addEventListener("change", applyForm);963
$("prop-line").addEventListener("change", applyForm);970
$("prop-line").addEventListener("change", applyForm);964
$("prop-fill").addEventListener("change", applyForm);971
$("prop-fill").addEventListener("change", applyForm);@@ -1104,9 +1111,26 @@ function moveLayer (dir)1104
schedulePreview();1111
schedulePreview();1105
}1112
}1106
1113
1114
function showOverlaps (count)1115
{1116
const label = $("ignore-overlap-label");1117
const on = $("ignore-overlap").checked;1118
if (!on && count > 0)1119
{1120
label.classList.add("pulse");1121
label.title = `${count} overlappende lijnen gevonden. Zet 'Overlappende lijnen negeren' aan.`;1122
}1123
else1124
{1125
label.classList.remove("pulse");1126
label.title = "";1127
}1128
}1129
1107
$("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); persist(); };1130
$("btn-fit").onclick = () => { zoom = 1; panX = 0; panY = 0; draw(); persist(); };1108
$("show-travel").onchange = () => { draw(); persist(); };1131
$("show-travel").onchange = () => { draw(); persist(); };1109
$("per-object").addEventListener("change", schedulePreview);1132
$("per-object").addEventListener("change", schedulePreview);1133
$("ignore-overlap").addEventListener("change", () => { persist(); schedulePreview(); });1110
$("jog-step").addEventListener("change", persist);1134
$("jog-step").addEventListener("change", persist);1111
$("new-text").addEventListener("input", persist);1135
$("new-text").addEventListener("input", persist);1112
$("new-font").addEventListener("change", persist);1136
$("new-font").addEventListener("change", persist);@@ -76,6 +76,7 @@
76
76
<button id="btn-front" type="button">Voor</button>
77
77
</div>
78
78
<label class="check"><input id="per-object" type="checkbox"> Objecten individueel tekenen</label>
79
<label class="check" id="ignore-overlap-label"><input id="ignore-overlap" type="checkbox"> Overlappende lijnen negeren</label>
79
80
<p class="hint">Slepen verplaatst. Hoeken schalen. Het handvat boven het kader draait. Delete wist, Ctrl+C /
80
81
Ctrl+V kopieert.</p>
81
82
</section>
@@ -119,6 +120,7 @@
119
120
<input id="prop-percent" type="number" min="2" max="100" step="1" value="20">
120
121
</label>
121
122
<label class="check"><input id="prop-cross" type="checkbox"> Crosshatch</label>
123
<label class="check"><input id="prop-zigzag" type="checkbox"> Zigzag</label>
122
124
<label class="check"><input id="prop-gray" type="checkbox"> Grijswaarden</label>
123
125
<div id="gray-props">
124
126
<label class="field">Tredes
@@ -76,6 +76,7 @@76
<button id="btn-front" type="button">Voor</button>76
<button id="btn-front" type="button">Voor</button>77
</div>77
</div>78
<label class="check"><input id="per-object" type="checkbox"> Objecten individueel tekenen</label>78
<label class="check"><input id="per-object" type="checkbox"> Objecten individueel tekenen</label>79
<label class="check" id="ignore-overlap-label"><input id="ignore-overlap" type="checkbox"> Overlappende lijnen negeren</label>79
<p class="hint">Slepen verplaatst. Hoeken schalen. Het handvat boven het kader draait. Delete wist, Ctrl+C /80
<p class="hint">Slepen verplaatst. Hoeken schalen. Het handvat boven het kader draait. Delete wist, Ctrl+C /80
Ctrl+V kopieert.</p>81
Ctrl+V kopieert.</p>81
</section>82
</section>@@ -119,6 +120,7 @@119
<input id="prop-percent" type="number" min="2" max="100" step="1" value="20">120
<input id="prop-percent" type="number" min="2" max="100" step="1" value="20">120
</label>121
</label>121
<label class="check"><input id="prop-cross" type="checkbox"> Crosshatch</label>122
<label class="check"><input id="prop-cross" type="checkbox"> Crosshatch</label>123
<label class="check"><input id="prop-zigzag" type="checkbox"> Zigzag</label>122
<label class="check"><input id="prop-gray" type="checkbox"> Grijswaarden</label>124
<label class="check"><input id="prop-gray" type="checkbox"> Grijswaarden</label>123
<div id="gray-props">125
<div id="gray-props">124
<label class="field">Tredes126
<label class="field">Tredes@@ -241,6 +241,16 @@ h2 {
241
241
font-size: 0.92rem;
242
242
}
243
243
244
.check.pulse {
245
border-radius: 0.35rem;
246
animation: soft-pulse 1.8s ease-in-out infinite;
247
}
248
249
@keyframes soft-pulse {
250
0%, 100% { background: transparent; }
251
50% { background: rgba(215, 38, 61, 0.16); }
252
}
253
244
254
.modes {
245
255
display: flex;
246
256
gap: 1rem;
@@ -241,6 +241,16 @@ h2 {241
font-size: 0.92rem;241
font-size: 0.92rem;242
}242
}243
243
244
.check.pulse {245
border-radius: 0.35rem;246
animation: soft-pulse 1.8s ease-in-out infinite;247
}248
249
@keyframes soft-pulse {250
0%, 100% { background: transparent; }251
50% { background: rgba(215, 38, 61, 0.16); }252
}253
244
.modes {254
.modes {245
display: flex;255
display: flex;246
gap: 1rem;256
gap: 1rem;@@ -16,6 +16,7 @@ from timdraw.geom import (
16
16
grbl_arc_ok,
17
17
is_closed,
18
18
length_of,
19
strip_overlaps,
19
20
transform_point,
20
21
)
21
22
from timdraw.hatch import hatch, spacing_for_gray
@@ -171,6 +172,7 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
171
172
angle = float(obj.get("hatchAngle", 45) or 0)
172
173
spacing = _clamp(float(obj.get("hatchSpacing", 2) or 2), 0.3, 30)
173
174
cross = bool(obj.get("crosshatch"))
175
zigzag = bool(obj.get("zigzag"))
174
176
use_gray = bool(obj.get("grayscale"))
175
177
steps = int(obj.get("graySteps", 5) or 5)
176
178
dark = _clamp(float(obj.get("spacingMin", spacing) or spacing), 0.3, 30)
@@ -191,9 +193,9 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
191
193
continue
192
194
193
195
def add_hatch(rings: list[Polyline], gap: float, rule: str) -> None:
194
lines = hatch(rings, angle, gap, rule)
196
lines = hatch(rings, angle, gap, rule, zigzag)
195
197
if cross:
196
lines += hatch(rings, angle + 90, gap, rule)
198
lines += hatch(rings, angle + 90, gap, rule, zigzag)
197
199
bucket.extend(lines)
198
200
199
201
if want_fill and fills:
@@ -246,6 +248,9 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
246
248
else:
247
249
flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]
248
250
draw = _order_paths(flat, start)
251
filtered, overlaps = strip_overlaps(draw)
252
if settings.get("ignoreOverlap"):
253
draw = filtered
249
254
outside_paper = False
250
255
for pts in draw:
251
256
for x, y in pts:
@@ -359,5 +364,6 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
359
364
"seconds": round(seconds, 1),
360
365
"outside": clipped,
361
366
"lines": len(gcode),
367
"overlaps": overlaps,
362
368
},
363
369
}
@@ -16,6 +16,7 @@ from timdraw.geom import (16
grbl_arc_ok,16
grbl_arc_ok,17
is_closed,17
is_closed,18
length_of,18
length_of,19
strip_overlaps,19
transform_point,20
transform_point,20
)21
)21
from timdraw.hatch import hatch, spacing_for_gray22
from timdraw.hatch import hatch, spacing_for_gray@@ -171,6 +172,7 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:171
angle = float(obj.get("hatchAngle", 45) or 0)172
angle = float(obj.get("hatchAngle", 45) or 0)172
spacing = _clamp(float(obj.get("hatchSpacing", 2) or 2), 0.3, 30)173
spacing = _clamp(float(obj.get("hatchSpacing", 2) or 2), 0.3, 30)173
cross = bool(obj.get("crosshatch"))174
cross = bool(obj.get("crosshatch"))175
zigzag = bool(obj.get("zigzag"))174
use_gray = bool(obj.get("grayscale"))176
use_gray = bool(obj.get("grayscale"))175
steps = int(obj.get("graySteps", 5) or 5)177
steps = int(obj.get("graySteps", 5) or 5)176
dark = _clamp(float(obj.get("spacingMin", spacing) or spacing), 0.3, 30)178
dark = _clamp(float(obj.get("spacingMin", spacing) or spacing), 0.3, 30)@@ -191,9 +193,9 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:191
continue193
continue192
194
193
def add_hatch(rings: list[Polyline], gap: float, rule: str) -> None:195
def add_hatch(rings: list[Polyline], gap: float, rule: str) -> None:194
lines = hatch(rings, angle, gap, rule)196
lines = hatch(rings, angle, gap, rule, zigzag)195
if cross:197
if cross:196
lines += hatch(rings, angle + 90, gap, rule)198
lines += hatch(rings, angle + 90, gap, rule, zigzag)197
bucket.extend(lines)199
bucket.extend(lines)198
200
199
if want_fill and fills:201
if want_fill and fills:@@ -246,6 +248,9 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:246
else:248
else:247
flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]249
flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]248
draw = _order_paths(flat, start)250
draw = _order_paths(flat, start)251
filtered, overlaps = strip_overlaps(draw)252
if settings.get("ignoreOverlap"):253
draw = filtered249
outside_paper = False254
outside_paper = False250
for pts in draw:255
for pts in draw:251
for x, y in pts:256
for x, y in pts:@@ -359,5 +364,6 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:359
"seconds": round(seconds, 1),364
"seconds": round(seconds, 1),360
"outside": clipped,365
"outside": clipped,361
"lines": len(gcode),366
"lines": len(gcode),367
"overlaps": overlaps,362
},368
},363
}369
}@@ -52,6 +52,83 @@ def dedupe(pts: Polyline, tol: float = 0.01) -> Polyline:
52
52
return out
53
53
54
54
55
def _perp(p: Point, origin: Point, ux: float, uy: float) -> float:
56
return abs((p[0] - origin[0]) * uy - (p[1] - origin[1]) * ux)
57
58
59
def _along(p: Point, origin: Point, ux: float, uy: float) -> float:
60
return (p[0] - origin[0]) * ux + (p[1] - origin[1]) * uy
61
62
63
def strip_overlaps(lines: list[Polyline]) -> tuple[list[Polyline], int]:
64
"""Laat een lijn die exact op een eerdere lijn ligt weg. Geeft ook het aantal terug."""
65
kept: list[tuple[Point, Point]] = []
66
result: list[Polyline] = []
67
removed = 0
68
for poly in lines:
69
if len(poly) < 2:
70
continue
71
chunk: Polyline = []
72
for a, b in zip(poly, poly[1:]):
73
length = dist(a, b)
74
parts = _uncovered(a, b, kept)
75
kept_length = sum(dist(p, q) for p, q in parts)
76
if length > 0.15 and length - kept_length > 0.15:
77
removed += 1
78
if not parts:
79
if len(chunk) >= 2:
80
result.append(chunk)
81
chunk = []
82
continue
83
for p0, p1 in parts:
84
kept.append((p0, p1))
85
if chunk and dist(chunk[-1], p0) <= 0.03:
86
chunk.append(p1)
87
else:
88
if len(chunk) >= 2:
89
result.append(chunk)
90
chunk = [p0, p1]
91
if len(chunk) >= 2:
92
result.append(chunk)
93
return result, removed
94
95
96
def _uncovered(a: Point, b: Point, kept: list[tuple[Point, Point]]) -> list[tuple[Point, Point]]:
97
length = dist(a, b)
98
if length < 1e-4:
99
return []
100
ux, uy = (b[0] - a[0]) / length, (b[1] - a[1]) / length
101
covered: list[tuple[float, float]] = []
102
for c, d in kept:
103
if _perp(c, a, ux, uy) > 0.02 or _perp(d, a, ux, uy) > 0.02:
104
continue
105
t0, t1 = _along(c, a, ux, uy), _along(d, a, ux, uy)
106
lo, hi = (t0, t1) if t0 <= t1 else (t1, t0)
107
lo, hi = max(0.0, lo), min(length, hi)
108
if hi - lo > 0.01:
109
covered.append((lo, hi))
110
covered.sort()
111
merged: list[list[float]] = []
112
for lo, hi in covered:
113
if merged and lo <= merged[-1][1] + 0.01:
114
merged[-1][1] = max(merged[-1][1], hi)
115
else:
116
merged.append([lo, hi])
117
pieces: list[tuple[Point, Point]] = []
118
cursor = 0.0
119
120
def at(t: float) -> Point:
121
return (a[0] + ux * t, a[1] + uy * t)
122
123
for lo, hi in merged:
124
if lo - cursor > 0.12:
125
pieces.append((at(cursor), at(lo)))
126
cursor = max(cursor, hi)
127
if length - cursor > 0.12:
128
pieces.append((at(cursor), at(length)))
129
return pieces
130
131
55
132
def _point_line_dist(p: Point, a: Point, b: Point) -> float:
56
133
ax, ay = a
57
134
bx, by = b
@@ -52,6 +52,83 @@ def dedupe(pts: Polyline, tol: float = 0.01) -> Polyline:52
return out52
return out53
53
54
54
55
def _perp(p: Point, origin: Point, ux: float, uy: float) -> float:56
return abs((p[0] - origin[0]) * uy - (p[1] - origin[1]) * ux)57
58
59
def _along(p: Point, origin: Point, ux: float, uy: float) -> float:60
return (p[0] - origin[0]) * ux + (p[1] - origin[1]) * uy61
62
63
def strip_overlaps(lines: list[Polyline]) -> tuple[list[Polyline], int]:64
"""Laat een lijn die exact op een eerdere lijn ligt weg. Geeft ook het aantal terug."""65
kept: list[tuple[Point, Point]] = []66
result: list[Polyline] = []67
removed = 068
for poly in lines:69
if len(poly) < 2:70
continue71
chunk: Polyline = []72
for a, b in zip(poly, poly[1:]):73
length = dist(a, b)74
parts = _uncovered(a, b, kept)75
kept_length = sum(dist(p, q) for p, q in parts)76
if length > 0.15 and length - kept_length > 0.15:77
removed += 178
if not parts:79
if len(chunk) >= 2:80
result.append(chunk)81
chunk = []82
continue83
for p0, p1 in parts:84
kept.append((p0, p1))85
if chunk and dist(chunk[-1], p0) <= 0.03:86
chunk.append(p1)87
else:88
if len(chunk) >= 2:89
result.append(chunk)90
chunk = [p0, p1]91
if len(chunk) >= 2:92
result.append(chunk)93
return result, removed94
95
96
def _uncovered(a: Point, b: Point, kept: list[tuple[Point, Point]]) -> list[tuple[Point, Point]]:97
length = dist(a, b)98
if length < 1e-4:99
return []100
ux, uy = (b[0] - a[0]) / length, (b[1] - a[1]) / length101
covered: list[tuple[float, float]] = []102
for c, d in kept:103
if _perp(c, a, ux, uy) > 0.02 or _perp(d, a, ux, uy) > 0.02:104
continue105
t0, t1 = _along(c, a, ux, uy), _along(d, a, ux, uy)106
lo, hi = (t0, t1) if t0 <= t1 else (t1, t0)107
lo, hi = max(0.0, lo), min(length, hi)108
if hi - lo > 0.01:109
covered.append((lo, hi))110
covered.sort()111
merged: list[list[float]] = []112
for lo, hi in covered:113
if merged and lo <= merged[-1][1] + 0.01:114
merged[-1][1] = max(merged[-1][1], hi)115
else:116
merged.append([lo, hi])117
pieces: list[tuple[Point, Point]] = []118
cursor = 0.0119
120
def at(t: float) -> Point:121
return (a[0] + ux * t, a[1] + uy * t)122
123
for lo, hi in merged:124
if lo - cursor > 0.12:125
pieces.append((at(cursor), at(lo)))126
cursor = max(cursor, hi)127
if length - cursor > 0.12:128
pieces.append((at(cursor), at(length)))129
return pieces130
131
55
def _point_line_dist(p: Point, a: Point, b: Point) -> float:132
def _point_line_dist(p: Point, a: Point, b: Point) -> float:56
ax, ay = a133
ax, ay = a57
bx, by = b134
bx, by = b@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
5
5
import math
6
6
7
from timdraw.geom import Point, Polyline
7
from timdraw.geom import Point, Polyline, dist
8
8
9
9
10
10
def _rotate(x: float, y: float, ca: float, sa: float) -> Point:
@@ -57,7 +57,82 @@ def _segments_at(rings: list[Polyline], y: float, rule: str) -> list[tuple[float
57
57
return pairs
58
58
59
59
60
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd") -> list[Polyline]:
60
def _dist_to_segment(p: Point, a: Point, b: Point) -> float:
61
dx, dy = b[0] - a[0], b[1] - a[1]
62
span = dx * dx + dy * dy
63
if span < 1e-12:
64
return dist(p, a)
65
t = max(0.0, min(1.0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / span))
66
return dist(p, (a[0] + t * dx, a[1] + t * dy))
67
68
69
def _inside(x: float, y: float, rings: list[Polyline], rule: str) -> bool:
70
for ring in rings:
71
for i in range(len(ring) - 1):
72
if _dist_to_segment((x, y), ring[i], ring[i + 1]) <= 1e-3:
73
return True
74
winding = 0
75
parity = 0
76
for ring in rings:
77
for i in range(len(ring) - 1):
78
x1, y1 = ring[i]
79
x2, y2 = ring[i + 1]
80
if y1 == y2 or not (min(y1, y2) <= y < max(y1, y2)):
81
continue
82
cross_x = x1 + (y - y1) / (y2 - y1) * (x2 - x1)
83
if cross_x < x:
84
continue
85
parity ^= 1
86
winding += 1 if y1 < y2 else -1
87
if rule == "nonzero":
88
return winding != 0
89
return parity % 2 == 1
90
91
92
def _clip_segment(a: Point, b: Point, rings: list[Polyline], rule: str) -> list[Polyline]:
93
ax, ay = a
94
bx, by = b
95
dx, dy = bx - ax, by - ay
96
cuts = [0.0, 1.0]
97
for ring in rings:
98
for i in range(len(ring) - 1):
99
cx, cy = ring[i]
100
ex, ey = ring[i + 1]
101
rx, ry = ex - cx, ey - cy
102
den = dx * ry - dy * rx
103
if abs(den) < 1e-12:
104
continue
105
t = ((cx - ax) * ry - (cy - ay) * rx) / den
106
u = ((cx - ax) * dy - (cy - ay) * dx) / den
107
if 1e-4 < t < 1 - 1e-4 and -1e-6 <= u <= 1 + 1e-6:
108
cuts.append(t)
109
cuts = sorted(cuts)
110
unique = [cuts[0]]
111
for value in cuts[1:]:
112
if value - unique[-1] > 1e-4:
113
unique.append(value)
114
parts: list[Polyline] = []
115
for t0, t1 in zip(unique, unique[1:]):
116
mid = (t0 + t1) / 2
117
if not _inside(ax + mid * dx, ay + mid * dy, rings, rule):
118
continue
119
parts.append([(ax + t0 * dx, ay + t0 * dy), (ax + t1 * dx, ay + t1 * dy)])
120
return parts
121
122
123
def _chain(parts: list[Polyline], tol: float = 0.03) -> list[Polyline]:
124
chains: list[Polyline] = []
125
for part in parts:
126
if len(part) < 2:
127
continue
128
if chains and dist(chains[-1][-1], part[0]) <= tol:
129
chains[-1].extend(part[1:])
130
else:
131
chains.append(list(part))
132
return chains
133
134
135
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd", zigzag: bool = False) -> list[Polyline]:
61
136
spacing = max(0.3, float(spacing))
62
137
cleaned: list[Polyline] = []
63
138
for ring in rings:
@@ -76,25 +151,40 @@ def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "
76
151
if y1 - y0 < spacing * 0.5:
77
152
return []
78
153
uca, usa = math.cos(angle), math.sin(angle)
79
rows: list[list[tuple[Point, Point]]] = []
154
scan: list[tuple[float, list[tuple[float, float]]]] = []
80
155
y = y0 + spacing * 0.5
81
156
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)
157
pairs = _segments_at(rotated, y, rule)
158
if pairs:
159
scan.append((y, pairs))
89
160
y += spacing
90
lines: list[Polyline] = []
91
for index, row in enumerate(rows):
92
ordered = row
161
ordered: list[tuple[Point, Point]] = []
162
for index, (row_y, pairs) in enumerate(scan):
163
segs = [((x0, row_y), (x1, row_y)) for x0, x1 in pairs]
93
164
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
165
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]
166
ordered.extend(segs)
167
if not zigzag:
168
return [[_rotate(a[0], a[1], uca, usa), _rotate(b[0], b[1], uca, usa)] for a, b in ordered]
169
170
pieces: list[Polyline] = []
171
for index, (start, end) in enumerate(ordered):
172
if index + 1 < len(ordered):
173
nxt = ordered[index + 1][0]
174
clipped = _clip_segment(start, nxt, rotated, rule)
175
joined = (
176
len(clipped) == 1
177
and dist(clipped[0][0], start) <= 0.03
178
and dist(clipped[0][-1], nxt) <= 0.03
179
)
180
if joined:
181
pieces.append(clipped[0])
182
continue
183
if len(clipped) == 1 and dist(clipped[0][0], start) <= 0.03 and dist(clipped[0][0], clipped[0][-1]) > 0.2:
184
pieces.append(clipped[0])
185
continue
186
pieces.append([start, end])
187
return [[_rotate(x, y, uca, usa) for x, y in poly] for poly in _chain(pieces)]
98
188
99
189
100
190
def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:
@@ -4,7 +4,7 @@ from __future__ import annotations4
4
5
import math5
import math6
6
7
from timdraw.geom import Point, Polyline7
from timdraw.geom import Point, Polyline, dist8
8
9
9
10
def _rotate(x: float, y: float, ca: float, sa: float) -> Point:10
def _rotate(x: float, y: float, ca: float, sa: float) -> Point:@@ -57,7 +57,82 @@ def _segments_at(rings: list[Polyline], y: float, rule: str) -> list[tuple[float57
return pairs57
return pairs58
58
59
59
60
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd") -> list[Polyline]:60
def _dist_to_segment(p: Point, a: Point, b: Point) -> float:61
dx, dy = b[0] - a[0], b[1] - a[1]62
span = dx * dx + dy * dy63
if span < 1e-12:64
return dist(p, a)65
t = max(0.0, min(1.0, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / span))66
return dist(p, (a[0] + t * dx, a[1] + t * dy))67
68
69
def _inside(x: float, y: float, rings: list[Polyline], rule: str) -> bool:70
for ring in rings:71
for i in range(len(ring) - 1):72
if _dist_to_segment((x, y), ring[i], ring[i + 1]) <= 1e-3:73
return True74
winding = 075
parity = 076
for ring in rings:77
for i in range(len(ring) - 1):78
x1, y1 = ring[i]79
x2, y2 = ring[i + 1]80
if y1 == y2 or not (min(y1, y2) <= y < max(y1, y2)):81
continue82
cross_x = x1 + (y - y1) / (y2 - y1) * (x2 - x1)83
if cross_x < x:84
continue85
parity ^= 186
winding += 1 if y1 < y2 else -187
if rule == "nonzero":88
return winding != 089
return parity % 2 == 190
91
92
def _clip_segment(a: Point, b: Point, rings: list[Polyline], rule: str) -> list[Polyline]:93
ax, ay = a94
bx, by = b95
dx, dy = bx - ax, by - ay96
cuts = [0.0, 1.0]97
for ring in rings:98
for i in range(len(ring) - 1):99
cx, cy = ring[i]100
ex, ey = ring[i + 1]101
rx, ry = ex - cx, ey - cy102
den = dx * ry - dy * rx103
if abs(den) < 1e-12:104
continue105
t = ((cx - ax) * ry - (cy - ay) * rx) / den106
u = ((cx - ax) * dy - (cy - ay) * dx) / den107
if 1e-4 < t < 1 - 1e-4 and -1e-6 <= u <= 1 + 1e-6:108
cuts.append(t)109
cuts = sorted(cuts)110
unique = [cuts[0]]111
for value in cuts[1:]:112
if value - unique[-1] > 1e-4:113
unique.append(value)114
parts: list[Polyline] = []115
for t0, t1 in zip(unique, unique[1:]):116
mid = (t0 + t1) / 2117
if not _inside(ax + mid * dx, ay + mid * dy, rings, rule):118
continue119
parts.append([(ax + t0 * dx, ay + t0 * dy), (ax + t1 * dx, ay + t1 * dy)])120
return parts121
122
123
def _chain(parts: list[Polyline], tol: float = 0.03) -> list[Polyline]:124
chains: list[Polyline] = []125
for part in parts:126
if len(part) < 2:127
continue128
if chains and dist(chains[-1][-1], part[0]) <= tol:129
chains[-1].extend(part[1:])130
else:131
chains.append(list(part))132
return chains133
134
135
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd", zigzag: bool = False) -> list[Polyline]:61
spacing = max(0.3, float(spacing))136
spacing = max(0.3, float(spacing))62
cleaned: list[Polyline] = []137
cleaned: list[Polyline] = []63
for ring in rings:138
for ring in rings:@@ -76,25 +151,40 @@ def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "76
if y1 - y0 < spacing * 0.5:151
if y1 - y0 < spacing * 0.5:77
return []152
return []78
uca, usa = math.cos(angle), math.sin(angle)153
uca, usa = math.cos(angle), math.sin(angle)79
rows: list[list[tuple[Point, Point]]] = []154
scan: list[tuple[float, list[tuple[float, float]]]] = []80
y = y0 + spacing * 0.5155
y = y0 + spacing * 0.581
while y < y1 - 1e-6:156
while y < y1 - 1e-6:82
row = []157
pairs = _segments_at(rotated, y, rule)83
for x0, x1 in _segments_at(rotated, y, rule):158
if pairs:84
a = _rotate(x0, y, uca, usa)159
scan.append((y, pairs))85
b = _rotate(x1, y, uca, usa)86
row.append((a, b))87
if row:88
rows.append(row)89
y += spacing160
y += spacing90
lines: list[Polyline] = []161
ordered: list[tuple[Point, Point]] = []91
for index, row in enumerate(rows):162
for index, (row_y, pairs) in enumerate(scan):92
ordered = row163
segs = [((x0, row_y), (x1, row_y)) for x0, x1 in pairs]93
if index % 2 == 1:164
if index % 2 == 1:94
ordered = [(b, a) for a, b in reversed(row)]165
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]95
for a, b in ordered:166
ordered.extend(segs)96
lines.append([a, b])167
if not zigzag:97
return lines168
return [[_rotate(a[0], a[1], uca, usa), _rotate(b[0], b[1], uca, usa)] for a, b in ordered]169
170
pieces: list[Polyline] = []171
for index, (start, end) in enumerate(ordered):172
if index + 1 < len(ordered):173
nxt = ordered[index + 1][0]174
clipped = _clip_segment(start, nxt, rotated, rule)175
joined = (176
len(clipped) == 1177
and dist(clipped[0][0], start) <= 0.03178
and dist(clipped[0][-1], nxt) <= 0.03179
)180
if joined:181
pieces.append(clipped[0])182
continue183
if len(clipped) == 1 and dist(clipped[0][0], start) <= 0.03 and dist(clipped[0][0], clipped[0][-1]) > 0.2:184
pieces.append(clipped[0])185
continue186
pieces.append([start, end])187
return [[_rotate(x, y, uca, usa) for x, y in poly] for poly in _chain(pieces)]98
188
99
189
100
def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:190
def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:@@ -376,12 +376,54 @@ def test_virtual_machine() -> None:
376
376
machine.disconnect()
377
377
378
378
379
def test_zigzag_and_overlaps() -> None:
380
square = [(10, 10), (50, 10), (50, 50), (10, 50), (10, 10)]
381
382
def filled(zigzag: bool, cross: bool) -> dict:
383
return plan([{
384
"x": 0, "y": 0, "scale": 1, "rotation": 0,
385
"drawLine": False, "drawFill": True,
386
"hatchAngle": 0, "hatchSpacing": 4,
387
"crosshatch": cross, "zigzag": zigzag,
388
"strokes": [],
389
"fills": [{"rings": [square], "rule": "evenodd"}],
390
}])
391
392
plain = filled(False, False)
393
zag = filled(True, False)
394
check("zigzag maakt minder losse lijnen", len(zag["draw"]) < len(plain["draw"]), f"{len(zag['draw'])} tegen {len(plain['draw'])}")
395
lifts = lambda item: item["gcode"].count("$1=255")
396
check("zigzag tilt de pen minder", lifts(zag) < lifts(plain), f"{lifts(zag)} tegen {lifts(plain)}")
397
for poly in zag["draw"]:
398
for (x0, y0), (x1, y1) in zip(poly, poly[1:]):
399
mid = ((x0 + x1) / 2, (y0 + y1) / 2)
400
inside = 10 - 0.05 <= mid[0] <= 50 + 0.05 and 10 - 0.05 <= mid[1] <= 50 + 0.05
401
check("zigzag blijft in het vierkant", inside, str(mid))
402
if not inside:
403
return
404
both = filled(True, True)
405
check("zigzag met crosshatch tekent twee richtingen", len(both["draw"]) >= 2 and lifts(both) > lifts(zag), str(len(both["draw"])))
406
stroke = {"pts": [(12, 12), (40, 12), (40, 28), (12, 12)]}
407
obj = {
408
"x": 0, "y": 0, "scale": 1, "rotation": 0,
409
"drawLine": True, "drawFill": False,
410
"strokes": [stroke], "fills": [],
411
}
412
duplicated = plan([obj, dict(obj)], {"ignoreOverlap": False})
413
skipped = plan([obj, dict(obj)], {"ignoreOverlap": True})
414
segments = lambda item: sum(max(0, len(poly) - 1) for poly in item["draw"])
415
check("overlap wordt gezien", duplicated["stats"]["overlaps"] >= 3, str(duplicated["stats"]["overlaps"]))
416
check("overlap uit laat beide lijnen staan", segments(duplicated) > segments(skipped), f"{segments(duplicated)} tegen {segments(skipped)}")
417
check("overlap aan tekent de lijn één keer", segments(skipped) == segments(plan([obj], {"ignoreOverlap": False})), str(segments(skipped)))
418
419
379
420
if __name__ == "__main__":
380
421
test_arc()
381
422
test_svg("Heart.svg", False)
382
423
test_svg("Dolphin.svg", True)
383
424
test_svg("wiresphere.svg", False)
384
425
test_text_and_gcode()
426
test_zigzag_and_overlaps()
385
427
test_pen_lerp()
386
428
test_virtual_machine()
387
429
print("alle controles geslaagd")
@@ -376,12 +376,54 @@ def test_virtual_machine() -> None:376
machine.disconnect()376
machine.disconnect()377
377
378
378
379
def test_zigzag_and_overlaps() -> None:380
square = [(10, 10), (50, 10), (50, 50), (10, 50), (10, 10)]381
382
def filled(zigzag: bool, cross: bool) -> dict:383
return plan([{384
"x": 0, "y": 0, "scale": 1, "rotation": 0,385
"drawLine": False, "drawFill": True,386
"hatchAngle": 0, "hatchSpacing": 4,387
"crosshatch": cross, "zigzag": zigzag,388
"strokes": [],389
"fills": [{"rings": [square], "rule": "evenodd"}],390
}])391
392
plain = filled(False, False)393
zag = filled(True, False)394
check("zigzag maakt minder losse lijnen", len(zag["draw"]) < len(plain["draw"]), f"{len(zag['draw'])} tegen {len(plain['draw'])}")395
lifts = lambda item: item["gcode"].count("$1=255")396
check("zigzag tilt de pen minder", lifts(zag) < lifts(plain), f"{lifts(zag)} tegen {lifts(plain)}")397
for poly in zag["draw"]:398
for (x0, y0), (x1, y1) in zip(poly, poly[1:]):399
mid = ((x0 + x1) / 2, (y0 + y1) / 2)400
inside = 10 - 0.05 <= mid[0] <= 50 + 0.05 and 10 - 0.05 <= mid[1] <= 50 + 0.05401
check("zigzag blijft in het vierkant", inside, str(mid))402
if not inside:403
return404
both = filled(True, True)405
check("zigzag met crosshatch tekent twee richtingen", len(both["draw"]) >= 2 and lifts(both) > lifts(zag), str(len(both["draw"])))406
stroke = {"pts": [(12, 12), (40, 12), (40, 28), (12, 12)]}407
obj = {408
"x": 0, "y": 0, "scale": 1, "rotation": 0,409
"drawLine": True, "drawFill": False,410
"strokes": [stroke], "fills": [],411
}412
duplicated = plan([obj, dict(obj)], {"ignoreOverlap": False})413
skipped = plan([obj, dict(obj)], {"ignoreOverlap": True})414
segments = lambda item: sum(max(0, len(poly) - 1) for poly in item["draw"])415
check("overlap wordt gezien", duplicated["stats"]["overlaps"] >= 3, str(duplicated["stats"]["overlaps"]))416
check("overlap uit laat beide lijnen staan", segments(duplicated) > segments(skipped), f"{segments(duplicated)} tegen {segments(skipped)}")417
check("overlap aan tekent de lijn één keer", segments(skipped) == segments(plan([obj], {"ignoreOverlap": False})), str(segments(skipped)))418
419
379
if __name__ == "__main__":420
if __name__ == "__main__":380
test_arc()421
test_arc()381
test_svg("Heart.svg", False)422
test_svg("Heart.svg", False)382
test_svg("Dolphin.svg", True)423
test_svg("Dolphin.svg", True)383
test_svg("wiresphere.svg", False)424
test_svg("wiresphere.svg", False)384
test_text_and_gcode()425
test_text_and_gcode()426
test_zigzag_and_overlaps()385
test_pen_lerp()427
test_pen_lerp()386
test_virtual_machine()428
test_virtual_machine()387
print("alle controles geslaagd")429
print("alle controles geslaagd")