1//! 2D vector shape command generation, adaptive curve flattening, path trimming,
2//! and viewport clipping.
3
4use super::super::warps_masks::bspline::eval_rational_cubic_bspline_2d;
5use super::modifiers::{
6 Contour, apply_path_modifier_contours, dash_contours, dedup_contour_points, expand_contour,
7};
8use super::{Affine2D, PathModifier, ShapeCmd, ShapePrimKind};
9
10#[inline]
11fn shape_to_px(wpt: [f32; 2], dims: [u32; 2]) -> zeno::Vector {
12 let wf = dims[0] as f32;
13 let hf = dims[1] as f32;
14 zeno::Vector::new((wpt[0] + 0.5) * wf, 0.5 * hf - wpt[1] * wf)
15}
16
17/// Builds shape-space `zeno::Command`s for a primitive and returns `(cmds, closed)`.
18fn build_primitive_commands_shape(kind: &ShapePrimKind, xform: Affine2D) -> (Vec<zeno::Command>, bool) {
19 let to_v = |local: [f32; 2]| -> zeno::Vector {
20 let p = xform.apply(local);
21 zeno::Vector::new(p[0], p[1])
22 };
23
24 const KAPPA: f32 = 0.55228475;
25 let mut cmds = Vec::new();
26 match kind {
27 ShapePrimKind::NGon { sides, width, height } => {
28 let n = (*sides).max(3);
29 let rx = width * 0.5;
30 let ry = height * 0.5;
31 if rx <= 1e-6 || ry <= 1e-6 {
32 return (cmds, true);
33 }
34 for k in 0..n {
35 let theta = (k as f32) * std::f32::consts::TAU / (n as f32);
36 let v = to_v([rx * theta.cos(), ry * theta.sin()]);
37 if k == 0 {
38 cmds.push(zeno::Command::MoveTo(v));
39 } else {
40 cmds.push(zeno::Command::LineTo(v));
41 }
42 }
43 cmds.push(zeno::Command::Close);
44 (cmds, true)
45 }
46 ShapePrimKind::Rectangle { width, height, corner_radius } => {
47 let hx = width * 0.5;
48 let hy = height * 0.5;
49 if hx <= 1e-6 || hy <= 1e-6 {
50 return (cmds, true);
51 }
52 let r = corner_radius.min(hx.min(hy));
53 if r <= 1e-5 {
54 // Start at mid-right (+hx, 0) counter-clockwise so WritePosition matches sNGon/sEllipse.
55 cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0])));
56 cmds.push(zeno::Command::LineTo(to_v([hx, hy])));
57 cmds.push(zeno::Command::LineTo(to_v([-hx, hy])));
58 cmds.push(zeno::Command::LineTo(to_v([-hx, -hy])));
59 cmds.push(zeno::Command::LineTo(to_v([hx, -hy])));
60 cmds.push(zeno::Command::Close);
61 } else {
62 let k = r * KAPPA;
63 cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0])));
64 cmds.push(zeno::Command::LineTo(to_v([hx, hy - r])));
65 cmds.push(zeno::Command::CurveTo(
66 to_v([hx, hy - r + k]),
67 to_v([hx - r + k, hy]),
68 to_v([hx - r, hy]),
69 ));
70 cmds.push(zeno::Command::LineTo(to_v([-hx + r, hy])));
71 cmds.push(zeno::Command::CurveTo(
72 to_v([-hx + r - k, hy]),
73 to_v([-hx, hy - r + k]),
74 to_v([-hx, hy - r]),
75 ));
76 cmds.push(zeno::Command::LineTo(to_v([-hx, -hy + r])));
77 cmds.push(zeno::Command::CurveTo(
78 to_v([-hx, -hy + r - k]),
79 to_v([-hx + r - k, -hy]),
80 to_v([-hx + r, -hy]),
81 ));
82 cmds.push(zeno::Command::LineTo(to_v([hx - r, -hy])));
83 cmds.push(zeno::Command::CurveTo(
84 to_v([hx - r + k, -hy]),
85 to_v([hx, -hy + r - k]),
86 to_v([hx, -hy + r]),
87 ));
88 cmds.push(zeno::Command::Close);
89 }
90 (cmds, true)
91 }
92 ShapePrimKind::Ellipse { width, height } => {
93 let rx = width * 0.5;
94 let ry = height * 0.5;
95 if rx <= 1e-6 || ry <= 1e-6 {
96 return (cmds, true);
97 }
98 let kx = rx * KAPPA;
99 let ky = ry * KAPPA;
100 cmds.push(zeno::Command::MoveTo(to_v([rx, 0.0])));
101 cmds.push(zeno::Command::CurveTo(
102 to_v([rx, ky]),
103 to_v([kx, ry]),
104 to_v([0.0, ry]),
105 ));
106 cmds.push(zeno::Command::CurveTo(
107 to_v([-kx, ry]),
108 to_v([-rx, ky]),
109 to_v([-rx, 0.0]),
110 ));
111 cmds.push(zeno::Command::CurveTo(
112 to_v([-rx, -ky]),
113 to_v([-kx, -ry]),
114 to_v([0.0, -ry]),
115 ));
116 cmds.push(zeno::Command::CurveTo(
117 to_v([kx, -ry]),
118 to_v([rx, -ky]),
119 to_v([rx, 0.0]),
120 ));
121 cmds.push(zeno::Command::Close);
122 (cmds, true)
123 }
124 ShapePrimKind::Star { points, depth, width, height, corner_radius } => {
125 let n = (*points).max(3) as usize;
126 let rx = width * 0.5;
127 let ry = height * 0.5;
128 if rx <= 1e-6 || ry <= 1e-6 {
129 return (cmds, true);
130 }
131 let total = n * 2;
132 let mut verts = Vec::with_capacity(total);
133 for k in 0..total {
134 let theta = (k as f32) * std::f32::consts::PI / (n as f32);
135 let s = if k % 2 == 0 { 1.0 } else { *depth };
136 verts.push([rx * s * theta.cos(), ry * s * theta.sin()]);
137 }
138 if *corner_radius <= 1e-5 {
139 for (k, &pt) in verts.iter().enumerate() {
140 let v = to_v(pt);
141 if k == 0 {
142 cmds.push(zeno::Command::MoveTo(v));
143 } else {
144 cmds.push(zeno::Command::LineTo(v));
145 }
146 }
147 cmds.push(zeno::Command::Close);
148 } else {
149 for k in 0..total {
150 let prev = verts[(k + total - 1) % total];
151 let curr = verts[k];
152 let next = verts[(k + 1) % total];
153 let d_prev = [prev[0] - curr[0], prev[1] - curr[1]];
154 let d_next = [next[0] - curr[0], next[1] - curr[1]];
155 let l_prev = d_prev[0].hypot(d_prev[1]);
156 let l_next = d_next[0].hypot(d_next[1]);
157 let r = corner_radius.min(0.45 * l_prev.min(l_next));
158 if r <= 1e-6 {
159 let v = to_v(curr);
160 if k == 0 {
161 cmds.push(zeno::Command::MoveTo(v));
162 } else {
163 cmds.push(zeno::Command::LineTo(v));
164 }
165 } else {
166 let p_in = [curr[0] + d_prev[0] * (r / l_prev), curr[1] + d_prev[1] * (r / l_prev)];
167 let p_out = [curr[0] + d_next[0] * (r / l_next), curr[1] + d_next[1] * (r / l_next)];
168 if k == 0 {
169 cmds.push(zeno::Command::MoveTo(to_v(p_in)));
170 } else {
171 cmds.push(zeno::Command::LineTo(to_v(p_in)));
172 }
173 cmds.push(zeno::Command::QuadTo(to_v(curr), to_v(p_out)));
174 }
175 }
176 cmds.push(zeno::Command::Close);
177 }
178 (cmds, true)
179 }
180 ShapePrimKind::Polygon { points, closed } => {
181 if points.len() < 2 {
182 return (cmds, *closed);
183 }
184 cmds.push(zeno::Command::MoveTo(to_v([points[0].x as f32, points[0].y as f32])));
185 let segs = if *closed { points.len() } else { points.len() - 1 };
186 for i in 0..segs {
187 let a = &points[i];
188 let b = &points[(i + 1) % points.len()];
189 let p_b = to_v([b.x as f32, b.y as f32]);
190 let is_linear = (a.linear && b.linear)
191 || (a.rx.abs() < 1e-9 && a.ry.abs() < 1e-9 && b.lx.abs() < 1e-9 && b.ly.abs() < 1e-9);
192 if is_linear {
193 cmds.push(zeno::Command::LineTo(p_b));
194 } else {
195 let c1 = to_v([(a.x + a.rx) as f32, (a.y + a.ry) as f32]);
196 let c2 = to_v([(b.x + b.lx) as f32, (b.y + b.ly) as f32]);
197 cmds.push(zeno::Command::CurveTo(c1, c2, p_b));
198 }
199 }
200 if *closed {
201 cmds.push(zeno::Command::Close);
202 }
203 (cmds, *closed)
204 }
205 ShapePrimKind::BSpline { points, closed, tessellation } => {
206 let min_steps = (12.0 + tessellation.clamp(0.0, 9.0) * 4.0).round() as usize;
207 let xf_pts: Vec<([f32; 2], f32)> = points
208 .iter()
209 .map(|p| (xform.apply([p.x as f32, p.y as f32]), p.w as f32))
210 .collect();
211 let poly = eval_rational_cubic_bspline_2d(&xf_pts, *closed, |chord| {
212 ((chord * 128.0).ceil() as usize).clamp(min_steps, 96)
213 });
214 for (i, &pt) in poly.iter().enumerate() {
215 let v = zeno::Vector::new(pt[0], pt[1]);
216 if i == 0 {
217 cmds.push(zeno::Command::MoveTo(v));
218 } else {
219 cmds.push(zeno::Command::LineTo(v));
220 }
221 }
222 if *closed && !cmds.is_empty() {
223 cmds.push(zeno::Command::Close);
224 }
225 (cmds, *closed)
226 }
227 ShapePrimKind::Text { cmds: text_cmds } => {
228 cmds.reserve(text_cmds.len());
229 for &c in text_cmds {
230 cmds.push(match c {
231 ShapeCmd::MoveTo(p) => zeno::Command::MoveTo(to_v(p)),
232 ShapeCmd::LineTo(p) => zeno::Command::LineTo(to_v(p)),
233 ShapeCmd::QuadTo(a, p) => zeno::Command::QuadTo(to_v(a), to_v(p)),
234 ShapeCmd::CurveTo(a, b, p) => zeno::Command::CurveTo(to_v(a), to_v(b), to_v(p)),
235 ShapeCmd::Close => zeno::Command::Close,
236 });
237 }
238 (cmds, true)
239 }
240 }
241}
242
243/// Flattens `CurveTo` and `QuadTo` segments adaptively in pixel space to sub-0.02px accuracy
244/// so smooth curves (like `sEllipse`, `sText`, rounded corners) avoid coarse polygon facets.
245fn flatten_quad_adaptive(
246 p0: [f32; 2],
247 c: [f32; 2],
248 p1: [f32; 2],
249 tol_sq: f32,
250 depth: u8,
251 out: &mut Vec<[f32; 2]>,
252) {
253 let mx = 0.5 * (p0[0] + p1[0]);
254 let my = 0.5 * (p0[1] + p1[1]);
255 let dx = c[0] - mx;
256 let dy = c[1] - my;
257 if depth >= 9 || (dx * dx + dy * dy) <= 16.0 * tol_sq {
258 out.push(p1);
259 return;
260 }
261 let q0 = [0.5 * (p0[0] + c[0]), 0.5 * (p0[1] + c[1])];
262 let q1 = [0.5 * (c[0] + p1[0]), 0.5 * (c[1] + p1[1])];
263 let mid = [0.5 * (q0[0] + q1[0]), 0.5 * (q0[1] + q1[1])];
264 flatten_quad_adaptive(p0, q0, mid, tol_sq, depth + 1, out);
265 flatten_quad_adaptive(mid, q1, p1, tol_sq, depth + 1, out);
266}
267
268fn flatten_cubic_adaptive(
269 p0: [f32; 2],
270 c1: [f32; 2],
271 c2: [f32; 2],
272 p1: [f32; 2],
273 tol_sq: f32,
274 depth: u8,
275 out: &mut Vec<[f32; 2]>,
276) {
277 let dx = p1[0] - p0[0];
278 let dy = p1[1] - p0[1];
279 let len_sq = dx * dx + dy * dy;
280 let d1 = (c1[0] - p1[0]) * dy - (c1[1] - p1[1]) * dx;
281 let d2 = (c2[0] - p1[0]) * dy - (c2[1] - p1[1]) * dx;
282 let d_max = d1.abs().max(d2.abs());
283 let flat_ok = if len_sq > 1e-8 {
284 (d_max * d_max) <= (16.0 / 9.0) * tol_sq * len_sq
285 } else {
286 (c1[0] - p0[0]).hypot(c1[1] - p0[1]).max((c2[0] - p0[0]).hypot(c2[1] - p0[1])) <= 0.1
287 };
288 if depth >= 9 || (flat_ok && depth >= 2) {
289 out.push(p1);
290 return;
291 }
292 let p01 = [0.5 * (p0[0] + c1[0]), 0.5 * (p0[1] + c1[1])];
293 let p12 = [0.5 * (c1[0] + c2[0]), 0.5 * (c1[1] + c2[1])];
294 let p23 = [0.5 * (c2[0] + p1[0]), 0.5 * (c2[1] + p1[1])];
295 let p012 = [0.5 * (p01[0] + p12[0]), 0.5 * (p01[1] + p12[1])];
296 let p123 = [0.5 * (p12[0] + p23[0]), 0.5 * (p12[1] + p23[1])];
297 let mid = [0.5 * (p012[0] + p123[0]), 0.5 * (p012[1] + p123[1])];
298 flatten_cubic_adaptive(p0, p01, p012, mid, tol_sq, depth + 1, out);
299 flatten_cubic_adaptive(mid, p123, p23, p1, tol_sq, depth + 1, out);
300}
301
302/// Splits `cmds` into per-subpath `Contour`s, adaptively flattening curves in `tol_px` units.
303pub(super) fn flatten_commands_to_contours(
304 cmds: &[zeno::Command],
305 default_closed: bool,
306 tol_px: f32,
307) -> Vec<Contour> {
308 use zeno::Command::{Close, CurveTo, LineTo, MoveTo, QuadTo};
309 let tol_sq = tol_px * tol_px;
310 let mut contours: Vec<Contour> = Vec::new();
311 let mut cur: Vec<[f32; 2]> = Vec::new();
312 let mut cur_closed = false;
313
314 let flush = |cur: &mut Vec<[f32; 2]>, closed: bool, out: &mut Vec<Contour>| {
315 let pts = dedup_contour_points(std::mem::take(cur), closed);
316 if pts.len() >= 2 && (!closed || pts.len() >= 3) {
317 out.push(Contour { points: pts, closed });
318 }
319 };
320
321 for c in cmds {
322 match *c {
323 MoveTo(p) => {
324 if !cur.is_empty() {
325 flush(&mut cur, cur_closed || default_closed, &mut contours);
326 }
327 cur_closed = false;
328 cur.push([p.x, p.y]);
329 }
330 LineTo(p) => {
331 cur.push([p.x, p.y]);
332 }
333 QuadTo(a, p) => {
334 let p0 = cur.last().copied().unwrap_or([a.x, a.y]);
335 flatten_quad_adaptive(p0, [a.x, a.y], [p.x, p.y], tol_sq, 0, &mut cur);
336 }
337 CurveTo(a, b, p) => {
338 let p0 = cur.last().copied().unwrap_or([a.x, a.y]);
339 flatten_cubic_adaptive(p0, [a.x, a.y], [b.x, b.y], [p.x, p.y], tol_sq, 0, &mut cur);
340 }
341 Close => {
342 cur_closed = true;
343 flush(&mut cur, true, &mut contours);
344 }
345 }
346 }
347 if !cur.is_empty() {
348 flush(&mut cur, cur_closed || default_closed, &mut contours);
349 }
350 contours
351}
352
353pub(super) fn contours_to_commands(contours: &[Contour]) -> Vec<zeno::Command> {
354 let mut cmds = Vec::new();
355 for c in contours {
356 if c.points.len() < 2 || (c.closed && c.points.len() < 3) {
357 continue;
358 }
359 for (i, &pt) in c.points.iter().enumerate() {
360 let v = zeno::Vector::new(pt[0], pt[1]);
361 if i == 0 {
362 cmds.push(zeno::Command::MoveTo(v));
363 } else {
364 cmds.push(zeno::Command::LineTo(v));
365 }
366 }
367 if c.closed {
368 cmds.push(zeno::Command::Close);
369 }
370 }
371 cmds
372}
373
374/// Builds pixel-space `zeno::Command`s for a primitive after applying any inner-to-outer `PathModifier`s.
375pub(super) fn build_primitive_commands_px(
376 kind: &ShapePrimKind,
377 xform: Affine2D,
378 mods: &[(PathModifier, Affine2D)],
379 shape_idx: u32,
380 dims: [u32; 2],
381) -> (Vec<zeno::Command>, bool) {
382 let (shape_cmds, closed) = build_primitive_commands_shape(kind, xform);
383 if shape_cmds.is_empty() {
384 return (Vec::new(), closed);
385 }
386
387 if mods.is_empty() {
388 let px_cmds: Vec<zeno::Command> = shape_cmds
389 .into_iter()
390 .map(|c| match c {
391 zeno::Command::MoveTo(p) => zeno::Command::MoveTo(shape_to_px([p.x, p.y], dims)),
392 zeno::Command::LineTo(p) => zeno::Command::LineTo(shape_to_px([p.x, p.y], dims)),
393 zeno::Command::QuadTo(a, p) => zeno::Command::QuadTo(
394 shape_to_px([a.x, a.y], dims),
395 shape_to_px([p.x, p.y], dims),
396 ),
397 zeno::Command::CurveTo(a, b, p) => zeno::Command::CurveTo(
398 shape_to_px([a.x, a.y], dims),
399 shape_to_px([b.x, b.y], dims),
400 shape_to_px([p.x, p.y], dims),
401 ),
402 zeno::Command::Close => zeno::Command::Close,
403 })
404 .collect();
405 let has_curves = px_cmds
406 .iter()
407 .any(|c| matches!(c, zeno::Command::QuadTo(..) | zeno::Command::CurveTo(..)));
408 if has_curves {
409 let contours = flatten_commands_to_contours(&px_cmds, closed, 0.015);
410 return (contours_to_commands(&contours), closed);
411 }
412 return (px_cmds, closed);
413 }
414
415 let tol_shape = 0.02 / (dims[0].max(dims[1]).max(1) as f32);
416 let mut contours = flatten_commands_to_contours(&shape_cmds, closed, tol_shape);
417
418 for (mod_idx, &(op, post_xform)) in mods.iter().enumerate() {
419 if contours.is_empty() {
420 return (Vec::new(), closed);
421 }
422 contours = apply_path_modifier_contours(contours, op, shape_idx, mod_idx as u32);
423 for c in &mut contours {
424 for p in &mut c.points {
425 *p = post_xform.apply(*p);
426 }
427 }
428 }
429
430 let eff_closed = contours.first().is_some_and(|c| c.closed);
431 let mut px_cmds = Vec::new();
432 for c in &contours {
433 if c.points.len() < 2 || (c.closed && c.points.len() < 3) {
434 continue;
435 }
436 for (i, &pt) in c.points.iter().enumerate() {
437 let v = shape_to_px(pt, dims);
438 if i == 0 {
439 px_cmds.push(zeno::Command::MoveTo(v));
440 } else {
441 px_cmds.push(zeno::Command::LineTo(v));
442 }
443 }
444 if c.closed {
445 px_cmds.push(zeno::Command::Close);
446 }
447 }
448 (px_cmds, eff_closed)
449}
450
451/// Builds a closed-ring fill path (`outer` + reversed `inner`) for thick single-contour outlines,
452/// avoiding `zeno::Stroke`'s inner-corner self-overlap artifact.
453pub(super) fn closed_outline_fill_commands(
454 cmds: &[zeno::Command],
455 stroke_px: f32,
456 join_style: u8,
457 miter_limit: f32,
458) -> Option<Vec<zeno::Command>> {
459 let contours = flatten_commands_to_contours(cmds, true, 0.02);
460 if contours.len() != 1 || !contours[0].closed || contours[0].points.len() < 3 {
461 return None;
462 }
463 let half = stroke_px * 0.5;
464 let outer = expand_contour(contours[0].clone(), half, join_style, miter_limit, None);
465 if outer.points.len() < 3 {
466 return None;
467 }
468 let mut inner = expand_contour(contours[0].clone(), -half, join_style, miter_limit, None);
469 let mut out = contours_to_commands(&[outer]);
470 if inner.points.len() >= 3 {
471 inner.points.reverse();
472 out.extend(contours_to_commands(&[inner]));
473 }
474 Some(out)
475}
476
477/// Applies `line_type` dashing (`1..=4`) to pixel-space `cmds`.
478pub(super) fn dash_path_commands(
479 cmds: Vec<zeno::Command>,
480 closed: bool,
481 line_type: u8,
482 stroke_px: f32,
483) -> Vec<zeno::Command> {
484 if line_type == 0 {
485 return cmds;
486 }
487 let contours = flatten_commands_to_contours(&cmds, closed, 0.05);
488 dash_contours(&contours, line_type, stroke_px)
489}
490
491/// Trims each contour in `cmds` to arc-length fraction `[write_pos, write_pos + write_len]`.
492pub(super) fn trim_path_commands(
493 cmds: Vec<zeno::Command>,
494 closed: bool,
495 write_pos: f32,
496 write_len: f32,
497) -> Vec<zeno::Command> {
498 if write_len <= 1e-5 {
499 return Vec::new();
500 }
501 if write_len >= 1.0 - 1e-5 && (!closed || write_pos.rem_euclid(1.0) <= 1e-5) {
502 return cmds;
503 }
504 let contours = flatten_commands_to_contours(&cmds, closed, 0.02);
505 let mut out = Vec::new();
506 for c in contours {
507 out.extend(trim_single_contour(&c.points, c.closed, write_pos, write_len));
508 }
509 out
510}
511
512fn trim_single_contour(
513 poly: &[[f32; 2]],
514 closed: bool,
515 write_pos: f32,
516 write_len: f32,
517) -> Vec<zeno::Command> {
518 let n = poly.len();
519 if n < 2 {
520 return Vec::new();
521 }
522 let seg_count = if closed { n } else { n - 1 };
523 let mut segs = Vec::with_capacity(seg_count);
524 let mut total = 0.0_f32;
525 for i in 0..seg_count {
526 let a = poly[i];
527 let b = poly[(i + 1) % n];
528 let len = (b[0] - a[0]).hypot(b[1] - a[1]);
529 segs.push((a, b, len));
530 total += len;
531 }
532 if total <= 1e-5 {
533 return Vec::new();
534 }
535 let s0 = if closed {
536 write_pos.rem_euclid(1.0) * total
537 } else {
538 write_pos.clamp(0.0, 1.0) * total
539 };
540 let target = if closed {
541 write_len * total
542 } else {
543 (write_len * total).min((total - s0).max(0.0))
544 };
545 if target <= 1e-5 {
546 return Vec::new();
547 }
548 let mut out = Vec::new();
549 let mut acc = 0.0_f32;
550 let mut started = false;
551 let mut idx = 0usize;
552 let max_iters = if closed { seg_count * 2 + 2 } else { seg_count };
553 while acc < s0 + target - 1e-5 && idx < max_iters {
554 let (a, b, len) = segs[idx % seg_count];
555 idx += 1;
556 if len <= 1e-6 {
557 continue;
558 }
559 let seg_start = acc;
560 let seg_end = acc + len;
561 acc = seg_end;
562 if seg_end <= s0 {
563 continue;
564 }
565 let t0 = if !started { ((s0 - seg_start) / len).clamp(0.0, 1.0) } else { 0.0 };
566 let t1 = ((s0 + target - seg_start) / len).clamp(0.0, 1.0);
567 if !started {
568 let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])];
569 out.push(zeno::Command::MoveTo(zeno::Vector::new(p[0], p[1])));
570 started = true;
571 }
572 let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])];
573 out.push(zeno::Command::LineTo(zeno::Vector::new(q[0], q[1])));
574 }
575 out
576}
577
578/// Flattens `cmds` and clips closed polygons to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long.
579pub(super) fn clip_to_viewport(
580 cmds: Vec<zeno::Command>,
581 closed: bool,
582 dims: [u32; 2],
583 margin: f32,
584) -> Vec<zeno::Command> {
585 use zeno::Command::{Close, CurveTo, LineTo, MoveTo};
586 let [w, h] = [dims[0] as f32, dims[1] as f32];
587 let limit = 4.0 * w.max(h);
588 let far = |v: &zeno::Vector| v.x.abs() > limit || v.y.abs() > limit;
589 let huge = cmds.iter().any(|c| match c {
590 MoveTo(p) | LineTo(p) => far(p),
591 zeno::Command::QuadTo(a, p) => far(a) || far(p),
592 CurveTo(a, b, p) => far(a) || far(b) || far(p),
593 _ => false,
594 });
595 if !huge || !closed {
596 return cmds;
597 }
598 let contours = flatten_commands_to_contours(&cmds, closed, 0.05);
599 let edges: [(usize, f32, f32); 4] = [
600 (0, 1.0, -margin),
601 (0, -1.0, w + margin),
602 (1, 1.0, -margin),
603 (1, -1.0, h + margin),
604 ];
605 let mut out = Vec::new();
606 for contour in contours {
607 let mut poly = contour.points;
608 for (axis, sign, bound) in edges {
609 let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0;
610 let input = std::mem::take(&mut poly);
611 for (i, &cur) in input.iter().enumerate() {
612 let prev = input[(i + input.len() - 1) % input.len()];
613 if inside(cur) != inside(prev) {
614 let t = (bound - prev[axis]) / (cur[axis] - prev[axis]);
615 poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]);
616 }
617 if inside(cur) {
618 poly.push(cur);
619 }
620 }
621 }
622 for (i, p) in poly.iter().enumerate() {
623 let v = zeno::Vector::new(p[0], p[1]);
624 out.push(if i == 0 { MoveTo(v) } else { LineTo(v) });
625 }
626 if !poly.is_empty() {
627 out.push(Close);
628 }
629 }
630 out
631}