zigzag tweaks
@@ -4,7 +4,7 @@ from __future__ import annotations
4
4
5
5
import math
6
6
7
from timdraw.geom import Point, Polyline, dist
7
from timdraw.geom import Point, Polyline, dist, length_of
8
8
9
9
10
10
def _rotate(x: float, y: float, ca: float, sa: float) -> Point:
@@ -120,16 +120,271 @@ def _clip_segment(a: Point, b: Point, rings: list[Polyline], rule: str) -> list[
120
120
return parts
121
121
122
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:
123
class _Seg:
124
def __init__(self, x0: float, x1: float, y: float, row: int) -> None:
125
self.x0 = x0
126
self.x1 = x1
127
self.y = y
128
self.row = row
129
130
131
def _ends(seg: _Seg, forward: bool) -> tuple[Point, Point]:
132
if forward:
133
return (seg.x0, seg.y), (seg.x1, seg.y)
134
return (seg.x1, seg.y), (seg.x0, seg.y)
135
136
137
def _append(poly: Polyline, pts: Polyline) -> None:
138
for point in pts:
139
if poly and dist(poly[-1], point) <= 0.02:
140
continue
141
poly.append(point)
142
143
144
def _straight(a: Point, b: Point, rings: list[Polyline], rule: str) -> Polyline | None:
145
if dist(a, b) <= 0.03:
146
return [a, b]
147
parts = _clip_segment(a, b, rings, rule)
148
if len(parts) == 1 and dist(parts[0][0], a) <= 0.05 and dist(parts[0][-1], b) <= 0.05:
149
return parts[0]
150
return None
151
152
153
def _ring_edges(ring: Polyline) -> tuple[float, list[tuple[float, float, Point, Point]]]:
154
edges: list[tuple[float, float, Point, Point]] = []
155
acc = 0.0
156
for start, end in zip(ring, ring[1:]):
157
span = dist(start, end)
158
edges.append((acc, acc + span, start, end))
159
acc += span
160
return acc, edges
161
162
163
def _locate(point: Point, rings: list[Polyline]) -> tuple[int, float] | None:
164
found: tuple[int, float] | None = None
165
best = 0.08
166
for index, ring in enumerate(rings):
167
acc = 0.0
168
for start, end in zip(ring, ring[1:]):
169
dx, dy = end[0] - start[0], end[1] - start[1]
170
span = dx * dx + dy * dy
171
length = math.sqrt(span) if span > 0 else 0.0
172
if span < 1e-12:
173
t = 0.0
174
gap = dist(point, start)
175
else:
176
t = max(0.0, min(1.0, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / span))
177
gap = dist(point, (start[0] + t * dx, start[1] + t * dy))
178
if gap < best:
179
best = gap
180
found = (index, acc + t * length)
181
acc += length
182
return found
183
184
185
def _point_on(edges: list[tuple[float, float, Point, Point]], perim: float, distance: float) -> Point:
186
if perim <= 1e-9:
187
return edges[0][2]
188
distance %= perim
189
for start, end, a, b in edges:
190
if distance <= end + 1e-8:
191
span = end - start
192
if span < 1e-12:
193
return a
194
t = (distance - start) / span
195
return (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))
196
return edges[-1][3]
197
198
199
def _boundary(a: Point, b: Point, rings: list[Polyline], limit: float) -> Polyline | None:
200
"""Kortste stuk rand tussen twee punten, als ze op dezelfde contour liggen."""
201
left = _locate(a, rings)
202
right = _locate(b, rings)
203
if left is None or right is None or left[0] != right[0]:
204
return None
205
perim, edges = _ring_edges(rings[left[0]])
206
if perim < 1e-4:
207
return None
208
forward = (right[1] - left[1]) % perim
209
backward = (left[1] - right[1]) % perim
210
length = forward if forward <= backward else backward
211
if length < 1e-3 or length > limit or length > perim * 0.5 + 1e-6:
212
return None
213
increasing = forward <= backward
214
points = [_point_on(edges, perim, left[1])]
215
marks: list[tuple[float, Point]] = []
216
for start, end, _start_point, p1 in edges:
217
# Het sluitpunt van de ring ligt op afstand 0, niet op de start van de laatste zijde.
218
vertex_at = 0.0 if end >= perim - 1e-8 else end
219
vertex = p1
220
along = (vertex_at - left[1]) % perim if increasing else (left[1] - vertex_at) % perim
221
if 1e-3 < along < length - 1e-3:
222
marks.append((along, vertex))
223
marks.sort(key=lambda item: item[0])
224
for _, vertex in marks:
225
if dist(points[-1], vertex) > 1e-3:
226
points.append(vertex)
227
end_at = left[1] + length if increasing else left[1] - length
228
finish = _point_on(edges, perim, end_at)
229
if dist(points[-1], finish) > 1e-3:
230
points.append(finish)
231
else:
232
points[-1] = finish
233
points[0] = a
234
points[-1] = b
235
return points
236
237
238
def _covers(seg: _Seg, line: Polyline, spacing: float) -> bool:
239
"""Een schuine lijn telt alleen als hij deze arceerlijn echt dekt."""
240
limit = spacing * 1.2 + 0.08
241
for x in (seg.x0, (seg.x0 + seg.x1) / 2, seg.x1):
242
if _dist_to_segment((x, seg.y), line[0], line[-1]) > limit:
243
return False
244
return True
245
246
247
def _link(
248
seg: _Seg,
249
forward: bool,
250
other: _Seg,
251
oforward: bool,
252
rings: list[Polyline],
253
rule: str,
254
spacing: float,
255
cap: float,
256
) -> tuple[float, Polyline] | None:
257
entry, exit_pt = _ends(seg, forward)
258
nentry, _ = _ends(other, oforward)
259
diagonal = _straight(entry, nentry, rings, rule)
260
if diagonal is not None and _covers(seg, diagonal, spacing):
261
extra = max(0.0, length_of(diagonal) - (seg.x1 - seg.x0))
262
if extra <= cap:
263
return extra, diagonal
264
direct = _straight(exit_pt, nentry, rings, rule)
265
if direct is not None and length_of(direct) <= cap:
266
return length_of(direct), [entry, exit_pt, *direct[1:]]
267
walk = _boundary(exit_pt, nentry, rings, cap)
268
if walk is None:
269
return None
270
return length_of(walk) + 1.5, [entry, exit_pt, *walk[1:]]
271
272
273
def _neighbors(seg: _Seg, rows: list[list[_Seg]], spacing: float) -> list[_Seg]:
274
found: list[_Seg] = []
275
for row in (seg.row - 1, seg.row + 1):
276
if row < 0 or row >= len(rows):
127
277
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
278
for other in rows[row]:
279
if abs(other.y - seg.y) > spacing * 1.75:
280
continue
281
gap = max(seg.x0, other.x0) - min(seg.x1, other.x1)
282
if gap <= spacing * 1.25:
283
found.append(other)
284
return found
285
286
287
def _best_link(
288
seg: _Seg,
289
forward: bool,
290
candidates: list[_Seg],
291
rings: list[Polyline],
292
rule: str,
293
spacing: float,
294
cap: float,
295
coming_y: float | None,
296
) -> tuple[_Seg, bool] | None:
297
best: tuple[tuple[float, float, float, int], _Seg, bool] | None = None
298
for other in candidates:
299
for oforward in (True, False):
300
linked = _link(seg, forward, other, oforward, rings, rule, spacing, cap)
301
if linked is None:
302
continue
303
dy = other.y - seg.y
304
# Iets duurder om terug te gaan, zodat een gang recht doorloopt.
305
# Een duidelijk kortere tak wint nog steeds.
306
turn = spacing if coming_y is not None and (seg.y - coming_y) * dy < 0 else 0.0
307
key = (linked[0] + turn, other.y, other.x0, 0.0 if oforward else 1.0)
308
if best is None or key < best[0]:
309
best = (key, other, oforward)
310
if best is None:
311
return None
312
return best[1], best[2]
313
314
315
def _zigzag(
316
segments: list[_Seg],
317
rows: list[list[_Seg]],
318
rings: list[Polyline],
319
rule: str,
320
spacing: float,
321
) -> list[Polyline]:
322
"""Volg arceerlijnen in één richting, en buig langs de rand als de vorm hol is.
323
324
De ingestelde hoek blijft de arceerrichting. Een rechte schuine verbinding
325
heeft voorrang; lukt die niet binnen de vorm, dan loopt de pen langs de contour
326
naar de volgende lijn. Alleen een te lange omweg wordt een penlift.
327
"""
328
if not segments:
329
return []
330
join_cap = max(spacing * 18.0, 45.0)
331
rescue_cap = max(spacing * 50.0, 120.0)
332
unused = set(segments)
333
chains: list[tuple[list[tuple[_Seg, bool]], list[float]]] = []
334
while unused:
335
start = min(unused, key=lambda seg: (len([n for n in _neighbors(seg, rows, spacing) if n in unused]), seg.y, seg.x0))
336
coming: float | None = None
337
nearby = [n for n in _neighbors(start, rows, spacing) if n in unused]
338
forward = True
339
left = _best_link(start, True, nearby, rings, rule, spacing, join_cap, None)
340
right = _best_link(start, False, nearby, rings, rule, spacing, join_cap, None)
341
left_cost = None if left is None else _link(start, True, left[0], left[1], rings, rule, spacing, join_cap)
342
right_cost = None if right is None else _link(start, False, right[0], right[1], rings, rule, spacing, join_cap)
343
if right_cost is not None and (left_cost is None or right_cost[0] < left_cost[0]):
344
forward = False
345
chain = [(start, forward)]
346
caps: list[float] = []
347
unused.remove(start)
348
while True:
349
seg, forward = chain[-1]
350
pool = [n for n in _neighbors(seg, rows, spacing) if n in unused]
351
step = _best_link(seg, forward, pool, rings, rule, spacing, join_cap, coming)
352
cap = join_cap
353
if step is None:
354
_, exit_pt = _ends(seg, forward)
355
nearest = sorted(
356
unused,
357
key=lambda other: min(dist(exit_pt, (other.x0, other.y)), dist(exit_pt, (other.x1, other.y))),
358
)[:8]
359
step = _best_link(seg, forward, nearest, rings, rule, spacing, rescue_cap, None)
360
cap = rescue_cap
361
if step is None:
362
break
363
coming = seg.y
364
chain.append(step)
365
caps.append(cap)
366
unused.remove(step[0])
367
chains.append((chain, caps))
368
369
polylines: list[Polyline] = []
370
for chain, caps in chains:
371
poly: Polyline = []
372
for index, (seg, forward) in enumerate(chain):
373
if index + 1 == len(chain):
374
_append(poly, list(_ends(seg, forward)))
375
break
376
other, oforward = chain[index + 1]
377
linked = _link(seg, forward, other, oforward, rings, rule, spacing, caps[index])
378
if linked is None:
379
_append(poly, list(_ends(seg, forward)))
380
if len(poly) >= 2:
381
polylines.append(poly)
382
poly = []
383
continue
384
_append(poly, linked[1])
385
if len(poly) >= 2:
386
polylines.append(poly)
387
return polylines
133
388
134
389
135
390
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd", zigzag: bool = False) -> list[Polyline]:
@@ -158,33 +413,25 @@ def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "
158
413
if pairs:
159
414
scan.append((y, pairs))
160
415
y += spacing
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]
164
if index % 2 == 1:
165
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]
166
ordered.extend(segs)
167
416
if not zigzag:
417
ordered: list[tuple[Point, Point]] = []
418
for index, (row_y, pairs) in enumerate(scan):
419
segs = [((x0, row_y), (x1, row_y)) for x0, x1 in pairs]
420
if index % 2 == 1:
421
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]
422
ordered.extend(segs)
168
423
return [[_rotate(a[0], a[1], uca, usa), _rotate(b[0], b[1], uca, usa)] for a, b in ordered]
169
424
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)]
425
segments: list[_Seg] = []
426
rows: list[list[_Seg]] = []
427
for row, (row_y, pairs) in enumerate(scan):
428
line: list[_Seg] = []
429
for x0, x1 in pairs:
430
seg = _Seg(x0, x1, row_y, row)
431
segments.append(seg)
432
line.append(seg)
433
rows.append(line)
434
return [[_rotate(x, y, uca, usa) for x, y in poly] for poly in _zigzag(segments, rows, rotated, rule, spacing)]
188
435
189
436
190
437
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, Polyline, dist7
from timdraw.geom import Point, Polyline, dist, length_of8
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:@@ -120,16 +120,271 @@ def _clip_segment(a: Point, b: Point, rings: list[Polyline], rule: str) -> list[120
return parts120
return parts121
121
122
122
123
def _chain(parts: list[Polyline], tol: float = 0.03) -> list[Polyline]:123
class _Seg:124
chains: list[Polyline] = []124
def __init__(self, x0: float, x1: float, y: float, row: int) -> None:125
for part in parts:125
self.x0 = x0126
if len(part) < 2:126
self.x1 = x1127
self.y = y128
self.row = row129
130
131
def _ends(seg: _Seg, forward: bool) -> tuple[Point, Point]:132
if forward:133
return (seg.x0, seg.y), (seg.x1, seg.y)134
return (seg.x1, seg.y), (seg.x0, seg.y)135
136
137
def _append(poly: Polyline, pts: Polyline) -> None:138
for point in pts:139
if poly and dist(poly[-1], point) <= 0.02:140
continue141
poly.append(point)142
143
144
def _straight(a: Point, b: Point, rings: list[Polyline], rule: str) -> Polyline | None:145
if dist(a, b) <= 0.03:146
return [a, b]147
parts = _clip_segment(a, b, rings, rule)148
if len(parts) == 1 and dist(parts[0][0], a) <= 0.05 and dist(parts[0][-1], b) <= 0.05:149
return parts[0]150
return None151
152
153
def _ring_edges(ring: Polyline) -> tuple[float, list[tuple[float, float, Point, Point]]]:154
edges: list[tuple[float, float, Point, Point]] = []155
acc = 0.0156
for start, end in zip(ring, ring[1:]):157
span = dist(start, end)158
edges.append((acc, acc + span, start, end))159
acc += span160
return acc, edges161
162
163
def _locate(point: Point, rings: list[Polyline]) -> tuple[int, float] | None:164
found: tuple[int, float] | None = None165
best = 0.08166
for index, ring in enumerate(rings):167
acc = 0.0168
for start, end in zip(ring, ring[1:]):169
dx, dy = end[0] - start[0], end[1] - start[1]170
span = dx * dx + dy * dy171
length = math.sqrt(span) if span > 0 else 0.0172
if span < 1e-12:173
t = 0.0174
gap = dist(point, start)175
else:176
t = max(0.0, min(1.0, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / span))177
gap = dist(point, (start[0] + t * dx, start[1] + t * dy))178
if gap < best:179
best = gap180
found = (index, acc + t * length)181
acc += length182
return found183
184
185
def _point_on(edges: list[tuple[float, float, Point, Point]], perim: float, distance: float) -> Point:186
if perim <= 1e-9:187
return edges[0][2]188
distance %= perim189
for start, end, a, b in edges:190
if distance <= end + 1e-8:191
span = end - start192
if span < 1e-12:193
return a194
t = (distance - start) / span195
return (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))196
return edges[-1][3]197
198
199
def _boundary(a: Point, b: Point, rings: list[Polyline], limit: float) -> Polyline | None:200
"""Kortste stuk rand tussen twee punten, als ze op dezelfde contour liggen."""201
left = _locate(a, rings)202
right = _locate(b, rings)203
if left is None or right is None or left[0] != right[0]:204
return None205
perim, edges = _ring_edges(rings[left[0]])206
if perim < 1e-4:207
return None208
forward = (right[1] - left[1]) % perim209
backward = (left[1] - right[1]) % perim210
length = forward if forward <= backward else backward211
if length < 1e-3 or length > limit or length > perim * 0.5 + 1e-6:212
return None213
increasing = forward <= backward214
points = [_point_on(edges, perim, left[1])]215
marks: list[tuple[float, Point]] = []216
for start, end, _start_point, p1 in edges:217
# Het sluitpunt van de ring ligt op afstand 0, niet op de start van de laatste zijde.218
vertex_at = 0.0 if end >= perim - 1e-8 else end219
vertex = p1220
along = (vertex_at - left[1]) % perim if increasing else (left[1] - vertex_at) % perim221
if 1e-3 < along < length - 1e-3:222
marks.append((along, vertex))223
marks.sort(key=lambda item: item[0])224
for _, vertex in marks:225
if dist(points[-1], vertex) > 1e-3:226
points.append(vertex)227
end_at = left[1] + length if increasing else left[1] - length228
finish = _point_on(edges, perim, end_at)229
if dist(points[-1], finish) > 1e-3:230
points.append(finish)231
else:232
points[-1] = finish233
points[0] = a234
points[-1] = b235
return points236
237
238
def _covers(seg: _Seg, line: Polyline, spacing: float) -> bool:239
"""Een schuine lijn telt alleen als hij deze arceerlijn echt dekt."""240
limit = spacing * 1.2 + 0.08241
for x in (seg.x0, (seg.x0 + seg.x1) / 2, seg.x1):242
if _dist_to_segment((x, seg.y), line[0], line[-1]) > limit:243
return False244
return True245
246
247
def _link(248
seg: _Seg,249
forward: bool,250
other: _Seg,251
oforward: bool,252
rings: list[Polyline],253
rule: str,254
spacing: float,255
cap: float,256
) -> tuple[float, Polyline] | None:257
entry, exit_pt = _ends(seg, forward)258
nentry, _ = _ends(other, oforward)259
diagonal = _straight(entry, nentry, rings, rule)260
if diagonal is not None and _covers(seg, diagonal, spacing):261
extra = max(0.0, length_of(diagonal) - (seg.x1 - seg.x0))262
if extra <= cap:263
return extra, diagonal264
direct = _straight(exit_pt, nentry, rings, rule)265
if direct is not None and length_of(direct) <= cap:266
return length_of(direct), [entry, exit_pt, *direct[1:]]267
walk = _boundary(exit_pt, nentry, rings, cap)268
if walk is None:269
return None270
return length_of(walk) + 1.5, [entry, exit_pt, *walk[1:]]271
272
273
def _neighbors(seg: _Seg, rows: list[list[_Seg]], spacing: float) -> list[_Seg]:274
found: list[_Seg] = []275
for row in (seg.row - 1, seg.row + 1):276
if row < 0 or row >= len(rows):127
continue277
continue128
if chains and dist(chains[-1][-1], part[0]) <= tol:278
for other in rows[row]:129
chains[-1].extend(part[1:])279
if abs(other.y - seg.y) > spacing * 1.75:130
else:280
continue131
chains.append(list(part))281
gap = max(seg.x0, other.x0) - min(seg.x1, other.x1)132
return chains282
if gap <= spacing * 1.25:283
found.append(other)284
return found285
286
287
def _best_link(288
seg: _Seg,289
forward: bool,290
candidates: list[_Seg],291
rings: list[Polyline],292
rule: str,293
spacing: float,294
cap: float,295
coming_y: float | None,296
) -> tuple[_Seg, bool] | None:297
best: tuple[tuple[float, float, float, int], _Seg, bool] | None = None298
for other in candidates:299
for oforward in (True, False):300
linked = _link(seg, forward, other, oforward, rings, rule, spacing, cap)301
if linked is None:302
continue303
dy = other.y - seg.y304
# Iets duurder om terug te gaan, zodat een gang recht doorloopt.305
# Een duidelijk kortere tak wint nog steeds.306
turn = spacing if coming_y is not None and (seg.y - coming_y) * dy < 0 else 0.0307
key = (linked[0] + turn, other.y, other.x0, 0.0 if oforward else 1.0)308
if best is None or key < best[0]:309
best = (key, other, oforward)310
if best is None:311
return None312
return best[1], best[2]313
314
315
def _zigzag(316
segments: list[_Seg],317
rows: list[list[_Seg]],318
rings: list[Polyline],319
rule: str,320
spacing: float,321
) -> list[Polyline]:322
"""Volg arceerlijnen in één richting, en buig langs de rand als de vorm hol is.323
324
De ingestelde hoek blijft de arceerrichting. Een rechte schuine verbinding325
heeft voorrang; lukt die niet binnen de vorm, dan loopt de pen langs de contour326
naar de volgende lijn. Alleen een te lange omweg wordt een penlift.327
"""328
if not segments:329
return []330
join_cap = max(spacing * 18.0, 45.0)331
rescue_cap = max(spacing * 50.0, 120.0)332
unused = set(segments)333
chains: list[tuple[list[tuple[_Seg, bool]], list[float]]] = []334
while unused:335
start = min(unused, key=lambda seg: (len([n for n in _neighbors(seg, rows, spacing) if n in unused]), seg.y, seg.x0))336
coming: float | None = None337
nearby = [n for n in _neighbors(start, rows, spacing) if n in unused]338
forward = True339
left = _best_link(start, True, nearby, rings, rule, spacing, join_cap, None)340
right = _best_link(start, False, nearby, rings, rule, spacing, join_cap, None)341
left_cost = None if left is None else _link(start, True, left[0], left[1], rings, rule, spacing, join_cap)342
right_cost = None if right is None else _link(start, False, right[0], right[1], rings, rule, spacing, join_cap)343
if right_cost is not None and (left_cost is None or right_cost[0] < left_cost[0]):344
forward = False345
chain = [(start, forward)]346
caps: list[float] = []347
unused.remove(start)348
while True:349
seg, forward = chain[-1]350
pool = [n for n in _neighbors(seg, rows, spacing) if n in unused]351
step = _best_link(seg, forward, pool, rings, rule, spacing, join_cap, coming)352
cap = join_cap353
if step is None:354
_, exit_pt = _ends(seg, forward)355
nearest = sorted(356
unused,357
key=lambda other: min(dist(exit_pt, (other.x0, other.y)), dist(exit_pt, (other.x1, other.y))),358
)[:8]359
step = _best_link(seg, forward, nearest, rings, rule, spacing, rescue_cap, None)360
cap = rescue_cap361
if step is None:362
break363
coming = seg.y364
chain.append(step)365
caps.append(cap)366
unused.remove(step[0])367
chains.append((chain, caps))368
369
polylines: list[Polyline] = []370
for chain, caps in chains:371
poly: Polyline = []372
for index, (seg, forward) in enumerate(chain):373
if index + 1 == len(chain):374
_append(poly, list(_ends(seg, forward)))375
break376
other, oforward = chain[index + 1]377
linked = _link(seg, forward, other, oforward, rings, rule, spacing, caps[index])378
if linked is None:379
_append(poly, list(_ends(seg, forward)))380
if len(poly) >= 2:381
polylines.append(poly)382
poly = []383
continue384
_append(poly, linked[1])385
if len(poly) >= 2:386
polylines.append(poly)387
return polylines133
388
134
389
135
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd", zigzag: bool = False) -> list[Polyline]:390
def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "evenodd", zigzag: bool = False) -> list[Polyline]:@@ -158,33 +413,25 @@ def hatch(rings: list[Polyline], angle_deg: float, spacing: float, rule: str = "158
if pairs:413
if pairs:159
scan.append((y, pairs))414
scan.append((y, pairs))160
y += spacing415
y += spacing161
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]164
if index % 2 == 1:165
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]166
ordered.extend(segs)167
if not zigzag:416
if not zigzag:417
ordered: list[tuple[Point, Point]] = []418
for index, (row_y, pairs) in enumerate(scan):419
segs = [((x0, row_y), (x1, row_y)) for x0, x1 in pairs]420
if index % 2 == 1:421
segs = [((x1, row_y), (x0, row_y)) for x0, x1 in reversed(pairs)]422
ordered.extend(segs)168
return [[_rotate(a[0], a[1], uca, usa), _rotate(b[0], b[1], uca, usa)] for a, b in ordered]423
return [[_rotate(a[0], a[1], uca, usa), _rotate(b[0], b[1], uca, usa)] for a, b in ordered]169
424
170
pieces: list[Polyline] = []425
segments: list[_Seg] = []171
for index, (start, end) in enumerate(ordered):426
rows: list[list[_Seg]] = []172
if index + 1 < len(ordered):427
for row, (row_y, pairs) in enumerate(scan):173
nxt = ordered[index + 1][0]428
line: list[_Seg] = []174
clipped = _clip_segment(start, nxt, rotated, rule)429
for x0, x1 in pairs:175
joined = (430
seg = _Seg(x0, x1, row_y, row)176
len(clipped) == 1431
segments.append(seg)177
and dist(clipped[0][0], start) <= 0.03432
line.append(seg)178
and dist(clipped[0][-1], nxt) <= 0.03433
rows.append(line)179
)434
return [[_rotate(x, y, uca, usa) for x, y in poly] for poly in _zigzag(segments, rows, rotated, rule, spacing)]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)]188
435
189
436
190
def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:437
def spacing_for_gray(gray: float, steps: int, dark: float, light: float) -> float:@@ -416,6 +416,85 @@ def test_zigzag_and_overlaps() -> None:
416
416
check("overlap uit laat beide lijnen staan", segments(duplicated) > segments(skipped), f"{segments(duplicated)} tegen {segments(skipped)}")
417
417
check("overlap aan tekent de lijn één keer", segments(skipped) == segments(plan([obj], {"ignoreOverlap": False})), str(segments(skipped)))
418
418
419
def shape(rings: list, spacing: float = 4) -> dict:
420
return plan([{
421
"x": 0, "y": 0, "scale": 1, "rotation": 0,
422
"drawLine": False, "drawFill": True,
423
"hatchAngle": 0, "hatchSpacing": spacing,
424
"crosshatch": False, "zigzag": True,
425
"strokes": [],
426
"fills": [{"rings": rings, "rule": "evenodd"}],
427
}])
428
429
def outside(item: dict, ring: list, hole: list | None = None) -> str:
430
def on_edge(x: float, y: float, path: list) -> bool:
431
for a, b in zip(path, path[1:]):
432
dx, dy = b[0] - a[0], b[1] - a[1]
433
span = dx * dx + dy * dy
434
if span < 1e-12:
435
if math.hypot(x - a[0], y - a[1]) <= 0.2:
436
return True
437
continue
438
t = max(0.0, min(1.0, ((x - a[0]) * dx + (y - a[1]) * dy) / span))
439
if math.hypot(x - (a[0] + t * dx), y - (a[1] + t * dy)) <= 0.2:
440
return True
441
return False
442
443
def contains(x: float, y: float, path: list) -> bool:
444
if on_edge(x, y, path):
445
return True
446
hits = 0
447
for a, b in zip(path, path[1:]):
448
if (a[1] > y) == (b[1] > y):
449
continue
450
cross = a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0])
451
if cross >= x:
452
hits += 1
453
return hits % 2 == 1
454
455
for poly in item["draw"]:
456
for (x0, y0), (x1, y1) in zip(poly, poly[1:]):
457
mid = ((x0 + x1) / 2, (y0 + y1) / 2)
458
if hole is not None and contains(mid[0], mid[1], hole) and not on_edge(mid[0], mid[1], hole):
459
return f"in het gat {mid}"
460
if not contains(mid[0], mid[1], ring):
461
return f"buiten {mid}"
462
return ""
463
464
crescent = [(0, 0), (46, 0), (46, 14), (18, 14), (18, 34), (46, 34), (46, 48), (0, 48), (0, 0)]
465
notch = [(0, 0), (40, 0), (40, 14), (24, 22), (40, 30), (40, 44), (0, 44), (0, 0)]
466
outer = [(0, 0), (48, 0), (48, 48), (0, 48), (0, 0)]
467
hole = [(16, 16), (32, 16), (32, 32), (16, 32), (16, 16)]
468
plain_c = plan([{
469
"x": 0, "y": 0, "scale": 1, "rotation": 0,
470
"drawLine": False, "drawFill": True,
471
"hatchAngle": 0, "hatchSpacing": 4,
472
"crosshatch": False, "zigzag": False,
473
"strokes": [],
474
"fills": [{"rings": [crescent], "rule": "evenodd"}],
475
}])
476
zag_c = shape([crescent])
477
check(
478
"holle vorm tilt minder",
479
lifts(zag_c) < lifts(plain_c) / 2,
480
f"{lifts(zag_c)} tegen {lifts(plain_c)}, {len(zag_c['draw'])} lijnen",
481
)
482
check("holle zigzag blijft in de vorm", outside(zag_c, crescent) == "", outside(zag_c, crescent))
483
zag_notch = shape([notch])
484
check("inkeping blijft één lijn", len(zag_notch["draw"]) == 1, str(len(zag_notch["draw"])))
485
check("inkeping blijft binnen", outside(zag_notch, notch) == "", outside(zag_notch, notch))
486
zag_hole = shape([outer, hole])
487
check("zigzag mijdt het gat", outside(zag_hole, outer, hole) == "", outside(zag_hole, outer, hole) or str(len(zag_hole["draw"])))
488
angled = plan([{
489
"x": 0, "y": 0, "scale": 1, "rotation": 0,
490
"drawLine": False, "drawFill": True,
491
"hatchAngle": 20, "hatchSpacing": 3,
492
"crosshatch": False, "zigzag": True,
493
"strokes": [],
494
"fills": [{"rings": [outer, hole], "rule": "evenodd"}],
495
}])
496
check("schuine zigzag mijdt het gat", outside(angled, outer, hole) == "", outside(angled, outer, hole) or f"{lifts(angled)} lifts")
497
419
498
420
499
if __name__ == "__main__":
421
500
test_arc()
@@ -416,6 +416,85 @@ def test_zigzag_and_overlaps() -> None:416
check("overlap uit laat beide lijnen staan", segments(duplicated) > segments(skipped), f"{segments(duplicated)} tegen {segments(skipped)}")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)))417
check("overlap aan tekent de lijn één keer", segments(skipped) == segments(plan([obj], {"ignoreOverlap": False})), str(segments(skipped)))418
418
419
def shape(rings: list, spacing: float = 4) -> dict:420
return plan([{421
"x": 0, "y": 0, "scale": 1, "rotation": 0,422
"drawLine": False, "drawFill": True,423
"hatchAngle": 0, "hatchSpacing": spacing,424
"crosshatch": False, "zigzag": True,425
"strokes": [],426
"fills": [{"rings": rings, "rule": "evenodd"}],427
}])428
429
def outside(item: dict, ring: list, hole: list | None = None) -> str:430
def on_edge(x: float, y: float, path: list) -> bool:431
for a, b in zip(path, path[1:]):432
dx, dy = b[0] - a[0], b[1] - a[1]433
span = dx * dx + dy * dy434
if span < 1e-12:435
if math.hypot(x - a[0], y - a[1]) <= 0.2:436
return True437
continue438
t = max(0.0, min(1.0, ((x - a[0]) * dx + (y - a[1]) * dy) / span))439
if math.hypot(x - (a[0] + t * dx), y - (a[1] + t * dy)) <= 0.2:440
return True441
return False442
443
def contains(x: float, y: float, path: list) -> bool:444
if on_edge(x, y, path):445
return True446
hits = 0447
for a, b in zip(path, path[1:]):448
if (a[1] > y) == (b[1] > y):449
continue450
cross = a[0] + (y - a[1]) / (b[1] - a[1]) * (b[0] - a[0])451
if cross >= x:452
hits += 1453
return hits % 2 == 1454
455
for poly in item["draw"]:456
for (x0, y0), (x1, y1) in zip(poly, poly[1:]):457
mid = ((x0 + x1) / 2, (y0 + y1) / 2)458
if hole is not None and contains(mid[0], mid[1], hole) and not on_edge(mid[0], mid[1], hole):459
return f"in het gat {mid}"460
if not contains(mid[0], mid[1], ring):461
return f"buiten {mid}"462
return ""463
464
crescent = [(0, 0), (46, 0), (46, 14), (18, 14), (18, 34), (46, 34), (46, 48), (0, 48), (0, 0)]465
notch = [(0, 0), (40, 0), (40, 14), (24, 22), (40, 30), (40, 44), (0, 44), (0, 0)]466
outer = [(0, 0), (48, 0), (48, 48), (0, 48), (0, 0)]467
hole = [(16, 16), (32, 16), (32, 32), (16, 32), (16, 16)]468
plain_c = plan([{469
"x": 0, "y": 0, "scale": 1, "rotation": 0,470
"drawLine": False, "drawFill": True,471
"hatchAngle": 0, "hatchSpacing": 4,472
"crosshatch": False, "zigzag": False,473
"strokes": [],474
"fills": [{"rings": [crescent], "rule": "evenodd"}],475
}])476
zag_c = shape([crescent])477
check(478
"holle vorm tilt minder",479
lifts(zag_c) < lifts(plain_c) / 2,480
f"{lifts(zag_c)} tegen {lifts(plain_c)}, {len(zag_c['draw'])} lijnen",481
)482
check("holle zigzag blijft in de vorm", outside(zag_c, crescent) == "", outside(zag_c, crescent))483
zag_notch = shape([notch])484
check("inkeping blijft één lijn", len(zag_notch["draw"]) == 1, str(len(zag_notch["draw"])))485
check("inkeping blijft binnen", outside(zag_notch, notch) == "", outside(zag_notch, notch))486
zag_hole = shape([outer, hole])487
check("zigzag mijdt het gat", outside(zag_hole, outer, hole) == "", outside(zag_hole, outer, hole) or str(len(zag_hole["draw"])))488
angled = plan([{489
"x": 0, "y": 0, "scale": 1, "rotation": 0,490
"drawLine": False, "drawFill": True,491
"hatchAngle": 20, "hatchSpacing": 3,492
"crosshatch": False, "zigzag": True,493
"strokes": [],494
"fills": [{"rings": [outer, hole], "rule": "evenodd"}],495
}])496
check("schuine zigzag mijdt het gat", outside(angled, outer, hole) == "", outside(angled, outer, hole) or f"{lifts(angled)} lifts")497
419
498
420
if __name__ == "__main__":499
if __name__ == "__main__":421
test_arc()500
test_arc()