1use crate::display::PixelFormat;
4use crate::solver::Region;
5use crate::style::Color;
6
7use super::math::{abs_f32, ceil_f32, floor_f32, round_f32, sqrt_f32};
8use super::path::FlattenedPath;
9
10use std::vec::Vec;
11
12
13#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
15pub enum SvgFillRule {
16 #[default]
18 NonZero,
19 EvenOdd,
21}
22
23#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
25pub enum SvgLineCap {
26 #[default]
28 Butt,
29 Round,
31 Square,
33}
34
35#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
37pub enum SvgLineJoin {
38 #[default]
40 Miter,
41 Round,
43 Bevel,
45}
46
47#[derive(Copy, Clone)]
48struct ScanEdge {
49 y0: f32,
50 y1: f32,
51 x0: f32,
52 dx_dy: f32,
53 dir: i8,
54}
55
56#[derive(Copy, Clone)]
57struct Crossing {
58 x: f32,
59 dir: i8,
60}
61
62#[allow(clippy::too_many_arguments)]
64pub fn fill_path<P: PixelFormat>(
65 path: &FlattenedPath,
66 color: Color,
67 fill_rule: SvgFillRule,
68 clip: Region,
69 origin_x: i16,
70 origin_y: i16,
71 stride: usize,
72 target: &mut [P],
73) {
74 if color.a() == 0 || clip.is_empty() || stride == 0 || path.is_empty() {
75 return;
76 }
77
78 let mut edges: Vec<ScanEdge> = Vec::with_capacity(path.points().len());
79
80 let pts = path.points();
81 let mut global_min_y = f32::MAX;
82 let mut global_max_y = f32::MIN;
83
84 for sp in path.subpaths() {
85 if sp.len < 2 {
86 continue;
87 }
88 let end = (sp.start + sp.len).min(pts.len());
89 if end <= sp.start + 1 {
90 continue;
91 }
92 let sub = &pts[sp.start..end];
93 let seg_count = sub.len();
94 for i in 0..seg_count {
95 let p0 = sub[i];
96 let p1 = sub[(i + 1) % seg_count];
97 let dy = p1.1 - p0.1;
98 if abs_f32(dy) < 1e-6 {
99 continue;
100 }
101 let edge = if dy > 0.0 {
102 ScanEdge {
103 y0: p0.1,
104 y1: p1.1,
105 x0: p0.0,
106 dx_dy: (p1.0 - p0.0) / dy,
107 dir: 1,
108 }
109 } else {
110 ScanEdge {
111 y0: p1.1,
112 y1: p0.1,
113 x0: p1.0,
114 dx_dy: (p0.0 - p1.0) / (-dy),
115 dir: -1,
116 }
117 };
118 if edge.y0 < global_min_y {
119 global_min_y = edge.y0;
120 }
121 if edge.y1 > global_max_y {
122 global_max_y = edge.y1;
123 }
124 edges.push(edge);
125 }
126 }
127
128 if edges.is_empty() {
129 return;
130 }
131
132 let y_start = (floor_f32(global_min_y) as i32)
133 .max(clip.y as i32)
134 .min(clip.bottom() as i32);
135 let y_end = (ceil_f32(global_max_y) as i32)
136 .max(clip.y as i32)
137 .min(clip.bottom() as i32);
138 if y_start >= y_end {
139 return;
140 }
141
142 let clip_x0 = clip.x as i32;
143 let clip_x1 = clip.right() as i32;
144 let clip_w = (clip_x1 - clip_x0).max(0) as usize;
145 if clip_w == 0 {
146 return;
147 }
148
149 const SUB_OFFSETS: [f32; 4] = [0.125, 0.375, 0.625, 0.875];
150
151 let mut row_cov = std::vec![0.0f32; clip_w];
152 let mut crossings: Vec<Crossing> = Vec::with_capacity(32);
153
154
155 for py_i32 in y_start..y_end {
156 let py = py_i32 as i16;
157 let row_offset = ((py - origin_y) as usize) * stride;
158
159 {
160 row_cov.fill(0.0);
161 for &sub_y in &SUB_OFFSETS {
162 let sy = (py_i32 as f32) + sub_y;
163 crossings.clear();
164 for e in &edges {
165 if e.y0 <= sy && sy < e.y1 {
166 let x = e.x0 + (sy - e.y0) * e.dx_dy;
167 crossings.push(Crossing { x, dir: e.dir });
168 }
169 }
170 if crossings.len() < 2 {
171 continue;
172 }
173 sort_crossings(&mut crossings);
174 accumulate_scanline_spans(&crossings, fill_rule, clip_x0, clip_x1, &mut row_cov);
175 }
176 flush_row_coverage(
177 &row_cov,
178 clip_x0,
179 origin_x,
180 row_offset,
181 color,
182 1.0,
183 target,
184 );
185 }
186
187 }
188}
189
190#[inline]
191fn sort_crossings(list: &mut [Crossing]) {
192 for i in 1..list.len() {
193 let key = list[i];
194 let mut j = i;
195 while j > 0 && list[j - 1].x > key.x {
196 list[j] = list[j - 1];
197 j -= 1;
198 }
199 list[j] = key;
200 }
201}
202
203#[inline]
204fn accumulate_scanline_spans(
205 crossings: &[Crossing],
206 fill_rule: SvgFillRule,
207 tile_x0: i32,
208 tile_x1: i32,
209 row_cov: &mut [f32],
210) {
211 let mut winding: i32 = 0;
212 let mut span_start = 0.0f32;
213 let mut inside = false;
214 let tile_x0_f = tile_x0 as f32;
215 let tile_x1_f = tile_x1 as f32;
216
217 for c in crossings {
218 winding += c.dir as i32;
219 let now_inside = match fill_rule {
220 SvgFillRule::NonZero => winding != 0,
221 SvgFillRule::EvenOdd => (winding & 1) != 0,
222 };
223 if !inside && now_inside {
224 span_start = c.x;
225 inside = true;
226 } else if inside && !now_inside {
227 let x0 = span_start.max(tile_x0_f);
228 let x1 = c.x.min(tile_x1_f);
229 if x1 > x0 {
230 let ix0 = floor_f32(x0) as i32;
231 let ix1 = (ceil_f32(x1) as i32).min(tile_x1);
232 for px in ix0..ix1 {
233 let px_f = px as f32;
234 let cov = (x1.min(px_f + 1.0) - x0.max(px_f)).clamp(0.0, 1.0);
235 let idx = (px - tile_x0) as usize;
236 if let Some(slot) = row_cov.get_mut(idx) {
237 *slot += cov * 0.25;
238 }
239 }
240 }
241 inside = false;
242 }
243 }
244}
245
246#[derive(Copy, Clone)]
247struct StrokeSeg {
248 ax: f32,
249 ay: f32,
250 ux: f32,
251 uy: f32,
252 len: f32,
253 min_x: f32,
254 max_x: f32,
255 min_y: f32,
256 max_y: f32,
257 cap_start: SvgLineCap,
258 cap_end: SvgLineCap,
259}
260
261#[derive(Copy, Clone)]
262struct MiterTri {
263 ax: f32,
264 ay: f32,
265 bx: f32,
266 by: f32,
267 cx: f32,
268 cy: f32,
269 min_x: f32,
270 max_x: f32,
271 min_y: f32,
272 max_y: f32,
273}
274
275#[allow(clippy::too_many_arguments)]
277pub fn stroke_path<P: PixelFormat>(
278 path: &FlattenedPath,
279 color: Color,
280 stroke_width_px: f32,
281 line_cap: SvgLineCap,
282 line_join: SvgLineJoin,
283 miter_limit: f32,
284 clip: Region,
285 origin_x: i16,
286 origin_y: i16,
287 stride: usize,
288 target: &mut [P],
289) {
290 if color.a() == 0 || stroke_width_px <= 1e-4 || clip.is_empty() || stride == 0 || path.is_empty()
291 {
292 return;
293 }
294
295 let (half_w, alpha_scale) = if stroke_width_px < 1.0 {
297 (0.5, stroke_width_px.clamp(0.0, 1.0))
298 } else {
299 (stroke_width_px * 0.5, 1.0)
300 };
301 let pad = half_w + 1.0;
302
303 let mut segs: Vec<StrokeSeg> = Vec::with_capacity(path.points().len());
304
305 let mut miters: Vec<MiterTri> = Vec::new();
306
307 let pts = path.points();
308 let mut global_min_y = f32::MAX;
309 let mut global_max_y = f32::MIN;
310
311 let internal_cap = match line_join {
312 SvgLineJoin::Round => SvgLineCap::Round,
313 SvgLineJoin::Bevel | SvgLineJoin::Miter => SvgLineCap::Butt,
314 };
315
316 for sp in path.subpaths() {
317 let end = (sp.start + sp.len).min(pts.len());
318 let sub = &pts[sp.start..end];
319 if sub.is_empty() {
320 continue;
321 }
322 if sub.len() == 1 {
323 if line_cap != SvgLineCap::Butt {
325 let (x, y) = sub[0];
326 let seg = StrokeSeg {
327 ax: x,
328 ay: y,
329 ux: 1.0,
330 uy: 0.0,
331 len: 0.0,
332 min_x: x - pad,
333 max_x: x + pad,
334 min_y: y - pad,
335 max_y: y + pad,
336 cap_start: line_cap,
337 cap_end: line_cap,
338 };
339 global_min_y = global_min_y.min(seg.min_y);
340 global_max_y = global_max_y.max(seg.max_y);
341 segs.push(seg);
342 }
343 continue;
344 }
345
346 let seg_count = if sp.closed { sub.len() } else { sub.len() - 1 };
347 let sub_seg_base = segs.len();
348 for i in 0..seg_count {
349 let p0 = sub[i];
350 let p1 = sub[(i + 1) % sub.len()];
351 let dx = p1.0 - p0.0;
352 let dy = p1.1 - p0.1;
353 let len = sqrt_f32(dx * dx + dy * dy);
354 if len < 1e-5 {
355 continue;
356 }
357 let cap_start = if !sp.closed && i == 0 {
358 line_cap
359 } else {
360 internal_cap
361 };
362 let cap_end = if !sp.closed && i + 1 == seg_count {
363 line_cap
364 } else {
365 internal_cap
366 };
367 let ext = if cap_start == SvgLineCap::Square || cap_end == SvgLineCap::Square {
368 pad + half_w
369 } else {
370 pad
371 };
372 let seg = StrokeSeg {
373 ax: p0.0,
374 ay: p0.1,
375 ux: dx / len,
376 uy: dy / len,
377 len,
378 min_x: p0.0.min(p1.0) - ext,
379 max_x: p0.0.max(p1.0) + ext,
380 min_y: p0.1.min(p1.1) - ext,
381 max_y: p0.1.max(p1.1) + ext,
382 cap_start,
383 cap_end,
384 };
385 global_min_y = global_min_y.min(seg.min_y);
386 global_max_y = global_max_y.max(seg.max_y);
387 segs.push(seg);
388 }
389
390 let added = segs.len() - sub_seg_base;
392 if added >= 2 && line_join != SvgLineJoin::Round {
393 let join_count = if sp.closed { added } else { added - 1 };
394 for j in 0..join_count {
395 let s0 = segs.as_slice()[sub_seg_base + j];
396 let s1 = segs.as_slice()[sub_seg_base + ((j + 1) % added)];
397 let vx = s1.ax;
398 let vy = s1.ay;
399 let cross = s0.ux * s1.uy - s0.uy * s1.ux;
400 if abs_f32(cross) < 1e-4 {
401 continue;
402 }
403 let sign = if cross > 0.0 { 1.0 } else { -1.0 };
405 let n0x = sign * s0.uy;
406 let n0y = -sign * s0.ux;
407 let n1x = sign * s1.uy;
408 let n1y = -sign * s1.ux;
409 let p0 = (vx + n0x * half_w, vy + n0y * half_w);
410 let p1 = (vx + n1x * half_w, vy + n1y * half_w);
411 push_tri(&mut miters, (vx, vy), p0, p1, &mut global_min_y, &mut global_max_y);
413
414 if line_join == SvgLineJoin::Miter {
415 let mx = n0x + n1x;
417 let my = n0y + n1y;
418 let m_len_sq = mx * mx + my * my;
419 if m_len_sq > 1e-5 {
420 let inv_cos = 2.0 / sqrt_f32(m_len_sq);
421 if inv_cos <= miter_limit.max(1.0) {
422 let scale = half_w * inv_cos / sqrt_f32(m_len_sq);
423 let apex = (vx + mx * scale, vy + my * scale);
424 push_tri(
425 &mut miters,
426 p0,
427 apex,
428 p1,
429 &mut global_min_y,
430 &mut global_max_y,
431 );
432 }
433 }
434 }
435 }
436 }
437 }
438
439 if segs.is_empty() {
440 return;
441 }
442
443 let y_start = (floor_f32(global_min_y) as i32)
444 .max(clip.y as i32)
445 .min(clip.bottom() as i32);
446 let y_end = (ceil_f32(global_max_y) as i32)
447 .max(clip.y as i32)
448 .min(clip.bottom() as i32);
449 if y_start >= y_end {
450 return;
451 }
452
453 let clip_x0 = clip.x as i32;
454 let clip_x1 = clip.right() as i32;
455 let clip_w = (clip_x1 - clip_x0).max(0) as usize;
456 if clip_w == 0 {
457 return;
458 }
459
460 let mut row_cov = std::vec![0.0f32; clip_w];
461
462 for py_i32 in y_start..y_end {
463 let py = py_i32 as i16;
464 let py_c = (py_i32 as f32) + 0.5;
465 let row_offset = ((py - origin_y) as usize) * stride;
466
467 {
468 row_cov.fill(0.0);
469 raster_stroke_row(
470 py_c,
471 clip_x0,
472 clip_x1,
473 half_w,
474 &segs,
475 &miters,
476 &mut row_cov,
477 );
478 flush_row_coverage(
479 &row_cov,
480 clip_x0,
481 origin_x,
482 row_offset,
483 color,
484 alpha_scale,
485 target,
486 );
487 }
488
489 }
490}
491
492fn push_tri(
493 out: &mut Vec<MiterTri>,
494 a: (f32, f32),
495 b: (f32, f32),
496 c: (f32, f32),
497 g_min_y: &mut f32,
498 g_max_y: &mut f32,
499) {
500 let min_x = a.0.min(b.0).min(c.0) - 1.0;
501 let max_x = a.0.max(b.0).max(c.0) + 1.0;
502 let min_y = a.1.min(b.1).min(c.1) - 1.0;
503 let max_y = a.1.max(b.1).max(c.1) + 1.0;
504 *g_min_y = g_min_y.min(min_y);
505 *g_max_y = g_max_y.max(max_y);
506 out.push(MiterTri {
507 ax: a.0,
508 ay: a.1,
509 bx: b.0,
510 by: b.1,
511 cx: c.0,
512 cy: c.1,
513 min_x,
514 max_x,
515 min_y,
516 max_y,
517 });
518}
519
520
521fn raster_stroke_row(
522 py_c: f32,
523 tile_x0: i32,
524 tile_x1: i32,
525 half_w: f32,
526 segs: &[StrokeSeg],
527 miters: &[MiterTri],
528 row_cov: &mut [f32],
529) {
530 for seg in segs {
531 if py_c < seg.min_y || py_c > seg.max_y {
532 continue;
533 }
534 let sx0 = (floor_f32(seg.min_x) as i32).max(tile_x0);
535 let sx1 = (ceil_f32(seg.max_x) as i32).min(tile_x1);
536 if sx0 >= sx1 {
537 continue;
538 }
539 let dy = py_c - seg.ay;
540 for px in sx0..sx1 {
541 let dx = (px as f32 + 0.5) - seg.ax;
542 let along = dx * seg.ux + dy * seg.uy;
543 let perp = abs_f32(dx * (-seg.uy) + dy * seg.ux);
544
545 let sd = if along < 0.0 {
546 match seg.cap_start {
547 SvgLineCap::Round => sqrt_f32(dx * dx + dy * dy) - half_w,
548 SvgLineCap::Butt => box_outside_sd(-along, perp - half_w),
549 SvgLineCap::Square => box_outside_sd(-along - half_w, perp - half_w),
550 }
551 } else if along > seg.len {
552 let over = along - seg.len;
553 match seg.cap_end {
554 SvgLineCap::Round => {
555 let ex = dx - seg.ux * seg.len;
556 let ey = dy - seg.uy * seg.len;
557 sqrt_f32(ex * ex + ey * ey) - half_w
558 }
559 SvgLineCap::Butt => box_outside_sd(over, perp - half_w),
560 SvgLineCap::Square => box_outside_sd(over - half_w, perp - half_w),
561 }
562 } else {
563 perp - half_w
564 };
565
566 let cov = (0.5 - sd).clamp(0.0, 1.0);
567 if cov > 0.0 {
568 let idx = (px - tile_x0) as usize;
569 if let Some(slot) = row_cov.get_mut(idx) {
570 if cov > *slot {
571 *slot = cov;
572 }
573 }
574 }
575 }
576 }
577
578 for tri in miters {
579 if py_c < tri.min_y || py_c > tri.max_y {
580 continue;
581 }
582 let sx0 = (floor_f32(tri.min_x) as i32).max(tile_x0);
583 let sx1 = (ceil_f32(tri.max_x) as i32).min(tile_x1);
584 if sx0 >= sx1 {
585 continue;
586 }
587 for px in sx0..sx1 {
588 let sd = sd_triangle(
589 px as f32 + 0.5,
590 py_c,
591 tri.ax,
592 tri.ay,
593 tri.bx,
594 tri.by,
595 tri.cx,
596 tri.cy,
597 );
598 let cov = (0.5 - sd).clamp(0.0, 1.0);
599 if cov > 0.0 {
600 let idx = (px - tile_x0) as usize;
601 if let Some(slot) = row_cov.get_mut(idx) {
602 if cov > *slot {
603 *slot = cov;
604 }
605 }
606 }
607 }
608 }
609}
610
611#[inline(always)]
613fn box_outside_sd(dx_out: f32, dy_out: f32) -> f32 {
614 if dx_out > 0.0 && dy_out > 0.0 {
615 sqrt_f32(dx_out * dx_out + dy_out * dy_out)
616 } else {
617 dx_out.max(dy_out)
618 }
619}
620
621#[allow(clippy::too_many_arguments)]
623fn sd_triangle(
624 px: f32,
625 py: f32,
626 ax: f32,
627 ay: f32,
628 bx: f32,
629 by: f32,
630 cx: f32,
631 cy: f32,
632) -> f32 {
633 let e0x = bx - ax;
634 let e0y = by - ay;
635 let e1x = cx - bx;
636 let e1y = cy - by;
637 let e2x = ax - cx;
638 let e2y = ay - cy;
639
640 let v0x = px - ax;
641 let v0y = py - ay;
642 let v1x = px - bx;
643 let v1y = py - by;
644 let v2x = px - cx;
645 let v2y = py - cy;
646
647 let t0 = ((v0x * e0x + v0y * e0y) / (e0x * e0x + e0y * e0y).max(1e-10)).clamp(0.0, 1.0);
648 let t1 = ((v1x * e1x + v1y * e1y) / (e1x * e1x + e1y * e1y).max(1e-10)).clamp(0.0, 1.0);
649 let t2 = ((v2x * e2x + v2y * e2y) / (e2x * e2x + e2y * e2y).max(1e-10)).clamp(0.0, 1.0);
650
651 let pq0x = v0x - e0x * t0;
652 let pq0y = v0y - e0y * t0;
653 let pq1x = v1x - e1x * t1;
654 let pq1y = v1y - e1y * t1;
655 let pq2x = v2x - e2x * t2;
656 let pq2y = v2y - e2y * t2;
657
658 let s = if e0x * e2y - e0y * e2x >= 0.0 {
659 1.0
660 } else {
661 -1.0
662 };
663 let d0 = pq0x * pq0x + pq0y * pq0y;
664 let d1 = pq1x * pq1x + pq1y * pq1y;
665 let d2 = pq2x * pq2x + pq2y * pq2y;
666 let min_d2 = d0.min(d1).min(d2);
667
668 let c0 = s * (v0x * e0y - v0y * e0x);
669 let c1 = s * (v1x * e1y - v1y * e1x);
670 let c2 = s * (v2x * e2y - v2y * e2x);
671 let min_c = c0.min(c1).min(c2);
672
673 let dist = sqrt_f32(min_d2);
674 if min_c >= 0.0 {
675 -dist
676 } else {
677 dist
678 }
679}
680
681#[inline]
682fn flush_row_coverage<P: PixelFormat>(
683 row_cov: &[f32],
684 tile_x0: i32,
685 origin_x: i16,
686 row_offset: usize,
687 color: Color,
688 alpha_scale: f32,
689 target: &mut [P],
690) {
691 let base_dst = tile_x0 - (origin_x as i32);
692 for (i, &cov_raw) in row_cov.iter().enumerate() {
693 if cov_raw <= 1e-4 {
694 continue;
695 }
696 let cov_f = (cov_raw * alpha_scale).clamp(0.0, 1.0);
697 let cov_u8 = round_f32(cov_f * 255.0) as u8;
698 if cov_u8 == 0 {
699 continue;
700 }
701 let dst_x = base_dst + (i as i32);
702 if dst_x >= 0 {
703 let idx = row_offset + (dst_x as usize);
704 if let Some(dst) = target.get_mut(idx) {
705 *dst = dst.blend(color, cov_u8);
706 }
707 }
708 }
709}