1use crate::rasterizer::FrameBuffer;
7use strata_layout::Rect;
8pub use strata_primitives::geom::Transform2D;
9use strata_style::types::Color;
10
11#[derive(Debug, Clone, PartialEq)]
13pub enum CanvasPathVerb {
14 MoveTo(f32, f32),
15 LineTo(f32, f32),
16 Arc {
17 cx: f32,
18 cy: f32,
19 radius: f32,
20 start_angle: f32,
21 end_angle: f32,
22 counter_clockwise: bool,
23 },
24 Close,
25}
26
27#[derive(Debug, Clone, PartialEq)]
29pub enum CanvasCommand {
30 FillRect {
31 bounds: Rect,
32 color: Color,
33 },
34 StrokeRect {
35 bounds: Rect,
36 color: Color,
37 line_width: f32,
38 },
39 ClearRect {
40 bounds: Rect,
41 },
42 DrawLine {
43 p0: (f32, f32),
44 p1: (f32, f32),
45 color: Color,
46 line_width: f32,
47 },
48 DrawCircle {
49 center: (f32, f32),
50 radius: f32,
51 fill_color: Option<Color>,
52 stroke_color: Option<Color>,
53 line_width: f32,
54 },
55 DrawPath {
56 verbs: Vec<CanvasPathVerb>,
57 fill_color: Option<Color>,
58 stroke_color: Option<Color>,
59 line_width: f32,
60 },
61}
62
63#[derive(Debug, Clone, PartialEq)]
64struct CanvasState {
65 transform: Transform2D,
66 fill_style: Color,
67 stroke_style: Color,
68 line_width: f32,
69 global_alpha: f32,
70}
71
72impl Default for CanvasState {
73 fn default() -> Self {
74 Self {
75 transform: Transform2D::IDENTITY,
76 fill_style: Color::BLACK,
77 stroke_style: Color::BLACK,
78 line_width: 1.0,
79 global_alpha: 1.0,
80 }
81 }
82}
83
84#[derive(Debug, Clone)]
86pub struct Canvas2DContext {
87 pub width: f32,
88 pub height: f32,
89 current_state: CanvasState,
90 state_stack: Vec<CanvasState>,
91 current_path: Vec<CanvasPathVerb>,
92 commands: Vec<CanvasCommand>,
93}
94
95impl Canvas2DContext {
96 pub fn new(width: f32, height: f32) -> Self {
97 Self {
98 width,
99 height,
100 current_state: CanvasState::default(),
101 state_stack: Vec::new(),
102 current_path: Vec::new(),
103 commands: Vec::new(),
104 }
105 }
106
107 pub fn save(&mut self) {
110 self.state_stack.push(self.current_state.clone());
111 }
112
113 pub fn restore(&mut self) {
114 if let Some(state) = self.state_stack.pop() {
115 self.current_state = state;
116 }
117 }
118
119 pub fn translate(&mut self, dx: f32, dy: f32) {
122 self.current_state.transform.translate(dx, dy);
123 }
124
125 pub fn scale(&mut self, sx: f32, sy: f32) {
126 self.current_state.transform.scale_mut(sx, sy);
127 }
128
129 pub fn rotate(&mut self, radians: f32) {
130 self.current_state.transform.rotate_mut(radians);
131 }
132
133 pub fn transform(&mut self, a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) {
134 let other = Transform2D::from_w3c(a, b, c, d, e, f);
135 self.current_state.transform = self.current_state.transform.multiply(other);
136 }
137
138 pub fn set_transform(&mut self, transform: Transform2D) {
139 self.current_state.transform = transform;
140 }
141
142 pub fn get_transform(&self) -> Transform2D {
143 self.current_state.transform
144 }
145
146 pub fn reset_transform(&mut self) {
147 self.current_state.transform = Transform2D::IDENTITY;
148 }
149
150 pub fn set_fill_style(&mut self, color: Color) {
153 self.current_state.fill_style = color;
154 }
155
156 pub fn set_stroke_style(&mut self, color: Color) {
157 self.current_state.stroke_style = color;
158 }
159
160 pub fn set_line_width(&mut self, width: f32) {
161 self.current_state.line_width = width.max(0.1);
162 }
163
164 pub fn set_global_alpha(&mut self, alpha: f32) {
165 self.current_state.global_alpha = alpha.clamp(0.0, 1.0);
166 }
167
168 fn apply_alpha(&self, color: Color) -> Color {
169 if (self.current_state.global_alpha - 1.0).abs() < 1e-4 {
170 color
171 } else {
172 let (r, g, b, a) = color.to_f32();
173 Color::from_f32(r, g, b, a * self.current_state.global_alpha)
174 }
175 }
176
177 pub fn begin_path(&mut self) {
180 self.current_path.clear();
181 }
182
183 pub fn move_to(&mut self, x: f32, y: f32) {
184 let (tx, ty) = self.current_state.transform.transform_xy(x, y);
185 self.current_path.push(CanvasPathVerb::MoveTo(tx, ty));
186 }
187
188 pub fn line_to(&mut self, x: f32, y: f32) {
189 let (tx, ty) = self.current_state.transform.transform_xy(x, y);
190 self.current_path.push(CanvasPathVerb::LineTo(tx, ty));
191 }
192
193 pub fn arc(
194 &mut self,
195 cx: f32,
196 cy: f32,
197 radius: f32,
198 start_angle: f32,
199 end_angle: f32,
200 ccw: bool,
201 ) {
202 let (tcx, tcy) = self.current_state.transform.transform_xy(cx, cy);
203 let scale_x = (self.current_state.transform.a.powi(2)
205 + self.current_state.transform.b.powi(2))
206 .sqrt();
207 self.current_path.push(CanvasPathVerb::Arc {
208 cx: tcx,
209 cy: tcy,
210 radius: radius * scale_x,
211 start_angle,
212 end_angle,
213 counter_clockwise: ccw,
214 });
215 }
216
217 pub fn rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
218 self.move_to(x, y);
219 self.line_to(x + w, y);
220 self.line_to(x + w, y + h);
221 self.line_to(x, y + h);
222 self.close_path();
223 }
224
225 pub fn close_path(&mut self) {
226 self.current_path.push(CanvasPathVerb::Close);
227 }
228
229 pub fn fill_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
232 let (x0, y0) = self.current_state.transform.transform_xy(x, y);
233 let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
234 let min_x = x0.min(x1);
235 let max_x = x0.max(x1);
236 let min_y = y0.min(y1);
237 let max_y = y0.max(y1);
238
239 let color = self.apply_alpha(self.current_state.fill_style);
240 self.commands.push(CanvasCommand::FillRect {
241 bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
242 color,
243 });
244 }
245
246 pub fn stroke_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
247 let (x0, y0) = self.current_state.transform.transform_xy(x, y);
248 let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
249 let min_x = x0.min(x1);
250 let max_x = x0.max(x1);
251 let min_y = y0.min(y1);
252 let max_y = y0.max(y1);
253
254 let color = self.apply_alpha(self.current_state.stroke_style);
255 self.commands.push(CanvasCommand::StrokeRect {
256 bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
257 color,
258 line_width: self.current_state.line_width,
259 });
260 }
261
262 pub fn clear_rect(&mut self, x: f32, y: f32, w: f32, h: f32) {
263 let (x0, y0) = self.current_state.transform.transform_xy(x, y);
264 let (x1, y1) = self.current_state.transform.transform_xy(x + w, y + h);
265 let min_x = x0.min(x1);
266 let max_x = x0.max(x1);
267 let min_y = y0.min(y1);
268 let max_y = y0.max(y1);
269
270 self.commands.push(CanvasCommand::ClearRect {
271 bounds: Rect::new(min_x, min_y, max_x - min_x, max_y - min_y),
272 });
273 }
274
275 pub fn stroke(&mut self) {
276 if self.current_path.is_empty() {
277 return;
278 }
279 let color = self.apply_alpha(self.current_state.stroke_style);
280 self.commands.push(CanvasCommand::DrawPath {
281 verbs: self.current_path.clone(),
282 fill_color: None,
283 stroke_color: Some(color),
284 line_width: self.current_state.line_width,
285 });
286 }
287
288 pub fn fill(&mut self) {
289 if self.current_path.is_empty() {
290 return;
291 }
292 let color = self.apply_alpha(self.current_state.fill_style);
293 self.commands.push(CanvasCommand::DrawPath {
294 verbs: self.current_path.clone(),
295 fill_color: Some(color),
296 stroke_color: None,
297 line_width: self.current_state.line_width,
298 });
299 }
300
301 pub fn finish(self) -> Vec<CanvasCommand> {
303 self.commands
304 }
305
306 pub fn commands(&self) -> &[CanvasCommand] {
307 &self.commands
308 }
309
310 pub fn rasterize(
312 &self,
313 fb: &mut FrameBuffer,
314 origin_x: f32,
315 origin_y: f32,
316 clip: Option<Rect>,
317 ) {
318 rasterize_canvas_commands(fb, &self.commands, origin_x, origin_y, clip);
319 }
320}
321
322pub fn rasterize_canvas_commands(
324 fb: &mut FrameBuffer,
325 commands: &[CanvasCommand],
326 origin_x: f32,
327 origin_y: f32,
328 clip: Option<Rect>,
329) {
330 for cmd in commands {
331 match cmd {
332 CanvasCommand::FillRect { bounds, color } => {
333 let translated = Rect::new(
334 bounds.x + origin_x,
335 bounds.y + origin_y,
336 bounds.width,
337 bounds.height,
338 );
339 fb.draw_rect(translated, *color, clip);
340 }
341 CanvasCommand::ClearRect { bounds } => {
342 let translated = Rect::new(
343 bounds.x + origin_x,
344 bounds.y + origin_y,
345 bounds.width,
346 bounds.height,
347 );
348 fb.clear_rect(translated, Color::TRANSPARENT);
349 }
350 CanvasCommand::StrokeRect {
351 bounds,
352 color,
353 line_width,
354 } => {
355 let lw = *line_width;
356 let translated = Rect::new(
357 bounds.x + origin_x,
358 bounds.y + origin_y,
359 bounds.width,
360 bounds.height,
361 );
362 fb.draw_rect(
364 Rect::new(translated.x, translated.y, translated.width, lw),
365 *color,
366 clip,
367 );
368 fb.draw_rect(
370 Rect::new(translated.x, translated.max_y() - lw, translated.width, lw),
371 *color,
372 clip,
373 );
374 fb.draw_rect(
376 Rect::new(translated.x, translated.y, lw, translated.height),
377 *color,
378 clip,
379 );
380 fb.draw_rect(
382 Rect::new(translated.max_x() - lw, translated.y, lw, translated.height),
383 *color,
384 clip,
385 );
386 }
387 CanvasCommand::DrawLine {
388 p0,
389 p1,
390 color,
391 line_width,
392 } => {
393 rasterize_line(
394 fb,
395 p0.0 + origin_x,
396 p0.1 + origin_y,
397 p1.0 + origin_x,
398 p1.1 + origin_y,
399 *color,
400 *line_width,
401 clip,
402 );
403 }
404 CanvasCommand::DrawCircle {
405 center,
406 radius,
407 fill_color,
408 stroke_color,
409 line_width,
410 } => {
411 let cx = center.0 + origin_x;
412 let cy = center.1 + origin_y;
413 let r = *radius;
414 let lw = *line_width;
415
416 let min_x = ((cx - r - lw).floor() as isize).max(0) as usize;
417 let max_x = ((cx + r + lw).ceil() as usize).min(fb.width);
418 let min_y = ((cy - r - lw).floor() as isize).max(0) as usize;
419 let max_y = ((cy + r + lw).ceil() as usize).min(fb.height);
420
421 for y in min_y..max_y {
422 let dy = y as f32 + 0.5 - cy;
423 for x in min_x..max_x {
424 let dx = x as f32 + 0.5 - cx;
425 let dist = (dx * dx + dy * dy).sqrt();
426
427 if let Some(fc) = fill_color {
428 let coverage = (0.5 + r - dist).clamp(0.0, 1.0);
429 if coverage > 0.005 {
430 fb.set_pixel(
431 x,
432 y,
433 Color::rgba(
434 fc.r,
435 fc.g,
436 fc.b,
437 (fc.a() * coverage * 255.0) as u8,
438 ),
439 );
440 }
441 }
442
443 if let Some(sc) = stroke_color {
444 let stroke_dist = (dist - r).abs();
445 let coverage = (0.5 + lw * 0.5 - stroke_dist).clamp(0.0, 1.0);
446 if coverage > 0.005 {
447 fb.set_pixel(
448 x,
449 y,
450 Color::rgba(
451 sc.r,
452 sc.g,
453 sc.b,
454 (sc.a() * coverage * 255.0) as u8,
455 ),
456 );
457 }
458 }
459 }
460 }
461 }
462 CanvasCommand::DrawPath {
463 verbs,
464 fill_color,
465 stroke_color,
466 line_width,
467 } => {
468 if let Some(fc) = fill_color {
469 for verb in verbs {
470 if let CanvasPathVerb::Arc { cx, cy, radius, .. } = verb {
471 let r = *radius;
472 let acx = *cx + origin_x;
473 let acy = *cy + origin_y;
474 let min_x = ((acx - r).floor() as isize).max(0) as usize;
475 let max_x = ((acx + r).ceil() as usize).min(fb.width);
476 let min_y = ((acy - r).floor() as isize).max(0) as usize;
477 let max_y = ((acy + r).ceil() as usize).min(fb.height);
478
479 for y in min_y..max_y {
480 if let Some(c) = clip {
481 if (y as f32) < c.y || (y as f32) >= c.max_y() {
482 continue;
483 }
484 }
485 let dy = y as f32 + 0.5 - acy;
486 for x in min_x..max_x {
487 if let Some(c) = clip {
488 if (x as f32) < c.x || (x as f32) >= c.max_x() {
489 continue;
490 }
491 }
492 let dx = x as f32 + 0.5 - acx;
493 let dist = (dx * dx + dy * dy).sqrt();
494 let coverage = (0.5 + r - dist).clamp(0.0, 1.0);
495 if coverage > 0.005 {
496 fb.set_pixel(
497 x,
498 y,
499 Color::rgba(
500 fc.r,
501 fc.g,
502 fc.b,
503 (fc.a() * coverage * 255.0) as u8,
504 ),
505 );
506 }
507 }
508 }
509 }
510 }
511 }
512
513 let mut current = (origin_x, origin_y);
515 let mut start = (origin_x, origin_y);
516
517 for verb in verbs {
518 match verb {
519 CanvasPathVerb::MoveTo(x, y) => {
520 current = (*x + origin_x, *y + origin_y);
521 start = current;
522 }
523 CanvasPathVerb::LineTo(x, y) => {
524 let next = (*x + origin_x, *y + origin_y);
525 if let Some(color) = stroke_color {
526 rasterize_line(
527 fb,
528 current.0,
529 current.1,
530 next.0,
531 next.1,
532 *color,
533 *line_width,
534 clip,
535 );
536 }
537 current = next;
538 }
539 CanvasPathVerb::Close => {
540 if current != start {
541 if let Some(color) = stroke_color {
542 rasterize_line(
543 fb,
544 current.0,
545 current.1,
546 start.0,
547 start.1,
548 *color,
549 *line_width,
550 clip,
551 );
552 }
553 current = start;
554 }
555 }
556 CanvasPathVerb::Arc { cx, cy, radius, .. } => {
557 current = (*cx + origin_x + *radius, *cy + origin_y);
559 }
560 }
561 }
562 }
563 }
564 }
565}
566
567fn rasterize_line(
569 fb: &mut FrameBuffer,
570 x0: f32,
571 y0: f32,
572 x1: f32,
573 y1: f32,
574 color: Color,
575 line_width: f32,
576 clip: Option<Rect>,
577) {
578 let min_x = (x0.min(x1) - line_width - 1.0).max(0.0).floor() as usize;
579 let max_x = ((x0.max(x1) + line_width + 1.0).ceil() as usize).min(fb.width);
580 let min_y = (y0.min(y1) - line_width - 1.0).max(0.0).floor() as usize;
581 let max_y = ((y0.max(y1) + line_width + 1.0).ceil() as usize).min(fb.height);
582
583 let vx = x1 - x0;
584 let vy = y1 - y0;
585 let v_len_sq = vx * vx + vy * vy;
586 let half_lw = line_width * 0.5;
587
588 for y in min_y..max_y {
589 if let Some(c) = clip {
590 if (y as f32) < c.y || (y as f32) >= c.max_y() {
591 continue;
592 }
593 }
594 let py = y as f32 + 0.5;
595
596 for x in min_x..max_x {
597 if let Some(c) = clip {
598 if (x as f32) < c.x || (x as f32) >= c.max_x() {
599 continue;
600 }
601 }
602 let px = x as f32 + 0.5;
603
604 let wx = px - x0;
606 let wy = py - y0;
607
608 let t = if v_len_sq > 1e-6 {
609 ((wx * vx + wy * vy) / v_len_sq).clamp(0.0, 1.0)
610 } else {
611 0.0
612 };
613
614 let proj_x = x0 + t * vx;
615 let proj_y = y0 + t * vy;
616
617 let dist = ((px - proj_x).powi(2) + (py - proj_y).powi(2)).sqrt();
618 let coverage = (0.5 + half_lw - dist).clamp(0.0, 1.0);
619
620 if coverage > 0.005 {
621 let effective_color = Color::rgba(
622 color.r,
623 color.g,
624 color.b,
625 (color.a() * coverage * 255.0) as u8,
626 );
627 fb.set_pixel(x, y, effective_color);
628 }
629 }
630 }
631}
632
633#[cfg(test)]
634mod tests {
635 use super::*;
636
637 #[test]
638 fn test_transform2d_operations() {
639 let mut t = Transform2D::IDENTITY;
640 t.translate(100.0, 50.0);
641 let p = t.transform_xy(10.0, 20.0);
642 assert_eq!(p, (110.0, 70.0));
643
644 let mut s = Transform2D::IDENTITY;
645 s.scale_mut(2.0, 3.0);
646 let p2 = s.transform_xy(10.0, 10.0);
647 assert_eq!(p2, (20.0, 30.0));
648 }
649
650 #[test]
651 fn test_canvas_context_recording() {
652 let mut ctx = Canvas2DContext::new(400.0, 300.0);
653
654 ctx.set_fill_style(Color::rgb(255, 0, 0));
655 ctx.fill_rect(10.0, 10.0, 80.0, 50.0);
656
657 ctx.set_stroke_style(Color::rgb(0, 0, 255));
658 ctx.set_line_width(2.0);
659 ctx.begin_path();
660 ctx.move_to(0.0, 0.0);
661 ctx.line_to(100.0, 100.0);
662 ctx.stroke();
663
664 assert_eq!(ctx.commands().len(), 2);
665 }
666
667 #[test]
668 fn test_canvas_rasterize_to_framebuffer() {
669 let mut fb = FrameBuffer::new(200, 200);
670 let mut ctx = Canvas2DContext::new(200.0, 200.0);
671
672 ctx.set_fill_style(Color::rgb(0, 255, 0));
673 ctx.fill_rect(20.0, 20.0, 40.0, 40.0);
674
675 ctx.rasterize(&mut fb, 0.0, 0.0, None);
676
677 let pixel = fb.get_pixel(40, 40);
679 assert_eq!(pixel, Color::rgb(0, 255, 0));
680
681 assert_eq!(fb.get_pixel(5, 5), Color::TRANSPARENT);
683 }
684}