kui_core/line.rs
1//! Strokes: what a `line` node draws.
2//!
3//! A line is a run of points and a [`Stroke`]; the core flattens a curve
4//! into a polyline here, boxes the run, and emits one
5//! [`crate::QuadKind::Segment`] per straight piece. The points live in a
6//! per-frame list beside the tree — rebuilt every frame, capacities kept —
7//! and a node refers to its run by [`LineId`] the way a text node refers to
8//! the frame's text list. The previous frame's list is kept by the same
9//! gated buffer swap the text list uses, so a departing line can copy its
10//! points out for its ghost.
11
12use crate::color::Color;
13use crate::geom::{Rect, Vec2};
14use crate::retain::Kept;
15
16/// Index into the frame's line list.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct LineId(pub u32);
19
20/// How a `line` is drawn: a width, a colour, and whether the points are
21/// the corners of a polyline or the knots of a curve through them.
22#[derive(Clone, Copy, Debug, PartialEq)]
23pub struct Stroke {
24 /// Stroke width in logical px. Round caps at both ends of every
25 /// segment, which is also the join between two of them.
26 pub width: f32,
27 /// The stroke colour. Inside the core it rides in the node's `bg`
28 /// slot, so a `transition` eases it and `enter` / `exit` can start
29 /// or end it there.
30 pub color: Color,
31 /// Draw a smooth curve *through* the points (a centripetal Catmull-Rom
32 /// spline, flattened by [`flatten_curve`]) instead of the polyline. Two
33 /// points are a straight segment either way.
34 pub curve: bool,
35 /// The marks and gaps the stroke is cut into; [`Dash::SOLID`], the
36 /// default, is none.
37 pub dash: Dash,
38}
39
40impl Stroke {
41 pub fn new(width: f32, color: Color) -> Self {
42 Self {
43 width,
44 color,
45 curve: false,
46 dash: Dash::SOLID,
47 }
48 }
49
50 pub fn curve(mut self) -> Self {
51 self.curve = true;
52 self
53 }
54
55 /// Cuts the stroke into marks `on` long with gaps `off` long between
56 /// them; see [`Dash`].
57 pub fn dash(mut self, on: f32, off: f32) -> Self {
58 self.dash = Dash {
59 offset: self.dash.offset,
60 ..Dash::new(on, off)
61 };
62 self
63 }
64
65 /// The whole pattern at once, for a dash-dot or one read from data.
66 pub fn dashed(mut self, dash: Dash) -> Self {
67 self.dash = dash;
68 self
69 }
70
71 /// How far into the pattern the stroke starts; see [`Dash::offset`].
72 pub fn dash_offset(mut self, offset: f32) -> Self {
73 self.dash.offset = offset;
74 self
75 }
76}
77
78/// A stroke's dash pattern (backlog V2): a mark, a gap, a second mark and
79/// a second gap, repeated along the stroke's length from its first point.
80///
81/// The lengths are the ones **seen**, in logical px. Every mark is
82/// round-capped, as the stroke itself is, so a mark `on` long is drawn as
83/// a capsule whose centre line is `on − width` long, and a mark no longer
84/// than the stroke is wide is a dot. (SVG's `stroke-dasharray` measures
85/// the centre line instead, which with a round cap makes `4 4` at a width
86/// of 4 a solid line; this pattern at any width is SVG's
87/// `on − width, off + width`.) The first mark's cap sits where a solid
88/// stroke's would, half the width before the first point.
89///
90/// The pattern runs along the arc length of the whole stroke, so it keeps
91/// its phase across the corners of a polyline and the pieces of a curve;
92/// on a `path` it restarts at every subpath, as SVG's does.
93#[derive(Clone, Copy, Debug, PartialEq)]
94pub struct Dash {
95 /// Mark, gap, mark, gap. A two-length pattern is the same pair twice.
96 pub pattern: [f32; 4],
97 /// How far into the pattern the stroke starts, in logical px: growing
98 /// it moves the marks towards the stroke's first point, which is what
99 /// a marquee's marching ants are. Any number; it wraps.
100 pub offset: f32,
101}
102
103impl Default for Dash {
104 fn default() -> Self {
105 Dash::SOLID
106 }
107}
108
109/// What a dashed stroke is cut by: the centre-line lengths of the
110/// pattern's four entries — mark, gap, mark, gap — and where in it the
111/// stroke starts, `0 <= offset < period`. Logical px.
112#[derive(Clone, Copy, Debug, PartialEq)]
113pub struct Cut {
114 pub lens: [f32; 4],
115 pub offset: f32,
116}
117
118impl Cut {
119 pub fn period(&self) -> f32 {
120 self.lens.iter().sum()
121 }
122
123 /// Whether a mark and its gap come to less than `min` together, on
124 /// average: a pattern that fine reads as a tint, and is drawn solid.
125 pub fn finer_than(&self, min: f32) -> bool {
126 let pair = self.period() * 0.5;
127 pair.is_nan() || pair < min
128 }
129
130 /// The pattern as one number, for a mask's key and for telling a
131 /// pattern that moved from one that held.
132 pub(crate) fn hash(&self) -> u64 {
133 let [a, b, c, d] = self.lens.map(|l| u64::from(l.to_bits()));
134 let mut h = a ^ b.rotate_left(16) ^ c.rotate_left(32) ^ d.rotate_left(48);
135 h = h.wrapping_mul(0x0000_0100_0000_01b3) ^ u64::from(self.offset.to_bits());
136 h.wrapping_mul(0x0000_0100_0000_01b3)
137 }
138}
139
140/// The most marks one stroke is cut into; a pattern that would make more
141/// — a period of a pixel along a line no screen is long enough for —
142/// draws solid, which is what it would read as.
143pub const MAX_MARKS: usize = 16384;
144
145impl Dash {
146 /// No dashes: the stroke unbroken.
147 pub const SOLID: Dash = Dash {
148 pattern: [0.0; 4],
149 offset: 0.0,
150 };
151
152 /// Marks `on` long with gaps `off` long between them.
153 pub fn new(on: f32, off: f32) -> Self {
154 Dash {
155 pattern: [on, off, on, off],
156 offset: 0.0,
157 }
158 }
159
160 /// The pattern as the bindings spell it: one length (marks and gaps
161 /// alike), two (a mark and a gap) or four (a mark, a gap, a second
162 /// mark, a second gap — a dash-dot). None for any other count.
163 pub fn of(lengths: &[f32]) -> Option<Self> {
164 let pattern = match *lengths {
165 [a] => [a, a, a, a],
166 [a, b] => [a, b, a, b],
167 [a, b, c, d] => [a, b, c, d],
168 _ => return None,
169 };
170 Some(Dash {
171 pattern,
172 offset: 0.0,
173 })
174 }
175
176 /// [`Self::offset`] set.
177 pub fn offset(mut self, offset: f32) -> Self {
178 self.offset = offset;
179 self
180 }
181
182 /// Whether the pattern leaves the stroke unbroken: no gap in it, or a
183 /// length that is not a number.
184 pub fn is_solid(&self) -> bool {
185 self.cut(0.0).is_none()
186 }
187
188 /// The pattern as centre-line lengths for a stroke `width` wide, or
189 /// None for one that draws solid: a length that is not finite, or no
190 /// gap anywhere. Negative lengths are zero, and a pair that is zero
191 /// altogether is the other pair.
192 #[inline]
193 pub fn cut(&self, width: f32) -> Option<Cut> {
194 // The solid stroke, which is nearly every stroke, is told by its
195 // zeroes and pays for nothing below (backlog C52).
196 if self.pattern == Dash::SOLID.pattern {
197 return None;
198 }
199 self.cut_pattern(width)
200 }
201
202 #[cold]
203 #[inline(never)]
204 fn cut_pattern(&self, width: f32) -> Option<Cut> {
205 if !self.pattern.iter().all(|l| l.is_finite()) || !self.offset.is_finite() {
206 return None;
207 }
208 let [a, b, c, d] = self.pattern.map(|l| l.max(0.0));
209 if b <= 0.0 && d <= 0.0 {
210 return None;
211 }
212 let (first, second) = match (a + b > 0.0, c + d > 0.0) {
213 (true, true) => ([a, b], [c, d]),
214 (true, false) => ([a, b], [a, b]),
215 (false, _) => ([c, d], [c, d]),
216 };
217 let w = width.max(0.0);
218 // The mark's caps are part of what is seen, so they come out of
219 // its centre line and go into the gap's.
220 let centre = |[on, off]: [f32; 2]| {
221 let mark = (on - w).max(0.0);
222 [mark, on + off - mark]
223 };
224 let ([m0, g0], [m1, g1]) = (centre(first), centre(second));
225 let lens = [m0, g0, m1, g1];
226 let period: f32 = lens.iter().sum();
227 Some(Cut {
228 lens,
229 offset: self.offset.rem_euclid(period),
230 })
231 }
232}
233
234impl Cut {
235 /// Calls `mark(from, to)` for every mark along the polyline `points`,
236 /// in order — a mark that turns a corner is one call per piece it
237 /// lies on, meeting at the corner, and a dot is a call with both ends
238 /// the same. False, with nothing called, for a stroke that draws
239 /// solid instead: a pattern [`Self::finer_than`] `min`, more than
240 /// [`MAX_MARKS`] marks, or a length that is zero or not finite.
241 pub fn marks(&self, points: &[Vec2], min: f32, mut mark: impl FnMut(Vec2, Vec2)) -> bool {
242 let period = self.period();
243 let piece = |pair: &[Vec2]| (pair[1].x - pair[0].x).hypot(pair[1].y - pair[0].y);
244 let total: f32 = points.windows(2).map(piece).sum();
245 // Two marks a period; `!(..)` so a NaN draws solid too.
246 let marks = total / period * 2.0;
247 // A stroke of no length has no mark to lie on and is the dot its
248 // solid one is (RG116).
249 if self.finer_than(min) || marks.is_nan() || marks > MAX_MARKS as f32 || total <= 0.0 {
250 return false;
251 }
252 // Where the stroke starts in the pattern: the entry and what is
253 // left of it.
254 let (mut i, mut left) = (0, self.lens[0]);
255 let mut skip = self.offset;
256 while skip >= left && skip > 0.0 {
257 skip -= left;
258 i = (i + 1) & 3;
259 left = self.lens[i];
260 }
261 left -= skip;
262 // A mark that ended exactly on a corner has been drawn up to it;
263 // the entry after it starts on the next piece.
264 for pair in points.windows(2) {
265 let len = piece(pair);
266 if len <= 0.0 {
267 continue;
268 }
269 let (a, b) = (pair[0], pair[1]);
270 let at = |s: f32| {
271 let t = s / len;
272 Vec2::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
273 };
274 let mut pos = 0.0;
275 loop {
276 let take = left.min(len - pos);
277 if i & 1 == 0 {
278 mark(at(pos), at(pos + take));
279 }
280 pos += take;
281 left -= take;
282 if left > 0.0 {
283 break;
284 }
285 i = (i + 1) & 3;
286 left = self.lens[i];
287 // The piece is used up: what starts here starts on the
288 // next one, except a dot, which has nowhere else to be
289 // when this is the last.
290 if pos >= len && left > 0.0 {
291 break;
292 }
293 }
294 }
295 true
296 }
297}
298
299/// One stroke's run in the frame's point list. The points are stored
300/// relative to the node's box, so a node that eases or slides carries
301/// them along.
302#[derive(Clone, Copy, Debug, PartialEq)]
303pub(crate) struct Run {
304 pub first: u32,
305 pub len: u32,
306 /// Logical px.
307 pub width: f32,
308 /// What cuts the stroke into marks; None for a solid one.
309 pub dash: Option<Cut>,
310}
311
312/// The frame's strokes, and the previous frame's while an `exit` needs it.
313#[derive(Default)]
314pub struct LineStore {
315 runs: Kept<Run>,
316 points: Kept<Vec2>,
317}
318
319/// How far a stroke's box extends past its points: half the width, plus
320/// two logical px so a backend's edge ramp (`AA` = 0.75 physical px each
321/// side, sampled at pixel centres) is never cut by the quad, at scale 1
322/// included.
323pub(crate) fn pad(width: f32) -> f32 {
324 width.max(0.0) * 0.5 + 2.0
325}
326
327/// A curve span is flattened into one piece per this many logical px of
328/// chord, at least one and at most [`CURVE_MAX_PIECES`]. Fixed rather than
329/// tolerance-driven so the piece count is a function of the declared
330/// geometry alone — every binding gets the same segments, and the
331/// conformance corpus can pin them.
332pub const CURVE_STEP: f32 = 6.0;
333pub const CURVE_MAX_PIECES: usize = 32;
334
335impl LineStore {
336 /// Starts a frame. `keep_prev` retains the list just finished so a
337 /// departing line's ghost can copy its points out of it.
338 pub(crate) fn begin_frame(&mut self, keep_prev: bool) {
339 self.runs.begin(keep_prev);
340 self.points.begin(keep_prev);
341 }
342
343 /// Adds a stroke through `points` (parent-box coordinates): flattens a
344 /// curve, boxes the run, and stores the points relative to the box.
345 /// Returns the id and the box, or None for fewer than two points,
346 /// which draw nothing.
347 pub(crate) fn push(&mut self, points: &[Vec2], stroke: &Stroke) -> Option<(LineId, Rect)> {
348 if points.len() < 2 {
349 return None;
350 }
351 let first = self.points.len();
352 if stroke.curve && points.len() > 2 {
353 flatten_curve(points, &mut self.points);
354 } else {
355 self.points.extend_from_slice(points);
356 }
357 let run = &mut self.points[first..];
358 let (mut min, mut max) = (run[0], run[0]);
359 for p in run.iter() {
360 min.x = min.x.min(p.x);
361 min.y = min.y.min(p.y);
362 max.x = max.x.max(p.x);
363 max.y = max.y.max(p.y);
364 }
365 let pad = pad(stroke.width);
366 let origin = Vec2::new(min.x - pad, min.y - pad);
367 for p in run.iter_mut() {
368 p.x -= origin.x;
369 p.y -= origin.y;
370 }
371 let rect = Rect::new(
372 origin.x,
373 origin.y,
374 max.x - min.x + 2.0 * pad,
375 max.y - min.y + 2.0 * pad,
376 );
377 let id = LineId(self.runs.len() as u32);
378 self.runs.push(Run {
379 first: first as u32,
380 len: (self.points.len() - first) as u32,
381 width: stroke.width,
382 dash: stroke.dash.cut(stroke.width),
383 });
384 Some((id, rect))
385 }
386
387 /// This frame's run: its width and its points, relative to the node.
388 pub(crate) fn run(&self, id: LineId) -> (Run, &[Vec2]) {
389 let run = self.runs[id.0 as usize];
390 (
391 run,
392 &self.points[run.first as usize..(run.first + run.len) as usize],
393 )
394 }
395
396 /// The same, read from the previous frame's list (a departing line's
397 /// id indexes that list, not this frame's). Empty for an id the kept
398 /// frame does not have, which cannot happen while `begin_frame` keeps
399 /// the two in step.
400 pub(crate) fn prev_run(&self, id: LineId) -> (Run, &[Vec2]) {
401 match self.runs.prev().get(id.0 as usize) {
402 Some(run) => (
403 *run,
404 &self.points.prev()[run.first as usize..(run.first + run.len) as usize],
405 ),
406 None => (
407 Run {
408 first: 0,
409 len: 0,
410 width: 0.0,
411 dash: None,
412 },
413 &[],
414 ),
415 }
416 }
417
418 /// Runs this frame.
419 pub fn len(&self) -> usize {
420 self.runs.len()
421 }
422
423 pub fn is_empty(&self) -> bool {
424 self.runs.is_empty()
425 }
426}
427
428/// Flattens a **centripetal** Catmull-Rom spline through `knots` (at least
429/// three) into `out`, starting at the first knot and ending at the last.
430/// Each span is cut into `ceil(chord / CURVE_STEP)` pieces, clamped to
431/// `1..=CURVE_MAX_PIECES`.
432///
433/// Centripetal means the spline's knot parameter advances by the square
434/// root of each chord instead of by 1. A *uniform*
435/// spline — the textbook one, and what this was until it drew a mind
436/// map — ignores how far apart its knots are, so knots that are close
437/// together get as much parameter as knots that are far apart, and the
438/// curve has to move fast through the tight ones. On an elbow (a long run,
439/// then a sharp turn) that shows up as a bow out of the wrong side of the
440/// corner; on knots spaced unevenly enough it becomes a cusp or a loop,
441/// which a centripetal span provably never has. It bows less
442/// too, though it is not overshoot-free: a spline that must pass *through*
443/// a corner has to lean into it. A shape that should only be *pulled*
444/// towards its middle points is a Bézier, and the caller samples one
445/// (`examples/rust/widgets/line.rs`).
446///
447/// The end knots are not doubled — a repeated knot is a zero-length chord,
448/// which centripetal has no parameter for. Each end gets a mirrored
449/// phantom instead (`2·p1 − p2`), which spaces evenly and leaves the first
450/// span's tangent along its own chord. A coincident pair of *real* knots
451/// takes the same branch, so a duplicated point in a caller's list stays a
452/// harmless kink rather than a division by zero.
453///
454/// The chords are rolled forward rather than recomputed, so a span costs
455/// two square roots and not six; `frame_1k_curves` is the bench that
456/// watches the rest of it.
457pub fn flatten_curve(knots: &[Vec2], out: &mut Vec<Vec2>) {
458 let n = knots.len();
459 if n < 2 {
460 return;
461 }
462 out.push(knots[0]);
463 // This span's chord and its knot step (√chord), and the span before's:
464 // a zero chord means there is no neighbour on that side, either
465 // because the run ends there or because the two knots coincide.
466 let (mut prev, mut prev_step) = (0.0, 0.0);
467 let (mut chord, mut step) = chord_and_step(knots[0], knots[1]);
468 for i in 0..n - 1 {
469 let (p1, p2) = (knots[i], knots[i + 1]);
470 let (next, next_step) = match knots.get(i + 2) {
471 Some(&p) => chord_and_step(p2, p),
472 None => (0.0, 0.0),
473 };
474 let pieces = ((chord / CURVE_STEP).ceil() as usize).clamp(1, CURVE_MAX_PIECES);
475 if chord == 0.0 {
476 // Nothing to parameterize: the span is a point.
477 out.push(p2);
478 } else {
479 let mirror = |p: Vec2, q: Vec2| Vec2::new(2.0 * p.x - q.x, 2.0 * p.y - q.y);
480 let (p0, s0) = match prev > 0.0 {
481 true => (knots[i - 1], prev_step),
482 false => (mirror(p1, p2), step),
483 };
484 let (p3, s2) = match next > 0.0 {
485 true => (knots[i + 2], next_step),
486 false => (mirror(p2, p1), step),
487 };
488 // Knot times: 0, then one step per span.
489 let span = Span::new([p0, p1, p2, p3], [0.0, s0, s0 + step, s0 + step + s2]);
490 for k in 1..pieces {
491 out.push(span.at(s0 + step * (k as f32 / pieces as f32)));
492 }
493 // The knot itself rather than the evaluation at its time, so
494 // the run passes through it bit for bit whatever the
495 // arithmetic rounds to.
496 out.push(p2);
497 }
498 (prev, prev_step) = (chord, step);
499 (chord, step) = (next, next_step);
500 }
501}
502
503/// A span's length and the parameter it is worth: `√chord` is Lee's
504/// α = ½, the centripetal one. α = 0 would be `1.0` (uniform) and α = 1
505/// the chord itself (chordal).
506fn chord_and_step(a: Vec2, b: Vec2) -> (f32, f32) {
507 let chord = ((b.x - a.x).powi(2) + (b.y - a.y).powi(2)).sqrt();
508 (chord, chord.sqrt())
509}
510
511/// One span of the spline, evaluated between `p[1]` and `p[2]` by Barry
512/// and Goldman's pyramid: three interpolations of the knots in their own
513/// times, then two of those, then one. Written this way rather than as a
514/// cubic in `t` because the times are no longer evenly spaced.
515///
516/// A span is built once and asked for every piece, because the pyramid's
517/// five distinct denominators are the same five numbers each time. They
518/// are reciprocals, so `at(t[2])` is only *nearly* `p[2]` — the caller
519/// pushes the knot itself instead of asking for it.
520struct Span {
521 p: [Vec2; 4],
522 t: [f32; 4],
523 /// `1/(t[1]-t[0])`, `1/(t[2]-t[1])`, `1/(t[3]-t[2])`, `1/(t[2]-t[0])`,
524 /// `1/(t[3]-t[1])`, in the order the pyramid needs them.
525 inv: [f32; 5],
526}
527
528impl Span {
529 fn new(p: [Vec2; 4], t: [f32; 4]) -> Self {
530 let inv = [
531 1.0 / (t[1] - t[0]),
532 1.0 / (t[2] - t[1]),
533 1.0 / (t[3] - t[2]),
534 1.0 / (t[2] - t[0]),
535 1.0 / (t[3] - t[1]),
536 ];
537 Span { p, t, inv }
538 }
539
540 fn at(&self, u: f32) -> Vec2 {
541 let (p, t) = (&self.p, &self.t);
542 let blend = |a: Vec2, b: Vec2, ta: f32, inv: f32| {
543 let w = (u - ta) * inv;
544 Vec2::new(a.x + (b.x - a.x) * w, a.y + (b.y - a.y) * w)
545 };
546 let a1 = blend(p[0], p[1], t[0], self.inv[0]);
547 let a2 = blend(p[1], p[2], t[1], self.inv[1]);
548 let a3 = blend(p[2], p[3], t[2], self.inv[2]);
549 let b1 = blend(a1, a2, t[0], self.inv[3]);
550 let b2 = blend(a2, a3, t[1], self.inv[4]);
551 blend(b1, b2, t[1], self.inv[1])
552 }
553}
554
555#[cfg(test)]
556mod tests {
557 use super::*;
558
559 #[test]
560 fn a_curve_passes_through_its_knots_and_ends_where_they_end() {
561 let knots = [
562 Vec2::new(0.0, 0.0),
563 Vec2::new(30.0, 40.0),
564 Vec2::new(60.0, 0.0),
565 ];
566 let mut out = Vec::new();
567 flatten_curve(&knots, &mut out);
568 assert_eq!(out[0], knots[0]);
569 assert_eq!(*out.last().unwrap(), knots[2]);
570 // Chord 50 → 9 pieces per span, 1 + 9 + 9 points.
571 assert_eq!(out.len(), 19);
572 assert_eq!(out[9], knots[1]);
573 }
574
575 /// How sharply the run doubles back, worst piece, in degrees. A
576 /// smoothly flattened curve turns a few degrees a piece; a cusp turns
577 /// most of the way round.
578 fn worst_turn(pts: &[Vec2]) -> f32 {
579 pts.windows(3).fold(0.0f32, |worst, w| {
580 let (a, b) = (
581 Vec2::new(w[1].x - w[0].x, w[1].y - w[0].y),
582 Vec2::new(w[2].x - w[1].x, w[2].y - w[1].y),
583 );
584 let len = |v: Vec2| (v.x * v.x + v.y * v.y).sqrt();
585 let (la, lb) = (len(a), len(b));
586 if la < 1e-6 || lb < 1e-6 {
587 return worst;
588 }
589 let cos = ((a.x * b.x + a.y * b.y) / (la * lb)).clamp(-1.0, 1.0);
590 worst.max(cos.acos().to_degrees())
591 })
592 }
593
594 /// Whether any two non-adjacent pieces of the run cross.
595 fn ties_a_loop(pts: &[Vec2]) -> bool {
596 let side =
597 |a: Vec2, b: Vec2, c: Vec2| (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
598 (0..pts.len() - 1).any(|i| {
599 (i + 2..pts.len() - 1).any(|j| {
600 let (a, b, c, d) = (pts[i], pts[i + 1], pts[j], pts[j + 1]);
601 side(a, b, c) * side(a, b, d) < 0.0 && side(c, d, a) * side(c, d, b) < 0.0
602 })
603 })
604 }
605
606 /// The reason the parameterization is centripetal and not uniform.
607 /// Chords 671, 36 and 328: a knot pair nineteen times tighter than its
608 /// neighbours. A uniform parameter hands that 36px chord as much curve
609 /// as the 671px one, and the middle span has to tie a loop to spend
610 /// it — at `CURVE_STEP`'s own sampling, one crossing and a piece that
611 /// turns 95°. Centripetal spends parameter by `√chord`, so the tight
612 /// pair is just a corner.
613 #[test]
614 fn a_tight_knot_between_two_long_ones_neither_loops_nor_cusps() {
615 let knots = [
616 Vec2::new(0.0, 400.0),
617 Vec2::new(600.0, 100.0),
618 Vec2::new(630.0, 80.0),
619 Vec2::new(560.0, 400.0),
620 ];
621 let mut out = Vec::new();
622 flatten_curve(&knots, &mut out);
623 assert!(!ties_a_loop(&out), "the run crosses itself");
624 assert!(worst_turn(&out) < 45.0, "cusp: {:.1}°", worst_turn(&out));
625 }
626
627 /// A caller's list may repeat a point — a mind map with two cards at
628 /// the same place, a path snapped to a grid. The mirrored phantom
629 /// covers it: a zero chord has no `√chord` to divide by, and every
630 /// point that comes back is a number.
631 #[test]
632 fn a_repeated_knot_is_a_kink_and_not_a_division_by_zero() {
633 let knots = [
634 Vec2::new(0.0, 0.0),
635 Vec2::new(40.0, 0.0),
636 Vec2::new(40.0, 0.0),
637 Vec2::new(40.0, 40.0),
638 Vec2::new(80.0, 40.0),
639 ];
640 let mut out = Vec::new();
641 flatten_curve(&knots, &mut out);
642 assert!(out.iter().all(|p| p.x.is_finite() && p.y.is_finite()));
643 assert_eq!(out[0], knots[0]);
644 assert_eq!(*out.last().unwrap(), knots[4]);
645 }
646
647 #[test]
648 fn two_points_are_one_segment_even_as_a_curve() {
649 let mut store = LineStore::default();
650 let (id, rect) = store
651 .push(
652 &[Vec2::new(10.0, 10.0), Vec2::new(50.0, 40.0)],
653 &Stroke::new(2.0, Color::WHITE).curve(),
654 )
655 .unwrap();
656 let (run, pts) = store.run(id);
657 assert_eq!(run.len, 2);
658 assert_eq!(run.width, 2.0);
659 // Padded by half the width plus two: the box starts at (7, 7).
660 assert_eq!((rect.x, rect.y, rect.w, rect.h), (7.0, 7.0, 46.0, 36.0));
661 assert_eq!(pts[0], Vec2::new(3.0, 3.0));
662 assert_eq!(pts[1], Vec2::new(43.0, 33.0));
663 }
664
665 #[test]
666 fn one_point_draws_nothing() {
667 let mut store = LineStore::default();
668 assert!(
669 store
670 .push(&[Vec2::new(1.0, 1.0)], &Stroke::new(1.0, Color::WHITE))
671 .is_none()
672 );
673 }
674
675 #[test]
676 fn the_previous_frame_is_kept_only_when_asked() {
677 let mut store = LineStore::default();
678 let (id, _) = store
679 .push(
680 &[Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0)],
681 &Stroke::new(1.0, Color::WHITE),
682 )
683 .unwrap();
684 store.begin_frame(true);
685 assert_eq!(store.prev_run(id).0.len, 2);
686 assert!(store.is_empty());
687 store.begin_frame(false);
688 assert_eq!(store.prev_run(id).0.len, 0);
689 }
690}