Skip to main content

cranpose_render_pixels/
draw.rs

1use std::rc::Rc;
2
3use cranpose_render_common::brush_sampling::sample_brush_rgba;
4use cranpose_render_common::graph_scene::RenderDiagnostics;
5use cranpose_render_common::software_text_raster::rasterize_text_to_image;
6use cranpose_render_common::text_measure::SoftwareTextResources;
7#[cfg(test)]
8use cranpose_render_common::text_measure::{
9    fallback_char_width, fallback_cursor_x_for_byte_offset, fallback_line_height,
10    fallback_text_metrics,
11};
12use cranpose_ui::text::TextMotion;
13use cranpose_ui_graphics::{BlendMode, ColorFilter, Point, Rect};
14
15use crate::pipeline;
16use crate::scene::{ImageDraw, RasterScene, Scene, TextDraw};
17use crate::style::point_in_resolved_rounded_rect;
18
19fn is_blend_mode_supported(mode: BlendMode) -> bool {
20    matches!(mode, BlendMode::SrcOver | BlendMode::DstOut)
21}
22
23fn snap_delta_for_anchor(anchor: Point) -> Point {
24    Point::new(anchor.x.round() - anchor.x, anchor.y.round() - anchor.y)
25}
26
27#[derive(Clone, Copy)]
28struct ClipBounds {
29    min_x: i32,
30    min_y: i32,
31    max_x: i32,
32    max_y: i32,
33}
34
35fn clip_rect_to_bounds(
36    rect: Rect,
37    clip: Option<Rect>,
38    width: u32,
39    height: u32,
40) -> Option<ClipBounds> {
41    let mut min_x = rect.x;
42    let mut min_y = rect.y;
43    let mut max_x = rect.x + rect.width;
44    let mut max_y = rect.y + rect.height;
45
46    if let Some(clip_rect) = clip {
47        min_x = min_x.max(clip_rect.x);
48        min_y = min_y.max(clip_rect.y);
49        max_x = max_x.min(clip_rect.x + clip_rect.width);
50        max_y = max_y.min(clip_rect.y + clip_rect.height);
51    }
52
53    min_x = min_x.max(0.0);
54    min_y = min_y.max(0.0);
55    max_x = max_x.min(width as f32);
56    max_y = max_y.min(height as f32);
57
58    if max_x <= min_x || max_y <= min_y {
59        return None;
60    }
61
62    let min_x = min_x.floor() as i32;
63    let min_y = min_y.floor() as i32;
64    let max_x = max_x.ceil() as i32;
65    let max_y = max_y.ceil() as i32;
66
67    let min_x = min_x.clamp(0, width as i32);
68    let min_y = min_y.clamp(0, height as i32);
69    let max_x = max_x.clamp(0, width as i32);
70    let max_y = max_y.clamp(0, height as i32);
71
72    if min_x >= max_x || min_y >= max_y {
73        return None;
74    }
75
76    Some(ClipBounds {
77        min_x,
78        min_y,
79        max_x,
80        max_y,
81    })
82}
83
84pub fn draw_scene(frame: &mut [u8], width: u32, height: u32, scene: &Scene) {
85    let text_resources = SoftwareTextResources::default();
86    draw_scene_with_text_resources(frame, width, height, scene, &text_resources);
87}
88
89pub fn draw_scene_with_text_resources(
90    frame: &mut [u8],
91    width: u32,
92    height: u32,
93    scene: &Scene,
94    text_resources: &SoftwareTextResources,
95) {
96    if let Some(graph) = scene.graph.as_ref() {
97        let raster_scene = pipeline::build_raster_scene(graph, scene.diagnostics());
98        draw_raster_scene(
99            frame,
100            width,
101            height,
102            &raster_scene,
103            scene.diagnostics(),
104            text_resources,
105        );
106    } else {
107        clear_frame(frame);
108    }
109}
110
111fn clear_frame(frame: &mut [u8]) {
112    for chunk in frame.chunks_exact_mut(4) {
113        chunk.copy_from_slice(&[18, 18, 24, 255]);
114    }
115}
116
117fn draw_raster_scene(
118    frame: &mut [u8],
119    width: u32,
120    height: u32,
121    scene: &RasterScene,
122    diagnostics: &RenderDiagnostics,
123    text_resources: &SoftwareTextResources,
124) {
125    clear_frame(frame);
126    let mut ordered_items =
127        Vec::with_capacity(scene.shapes.len() + scene.images.len() + scene.texts.len());
128    for (index, shape) in scene.shapes.iter().enumerate() {
129        ordered_items.push((shape.z_index, RenderItem::Shape(index)));
130    }
131    for (index, image) in scene.images.iter().enumerate() {
132        ordered_items.push((image.z_index, RenderItem::Image(index)));
133    }
134    for (index, text) in scene.texts.iter().enumerate() {
135        ordered_items.push((text.z_index, RenderItem::Text(index)));
136    }
137    ordered_items.sort_by_key(|(z, _)| *z);
138
139    for (_, item) in ordered_items {
140        match item {
141            RenderItem::Shape(index) => {
142                draw_shape(frame, width, height, &scene.shapes[index], diagnostics);
143            }
144            RenderItem::Image(index) => {
145                draw_image(frame, width, height, &scene.images[index], diagnostics);
146            }
147            RenderItem::Text(index) => {
148                draw_text(
149                    frame,
150                    width,
151                    height,
152                    &scene.texts[index],
153                    diagnostics,
154                    text_resources,
155                );
156            }
157        }
158    }
159}
160
161#[derive(Clone, Copy, Debug, PartialEq, Eq)]
162enum RenderItem {
163    Shape(usize),
164    Image(usize),
165    Text(usize),
166}
167
168fn draw_shape(
169    frame: &mut [u8],
170    width: u32,
171    height: u32,
172    draw: &crate::scene::DrawShape,
173    diagnostics: &RenderDiagnostics,
174) {
175    let snap_delta = draw
176        .snap_anchor
177        .map(snap_delta_for_anchor)
178        .unwrap_or_default();
179    let rect = draw.rect.translate(snap_delta.x, snap_delta.y);
180    let clip = draw
181        .clip
182        .map(|clip| clip.translate(snap_delta.x, snap_delta.y));
183    let rect = if draw.snap_to_pixel_grid {
184        Rect {
185            x: rect.x.round(),
186            y: rect.y.round(),
187            width: if rect.width > 0.0 {
188                rect.width.ceil().max(1.0)
189            } else {
190                rect.width
191            },
192            height: if rect.height > 0.0 {
193                rect.height.ceil().max(1.0)
194            } else {
195                rect.height
196            },
197        }
198    } else {
199        rect
200    };
201    let clip_bounds = match clip_rect_to_bounds(rect, clip, width, height) {
202        Some(bounds) => bounds,
203        None => return,
204    };
205    let Rect {
206        width: rect_width,
207        height: rect_height,
208        ..
209    } = rect;
210    let resolved_shape = draw
211        .shape
212        .map(|shape| shape.resolve(rect_width, rect_height));
213    for py in clip_bounds.min_y..clip_bounds.max_y {
214        if py < 0 || py >= height as i32 {
215            continue;
216        }
217        for px in clip_bounds.min_x..clip_bounds.max_x {
218            if px < 0 || px >= width as i32 {
219                continue;
220            }
221            let center_x = px as f32 + 0.5;
222            let center_y = py as f32 + 0.5;
223            if let Some(ref radii) = resolved_shape {
224                if !point_in_resolved_rounded_rect(center_x, center_y, rect, radii) {
225                    continue;
226                }
227            }
228            let sample = sample_brush_rgba(&draw.brush, rect, center_x, center_y);
229            let alpha = sample[3];
230            if alpha <= 0.0 {
231                continue;
232            }
233            let idx = ((py as u32 * width + px as u32) * 4) as usize;
234            blend_pixel(
235                &mut frame[idx..idx + 4],
236                sample,
237                draw.blend_mode,
238                diagnostics,
239            );
240        }
241    }
242}
243
244fn draw_image(
245    frame: &mut [u8],
246    width: u32,
247    height: u32,
248    draw: &ImageDraw,
249    diagnostics: &RenderDiagnostics,
250) {
251    let snap_delta = draw
252        .snap_anchor
253        .map(snap_delta_for_anchor)
254        .unwrap_or_default();
255    let rect = draw.rect.translate(snap_delta.x, snap_delta.y);
256    let clip = draw
257        .clip
258        .map(|clip| clip.translate(snap_delta.x, snap_delta.y));
259
260    if draw.alpha <= 0.0 || rect.width <= 0.0 || rect.height <= 0.0 {
261        return;
262    }
263
264    let clip_bounds = match clip_rect_to_bounds(rect, clip, width, height) {
265        Some(bounds) => bounds,
266        None => return,
267    };
268
269    let img_width = draw.image.width();
270    let img_height = draw.image.height();
271    if img_width == 0 || img_height == 0 {
272        return;
273    }
274    let src_pixels = draw.image.pixels();
275
276    // Source region: either a sub-rect or the full image
277    let (sr_x, sr_y, sr_w, sr_h) = if let Some(sr) = draw.src_rect {
278        (sr.x, sr.y, sr.width, sr.height)
279    } else {
280        (0.0, 0.0, img_width as f32, img_height as f32)
281    };
282
283    for py in clip_bounds.min_y..clip_bounds.max_y {
284        for px in clip_bounds.min_x..clip_bounds.max_x {
285            let sample_x = px as f32 + 0.5;
286            let sample_y = py as f32 + 0.5;
287            let u = ((sample_x - rect.x) / rect.width).clamp(0.0, 1.0);
288            let v = ((sample_y - rect.y) / rect.height).clamp(0.0, 1.0);
289
290            let mut sample = match draw.sampling {
291                cranpose_ui_graphics::ImageSampling::Nearest => {
292                    let src_x = ((sr_x + u * sr_w).floor() as i32).clamp(0, img_width as i32 - 1);
293                    let src_y = ((sr_y + v * sr_h).floor() as i32).clamp(0, img_height as i32 - 1);
294                    sample_image_nearest(src_pixels, img_width, src_x as u32, src_y as u32)
295                }
296                cranpose_ui_graphics::ImageSampling::Linear => sample_image_linear(
297                    src_pixels,
298                    img_width,
299                    img_height,
300                    sr_x + u * sr_w - 0.5,
301                    sr_y + v * sr_h - 0.5,
302                ),
303            };
304
305            if let Some(filter) = draw.color_filter {
306                sample = apply_color_filter(sample, filter);
307            }
308
309            sample[3] *= draw.alpha.clamp(0.0, 1.0);
310            if sample[3] <= 0.0 {
311                continue;
312            }
313
314            let dst_idx = ((py as u32 * width + px as u32) * 4) as usize;
315            blend_pixel(
316                &mut frame[dst_idx..dst_idx + 4],
317                sample,
318                draw.blend_mode,
319                diagnostics,
320            );
321        }
322    }
323}
324
325fn sample_image_nearest(src_pixels: &[u8], img_width: u32, src_x: u32, src_y: u32) -> [f32; 4] {
326    let src_idx = ((src_y * img_width + src_x) * 4) as usize;
327    [
328        src_pixels[src_idx] as f32 / 255.0,
329        src_pixels[src_idx + 1] as f32 / 255.0,
330        src_pixels[src_idx + 2] as f32 / 255.0,
331        src_pixels[src_idx + 3] as f32 / 255.0,
332    ]
333}
334
335fn sample_image_linear(
336    src_pixels: &[u8],
337    img_width: u32,
338    img_height: u32,
339    x: f32,
340    y: f32,
341) -> [f32; 4] {
342    let x = x.clamp(0.0, img_width.saturating_sub(1) as f32);
343    let y = y.clamp(0.0, img_height.saturating_sub(1) as f32);
344    let x0 = x.floor();
345    let y0 = y.floor();
346    let tx = x - x0;
347    let ty = y - y0;
348    let x0 = (x0 as i32).clamp(0, img_width as i32 - 1) as u32;
349    let y0 = (y0 as i32).clamp(0, img_height as i32 - 1) as u32;
350    let x1 = (x0 + 1).min(img_width - 1);
351    let y1 = (y0 + 1).min(img_height - 1);
352    let top_left = sample_image_nearest(src_pixels, img_width, x0, y0);
353    let top_right = sample_image_nearest(src_pixels, img_width, x1, y0);
354    let bottom_left = sample_image_nearest(src_pixels, img_width, x0, y1);
355    let bottom_right = sample_image_nearest(src_pixels, img_width, x1, y1);
356
357    let mut out = [0.0; 4];
358    for channel in 0..4 {
359        let top = top_left[channel] + (top_right[channel] - top_left[channel]) * tx;
360        let bottom = bottom_left[channel] + (bottom_right[channel] - bottom_left[channel]) * tx;
361        out[channel] = top + (bottom - top) * ty;
362    }
363    out
364}
365
366fn draw_text(
367    frame: &mut [u8],
368    width: u32,
369    height: u32,
370    draw: &TextDraw,
371    diagnostics: &RenderDiagnostics,
372    text_resources: &SoftwareTextResources,
373) {
374    if draw.text.span_styles.is_empty() {
375        draw_text_plain(frame, width, height, draw, diagnostics, text_resources);
376        return;
377    }
378
379    draw_text_with_span_styles(frame, width, height, draw, diagnostics, text_resources);
380}
381
382fn draw_text_with_span_styles(
383    frame: &mut [u8],
384    width: u32,
385    height: u32,
386    draw: &TextDraw,
387    diagnostics: &RenderDiagnostics,
388    text_resources: &SoftwareTextResources,
389) {
390    let boundaries = draw.text.span_boundaries();
391    let mut cursor_x = draw.rect.x;
392    let mut cursor_y = draw.rect.y;
393    let base_line_height = draw
394        .text_style
395        .resolve_line_height(14.0, draw.font_size)
396        .max(1.0);
397    let mut current_line_height = base_line_height;
398
399    for window in boundaries.windows(2) {
400        let start = window[0];
401        let end = window[1];
402        if start == end {
403            continue;
404        }
405
406        let chunk = &draw.text.text[start..end];
407        let mut merged_span = draw.text_style.span_style.clone();
408        for span in &draw.text.span_styles {
409            if span.range.start <= start && span.range.end >= end {
410                merged_span = merged_span.merge(&span.item);
411            }
412        }
413
414        let mut chunk_style = draw.text_style.clone();
415        chunk_style.span_style = merged_span;
416
417        for part in chunk.split_inclusive('\n') {
418            let has_newline = part.ends_with('\n');
419            let content = if has_newline {
420                &part[..part.len().saturating_sub(1)]
421            } else {
422                part
423            };
424
425            if !content.is_empty() {
426                let segment = cranpose_ui::text::AnnotatedString::from(content);
427                let metrics = cranpose_ui::text::measure_text(&segment, &chunk_style);
428                let segment_draw = TextDraw {
429                    node_id: draw.node_id,
430                    rect: Rect {
431                        x: cursor_x,
432                        y: cursor_y,
433                        width: metrics.width.max(1.0),
434                        height: metrics.height.max(1.0),
435                    },
436                    snap_anchor: draw.snap_anchor,
437                    text: Rc::new(segment),
438                    color: chunk_style.resolve_text_color(draw.color),
439                    text_style: chunk_style.clone(),
440                    font_size: chunk_style.resolve_font_size(draw.font_size),
441                    scale: draw.scale,
442                    layout_options: draw.layout_options,
443                    z_index: draw.z_index,
444                    clip: draw.clip,
445                };
446                draw_text_plain(
447                    frame,
448                    width,
449                    height,
450                    &segment_draw,
451                    diagnostics,
452                    text_resources,
453                );
454                cursor_x += metrics.width;
455                current_line_height = current_line_height.max(metrics.line_height.max(1.0));
456            }
457
458            if has_newline {
459                cursor_x = draw.rect.x;
460                cursor_y += current_line_height;
461                current_line_height = base_line_height;
462            }
463        }
464    }
465}
466
467fn draw_text_plain(
468    frame: &mut [u8],
469    width: u32,
470    height: u32,
471    draw: &TextDraw,
472    diagnostics: &RenderDiagnostics,
473    text_resources: &SoftwareTextResources,
474) {
475    let text_scale = draw.scale.max(0.0);
476    if text_scale == 0.0 {
477        return;
478    }
479
480    let static_text_motion = draw
481        .text_style
482        .paragraph_style
483        .text_motion
484        .unwrap_or(TextMotion::Static)
485        == TextMotion::Static;
486    let snap_delta = if static_text_motion {
487        draw.snap_anchor
488            .map(snap_delta_for_anchor)
489            .unwrap_or_default()
490    } else {
491        Point::default()
492    };
493    let rect = draw.rect.translate(snap_delta.x, snap_delta.y);
494    let clip = draw
495        .clip
496        .map(|clip| clip.translate(snap_delta.x, snap_delta.y));
497
498    let raster_rect = if static_text_motion {
499        Rect {
500            x: rect.x.round(),
501            y: rect.y.round(),
502            width: if rect.width > 0.0 {
503                rect.width.ceil().max(1.0)
504            } else {
505                rect.width
506            },
507            height: if rect.height > 0.0 {
508                rect.height.ceil().max(1.0)
509            } else {
510                rect.height
511            },
512        }
513    } else {
514        rect
515    };
516
517    let Some(font) = text_resources.fonts().resolve(&draw.text_style) else {
518        return;
519    };
520
521    let Some(image) = rasterize_text_to_image(
522        draw.text.text.as_str(),
523        raster_rect,
524        &draw.text_style,
525        draw.color,
526        draw.font_size,
527        text_scale,
528        font,
529    ) else {
530        return;
531    };
532
533    let blit_origin = if static_text_motion {
534        Point::new(raster_rect.x, raster_rect.y)
535    } else {
536        Point::new(rect.x, rect.y)
537    };
538    let blit_rect = Rect {
539        x: blit_origin.x,
540        y: blit_origin.y,
541        width: image.width() as f32,
542        height: image.height() as f32,
543    };
544
545    blit_rasterized_text_image(frame, width, height, blit_rect, clip, &image, diagnostics);
546}
547
548fn blit_rasterized_text_image(
549    frame: &mut [u8],
550    width: u32,
551    height: u32,
552    rect: Rect,
553    clip: Option<Rect>,
554    image: &cranpose_ui_graphics::ImageBitmap,
555    diagnostics: &RenderDiagnostics,
556) {
557    if rect.width <= 0.0 || rect.height <= 0.0 {
558        return;
559    }
560    let clip_bounds = match clip_rect_to_bounds(rect, clip, width, height) {
561        Some(bounds) => bounds,
562        None => return,
563    };
564
565    let img_width = image.width();
566    let img_height = image.height();
567    if img_width == 0 || img_height == 0 {
568        return;
569    }
570    let src_pixels = image.pixels();
571
572    for py in clip_bounds.min_y..clip_bounds.max_y {
573        for px in clip_bounds.min_x..clip_bounds.max_x {
574            let sample_x = px as f32 + 0.5;
575            let sample_y = py as f32 + 0.5;
576            let u = ((sample_x - rect.x) / rect.width).clamp(0.0, 1.0);
577            let v = ((sample_y - rect.y) / rect.height).clamp(0.0, 1.0);
578
579            let src = sample_image_linear(
580                src_pixels,
581                img_width,
582                img_height,
583                u * img_width.saturating_sub(1) as f32,
584                v * img_height.saturating_sub(1) as f32,
585            );
586            if src[3] <= 0.0 {
587                continue;
588            }
589
590            let dst_idx = ((py as u32 * width + px as u32) * 4) as usize;
591            blend_pixel(
592                &mut frame[dst_idx..dst_idx + 4],
593                src,
594                BlendMode::SrcOver,
595                diagnostics,
596            );
597        }
598    }
599}
600
601fn blend_pixel(
602    dst: &mut [u8],
603    src: [f32; 4],
604    blend_mode: BlendMode,
605    diagnostics: &RenderDiagnostics,
606) {
607    let resolved_blend_mode = if is_blend_mode_supported(blend_mode) {
608        blend_mode
609    } else {
610        if diagnostics.claim_warning_once("pixels.unsupported-blend-mode") {
611            log::warn!(
612                "Pixels renderer currently supports BlendMode::SrcOver and BlendMode::DstOut; falling back to SrcOver for unsupported modes"
613            );
614        }
615        BlendMode::SrcOver
616    };
617
618    let src_alpha = src[3].clamp(0.0, 1.0);
619    if src_alpha <= 0.0 {
620        return;
621    }
622    let dst_r = dst[0] as f32 / 255.0;
623    let dst_g = dst[1] as f32 / 255.0;
624    let dst_b = dst[2] as f32 / 255.0;
625    let dst_a = dst[3] as f32 / 255.0;
626
627    let (out_r, out_g, out_b, out_a) = match resolved_blend_mode {
628        BlendMode::DstOut => {
629            let keep = 1.0 - src_alpha;
630            (dst_r * keep, dst_g * keep, dst_b * keep, dst_a * keep)
631        }
632        BlendMode::SrcOver => (
633            src[0].clamp(0.0, 1.0) * src_alpha + dst_r * (1.0 - src_alpha),
634            src[1].clamp(0.0, 1.0) * src_alpha + dst_g * (1.0 - src_alpha),
635            src[2].clamp(0.0, 1.0) * src_alpha + dst_b * (1.0 - src_alpha),
636            src_alpha + dst_a * (1.0 - src_alpha),
637        ),
638        _ => (
639            src[0].clamp(0.0, 1.0) * src_alpha + dst_r * (1.0 - src_alpha),
640            src[1].clamp(0.0, 1.0) * src_alpha + dst_g * (1.0 - src_alpha),
641            src[2].clamp(0.0, 1.0) * src_alpha + dst_b * (1.0 - src_alpha),
642            src_alpha + dst_a * (1.0 - src_alpha),
643        ),
644    };
645
646    dst[0] = (out_r.clamp(0.0, 1.0) * 255.0).round() as u8;
647    dst[1] = (out_g.clamp(0.0, 1.0) * 255.0).round() as u8;
648    dst[2] = (out_b.clamp(0.0, 1.0) * 255.0).round() as u8;
649    dst[3] = (out_a.clamp(0.0, 1.0) * 255.0).round() as u8;
650}
651
652fn apply_color_filter(sample: [f32; 4], filter: ColorFilter) -> [f32; 4] {
653    filter.apply_rgba(sample)
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use cranpose_render_common::brush_sampling::normalize_gradient_t;
660    use cranpose_render_common::graph::{
661        CachePolicy, DrawPrimitiveNode, IsolationReasons, LayerNode, PrimitiveEntry, PrimitiveNode,
662        PrimitivePhase, ProjectiveTransform, RenderGraph, RenderNode,
663    };
664    use cranpose_render_common::raster_cache::LayerRasterCacheHashes;
665    use cranpose_ui::Brush;
666    use cranpose_ui_graphics::{Color, TileMode};
667
668    fn draw_raster_scene_for_test(frame: &mut [u8], width: u32, height: u32, scene: &RasterScene) {
669        let diagnostics = RenderDiagnostics::new();
670        let text_resources = SoftwareTextResources::default();
671        draw_raster_scene(frame, width, height, scene, &diagnostics, &text_resources);
672    }
673
674    #[test]
675    fn fallback_text_metrics_cover_empty_and_multiline_text() {
676        let empty = fallback_text_metrics("", 10.0);
677        assert_eq!(empty.line_count, 1);
678        assert_eq!(empty.width, 0.0);
679        assert_eq!(empty.height, fallback_line_height(10.0));
680
681        let multiline = fallback_text_metrics("ab\ncde", 10.0);
682        assert_eq!(multiline.line_count, 2);
683        assert_eq!(multiline.width, 3.0 * fallback_char_width(10.0));
684        assert_eq!(multiline.height, 2.0 * fallback_line_height(10.0));
685    }
686
687    #[test]
688    fn fallback_cursor_position_handles_non_boundary_byte_offsets() {
689        let text = "éx";
690        let width = fallback_char_width(12.0);
691        assert_eq!(fallback_cursor_x_for_byte_offset(text, 0, 12.0), 0.0);
692        assert_eq!(fallback_cursor_x_for_byte_offset(text, 1, 12.0), width);
693        assert_eq!(
694            fallback_cursor_x_for_byte_offset(text, text.len(), 12.0),
695            width * 2.0
696        );
697    }
698
699    fn count_non_background_pixels(frame: &[u8], width: u32, height: u32) -> usize {
700        count_non_background_pixels_in_band(frame, width, 0, height)
701    }
702
703    fn render_single_text_frame(
704        style: cranpose_ui::TextStyle,
705        color: Color,
706        x: f32,
707    ) -> (u32, u32, Vec<u8>) {
708        let mut raster_scene = RasterScene::new();
709        raster_scene.push_text(
710            11,
711            Rect {
712                x,
713                y: 16.0,
714                width: 320.0,
715                height: 90.0,
716            },
717            Rc::new(cranpose_ui::text::AnnotatedString::from("MMMMMMMM")),
718            color,
719            style,
720            64.0,
721            1.0,
722            cranpose_ui::TextLayoutOptions::default(),
723            None,
724        );
725
726        let width = 360;
727        let height = 140;
728        let mut frame = vec![0u8; (width * height * 4) as usize];
729        draw_raster_scene_for_test(&mut frame, width, height, &raster_scene);
730        (width, height, frame)
731    }
732
733    fn average_ink_rgb(
734        frame: &[u8],
735        width: u32,
736        x_min: u32,
737        x_max: u32,
738        y_min: u32,
739        y_max: u32,
740    ) -> Option<[f32; 3]> {
741        let mut sum_r = 0.0f32;
742        let mut sum_g = 0.0f32;
743        let mut sum_b = 0.0f32;
744        let mut count = 0usize;
745
746        for y in y_min..y_max {
747            for x in x_min..x_max {
748                let idx = ((y * width + x) * 4) as usize;
749                let px = &frame[idx..idx + 4];
750                if px == [18, 18, 24, 255] {
751                    continue;
752                }
753                sum_r += px[0] as f32 / 255.0;
754                sum_g += px[1] as f32 / 255.0;
755                sum_b += px[2] as f32 / 255.0;
756                count += 1;
757            }
758        }
759
760        if count == 0 {
761            return None;
762        }
763        Some([
764            sum_r / count as f32,
765            sum_g / count as f32,
766            sum_b / count as f32,
767        ])
768    }
769
770    fn count_non_background_pixels_in_band(
771        frame: &[u8],
772        width: u32,
773        y_min_inclusive: u32,
774        y_max_exclusive: u32,
775    ) -> usize {
776        let mut count = 0usize;
777        for y in y_min_inclusive..y_max_exclusive {
778            for x in 0..width {
779                let idx = ((y * width + x) * 4) as usize;
780                let px = &frame[idx..idx + 4];
781                if px != [18, 18, 24, 255] {
782                    count += 1;
783                }
784            }
785        }
786        count
787    }
788
789    /// Returns `(top_y, bottom_y)` (exclusive) of all non-background ink rows.
790    fn ink_y_range(frame: &[u8], width: u32, height: u32) -> Option<(u32, u32)> {
791        let mut top = None;
792        let mut bottom = 0u32;
793        for y in 0..height {
794            for x in 0..width {
795                let idx = ((y * width + x) * 4) as usize;
796                if frame[idx..idx + 4] != [18, 18, 24, 255] {
797                    top.get_or_insert(y);
798                    bottom = y + 1;
799                    break;
800                }
801            }
802        }
803        top.map(|t| (t, bottom))
804    }
805
806    #[test]
807    fn blend_mode_support_matrix_is_explicit() {
808        assert!(is_blend_mode_supported(BlendMode::SrcOver));
809        assert!(is_blend_mode_supported(BlendMode::DstOut));
810        assert!(!is_blend_mode_supported(BlendMode::Clear));
811        assert!(!is_blend_mode_supported(BlendMode::Multiply));
812    }
813
814    #[test]
815    fn unsupported_blend_mode_falls_back_without_abort() {
816        let diagnostics = RenderDiagnostics::new();
817        let src = [1.0, 0.0, 0.0, 0.5];
818        let mut unsupported = [0, 0, 255, 255];
819        let mut src_over = unsupported;
820
821        blend_pixel(&mut unsupported, src, BlendMode::Multiply, &diagnostics);
822        blend_pixel(&mut src_over, src, BlendMode::SrcOver, &diagnostics);
823
824        assert_eq!(unsupported, src_over);
825    }
826
827    #[test]
828    fn mirror_tile_mode_reflects_second_interval() {
829        assert_eq!(normalize_gradient_t(1.25, TileMode::Mirror), Some(0.75));
830        assert_eq!(normalize_gradient_t(1.75, TileMode::Mirror), Some(0.25));
831    }
832
833    #[test]
834    fn multiline_text_renders_second_line_pixels() {
835        let mut raster_scene = RasterScene::new();
836        raster_scene.push_text(
837            1,
838            Rect {
839                x: 8.0,
840                y: 8.0,
841                width: 180.0,
842                height: 80.0,
843            },
844            Rc::new(cranpose_ui::text::AnnotatedString::from(
845                "Dynamic\nModifiers",
846            )),
847            Color::WHITE,
848            cranpose_ui::TextStyle::default(),
849            14.0,
850            1.0,
851            cranpose_ui::TextLayoutOptions::default(),
852            None,
853        );
854
855        let width = 220;
856        let height = 100;
857        let mut frame = vec![0u8; (width * height * 4) as usize];
858        draw_raster_scene_for_test(&mut frame, width, height, &raster_scene);
859
860        // Find the y-range of all ink pixels (font-agnostic approach).
861        let (ink_top, ink_bottom) =
862            ink_y_range(&frame, width, height).expect("expected ink pixels in rendered text");
863        let ink_height = ink_bottom - ink_top;
864        assert!(
865            ink_height >= 20,
866            "expected two lines of ink, ink spans only {ink_height}px (y={ink_top}..{ink_bottom})"
867        );
868        let mid_y = ink_top + ink_height / 2;
869        let first_line_ink = count_non_background_pixels_in_band(&frame, width, ink_top, mid_y);
870        let second_line_ink = count_non_background_pixels_in_band(&frame, width, mid_y, ink_bottom);
871        assert!(
872            first_line_ink > 20,
873            "expected first line to render, got {first_line_ink}"
874        );
875        assert!(
876            second_line_ink > 20,
877            "expected second line ink, got {second_line_ink}"
878        );
879    }
880
881    #[test]
882    fn draw_scene_renders_graph_backed_scene_without_flat_primitives() {
883        let mut scene = Scene::new();
884        scene.graph = Some(RenderGraph::new(LayerNode {
885            node_id: None,
886            local_bounds: Rect {
887                x: 0.0,
888                y: 0.0,
889                width: 16.0,
890                height: 16.0,
891            },
892            transform_to_parent: ProjectiveTransform::identity(),
893            motion_context_animated: false,
894            translated_content_context: false,
895            translated_content_offset: cranpose_ui_graphics::Point::default(),
896            content_offset: cranpose_ui_graphics::Point::default(),
897            graphics_layer: cranpose_ui_graphics::GraphicsLayer::default(),
898            clip_to_bounds: false,
899            shadow_clip: None,
900            hit_test: None,
901            has_hit_targets: false,
902            isolation: IsolationReasons::default(),
903            cache_policy: CachePolicy::None,
904            cache_hashes: LayerRasterCacheHashes::default(),
905            cache_hashes_valid: false,
906            children: vec![RenderNode::Primitive(PrimitiveEntry {
907                phase: PrimitivePhase::BeforeChildren,
908                node: PrimitiveNode::Draw(DrawPrimitiveNode {
909                    primitive: cranpose_ui_graphics::DrawPrimitive::Rect {
910                        rect: Rect {
911                            x: 2.0,
912                            y: 3.0,
913                            width: 6.0,
914                            height: 5.0,
915                        },
916                        brush: Brush::solid(Color::WHITE),
917                    },
918                    clip: None,
919                }),
920            })],
921        }));
922
923        let width = 20;
924        let height = 20;
925        let mut frame = vec![0u8; (width * height * 4) as usize];
926        draw_scene(&mut frame, width, height, &scene);
927
928        assert!(
929            count_non_background_pixels(&frame, width, height) > 0,
930            "graph-backed scenes should render even when flat primitive arrays are empty"
931        );
932    }
933
934    #[test]
935    fn text_clip_bounds_prevent_drawing_outside_scroll_window() {
936        let mut raster_scene = RasterScene::new();
937        raster_scene.push_text(
938            2,
939            Rect {
940                x: 8.0,
941                y: 40.0,
942                width: 180.0,
943                height: 24.0,
944            },
945            Rc::new(cranpose_ui::text::AnnotatedString::from("Clipped Text")),
946            Color::WHITE,
947            cranpose_ui::TextStyle::default(),
948            14.0,
949            1.0,
950            cranpose_ui::TextLayoutOptions::default(),
951            Some(Rect {
952                x: 0.0,
953                y: 0.0,
954                width: 220.0,
955                height: 20.0,
956            }),
957        );
958
959        let width = 220;
960        let height = 100;
961        let mut frame = vec![0u8; (width * height * 4) as usize];
962        draw_raster_scene_for_test(&mut frame, width, height, &raster_scene);
963
964        let total_ink = count_non_background_pixels_in_band(&frame, width, 0, height);
965        assert_eq!(
966            total_ink, 0,
967            "text should be fully clipped but rendered {total_ink} ink pixels"
968        );
969    }
970
971    #[test]
972    fn gradient_brush_contract_requires_visible_color_transition() {
973        let style = cranpose_ui::TextStyle {
974            span_style: cranpose_ui::SpanStyle {
975                brush: Some(Brush::linear_gradient_range(
976                    vec![Color(1.0, 0.0, 0.0, 1.0), Color(0.0, 0.0, 1.0, 1.0)],
977                    cranpose_ui_graphics::Point::new(0.0, 0.0),
978                    cranpose_ui_graphics::Point::new(320.0, 0.0),
979                )),
980                ..Default::default()
981            },
982            ..Default::default()
983        };
984
985        let (width, _height, frame) = render_single_text_frame(style, Color::WHITE, 12.0);
986        let left = average_ink_rgb(&frame, width, 20, 150, 20, 120).expect("left ink");
987        let right = average_ink_rgb(&frame, width, 200, 340, 20, 120).expect("right ink");
988
989        assert!(
990            left[0] > left[2] * 1.15,
991            "left side should be red-dominant for horizontal gradient, got {left:?}"
992        );
993        assert!(
994            right[2] > right[0] * 1.15,
995            "right side should be blue-dominant for horizontal gradient, got {right:?}"
996        );
997    }
998
999    #[test]
1000    fn draw_style_stroke_contract_changes_raster_output() {
1001        let fill_style = cranpose_ui::TextStyle::default();
1002        let stroke_style = cranpose_ui::TextStyle {
1003            span_style: cranpose_ui::SpanStyle {
1004                draw_style: Some(cranpose_ui::text::TextDrawStyle::Stroke { width: 6.0 }),
1005                ..Default::default()
1006            },
1007            ..Default::default()
1008        };
1009
1010        let (width, height, fill_frame) = render_single_text_frame(fill_style, Color::WHITE, 12.0);
1011        let (_, _, stroke_frame) = render_single_text_frame(stroke_style, Color::WHITE, 12.0);
1012        let fill_ink = count_non_background_pixels(&fill_frame, width, height);
1013        let stroke_ink = count_non_background_pixels(&stroke_frame, width, height);
1014
1015        assert_ne!(
1016            fill_frame, stroke_frame,
1017            "Fill and Stroke text must not rasterize identically"
1018        );
1019        assert!(
1020            fill_ink.abs_diff(stroke_ink) > 250,
1021            "Fill/Stroke ink coverage should differ; fill={fill_ink}, stroke={stroke_ink}"
1022        );
1023    }
1024
1025    #[test]
1026    fn shadow_blur_radius_contract_changes_raster_output() {
1027        let base_shadow = cranpose_ui::text::Shadow {
1028            color: Color(0.0, 0.0, 0.0, 0.85),
1029            offset: cranpose_ui_graphics::Point::new(6.0, 4.0),
1030            blur_radius: 0.0,
1031        };
1032        let zero_blur_style = cranpose_ui::TextStyle {
1033            span_style: cranpose_ui::SpanStyle {
1034                shadow: Some(base_shadow),
1035                ..Default::default()
1036            },
1037            ..Default::default()
1038        };
1039        let blurred_style = cranpose_ui::TextStyle {
1040            span_style: cranpose_ui::SpanStyle {
1041                shadow: Some(cranpose_ui::text::Shadow {
1042                    blur_radius: 10.0,
1043                    ..base_shadow
1044                }),
1045                ..Default::default()
1046            },
1047            ..Default::default()
1048        };
1049
1050        let (_, _, zero_frame) = render_single_text_frame(zero_blur_style, Color::WHITE, 12.0);
1051        let (_, _, blur_frame) = render_single_text_frame(blurred_style, Color::WHITE, 12.0);
1052
1053        assert_ne!(
1054            zero_frame, blur_frame,
1055            "Changing shadow blur radius must change rendered output"
1056        );
1057    }
1058
1059    #[test]
1060    fn text_motion_contract_changes_raster_output() {
1061        let static_style = cranpose_ui::TextStyle {
1062            paragraph_style: cranpose_ui::ParagraphStyle {
1063                text_motion: Some(cranpose_ui::text::TextMotion::Static),
1064                ..Default::default()
1065            },
1066            ..Default::default()
1067        };
1068        let animated_style = cranpose_ui::TextStyle {
1069            paragraph_style: cranpose_ui::ParagraphStyle {
1070                text_motion: Some(cranpose_ui::text::TextMotion::Animated),
1071                ..Default::default()
1072            },
1073            ..Default::default()
1074        };
1075
1076        let (_, _, static_frame) = render_single_text_frame(static_style, Color::WHITE, 12.35);
1077        let (_, _, animated_frame) = render_single_text_frame(animated_style, Color::WHITE, 12.35);
1078
1079        assert_ne!(
1080            static_frame, animated_frame,
1081            "TextMotion::Static and TextMotion::Animated should not rasterize identically"
1082        );
1083    }
1084}