Skip to main content

embedded_gui/
render.rs

1use core::marker::PhantomData;
2
3use embedded_graphics_core::{
4    Pixel,
5    draw_target::DrawTarget,
6    geometry::Point,
7    pixelcolor::{Rgb565, RgbColor},
8};
9
10#[cfg(not(feature = "std"))]
11use crate::math::F32Ext as _;
12use crate::{
13    font::{FontId, glyph_rows},
14    geometry::Rect,
15    image::{ImageFit, ImageRef, TileMode, TileRef},
16    style::{AlphaLinearGradient, AlphaRadialGradient, Border, GradientDirection, LinearGradient},
17    text,
18};
19
20pub const CHAR_WIDTH: u32 = 4;
21pub const CHAR_HEIGHT: u32 = 6;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum TextAlign {
25    Left,
26    Center,
27    Right,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub enum VerticalAlign {
32    Top,
33    Middle,
34    Bottom,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum TextWrap {
39    None,
40    Character,
41    Word,
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum TextOverflow {
46    Clip,
47    Ellipsis,
48}
49
50#[derive(Clone, Copy, Debug, PartialEq, Eq)]
51pub enum EllipsisMode {
52    ThreeDots,
53    SingleGlyph,
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum TextOverflowPolicy {
58    Global(TextOverflow),
59    WrapThenEllipsis { max_lines: u8 },
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct TextStyle {
64    pub color: Rgb565,
65    pub font: FontId,
66    pub opacity: u8,
67    pub align: TextAlign,
68    pub vertical_align: VerticalAlign,
69    pub wrap: TextWrap,
70    pub overflow: TextOverflow,
71    pub overflow_policy: TextOverflowPolicy,
72    pub kerning: bool,
73    pub max_lines: Option<u8>,
74    pub ellipsis: EllipsisMode,
75    pub line_spacing: u8,
76}
77
78impl TextStyle {
79    pub const fn new(color: Rgb565) -> Self {
80        Self {
81            color,
82            font: FontId::Tiny3x5,
83            opacity: 255,
84            align: TextAlign::Left,
85            vertical_align: VerticalAlign::Top,
86            wrap: TextWrap::None,
87            overflow: TextOverflow::Clip,
88            overflow_policy: TextOverflowPolicy::Global(TextOverflow::Clip),
89            kerning: false,
90            max_lines: None,
91            ellipsis: EllipsisMode::ThreeDots,
92            line_spacing: 1,
93        }
94    }
95
96    pub const fn centered(mut self) -> Self {
97        self.align = TextAlign::Center;
98        self.vertical_align = VerticalAlign::Middle;
99        self
100    }
101
102    pub const fn with_align(mut self, align: TextAlign) -> Self {
103        self.align = align;
104        self
105    }
106
107    pub const fn with_vertical_align(mut self, align: VerticalAlign) -> Self {
108        self.vertical_align = align;
109        self
110    }
111
112    pub const fn with_wrap(mut self, wrap: TextWrap) -> Self {
113        self.wrap = wrap;
114        self
115    }
116
117    pub const fn with_line_spacing(mut self, spacing: u8) -> Self {
118        self.line_spacing = spacing;
119        self
120    }
121
122    pub const fn with_overflow(mut self, overflow: TextOverflow) -> Self {
123        self.overflow = overflow;
124        self.overflow_policy = TextOverflowPolicy::Global(overflow);
125        self
126    }
127
128    pub const fn with_kerning(mut self, kerning: bool) -> Self {
129        self.kerning = kerning;
130        self
131    }
132
133    pub const fn with_max_lines(mut self, max_lines: Option<u8>) -> Self {
134        self.max_lines = max_lines;
135        self
136    }
137
138    pub const fn with_ellipsis_mode(mut self, ellipsis: EllipsisMode) -> Self {
139        self.ellipsis = ellipsis;
140        self
141    }
142
143    pub const fn with_overflow_policy(mut self, policy: TextOverflowPolicy) -> Self {
144        self.overflow_policy = policy;
145        self
146    }
147
148    pub const fn with_opacity(mut self, opacity: u8) -> Self {
149        self.opacity = opacity;
150        self
151    }
152
153    pub const fn with_font(mut self, font: FontId) -> Self {
154        self.font = font;
155        self
156    }
157}
158
159#[derive(Clone, Copy, Debug, PartialEq, Eq)]
160pub struct TextMetrics {
161    pub width: u32,
162    pub height: u32,
163}
164
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub enum RenderQuality {
167    Low,
168    Medium,
169    High,
170}
171
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub enum AntiAliasMode {
174    None,
175    Coverage,
176    Subpixel,
177}
178
179#[derive(Clone, Copy, Debug, PartialEq, Eq)]
180pub struct StrokeStyle {
181    pub color: Rgb565,
182    pub width: u8,
183    pub antialias: bool,
184    pub antialias_mode: AntiAliasMode,
185    pub cap: StrokeCap,
186    pub join: StrokeJoin,
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum StrokeCap {
191    Butt,
192    Round,
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum StrokeJoin {
197    Miter,
198    Round,
199}
200
201#[derive(Clone, Copy, Debug, PartialEq)]
202pub struct Transform2D {
203    pub m11: f32,
204    pub m12: f32,
205    pub m21: f32,
206    pub m22: f32,
207    pub tx: f32,
208    pub ty: f32,
209}
210
211impl Transform2D {
212    pub const IDENTITY: Self = Self {
213        m11: 1.0,
214        m12: 0.0,
215        m21: 0.0,
216        m22: 1.0,
217        tx: 0.0,
218        ty: 0.0,
219    };
220
221    pub const fn translation(x: f32, y: f32) -> Self {
222        Self {
223            tx: x,
224            ty: y,
225            ..Self::IDENTITY
226        }
227    }
228
229    pub const fn scale(x: f32, y: f32) -> Self {
230        Self {
231            m11: x,
232            m22: y,
233            ..Self::IDENTITY
234        }
235    }
236
237    pub fn rotation(deg: f32) -> Self {
238        let r = deg.to_radians();
239        Self {
240            m11: r.cos(),
241            m12: -r.sin(),
242            m21: r.sin(),
243            m22: r.cos(),
244            ..Self::IDENTITY
245        }
246    }
247
248    pub fn skew(x_deg: f32, y_deg: f32) -> Self {
249        Self {
250            m12: x_deg.to_radians().tan(),
251            m21: y_deg.to_radians().tan(),
252            ..Self::IDENTITY
253        }
254    }
255
256    pub fn then(self, rhs: Self) -> Self {
257        Self {
258            m11: self.m11 * rhs.m11 + self.m12 * rhs.m21,
259            m12: self.m11 * rhs.m12 + self.m12 * rhs.m22,
260            m21: self.m21 * rhs.m11 + self.m22 * rhs.m21,
261            m22: self.m21 * rhs.m12 + self.m22 * rhs.m22,
262            tx: self.m11 * rhs.tx + self.m12 * rhs.ty + self.tx,
263            ty: self.m21 * rhs.tx + self.m22 * rhs.ty + self.ty,
264        }
265    }
266
267    #[inline(always)]
268    pub fn is_identity(self) -> bool {
269        self.m11 == 1.0
270            && self.m12 == 0.0
271            && self.m21 == 0.0
272            && self.m22 == 1.0
273            && self.tx == 0.0
274            && self.ty == 0.0
275    }
276
277    #[inline(always)]
278    pub fn apply(self, x: i32, y: i32) -> (i32, i32) {
279        if self.is_identity() {
280            (x, y)
281        } else {
282            let xf = x as f32;
283            let yf = y as f32;
284            (
285                (self.m11 * xf + self.m12 * yf + self.tx).round() as i32,
286                (self.m21 * xf + self.m22 * yf + self.ty).round() as i32,
287            )
288        }
289    }
290
291    #[inline(always)]
292    pub fn apply_f32(self, x: f32, y: f32) -> (f32, f32) {
293        if self.is_identity() {
294            (x, y)
295        } else {
296            (
297                self.m11 * x + self.m12 * y + self.tx,
298                self.m21 * x + self.m22 * y + self.ty,
299            )
300        }
301    }
302
303    pub fn inverse(self) -> Option<Self> {
304        let det = self.m11 * self.m22 - self.m12 * self.m21;
305        if det.abs() < 1e-7 {
306            return None;
307        }
308        let inv_det = 1.0 / det;
309        let m11 = self.m22 * inv_det;
310        let m12 = -self.m12 * inv_det;
311        let m21 = -self.m21 * inv_det;
312        let m22 = self.m11 * inv_det;
313        let tx = (self.m12 * self.ty - self.m22 * self.tx) * inv_det;
314        let ty = (self.m21 * self.tx - self.m11 * self.ty) * inv_det;
315        Some(Self {
316            m11,
317            m12,
318            m21,
319            m22,
320            tx,
321            ty,
322        })
323    }
324}
325
326#[derive(Clone, Copy, Debug, PartialEq, Eq)]
327pub enum BlendMode {
328    Normal,
329    Add,
330    Multiply,
331    Screen,
332}
333
334/// Capability trait for draw targets that can read back a pixel they've
335/// already written. Optional: the default opacity/blend APIs on
336/// [`RenderCtx`] only require [`DrawTarget`] and approximate translucency
337/// with ordered dithering, so they keep working on write-only displays.
338/// Implementing `PixelRead` additionally unlocks the `*_true_alpha` methods,
339/// which composite against the destination's actual current contents
340/// instead of dithering.
341pub trait PixelRead: DrawTarget {
342    fn get_pixel(&self, point: Point) -> Self::Color;
343}
344
345/// Capability trait for hardware display controllers (e.g. ST7789, ILI9341, SSD1306)
346/// supporting direct column/row address window setting (`set_address_window`).
347/// Allows rendering dirty regions by transmitting SPI/DMA transfers exclusively to
348/// the target sub-window instead of the full screen.
349pub trait WindowedDrawTarget: DrawTarget {
350    fn set_window(
351        &mut self,
352        area: &embedded_graphics_core::primitives::Rectangle,
353    ) -> Result<(), Self::Error>;
354}
355
356/// Pixel-plotting policy for a [`RenderCtx`]. Selected by the ctx's `C` type
357/// parameter so the *same* drawing calls composite differently depending on
358/// the target's capabilities — with no runtime branch and no specialization.
359///
360/// - [`Dither`] (the default) approximates translucency with ordered dithering
361///   and works on any write-only [`DrawTarget`].
362/// - [`Blend`] performs true per-pixel alpha compositing and requires a
363///   readback-capable target ([`PixelRead`]), e.g. a
364///   [`Framebuffer`](crate::Framebuffer).
365///
366/// `plot` receives screen-space coords already transformed and clipped, the
367/// layer-combined `opacity`, and the active layer blend mode + backdrop.
368pub trait Compositor<D: DrawTarget<Color = Rgb565>> {
369    fn plot(
370        target: &mut D,
371        x: i32,
372        y: i32,
373        color: Rgb565,
374        opacity: u8,
375        blend: BlendMode,
376        backdrop: Rgb565,
377    ) -> Result<(), D::Error>;
378}
379
380/// Ordered-dither compositor (default). No readback required.
381#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
382pub struct Dither;
383
384/// True alpha-blending compositor. Requires a [`PixelRead`] target.
385#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
386pub struct Blend;
387
388impl<D: DrawTarget<Color = Rgb565>> Compositor<D> for Dither {
389    fn plot(
390        target: &mut D,
391        x: i32,
392        y: i32,
393        color: Rgb565,
394        opacity: u8,
395        blend: BlendMode,
396        backdrop: Rgb565,
397    ) -> Result<(), D::Error> {
398        if !should_draw_at_opacity(x, y, opacity) {
399            return Ok(());
400        }
401        let color = apply_blend_mode(color, blend, backdrop);
402        target.draw_iter([Pixel(Point::new(x, y), color)])
403    }
404}
405
406impl<D: DrawTarget<Color = Rgb565> + PixelRead> Compositor<D> for Blend {
407    fn plot(
408        target: &mut D,
409        x: i32,
410        y: i32,
411        color: Rgb565,
412        opacity: u8,
413        blend: BlendMode,
414        backdrop: Rgb565,
415    ) -> Result<(), D::Error> {
416        if opacity == 0 {
417            return Ok(());
418        }
419        let bg = target.get_pixel(Point::new(x, y));
420        let blended = lerp_rgb565(bg, color, opacity);
421        let blended = apply_blend_mode(blended, blend, backdrop);
422        target.draw_iter([Pixel(Point::new(x, y), blended)])
423    }
424}
425
426#[derive(Clone, Copy, Debug, PartialEq, Eq)]
427pub enum ColorFormat {
428    Rgb565,
429    Rgb888,
430    Argb8888,
431}
432
433#[derive(Clone, Copy, Debug, PartialEq, Eq)]
434pub struct RenderBackendCaps {
435    pub color_format: ColorFormat,
436    pub supports_layers: bool,
437    pub supports_subpixel: bool,
438}
439
440impl RenderBackendCaps {
441    pub const fn software_rgb565() -> Self {
442        Self {
443            color_format: ColorFormat::Rgb565,
444            supports_layers: true,
445            supports_subpixel: false,
446        }
447    }
448}
449
450#[derive(Clone, Copy, Debug, PartialEq, Eq)]
451pub struct LayerState {
452    pub opacity: u8,
453    pub blend: BlendMode,
454    pub backdrop: Rgb565,
455}
456
457impl LayerState {
458    pub const fn normal() -> Self {
459        Self {
460            opacity: 255,
461            blend: BlendMode::Normal,
462            backdrop: Rgb565::BLACK,
463        }
464    }
465}
466
467impl StrokeStyle {
468    pub const fn new(color: Rgb565) -> Self {
469        Self {
470            color,
471            width: 1,
472            antialias: false,
473            antialias_mode: AntiAliasMode::None,
474            cap: StrokeCap::Butt,
475            join: StrokeJoin::Miter,
476        }
477    }
478
479    pub const fn with_width(mut self, width: u8) -> Self {
480        self.width = if width == 0 { 1 } else { width };
481        self
482    }
483
484    pub const fn with_antialias(mut self, antialias: bool) -> Self {
485        self.antialias = antialias;
486        if antialias {
487            if let AntiAliasMode::None = self.antialias_mode {
488                self.antialias_mode = AntiAliasMode::Coverage;
489            }
490        }
491        if !antialias {
492            self.antialias_mode = AntiAliasMode::None;
493        }
494        self
495    }
496
497    pub const fn with_antialias_mode(mut self, mode: AntiAliasMode) -> Self {
498        self.antialias_mode = mode;
499        self.antialias = !matches!(mode, AntiAliasMode::None);
500        self
501    }
502
503    pub const fn with_cap(mut self, cap: StrokeCap) -> Self {
504        self.cap = cap;
505        self
506    }
507
508    pub const fn with_join(mut self, join: StrokeJoin) -> Self {
509        self.join = join;
510        self
511    }
512}
513
514pub struct RenderCtx<'a, D, C = Dither>
515where
516    D: DrawTarget<Color = Rgb565>,
517{
518    target: &'a mut D,
519    clip: Rect,
520    dirty: Option<Rect>,
521    quality: RenderQuality,
522    backend_caps: RenderBackendCaps,
523    transform_stack: [Transform2D; 8],
524    transform_len: usize,
525    layer_stack: [LayerState; 8],
526    layer_len: usize,
527    _compositor: PhantomData<C>,
528}
529
530impl<'a, D> RenderCtx<'a, D, Dither>
531where
532    D: DrawTarget<Color = Rgb565>,
533{
534    pub fn new(target: &'a mut D, viewport: Rect) -> Self {
535        Self {
536            target,
537            clip: viewport,
538            dirty: None,
539            quality: RenderQuality::High,
540            backend_caps: RenderBackendCaps::software_rgb565(),
541            transform_stack: [Transform2D::IDENTITY; 8],
542            transform_len: 1,
543            layer_stack: [LayerState::normal(); 8],
544            layer_len: 1,
545            _compositor: PhantomData,
546        }
547    }
548
549    pub fn with_dirty(target: &'a mut D, viewport: Rect, dirty: Rect) -> Self {
550        Self {
551            target,
552            clip: viewport,
553            dirty: Some(dirty),
554            quality: RenderQuality::High,
555            backend_caps: RenderBackendCaps::software_rgb565(),
556            transform_stack: [Transform2D::IDENTITY; 8],
557            transform_len: 1,
558            layer_stack: [LayerState::normal(); 8],
559            layer_len: 1,
560            _compositor: PhantomData,
561        }
562    }
563}
564
565impl<'a, D> RenderCtx<'a, D, Blend>
566where
567    D: DrawTarget<Color = Rgb565> + PixelRead,
568{
569    /// Like [`RenderCtx::new`], but every drawing call alpha-composites against
570    /// the target's current contents (true blending) instead of dithering.
571    /// Requires a readback-capable target ([`PixelRead`]), e.g. a
572    /// [`Framebuffer`](crate::Framebuffer).
573    pub fn compositing(target: &'a mut D, viewport: Rect) -> Self {
574        Self {
575            target,
576            clip: viewport,
577            dirty: None,
578            quality: RenderQuality::High,
579            backend_caps: RenderBackendCaps::software_rgb565(),
580            transform_stack: [Transform2D::IDENTITY; 8],
581            transform_len: 1,
582            layer_stack: [LayerState::normal(); 8],
583            layer_len: 1,
584            _compositor: PhantomData,
585        }
586    }
587
588    /// Apply Fast IIR Blur to a sub-region `rect` on the destination target.
589    pub fn blur_rect(&mut self, rect: Rect, blur_degree: u8) -> Result<(), D::Error> {
590        let draw = self.visible_rect(rect);
591        if draw.is_empty() || blur_degree == 0 {
592            return Ok(());
593        }
594        let x0 = draw.x;
595        let y0 = draw.y;
596        let x1 = draw.right();
597        let y1 = draw.bottom();
598        let alpha = 256 - (blur_degree as i32);
599
600        let mut row_buf = [Rgb565::BLACK; 1024];
601        let w_buf = ((x1 - x0) as usize).min(1024);
602
603        // Horizontal forward & reverse passes (row by row)
604        for y in y0..y1 {
605            let r_len = ((x1 - x0) as usize).min(w_buf);
606            if r_len == 0 {
607                continue;
608            }
609            for (i, x) in (x0..x1).take(r_len).enumerate() {
610                row_buf[i] = self.target.get_pixel(Point::new(x, y));
611            }
612
613            // Forward H pass
614            let p0 = row_buf[0];
615            let (r5, g6, b5) = (p0.r(), p0.g(), p0.b());
616            let mut acc_r = (((r5 << 3) | (r5 >> 2)) as i32) << 8;
617            let mut acc_g = (((g6 << 2) | (g6 >> 4)) as i32) << 8;
618            let mut acc_b = (((b5 << 3) | (b5 >> 2)) as i32) << 8;
619
620            for p in row_buf[..r_len].iter_mut() {
621                let (r5, g6, b5) = (p.r(), p.g(), p.b());
622                let r8 = ((r5 << 3) | (r5 >> 2)) as i32;
623                let g8 = ((g6 << 2) | (g6 >> 4)) as i32;
624                let b8 = ((b5 << 3) | (b5 >> 2)) as i32;
625                acc_r += (((r8 << 8) - acc_r) * alpha) >> 8;
626                acc_g += (((g8 << 8) - acc_g) * alpha) >> 8;
627                acc_b += (((b8 << 8) - acc_b) * alpha) >> 8;
628                *p = Rgb565::new(
629                    ((acc_r >> 8).clamp(0, 255) as u8) >> 3,
630                    ((acc_g >> 8).clamp(0, 255) as u8) >> 2,
631                    ((acc_b >> 8).clamp(0, 255) as u8) >> 3,
632                );
633            }
634
635            // Reverse H pass
636            let p_last = row_buf[r_len - 1];
637            let (r5, g6, b5) = (p_last.r(), p_last.g(), p_last.b());
638            let mut acc_r = (((r5 << 3) | (r5 >> 2)) as i32) << 8;
639            let mut acc_g = (((g6 << 2) | (g6 >> 4)) as i32) << 8;
640            let mut acc_b = (((b5 << 3) | (b5 >> 2)) as i32) << 8;
641
642            for p in row_buf[..r_len].iter_mut().rev() {
643                let (r5, g6, b5) = (p.r(), p.g(), p.b());
644                let r8 = ((r5 << 3) | (r5 >> 2)) as i32;
645                let g8 = ((g6 << 2) | (g6 >> 4)) as i32;
646                let b8 = ((b5 << 3) | (b5 >> 2)) as i32;
647                acc_r += (((r8 << 8) - acc_r) * alpha) >> 8;
648                acc_g += (((g8 << 8) - acc_g) * alpha) >> 8;
649                acc_b += (((b8 << 8) - acc_b) * alpha) >> 8;
650                *p = Rgb565::new(
651                    ((acc_r >> 8).clamp(0, 255) as u8) >> 3,
652                    ((acc_g >> 8).clamp(0, 255) as u8) >> 2,
653                    ((acc_b >> 8).clamp(0, 255) as u8) >> 3,
654                );
655            }
656
657            for (i, x) in (x0..x1).take(r_len).enumerate() {
658                self.target
659                    .draw_iter([Pixel(Point::new(x, y), row_buf[i])])?;
660            }
661        }
662
663        // Vertical forward & reverse passes (column by column)
664        let mut col_buf = [Rgb565::BLACK; 1024];
665        let h_buf = ((y1 - y0) as usize).min(1024);
666
667        for x in x0..x1 {
668            let c_len = ((y1 - y0) as usize).min(h_buf);
669            if c_len == 0 {
670                continue;
671            }
672            for (i, y) in (y0..y1).take(c_len).enumerate() {
673                col_buf[i] = self.target.get_pixel(Point::new(x, y));
674            }
675
676            // Forward V pass
677            let p0 = col_buf[0];
678            let (r5, g6, b5) = (p0.r(), p0.g(), p0.b());
679            let mut acc_r = (((r5 << 3) | (r5 >> 2)) as i32) << 8;
680            let mut acc_g = (((g6 << 2) | (g6 >> 4)) as i32) << 8;
681            let mut acc_b = (((b5 << 3) | (b5 >> 2)) as i32) << 8;
682
683            for p in col_buf[..c_len].iter_mut() {
684                let (r5, g6, b5) = (p.r(), p.g(), p.b());
685                let r8 = ((r5 << 3) | (r5 >> 2)) as i32;
686                let g8 = ((g6 << 2) | (g6 >> 4)) as i32;
687                let b8 = ((b5 << 3) | (b5 >> 2)) as i32;
688                acc_r += (((r8 << 8) - acc_r) * alpha) >> 8;
689                acc_g += (((g8 << 8) - acc_g) * alpha) >> 8;
690                acc_b += (((b8 << 8) - acc_b) * alpha) >> 8;
691                *p = Rgb565::new(
692                    ((acc_r >> 8).clamp(0, 255) as u8) >> 3,
693                    ((acc_g >> 8).clamp(0, 255) as u8) >> 2,
694                    ((acc_b >> 8).clamp(0, 255) as u8) >> 3,
695                );
696            }
697
698            // Reverse V pass
699            let p_last = col_buf[c_len - 1];
700            let (r5, g6, b5) = (p_last.r(), p_last.g(), p_last.b());
701            let mut acc_r = (((r5 << 3) | (r5 >> 2)) as i32) << 8;
702            let mut acc_g = (((g6 << 2) | (g6 >> 4)) as i32) << 8;
703            let mut acc_b = (((b5 << 3) | (b5 >> 2)) as i32) << 8;
704
705            for p in col_buf[..c_len].iter_mut().rev() {
706                let (r5, g6, b5) = (p.r(), p.g(), p.b());
707                let r8 = ((r5 << 3) | (r5 >> 2)) as i32;
708                let g8 = ((g6 << 2) | (g6 >> 4)) as i32;
709                let b8 = ((b5 << 3) | (b5 >> 2)) as i32;
710                acc_r += (((r8 << 8) - acc_r) * alpha) >> 8;
711                acc_g += (((g8 << 8) - acc_g) * alpha) >> 8;
712                acc_b += (((b8 << 8) - acc_b) * alpha) >> 8;
713                *p = Rgb565::new(
714                    ((acc_r >> 8).clamp(0, 255) as u8) >> 3,
715                    ((acc_g >> 8).clamp(0, 255) as u8) >> 2,
716                    ((acc_b >> 8).clamp(0, 255) as u8) >> 3,
717                );
718            }
719
720            for (i, y) in (y0..y1).take(c_len).enumerate() {
721                self.target
722                    .draw_iter([Pixel(Point::new(x, y), col_buf[i])])?;
723            }
724        }
725
726        Ok(())
727    }
728
729    /// Apply reverse colour (color inversion) filter on `rect` (PixelRead target).
730    pub fn reverse_colour_rect(&mut self, rect: Rect) -> Result<(), D::Error> {
731        let bounds = self.clip.intersection(rect);
732        if bounds.is_empty() {
733            return Ok(());
734        }
735        let x0 = bounds.x;
736        let y0 = bounds.y;
737        let x1 = bounds.right();
738        let y1 = bounds.bottom();
739
740        for y in y0..y1 {
741            for x in x0..x1 {
742                let pt = Point::new(x, y);
743                let c = self.target.get_pixel(pt);
744                let inv = Rgb565::new(31 - c.r(), 63 - c.g(), 31 - c.b());
745                self.target.draw_iter([Pixel(pt, inv)])?;
746            }
747        }
748        Ok(())
749    }
750
751    /// Fill `rect` using a horizontal 1D line mask array.
752    pub fn fill_rect_horizontal_line_mask(
753        &mut self,
754        rect: Rect,
755        mask: &[u8],
756        color: Rgb565,
757        opacity: u8,
758    ) -> Result<(), D::Error> {
759        if mask.is_empty() || opacity == 0 {
760            return Ok(());
761        }
762        let bounds = self.clip.intersection(rect);
763        if bounds.is_empty() {
764            return Ok(());
765        }
766
767        for y in bounds.y..bounds.bottom() {
768            for x in bounds.x..bounds.right() {
769                let mask_x = ((x - rect.x) as usize) % mask.len();
770                let alpha = ((mask[mask_x] as u32 * opacity as u32) >> 8) as u8;
771                if alpha == 0 {
772                    continue;
773                }
774                let pt = Point::new(x, y);
775                let bg = self.target.get_pixel(pt);
776                let blended = lerp_rgb565(bg, color, alpha);
777                self.target.draw_iter([Pixel(pt, blended)])?;
778            }
779        }
780        Ok(())
781    }
782
783    /// Fill `rect` using a vertical 1D line mask array.
784    pub fn fill_rect_vertical_line_mask(
785        &mut self,
786        rect: Rect,
787        mask: &[u8],
788        color: Rgb565,
789        opacity: u8,
790    ) -> Result<(), D::Error> {
791        if mask.is_empty() || opacity == 0 {
792            return Ok(());
793        }
794        let bounds = self.clip.intersection(rect);
795        if bounds.is_empty() {
796            return Ok(());
797        }
798
799        for y in bounds.y..bounds.bottom() {
800            let mask_y = ((y - rect.y) as usize) % mask.len();
801            let alpha = ((mask[mask_y] as u32 * opacity as u32) >> 8) as u8;
802            if alpha == 0 {
803                continue;
804            }
805            for x in bounds.x..bounds.right() {
806                let pt = Point::new(x, y);
807                let bg = self.target.get_pixel(pt);
808                let blended = lerp_rgb565(bg, color, alpha);
809                self.target.draw_iter([Pixel(pt, blended)])?;
810            }
811        }
812        Ok(())
813    }
814}
815
816impl<'a, D, C> RenderCtx<'a, D, C>
817where
818    D: DrawTarget<Color = Rgb565>,
819    C: Compositor<D>,
820{
821    pub const fn clip(&self) -> Rect {
822        self.clip
823    }
824
825    pub fn set_clip(&mut self, clip: Rect) {
826        self.clip = clip;
827    }
828
829    /// Draws any `embedded_graphics::Drawable` (e.g. an `embedded_text::TextBox`
830    /// built via [`crate::interop::text::text_box`], or an arranged
831    /// `embedded_layout` view group) onto this context's target, clipped to
832    /// the current [`clip`](Self::clip) rect.
833    #[cfg(any(
834        feature = "embedded-text",
835        feature = "embedded-layout",
836        feature = "embedded-graphics"
837    ))]
838    pub fn draw_embedded_graphics<T>(&mut self, drawable: &T) -> Result<T::Output, D::Error>
839    where
840        T: embedded_graphics::Drawable<Color = Rgb565>,
841    {
842        use embedded_graphics::draw_target::DrawTargetExt;
843
844        let clip_rect: embedded_graphics::primitives::Rectangle = self.clip.into();
845        let mut clipped = self.target.clipped(&clip_rect);
846        drawable.draw(&mut clipped)
847    }
848
849    pub const fn quality(&self) -> RenderQuality {
850        self.quality
851    }
852
853    pub fn set_quality(&mut self, quality: RenderQuality) {
854        self.quality = quality;
855    }
856
857    pub const fn backend_caps(&self) -> RenderBackendCaps {
858        self.backend_caps
859    }
860
861    pub fn set_backend_caps(&mut self, caps: RenderBackendCaps) {
862        self.backend_caps = caps;
863    }
864
865    pub fn push_transform(&mut self, transform: Transform2D) {
866        if self.transform_len >= self.transform_stack.len() {
867            return;
868        }
869        let current = self.current_transform();
870        self.transform_stack[self.transform_len] = current.then(transform);
871        self.transform_len += 1;
872    }
873
874    pub fn pop_transform(&mut self) {
875        if self.transform_len > 1 {
876            self.transform_len -= 1;
877        }
878    }
879
880    pub fn translate(&mut self, x: f32, y: f32) {
881        self.push_transform(Transform2D::translation(x, y));
882    }
883
884    pub fn scale(&mut self, x: f32, y: f32) {
885        self.push_transform(Transform2D::scale(x, y));
886    }
887
888    pub fn rotate(&mut self, deg: f32) {
889        self.push_transform(Transform2D::rotation(deg));
890    }
891
892    pub fn skew(&mut self, x_deg: f32, y_deg: f32) {
893        self.push_transform(Transform2D::skew(x_deg, y_deg));
894    }
895
896    pub fn push_layer(&mut self, layer: LayerState) {
897        if self.layer_len >= self.layer_stack.len() {
898            return;
899        }
900        let current = self.current_layer();
901        self.layer_stack[self.layer_len] = LayerState {
902            opacity: ((current.opacity as u16 * layer.opacity as u16) / 255) as u8,
903            blend: layer.blend,
904            backdrop: layer.backdrop,
905        };
906        self.layer_len += 1;
907    }
908
909    pub fn pop_layer(&mut self) {
910        if self.layer_len > 1 {
911            self.layer_len -= 1;
912        }
913    }
914
915    pub const fn shadow_spread_for(&self, spread: u8) -> u8 {
916        match self.quality {
917            RenderQuality::Low => 0,
918            RenderQuality::Medium => {
919                if spread > 1 {
920                    1
921                } else {
922                    spread
923                }
924            }
925            RenderQuality::High => spread,
926        }
927    }
928
929    pub fn fill_rect(&mut self, rect: Rect, color: Rgb565) -> Result<(), D::Error> {
930        self.fill_rect_alpha(rect, color, 255)
931    }
932
933    pub fn fill_rect_alpha(
934        &mut self,
935        rect: Rect,
936        color: Rgb565,
937        opacity: u8,
938    ) -> Result<(), D::Error> {
939        self.fill_rounded_rect_alpha(rect, 0, color, opacity)
940    }
941
942    pub fn fill_rounded_rect(
943        &mut self,
944        rect: Rect,
945        radius: u8,
946        color: Rgb565,
947    ) -> Result<(), D::Error> {
948        self.fill_rounded_rect_alpha(rect, radius, color, 255)
949    }
950
951    pub fn fill_rounded_rect_alpha(
952        &mut self,
953        rect: Rect,
954        radius: u8,
955        color: Rgb565,
956        opacity: u8,
957    ) -> Result<(), D::Error> {
958        let draw = self.visible_rect(rect);
959        if draw.is_empty() || opacity == 0 {
960            return Ok(());
961        }
962        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
963
964        let layer = self.current_layer();
965        let combined_opacity = ((opacity as u16 * layer.opacity as u16) / 255) as u8;
966
967        // Fast path for solid un-transformed rectangular fills:
968        // Leverages hardware fill_solid on the display target instead of per-pixel loops
969        if radius == 0
970            && combined_opacity == 255
971            && self.current_transform().is_identity()
972            && layer.blend == BlendMode::Normal
973        {
974            let eg_rect = embedded_graphics_core::primitives::Rectangle::new(
975                embedded_graphics_core::geometry::Point::new(draw.x, draw.y),
976                embedded_graphics_core::geometry::Size::new(draw.w, draw.h),
977            );
978            return self.target.fill_solid(&eg_rect, color);
979        }
980
981        for y in draw.y..draw.bottom() {
982            for x in draw.x..draw.right() {
983                if !in_rounded_rect(x, y, rect, radius) {
984                    continue;
985                }
986                self.pixel(x, y, color, opacity)?;
987            }
988        }
989        Ok(())
990    }
991
992    pub fn fill_rounded_rect_gradient_alpha(
993        &mut self,
994        rect: Rect,
995        radius: u8,
996        gradient: LinearGradient,
997        opacity: u8,
998    ) -> Result<(), D::Error> {
999        let draw = self.visible_rect(rect);
1000        if draw.is_empty() || opacity == 0 {
1001            return Ok(());
1002        }
1003        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
1004        let denom = match gradient.direction {
1005            GradientDirection::Horizontal => rect.w.saturating_sub(1).max(1),
1006            GradientDirection::Vertical => rect.h.saturating_sub(1).max(1),
1007        };
1008
1009        for y in draw.y..draw.bottom() {
1010            for x in draw.x..draw.right() {
1011                if !in_rounded_rect(x, y, rect, radius) {
1012                    continue;
1013                }
1014                let numer = match gradient.direction {
1015                    GradientDirection::Horizontal => (x - rect.x).max(0) as u32,
1016                    GradientDirection::Vertical => (y - rect.y).max(0) as u32,
1017                }
1018                .min(denom);
1019                let mut t = ((numer * 255) / denom) as u8;
1020                t = match self.quality {
1021                    RenderQuality::Low => 128,
1022                    RenderQuality::Medium => (t / 64) * 64,
1023                    RenderQuality::High => t,
1024                };
1025                let color = lerp_rgb565(gradient.start, gradient.end, t);
1026                self.pixel(x, y, color, opacity)?;
1027            }
1028        }
1029        Ok(())
1030    }
1031
1032    pub fn stroke_rect(&mut self, rect: Rect, border: Border) -> Result<(), D::Error> {
1033        self.stroke_rect_alpha(rect, border, 255)
1034    }
1035
1036    pub fn stroke_rect_alpha(
1037        &mut self,
1038        rect: Rect,
1039        border: Border,
1040        opacity: u8,
1041    ) -> Result<(), D::Error> {
1042        if border.width == 0 || rect.is_empty() {
1043            return Ok(());
1044        }
1045
1046        for i in 0..border.width as i32 {
1047            let w = rect.w.saturating_sub((i as u32).saturating_mul(2));
1048            let h = rect.h.saturating_sub((i as u32).saturating_mul(2));
1049            if w == 0 || h == 0 {
1050                break;
1051            }
1052            let r = Rect::new(rect.x + i, rect.y + i, w, h);
1053            self.fill_rect_alpha(Rect::new(r.x, r.y, r.w, 1), border.color, opacity)?;
1054            if r.h > 1 {
1055                self.fill_rect_alpha(
1056                    Rect::new(r.x, r.bottom() - 1, r.w, 1),
1057                    border.color,
1058                    opacity,
1059                )?;
1060            }
1061            if r.h > 2 {
1062                self.fill_rect_alpha(Rect::new(r.x, r.y + 1, 1, r.h - 2), border.color, opacity)?;
1063                if r.w > 1 {
1064                    self.fill_rect_alpha(
1065                        Rect::new(r.right() - 1, r.y + 1, 1, r.h - 2),
1066                        border.color,
1067                        opacity,
1068                    )?;
1069                }
1070            }
1071        }
1072        Ok(())
1073    }
1074
1075    pub fn stroke_rounded_rect(
1076        &mut self,
1077        rect: Rect,
1078        radius: u8,
1079        border: Border,
1080    ) -> Result<(), D::Error> {
1081        self.stroke_rounded_rect_alpha(rect, radius, border, 255)
1082    }
1083
1084    pub fn stroke_rounded_rect_alpha(
1085        &mut self,
1086        rect: Rect,
1087        radius: u8,
1088        border: Border,
1089        opacity: u8,
1090    ) -> Result<(), D::Error> {
1091        if border.width == 0 || rect.is_empty() || opacity == 0 {
1092            return Ok(());
1093        }
1094        let draw = self.visible_rect(rect);
1095        if draw.is_empty() {
1096            return Ok(());
1097        }
1098
1099        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
1100        for y in draw.y..draw.bottom() {
1101            for x in draw.x..draw.right() {
1102                if !in_rounded_rect(x, y, rect, radius) {
1103                    continue;
1104                }
1105
1106                let mut inner_hit = false;
1107                let mut i = 1u8;
1108                while i < border.width {
1109                    let inset = i as i32;
1110                    let inner = Rect::new(
1111                        rect.x + inset,
1112                        rect.y + inset,
1113                        rect.w.saturating_sub((i as u32) * 2),
1114                        rect.h.saturating_sub((i as u32) * 2),
1115                    );
1116                    let inner_radius = radius.saturating_sub(i);
1117                    if !inner.is_empty() && in_rounded_rect(x, y, inner, inner_radius) {
1118                        inner_hit = true;
1119                        break;
1120                    }
1121                    i += 1;
1122                }
1123
1124                if !inner_hit {
1125                    self.pixel(x, y, border.color, opacity)?;
1126                }
1127            }
1128        }
1129        Ok(())
1130    }
1131
1132    pub fn draw_text(&mut self, x: i32, y: i32, text: &str, color: Rgb565) -> Result<(), D::Error> {
1133        self.draw_text_with_font(x, y, text, color, FontId::Tiny3x5)
1134    }
1135
1136    pub fn draw_text_with_font(
1137        &mut self,
1138        x: i32,
1139        y: i32,
1140        text: &str,
1141        color: Rgb565,
1142        font: FontId,
1143    ) -> Result<(), D::Error> {
1144        let advance = font.advance() as i32;
1145        let line_h = font.line_height() as i32;
1146        let mut cursor_x = x;
1147        let mut cursor_y = y;
1148        for ch in text.chars() {
1149            if ch == '\n' {
1150                cursor_x = x;
1151                cursor_y += line_h;
1152                continue;
1153            }
1154            self.draw_char_with_font(cursor_x, cursor_y, ch, color, 255, font)?;
1155            cursor_x += advance;
1156        }
1157        Ok(())
1158    }
1159
1160    pub fn draw_text_in(
1161        &mut self,
1162        rect: Rect,
1163        text: &str,
1164        style: TextStyle,
1165    ) -> Result<(), D::Error> {
1166        self.draw_text_in_with_font(rect, text, style, style.font)
1167    }
1168
1169    pub fn draw_text_shaped_in<S, const N: usize>(
1170        &mut self,
1171        rect: Rect,
1172        text: &str,
1173        style: TextStyle,
1174        shaper: &S,
1175        config: crate::text::ShapingConfig,
1176    ) -> Result<(), D::Error>
1177    where
1178        S: crate::text::TextShaper,
1179    {
1180        if rect.is_empty() {
1181            return Ok(());
1182        }
1183        let mut shaped = heapless::Vec::<crate::text::ShapedGlyph, N>::new();
1184        shaper.shape(text, config, &mut shaped);
1185        if shaped.is_empty() {
1186            return Ok(());
1187        }
1188        let mut x = rect.x;
1189        let y = rect.y + rect.h.saturating_sub(style.font.line_height()) as i32 / 2;
1190        for glyph in shaped {
1191            self.draw_char_with_font(x, y, glyph.ch, style.color, style.opacity, style.font)?;
1192            x += (glyph.x_advance as i32).max(1) * style.font.advance() as i32;
1193            if x >= rect.right() {
1194                break;
1195            }
1196        }
1197        Ok(())
1198    }
1199
1200    pub fn draw_text_in_with_font(
1201        &mut self,
1202        rect: Rect,
1203        text: &str,
1204        style: TextStyle,
1205        font: FontId,
1206    ) -> Result<(), D::Error> {
1207        if rect.is_empty() {
1208            return Ok(());
1209        }
1210
1211        let advance = font.advance();
1212        let line_h = font.line_height();
1213        let max_chars = (rect.w / advance).max(1) as usize;
1214        let char_count = text.chars().count();
1215        let line_count = count_lines(text, max_chars, style.wrap).max(1);
1216        let line_step = line_h + style.line_spacing as u32;
1217        let total_h = line_count as u32 * line_h
1218            + line_count.saturating_sub(1) as u32 * style.line_spacing as u32;
1219        let mut y = match style.vertical_align {
1220            VerticalAlign::Top => rect.y,
1221            VerticalAlign::Middle => rect.y + rect.h.saturating_sub(total_h) as i32 / 2,
1222            VerticalAlign::Bottom => rect.y + rect.h.saturating_sub(total_h) as i32,
1223        };
1224
1225        let mut start = 0;
1226        let mut rendered_lines = 0u8;
1227        let max_lines = match style.overflow_policy {
1228            TextOverflowPolicy::WrapThenEllipsis { max_lines } => max_lines.max(1),
1229            TextOverflowPolicy::Global(_) => style.max_lines.unwrap_or(u8::MAX),
1230        };
1231        while start < char_count {
1232            if rendered_lines >= max_lines {
1233                break;
1234            }
1235            let (len, consumed_newline) = line_len_at(text, start, max_chars, style.wrap);
1236            let mut draw_len = len;
1237            let is_last_allowed_line = rendered_lines.saturating_add(1) >= max_lines;
1238            let use_ellipsis = match style.overflow_policy {
1239                TextOverflowPolicy::WrapThenEllipsis { .. } => is_last_allowed_line,
1240                TextOverflowPolicy::Global(mode) => mode == TextOverflow::Ellipsis,
1241            };
1242            if use_ellipsis
1243                && ((!consumed_newline && start + len < char_count) || is_last_allowed_line)
1244            {
1245                let ellipsis_width = match style.ellipsis {
1246                    EllipsisMode::ThreeDots => 3usize,
1247                    EllipsisMode::SingleGlyph => 1usize,
1248                };
1249                if len > ellipsis_width {
1250                    draw_len = len - ellipsis_width;
1251                }
1252            }
1253            let line_w = self.substring_width(text, start, draw_len, font, style.kerning);
1254            let x = match style.align {
1255                TextAlign::Left => rect.x,
1256                TextAlign::Center => rect.x + rect.w.saturating_sub(line_w) as i32 / 2,
1257                TextAlign::Right => rect.x + rect.w.saturating_sub(line_w) as i32,
1258            };
1259            self.draw_chars_with_font(
1260                x,
1261                y,
1262                text,
1263                start,
1264                draw_len,
1265                style.color,
1266                style.opacity,
1267                font,
1268                style.kerning,
1269            )?;
1270            if draw_len < len && use_ellipsis {
1271                let token = match style.ellipsis {
1272                    EllipsisMode::ThreeDots => "...",
1273                    EllipsisMode::SingleGlyph => ".",
1274                };
1275                self.draw_text_with_font(x + line_w as i32, y, token, style.color, font)?;
1276            }
1277            y += line_step as i32;
1278            rendered_lines = rendered_lines.saturating_add(1);
1279            start += len + usize::from(consumed_newline);
1280            if style.wrap == TextWrap::Word && start < char_count {
1281                while text.chars().nth(start).is_some_and(|ch| ch == ' ') {
1282                    start += 1;
1283                }
1284            }
1285            if len == 0 && !consumed_newline {
1286                break;
1287            }
1288        }
1289
1290        Ok(())
1291    }
1292
1293    pub fn draw_line_in(&mut self, rect: Rect, line: text::Line<'_>) -> Result<(), D::Error> {
1294        if rect.is_empty() {
1295            return Ok(());
1296        }
1297
1298        self.draw_line_segment_in(rect, line, 0, line.width_chars())
1299    }
1300
1301    pub fn draw_line(
1302        &mut self,
1303        x0: i32,
1304        y0: i32,
1305        x1: i32,
1306        y1: i32,
1307        color: Rgb565,
1308    ) -> Result<(), D::Error> {
1309        self.draw_line_styled(x0, y0, x1, y1, StrokeStyle::new(color))
1310    }
1311
1312    pub fn draw_line_styled(
1313        &mut self,
1314        x0: i32,
1315        y0: i32,
1316        x1: i32,
1317        y1: i32,
1318        style: StrokeStyle,
1319    ) -> Result<(), D::Error> {
1320        let mut x = x0;
1321        let mut y = y0;
1322        let dx = (x1 - x0).abs();
1323        let sx = if x0 < x1 { 1 } else { -1 };
1324        let dy = -(y1 - y0).abs();
1325        let sy = if y0 < y1 { 1 } else { -1 };
1326        let mut err = dx + dy;
1327        let half = (style.width as i32 / 2).max(0);
1328        let opacity = self.stroke_opacity(style);
1329
1330        loop {
1331            for oy in -half..=half {
1332                for ox in -half..=half {
1333                    self.pixel(x + ox, y + oy, style.color, opacity)?;
1334                }
1335            }
1336            if style.cap == StrokeCap::Round {
1337                self.fill_circle(x0, y0, half.max(1) as u32, style.color)?;
1338                self.fill_circle(x1, y1, half.max(1) as u32, style.color)?;
1339            }
1340            if x == x1 && y == y1 {
1341                break;
1342            }
1343            let e2 = 2 * err;
1344            if e2 >= dy {
1345                err += dy;
1346                x += sx;
1347            }
1348            if e2 <= dx {
1349                err += dx;
1350                y += sy;
1351            }
1352        }
1353        Ok(())
1354    }
1355
1356    pub fn fill_circle(
1357        &mut self,
1358        center_x: i32,
1359        center_y: i32,
1360        radius: u32,
1361        color: Rgb565,
1362    ) -> Result<(), D::Error> {
1363        let radius = radius as i32;
1364        if radius <= 0 {
1365            return Ok(());
1366        }
1367        let r_sq = radius * radius;
1368        for dy in -radius..=radius {
1369            let dx = ((r_sq - dy * dy) as f32).sqrt() as i32;
1370            if dx >= 0 {
1371                let w = (dx * 2 + 1) as u32;
1372                self.fill_rect(Rect::new(center_x - dx, center_y + dy, w, 1), color)?;
1373            }
1374        }
1375        Ok(())
1376    }
1377
1378    pub fn stroke_circle(
1379        &mut self,
1380        center_x: i32,
1381        center_y: i32,
1382        radius: u32,
1383        color: Rgb565,
1384    ) -> Result<(), D::Error> {
1385        let radius = radius as i32;
1386        if radius <= 0 {
1387            return Ok(());
1388        }
1389        let mut x = radius;
1390        let mut y = 0;
1391        let mut err = 1 - x;
1392        while x >= y {
1393            self.pixel(center_x + x, center_y + y, color, 255)?;
1394            self.pixel(center_x + y, center_y + x, color, 255)?;
1395            self.pixel(center_x - y, center_y + x, color, 255)?;
1396            self.pixel(center_x - x, center_y + y, color, 255)?;
1397            self.pixel(center_x - x, center_y - y, color, 255)?;
1398            self.pixel(center_x - y, center_y - x, color, 255)?;
1399            self.pixel(center_x + y, center_y - x, color, 255)?;
1400            self.pixel(center_x + x, center_y - y, color, 255)?;
1401            y += 1;
1402            if err < 0 {
1403                err += 2 * y + 1;
1404            } else {
1405                x -= 1;
1406                err += 2 * (y - x) + 1;
1407            }
1408        }
1409        Ok(())
1410    }
1411
1412    pub fn stroke_arc(
1413        &mut self,
1414        center_x: i32,
1415        center_y: i32,
1416        radius: u32,
1417        start_deg: i32,
1418        end_deg: i32,
1419        color: Rgb565,
1420    ) -> Result<(), D::Error> {
1421        self.stroke_arc_styled(
1422            center_x,
1423            center_y,
1424            radius,
1425            start_deg,
1426            end_deg,
1427            StrokeStyle::new(color),
1428        )
1429    }
1430
1431    pub fn stroke_arc_styled(
1432        &mut self,
1433        center_x: i32,
1434        center_y: i32,
1435        radius: u32,
1436        start_deg: i32,
1437        end_deg: i32,
1438        style: StrokeStyle,
1439    ) -> Result<(), D::Error> {
1440        let mut start = start_deg;
1441        let mut end = end_deg;
1442        if end < start {
1443            core::mem::swap(&mut start, &mut end);
1444        }
1445        let mut deg = start;
1446        let step = match self.quality {
1447            RenderQuality::Low => 8,
1448            RenderQuality::Medium => 4,
1449            RenderQuality::High => 2,
1450        };
1451        while deg <= end {
1452            let rad = (deg as f32).to_radians();
1453            let x = center_x + (radius as f32 * rad.cos()) as i32;
1454            let y = center_y + (radius as f32 * rad.sin()) as i32;
1455            let half = (style.width as i32 / 2).max(0);
1456            let opacity = self.stroke_opacity(style);
1457            for oy in -half..=half {
1458                for ox in -half..=half {
1459                    self.pixel(x + ox, y + oy, style.color, opacity)?;
1460                }
1461            }
1462            if style.join == StrokeJoin::Round {
1463                self.fill_circle(x, y, half.max(1) as u32, style.color)?;
1464            }
1465            deg += step;
1466        }
1467        Ok(())
1468    }
1469
1470    /// Fill a sector ("pie slice") using a start angle and sweep angle in degrees.
1471    ///
1472    /// Positive sweep draws counterclockwise, negative sweep clockwise.
1473    pub fn fill_sector_sweep(
1474        &mut self,
1475        center_x: i32,
1476        center_y: i32,
1477        radius: u32,
1478        start_deg: f32,
1479        sweep_deg: f32,
1480        color: Rgb565,
1481    ) -> Result<(), D::Error> {
1482        if radius == 0 {
1483            return Ok(());
1484        }
1485
1486        let draw = self.visible_rect(Rect::new(
1487            center_x - radius as i32,
1488            center_y - radius as i32,
1489            radius.saturating_mul(2).saturating_add(1),
1490            radius.saturating_mul(2).saturating_add(1),
1491        ));
1492        if draw.is_empty() {
1493            return Ok(());
1494        }
1495
1496        let max_sweep = sweep_deg.abs().min(360.0);
1497        if max_sweep <= 0.0 {
1498            return Ok(());
1499        }
1500
1501        let rr = (radius as i32) * (radius as i32);
1502        let start = normalize_angle_deg(start_deg);
1503        let ccw = sweep_deg >= 0.0;
1504
1505        for y in draw.y..draw.bottom() {
1506            for x in draw.x..draw.right() {
1507                let dx = x - center_x;
1508                let dy = y - center_y;
1509                let d2 = dx * dx + dy * dy;
1510                if d2 > rr {
1511                    continue;
1512                }
1513
1514                let mut angle = (dy as f32).atan2(dx as f32).to_degrees();
1515                if angle < 0.0 {
1516                    angle += 360.0;
1517                }
1518                let in_sweep = if ccw {
1519                    ccw_distance_deg(start, angle) <= max_sweep
1520                } else {
1521                    ccw_distance_deg(angle, start) <= max_sweep
1522                };
1523                if in_sweep {
1524                    self.pixel(x, y, color, 255)?;
1525                }
1526            }
1527        }
1528        Ok(())
1529    }
1530
1531    pub fn fill_polygon(&mut self, points: &[Point], color: Rgb565) -> Result<(), D::Error> {
1532        if points.len() < 3 {
1533            return Ok(());
1534        }
1535        let min_y = points.iter().map(|p| p.y).min().unwrap_or(0);
1536        let max_y = points.iter().map(|p| p.y).max().unwrap_or(-1);
1537        for y in min_y..=max_y {
1538            let mut intersections = [i32::MIN; 16];
1539            let mut count = 0usize;
1540            for i in 0..points.len() {
1541                let p1 = points[i];
1542                let p2 = points[(i + 1) % points.len()];
1543                let (y1, y2) = if p1.y <= p2.y {
1544                    (p1.y, p2.y)
1545                } else {
1546                    (p2.y, p1.y)
1547                };
1548                if y < y1 || y >= y2 || y1 == y2 {
1549                    continue;
1550                }
1551                if count >= intersections.len() {
1552                    break;
1553                }
1554                let x = p1.x + ((y - p1.y) * (p2.x - p1.x)) / (p2.y - p1.y);
1555                intersections[count] = x;
1556                count += 1;
1557            }
1558            intersections[..count].sort_unstable();
1559            let mut i = 0;
1560            while i + 1 < count {
1561                let x0 = intersections[i];
1562                let x1 = intersections[i + 1];
1563                for x in x0..=x1 {
1564                    self.pixel(x, y, color, 255)?;
1565                }
1566                i += 2;
1567            }
1568        }
1569        Ok(())
1570    }
1571
1572    pub fn draw_image(
1573        &mut self,
1574        rect: Rect,
1575        image: ImageRef<'_>,
1576        fit: ImageFit,
1577    ) -> Result<(), D::Error> {
1578        self.draw_image_region(rect, image, fit, Rect::new(0, 0, image.width, image.height))
1579    }
1580
1581    pub fn draw_image_region(
1582        &mut self,
1583        rect: Rect,
1584        image: ImageRef<'_>,
1585        fit: ImageFit,
1586        src_rect: Rect,
1587    ) -> Result<(), D::Error> {
1588        let bounds = image.bounds_at(rect, fit);
1589        if bounds.is_empty() || image.width == 0 || image.height == 0 {
1590            return Ok(());
1591        }
1592        let src_w = image.width as usize;
1593        for y in 0..bounds.h {
1594            let src_y = match fit {
1595                ImageFit::Stretch => {
1596                    src_rect.y.max(0) as usize
1597                        + ((y as u64 * src_rect.h as u64) / bounds.h as u64) as usize
1598                }
1599                ImageFit::Center => src_rect.y.max(0) as usize + y as usize,
1600            };
1601            for x in 0..bounds.w {
1602                let src_x = match fit {
1603                    ImageFit::Stretch => {
1604                        src_rect.x.max(0) as usize
1605                            + ((x as u64 * src_rect.w as u64) / bounds.w as u64) as usize
1606                    }
1607                    ImageFit::Center => src_rect.x.max(0) as usize + x as usize,
1608                };
1609                let idx = src_y.saturating_mul(src_w).saturating_add(src_x);
1610                if let Some(raw) = image.pixels.get(idx) {
1611                    let color = Rgb565::new(
1612                        ((raw >> 11) & 0x1F) as u8,
1613                        ((raw >> 5) & 0x3F) as u8,
1614                        (raw & 0x1F) as u8,
1615                    );
1616                    self.pixel(bounds.x + x as i32, bounds.y + y as i32, color, 255)?;
1617                }
1618            }
1619        }
1620        Ok(())
1621    }
1622
1623    pub fn draw_image_transformed(
1624        &mut self,
1625        rect: Rect,
1626        image: ImageRef<'_>,
1627        scale: f32,
1628        rotation_deg: f32,
1629    ) -> Result<(), D::Error> {
1630        if rect.is_empty() || image.width == 0 || image.height == 0 || scale <= 0.0 {
1631            return Ok(());
1632        }
1633        let cx = rect.x + rect.w as i32 / 2;
1634        let cy = rect.y + rect.h as i32 / 2;
1635        let rad = rotation_deg.to_radians();
1636        let cos_r = rad.cos();
1637        let sin_r = rad.sin();
1638        let src_w = image.width as usize;
1639        let src_cx = image.width as f32 / 2.0;
1640        let src_cy = image.height as f32 / 2.0;
1641        for y in rect.y..rect.bottom() {
1642            for x in rect.x..rect.right() {
1643                let dx = (x - cx) as f32 / scale;
1644                let dy = (y - cy) as f32 / scale;
1645                let sx = cos_r * dx + sin_r * dy + src_cx;
1646                let sy = -sin_r * dx + cos_r * dy + src_cy;
1647                if sx < 0.0 || sy < 0.0 || sx >= image.width as f32 || sy >= image.height as f32 {
1648                    continue;
1649                }
1650                let idx = (sy as usize)
1651                    .saturating_mul(src_w)
1652                    .saturating_add(sx as usize);
1653                if let Some(raw) = image.pixels.get(idx) {
1654                    let color = Rgb565::new(
1655                        ((raw >> 11) & 0x1F) as u8,
1656                        ((raw >> 5) & 0x3F) as u8,
1657                        (raw & 0x1F) as u8,
1658                    );
1659                    self.pixel(x, y, color, 255)?;
1660                }
1661            }
1662        }
1663        Ok(())
1664    }
1665
1666    pub fn fill_rect_masked(
1667        &mut self,
1668        rect: Rect,
1669        color: Rgb565,
1670        mask: fn(i32, i32) -> bool,
1671    ) -> Result<(), D::Error> {
1672        let draw = self.visible_rect(rect);
1673        if draw.is_empty() {
1674            return Ok(());
1675        }
1676        for y in draw.y..draw.bottom() {
1677            for x in draw.x..draw.right() {
1678                if mask(x, y) {
1679                    self.pixel(x, y, color, 255)?;
1680                }
1681            }
1682        }
1683        Ok(())
1684    }
1685
1686    pub fn draw_text_model_in(&mut self, rect: Rect, text: text::Text<'_>) -> Result<(), D::Error> {
1687        if rect.is_empty() || text.lines.is_empty() {
1688            return Ok(());
1689        }
1690
1691        let metrics = text.metrics(rect.w);
1692        let max_line_height = text
1693            .lines
1694            .iter()
1695            .map(|line| line.max_line_height())
1696            .max()
1697            .unwrap_or(CHAR_HEIGHT);
1698        let line_step = max_line_height + text.line_spacing as u32;
1699        let mut y = match text.vertical_align {
1700            VerticalAlign::Top => rect.y,
1701            VerticalAlign::Middle => rect.y + rect.h.saturating_sub(metrics.height) as i32 / 2,
1702            VerticalAlign::Bottom => rect.y + rect.h.saturating_sub(metrics.height) as i32,
1703        };
1704        for line in text.lines {
1705            let align = if line.align == TextAlign::Left {
1706                text.align
1707            } else {
1708                line.align
1709            };
1710            let line = text::Line { align, ..*line };
1711
1712            let mut start = 0;
1713            let char_count = line.char_count();
1714            if char_count == 0 {
1715                y += line_step as i32;
1716                continue;
1717            }
1718            while start < char_count {
1719                if y >= rect.bottom() {
1720                    return Ok(());
1721                }
1722                let (len, consumed_newline) = line.segment_len_at(start, rect.w, text.wrap);
1723                self.draw_line_segment_in(
1724                    Rect::new(rect.x, y, rect.w, max_line_height),
1725                    line,
1726                    start,
1727                    len,
1728                )?;
1729                y += line_step as i32;
1730                start += len + usize::from(consumed_newline);
1731                if len == 0 && !consumed_newline {
1732                    break;
1733                }
1734            }
1735        }
1736
1737        Ok(())
1738    }
1739
1740    pub fn text_metrics(text: &str) -> TextMetrics {
1741        Self::text_metrics_with_font(text, FontId::Tiny3x5)
1742    }
1743
1744    pub fn text_metrics_with_font(text: &str, font: FontId) -> TextMetrics {
1745        TextMetrics {
1746            width: text.chars().count() as u32 * font.advance(),
1747            height: font.line_height(),
1748        }
1749    }
1750
1751    pub fn text_metrics_wrapped(text: &str, max_width: u32, wrap: TextWrap) -> TextMetrics {
1752        Self::text_metrics_wrapped_with_font(text, max_width, wrap, FontId::Tiny3x5)
1753    }
1754
1755    pub fn text_metrics_wrapped_with_font(
1756        text: &str,
1757        max_width: u32,
1758        wrap: TextWrap,
1759        font: FontId,
1760    ) -> TextMetrics {
1761        let max_chars = (max_width / font.advance()).max(1) as usize;
1762        let lines = count_lines(text, max_chars, wrap).max(1);
1763        let widest = widest_line(text, max_chars, wrap) as u32 * font.advance();
1764        TextMetrics {
1765            width: widest.min(max_width),
1766            height: lines as u32 * font.line_height() + lines.saturating_sub(1) as u32,
1767        }
1768    }
1769
1770    #[allow(clippy::too_many_arguments)]
1771    fn draw_chars_with_font(
1772        &mut self,
1773        x: i32,
1774        y: i32,
1775        text: &str,
1776        start: usize,
1777        len: usize,
1778        color: Rgb565,
1779        opacity: u8,
1780        font: FontId,
1781        kerning: bool,
1782    ) -> Result<(), D::Error> {
1783        let advance = font.advance() as i32;
1784        let mut cursor_x = x;
1785        let mut prev: Option<char> = None;
1786        for ch in text.chars().skip(start).take(len) {
1787            self.draw_char_with_font(cursor_x, y, ch, color, opacity, font)?;
1788            cursor_x += advance + kerning_adjust(prev, ch, kerning);
1789            prev = Some(ch);
1790        }
1791        Ok(())
1792    }
1793
1794    fn substring_width(
1795        &self,
1796        text: &str,
1797        start: usize,
1798        len: usize,
1799        font: FontId,
1800        kerning: bool,
1801    ) -> u32 {
1802        let mut width = 0u32;
1803        let mut prev = None;
1804        for ch in text.chars().skip(start).take(len) {
1805            width = width.saturating_add(font.advance());
1806            let adjust = kerning_adjust(prev, ch, kerning);
1807            if adjust < 0 {
1808                width = width.saturating_sub((-adjust) as u32);
1809            } else {
1810                width = width.saturating_add(adjust as u32);
1811            }
1812            prev = Some(ch);
1813        }
1814        width
1815    }
1816
1817    fn draw_line_segment_in(
1818        &mut self,
1819        rect: Rect,
1820        line: text::Line<'_>,
1821        start: usize,
1822        len: usize,
1823    ) -> Result<(), D::Error> {
1824        if rect.is_empty() || len == 0 {
1825            return Ok(());
1826        }
1827
1828        let line_w = self.line_segment_width(line, start, len);
1829        let x = match line.align {
1830            TextAlign::Left => rect.x,
1831            TextAlign::Center => rect.x + rect.w.saturating_sub(line_w) as i32 / 2,
1832            TextAlign::Right => rect.x + rect.w.saturating_sub(line_w) as i32,
1833        };
1834
1835        let old_clip = self.clip;
1836        self.clip = self.clip.intersection(rect);
1837        let result = self.draw_span_chars(x, rect.y, line, start, len);
1838        self.clip = old_clip;
1839        result
1840    }
1841
1842    fn draw_span_chars(
1843        &mut self,
1844        x: i32,
1845        y: i32,
1846        line: text::Line<'_>,
1847        start: usize,
1848        len: usize,
1849    ) -> Result<(), D::Error> {
1850        let mut cursor_x = x;
1851        for (idx, (ch, style)) in line
1852            .spans
1853            .iter()
1854            .flat_map(|span| span.content.chars().map(move |ch| (ch, span.style)))
1855            .enumerate()
1856        {
1857            if idx < start {
1858                continue;
1859            }
1860            if idx >= start + len {
1861                break;
1862            }
1863            if ch != '\n' {
1864                self.draw_char_with_font(cursor_x, y, ch, style.color, 255, style.font)?;
1865                cursor_x += style.font.advance() as i32;
1866            }
1867        }
1868        Ok(())
1869    }
1870
1871    fn line_segment_width(&self, line: text::Line<'_>, start: usize, len: usize) -> u32 {
1872        line.spans
1873            .iter()
1874            .flat_map(|span| span.content.chars().map(move |ch| (ch, span.style.font)))
1875            .enumerate()
1876            .filter_map(|(idx, (ch, font))| {
1877                if idx < start || idx >= start + len || ch == '\n' {
1878                    None
1879                } else {
1880                    Some(font.advance())
1881                }
1882            })
1883            .sum()
1884    }
1885
1886    fn draw_char_with_font(
1887        &mut self,
1888        x: i32,
1889        y: i32,
1890        ch: char,
1891        color: Rgb565,
1892        opacity: u8,
1893        font: FontId,
1894    ) -> Result<(), D::Error> {
1895        let glyph = glyph_rows(font, ch);
1896        let layer = self.current_layer();
1897        let fast_spans = opacity == 255
1898            && layer.opacity == 255
1899            && self.current_transform().is_identity()
1900            && layer.blend == BlendMode::Normal;
1901
1902        match font {
1903            FontId::Tiny3x5 | FontId::Medium4x7 | FontId::Custom(_) => {
1904                for (row, bits) in glyph.iter().enumerate() {
1905                    let ry = y + row as i32;
1906                    if fast_spans && *bits == 0b111 {
1907                        self.fill_rect(Rect::new(x, ry, 3, 1), color)?;
1908                    } else if fast_spans && *bits == 0b110 {
1909                        self.fill_rect(Rect::new(x, ry, 2, 1), color)?;
1910                    } else if fast_spans && *bits == 0b011 {
1911                        self.fill_rect(Rect::new(x + 1, ry, 2, 1), color)?;
1912                    } else {
1913                        for col in 0..3 {
1914                            if bits & (1 << (2 - col)) != 0 {
1915                                self.pixel(x + col, ry, color, opacity)?;
1916                            }
1917                        }
1918                    }
1919                }
1920            }
1921            FontId::Scaled6x10 => {
1922                for (row, bits) in glyph.iter().enumerate() {
1923                    for col in 0..3 {
1924                        if bits & (1 << (2 - col)) != 0 {
1925                            let px = x + (col * 2);
1926                            let py = y + (row as i32 * 2);
1927                            self.pixel(px, py, color, opacity)?;
1928                            self.pixel(px + 1, py, color, opacity)?;
1929                            self.pixel(px, py + 1, color, opacity)?;
1930                            self.pixel(px + 1, py + 1, color, opacity)?;
1931                        }
1932                    }
1933                }
1934            }
1935        }
1936        Ok(())
1937    }
1938
1939    fn pixel(&mut self, x: i32, y: i32, color: Rgb565, opacity: u8) -> Result<(), D::Error> {
1940        let (x, y) = self.current_transform().apply(x, y);
1941        if !self.clip.contains(x, y) {
1942            return Ok(());
1943        }
1944        if let Some(dirty) = self.dirty {
1945            if !dirty.contains(x, y) {
1946                return Ok(());
1947            }
1948        }
1949        let layer = self.current_layer();
1950        let combined_opacity = ((opacity as u16 * layer.opacity as u16) / 255) as u8;
1951        // The compositor policy (`Dither` vs `Blend`) decides how the pixel
1952        // lands: ordered dither for write-only targets, true alpha blend for
1953        // readback-capable ones. Zero-cost — resolved by `C` at monomorphization.
1954        C::plot(
1955            self.target,
1956            x,
1957            y,
1958            color,
1959            combined_opacity,
1960            layer.blend,
1961            layer.backdrop,
1962        )
1963    }
1964
1965    fn visible_rect(&self, rect: Rect) -> Rect {
1966        let mut draw = rect.intersection(self.clip);
1967        if let Some(dirty) = self.dirty {
1968            draw = draw.intersection(dirty);
1969        }
1970        draw
1971    }
1972
1973    fn current_transform(&self) -> Transform2D {
1974        self.transform_stack[self.transform_len - 1]
1975    }
1976
1977    fn current_layer(&self) -> LayerState {
1978        self.layer_stack[self.layer_len - 1]
1979    }
1980
1981    fn stroke_opacity(&self, style: StrokeStyle) -> u8 {
1982        if !style.antialias || matches!(style.antialias_mode, AntiAliasMode::None) {
1983            return 255;
1984        }
1985        match style.antialias_mode {
1986            AntiAliasMode::None => 255,
1987            AntiAliasMode::Coverage => match self.quality {
1988                RenderQuality::Low => 96,
1989                RenderQuality::Medium => 160,
1990                RenderQuality::High => 220,
1991            },
1992            AntiAliasMode::Subpixel => {
1993                if self.backend_caps.supports_subpixel {
1994                    match self.quality {
1995                        RenderQuality::Low => 128,
1996                        RenderQuality::Medium => 192,
1997                        RenderQuality::High => 240,
1998                    }
1999                } else {
2000                    match self.quality {
2001                        RenderQuality::Low => 96,
2002                        RenderQuality::Medium => 160,
2003                        RenderQuality::High => 220,
2004                    }
2005                }
2006            }
2007        }
2008    }
2009}
2010
2011impl<'a, D, C> RenderCtx<'a, D, C>
2012where
2013    D: DrawTarget<Color = Rgb565> + PixelRead,
2014    C: Compositor<D>,
2015{
2016    /// Alpha-composite `color` over whatever is already at `(x, y)` in the
2017    /// destination, using true per-pixel blending (`lerp_rgb565`) rather
2018    /// than the dithered approximation `pixel()` uses.
2019    fn pixel_blended(&mut self, x: i32, y: i32, color: Rgb565, alpha: u8) -> Result<(), D::Error> {
2020        let (x, y) = self.current_transform().apply(x, y);
2021        if !self.clip.contains(x, y) {
2022            return Ok(());
2023        }
2024        if let Some(dirty) = self.dirty {
2025            if !dirty.contains(x, y) {
2026                return Ok(());
2027            }
2028        }
2029        let layer = self.current_layer();
2030        let combined_alpha = ((alpha as u16 * layer.opacity as u16) / 255) as u8;
2031        if combined_alpha == 0 {
2032            return Ok(());
2033        }
2034        let backdrop = self.target.get_pixel(Point::new(x, y));
2035        let blended = lerp_rgb565(backdrop, color, combined_alpha);
2036        let blended = apply_blend_mode(blended, layer.blend, layer.backdrop);
2037        self.target.draw_iter([Pixel(Point::new(x, y), blended)])
2038    }
2039
2040    /// Like [`RenderCtx::fill_rect_alpha`], but alpha-composites against the
2041    /// destination's real current pixels instead of dithering.
2042    pub fn fill_rect_true_alpha(
2043        &mut self,
2044        rect: Rect,
2045        color: Rgb565,
2046        alpha: u8,
2047    ) -> Result<(), D::Error> {
2048        self.fill_rounded_rect_true_alpha(rect, 0, color, alpha)
2049    }
2050
2051    /// Like [`RenderCtx::fill_rounded_rect_alpha`], but alpha-composites
2052    /// against the destination's real current pixels instead of dithering.
2053    pub fn fill_rounded_rect_true_alpha(
2054        &mut self,
2055        rect: Rect,
2056        radius: u8,
2057        color: Rgb565,
2058        alpha: u8,
2059    ) -> Result<(), D::Error> {
2060        let draw = self.visible_rect(rect);
2061        if draw.is_empty() || alpha == 0 {
2062            return Ok(());
2063        }
2064        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
2065
2066        for y in draw.y..draw.bottom() {
2067            for x in draw.x..draw.right() {
2068                if !in_rounded_rect(x, y, rect, radius) {
2069                    continue;
2070                }
2071                self.pixel_blended(x, y, color, alpha)?;
2072            }
2073        }
2074        Ok(())
2075    }
2076
2077    /// Fill a rectangle with an 8-bit alpha mask and solid color.
2078    pub fn fill_rect_alpha_mask(
2079        &mut self,
2080        rect: Rect,
2081        mask: &[u8],
2082        mask_stride: usize,
2083        color: Rgb565,
2084        opacity: u8,
2085    ) -> Result<(), D::Error> {
2086        let draw = self.visible_rect(rect);
2087        if draw.is_empty() || opacity == 0 || mask_stride == 0 {
2088            return Ok(());
2089        }
2090        for y in draw.y..draw.bottom() {
2091            let my = (y - rect.y) as usize;
2092            for x in draw.x..draw.right() {
2093                let mx = (x - rect.x) as usize;
2094                let idx = my * mask_stride + mx;
2095                if let Some(&m_val) = mask.get(idx) {
2096                    if m_val > 0 {
2097                        let pix_opacity = ((m_val as u16 * opacity as u16) / 255) as u8;
2098                        self.pixel(x, y, color, pix_opacity)?;
2099                    }
2100                }
2101            }
2102        }
2103        Ok(())
2104    }
2105
2106    /// Fill a rounded rectangle with an [`AlphaLinearGradient`].
2107    pub fn fill_rounded_rect_alpha_gradient(
2108        &mut self,
2109        rect: Rect,
2110        radius: u8,
2111        gradient: &AlphaLinearGradient,
2112        opacity: u8,
2113    ) -> Result<(), D::Error> {
2114        let draw = self.visible_rect(rect);
2115        if draw.is_empty() || opacity == 0 {
2116            return Ok(());
2117        }
2118        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
2119        let denom = match gradient.direction {
2120            GradientDirection::Horizontal => rect.w.saturating_sub(1).max(1),
2121            GradientDirection::Vertical => rect.h.saturating_sub(1).max(1),
2122        };
2123
2124        for y in draw.y..draw.bottom() {
2125            for x in draw.x..draw.right() {
2126                if !in_rounded_rect(x, y, rect, radius) {
2127                    continue;
2128                }
2129                let numer = match gradient.direction {
2130                    GradientDirection::Horizontal => (x - rect.x).max(0) as u32,
2131                    GradientDirection::Vertical => (y - rect.y).max(0) as u32,
2132                }
2133                .min(denom);
2134                let t = ((numer * 255) / denom) as u8;
2135                let (color, grad_alpha) = gradient.sample(t);
2136                let combined_alpha = ((grad_alpha as u16 * opacity as u16) / 255) as u8;
2137                self.pixel(x, y, color, combined_alpha)?;
2138            }
2139        }
2140        Ok(())
2141    }
2142
2143    /// Fill a rounded rectangle with an [`AlphaRadialGradient`].
2144    pub fn fill_rounded_rect_radial_gradient(
2145        &mut self,
2146        rect: Rect,
2147        radius: u8,
2148        gradient: &AlphaRadialGradient,
2149        opacity: u8,
2150    ) -> Result<(), D::Error> {
2151        let draw = self.visible_rect(rect);
2152        if draw.is_empty() || opacity == 0 {
2153            return Ok(());
2154        }
2155        let radius = radius.min((rect.w.min(rect.h) / 2) as u8);
2156        let cx = rect.x as f32 + rect.w as f32 * gradient.center_x;
2157        let cy = rect.y as f32 + rect.h as f32 * gradient.center_y;
2158
2159        for y in draw.y..draw.bottom() {
2160            let dy = y as f32 - cy;
2161            for x in draw.x..draw.right() {
2162                if !in_rounded_rect(x, y, rect, radius) {
2163                    continue;
2164                }
2165                let dx = x as f32 - cx;
2166                let dist = (dx * dx + dy * dy).sqrt();
2167                let (color, grad_alpha) = gradient.sample_at_dist(dist);
2168                let combined_alpha = ((grad_alpha as u16 * opacity as u16) / 255) as u8;
2169                self.pixel(x, y, color, combined_alpha)?;
2170            }
2171        }
2172        Ok(())
2173    }
2174
2175    /// Render a soft drop shadow around a rounded rectangle.
2176    pub fn draw_drop_shadow(
2177        &mut self,
2178        rect: Rect,
2179        _radius: u8,
2180        shadow_color: Rgb565,
2181        shadow_opacity: u8,
2182        shadow_spread: u8,
2183        blur_radius: u8,
2184    ) -> Result<(), D::Error> {
2185        if shadow_opacity == 0 {
2186            return Ok(());
2187        }
2188        let margin = (shadow_spread as i32) + (blur_radius as i32);
2189        let shadow_rect = Rect::new(
2190            rect.x - margin,
2191            rect.y - margin,
2192            rect.w + (margin as u32 * 2),
2193            rect.h + (margin as u32 * 2),
2194        );
2195        let draw = self.visible_rect(shadow_rect);
2196        if draw.is_empty() {
2197            return Ok(());
2198        }
2199
2200        for y in draw.y..draw.bottom() {
2201            for x in draw.x..draw.right() {
2202                let dx = if x < rect.x {
2203                    rect.x - x
2204                } else if x >= rect.right() {
2205                    x - rect.right() + 1
2206                } else {
2207                    0
2208                };
2209                let dy = if y < rect.y {
2210                    rect.y - y
2211                } else if y >= rect.bottom() {
2212                    y - rect.bottom() + 1
2213                } else {
2214                    0
2215                };
2216
2217                let dist = ((dx * dx + dy * dy) as f32).sqrt();
2218                if dist > margin as f32 {
2219                    continue;
2220                }
2221
2222                let factor = (1.0 - (dist / (margin as f32 + 1.0))).clamp(0.0, 1.0);
2223                let alpha = (shadow_opacity as f32 * factor) as u8;
2224                if alpha > 0 {
2225                    self.pixel(x, y, shadow_color, alpha)?;
2226                }
2227            }
2228        }
2229        Ok(())
2230    }
2231
2232    /// Draw a UI card fill with an alpha gradient background and soft drop shadow.
2233    pub fn draw_card_fill(
2234        &mut self,
2235        rect: Rect,
2236        radius: u8,
2237        bg_gradient: &AlphaLinearGradient,
2238        shadow_color: Rgb565,
2239        shadow_opacity: u8,
2240        blur_radius: u8,
2241    ) -> Result<(), D::Error> {
2242        if shadow_opacity > 0 && blur_radius > 0 {
2243            self.draw_drop_shadow(rect, radius, shadow_color, shadow_opacity, 2, blur_radius)?;
2244        }
2245        self.fill_rounded_rect_alpha_gradient(rect, radius, bg_gradient, 255)
2246    }
2247
2248    /// Render a tile with optional wrapping mode.
2249    pub fn draw_tile(
2250        &mut self,
2251        rect: Rect,
2252        tile: TileRef<'_>,
2253        opacity: u8,
2254    ) -> Result<(), D::Error> {
2255        self.draw_tile_transformed_ssaa(rect, tile, Transform2D::IDENTITY, opacity, false)
2256    }
2257
2258    /// Render a transformed tile with optional wrapping mode.
2259    pub fn draw_tile_transformed(
2260        &mut self,
2261        rect: Rect,
2262        tile: TileRef<'_>,
2263        transform: Transform2D,
2264        opacity: u8,
2265    ) -> Result<(), D::Error> {
2266        self.draw_tile_transformed_ssaa(rect, tile, transform, opacity, false)
2267    }
2268
2269    /// Render a transformed tile with 2xSSAA (2x Super-Sampling Anti-Aliasing).
2270    pub fn draw_tile_transformed_ssaa(
2271        &mut self,
2272        rect: Rect,
2273        tile: TileRef<'_>,
2274        transform: Transform2D,
2275        opacity: u8,
2276        enable_ssaa: bool,
2277    ) -> Result<(), D::Error> {
2278        let draw = self.visible_rect(rect);
2279        if draw.is_empty() || opacity == 0 || tile.width == 0 || tile.height == 0 {
2280            return Ok(());
2281        }
2282
2283        let inv_transform = match transform.inverse() {
2284            Some(inv) => inv,
2285            None => return Ok(()),
2286        };
2287
2288        let cx = rect.x as f32 + rect.w as f32 * 0.5;
2289        let cy = rect.y as f32 + rect.h as f32 * 0.5;
2290
2291        let offsets = [
2292            (0.25f32, 0.25f32),
2293            (0.75f32, 0.25f32),
2294            (0.25f32, 0.75f32),
2295            (0.75f32, 0.75f32),
2296        ];
2297
2298        for y in draw.y..draw.bottom() {
2299            for x in draw.x..draw.right() {
2300                if !enable_ssaa {
2301                    let px = (x as f32 + 0.5) - cx;
2302                    let py = (y as f32 + 0.5) - cy;
2303                    let (tx, ty) = inv_transform.apply_f32(px, py);
2304                    let u = (tx + tile.width as f32 * 0.5).floor() as i32;
2305                    let v = (ty + tile.height as f32 * 0.5).floor() as i32;
2306                    if let Some(col) = tile.get_pixel(u, v) {
2307                        self.pixel(x, y, col, opacity)?;
2308                    }
2309                } else {
2310                    let mut r_sum = 0u32;
2311                    let mut g_sum = 0u32;
2312                    let mut b_sum = 0u32;
2313                    let mut weight = 0u32;
2314
2315                    for &(ox, oy) in &offsets {
2316                        let px = (x as f32 + ox) - cx;
2317                        let py = (y as f32 + oy) - cy;
2318                        let (tx, ty) = inv_transform.apply_f32(px, py);
2319                        let u = (tx + tile.width as f32 * 0.5).floor() as i32;
2320                        let v = (ty + tile.height as f32 * 0.5).floor() as i32;
2321                        if let Some(col) = tile.get_pixel(u, v) {
2322                            r_sum += col.r() as u32;
2323                            g_sum += col.g() as u32;
2324                            b_sum += col.b() as u32;
2325                            weight += 1;
2326                        }
2327                    }
2328
2329                    if let Some(w) = (weight > 0).then_some(weight) {
2330                        let r_avg = (r_sum / w) as u8;
2331                        let g_avg = (g_sum / w) as u8;
2332                        let b_avg = (b_sum / w) as u8;
2333                        let color = Rgb565::new(r_avg, g_avg, b_avg);
2334                        let pix_opacity = ((weight * opacity as u32 + 2) / 4) as u8;
2335                        self.pixel(x, y, color, pix_opacity)?;
2336                    }
2337                }
2338            }
2339        }
2340        Ok(())
2341    }
2342
2343    /// Render a transformed image/tile with optional 2xSSAA.
2344    pub fn draw_image_transformed_ssaa(
2345        &mut self,
2346        rect: Rect,
2347        image: ImageRef<'_>,
2348        scale: f32,
2349        rotation_deg: f32,
2350        opacity: u8,
2351        enable_ssaa: bool,
2352    ) -> Result<(), D::Error> {
2353        let transform = Transform2D::rotation(rotation_deg).then(Transform2D::scale(scale, scale));
2354        let tile = TileRef::from_image(image, TileMode::None);
2355        self.draw_tile_transformed_ssaa(rect, tile, transform, opacity, enable_ssaa)
2356    }
2357}
2358
2359fn should_draw_at_opacity(x: i32, y: i32, opacity: u8) -> bool {
2360    if opacity == 255 {
2361        return true;
2362    }
2363    if opacity == 0 {
2364        return false;
2365    }
2366    let bayer4 = [
2367        [0u8, 8, 2, 10],
2368        [12, 4, 14, 6],
2369        [3, 11, 1, 9],
2370        [15, 7, 13, 5],
2371    ];
2372    let threshold = ((opacity as u16 * 16) / 255) as u8;
2373    let sample = bayer4[(y as usize) & 3][(x as usize) & 3];
2374    sample < threshold.max(1)
2375}
2376
2377fn lerp_rgb565(a: Rgb565, b: Rgb565, t: u8) -> Rgb565 {
2378    let t = t as u16;
2379    let inv = 255u16.saturating_sub(t);
2380    let r = ((a.r() as u16 * inv) + (b.r() as u16 * t)) / 255;
2381    let g = ((a.g() as u16 * inv) + (b.g() as u16 * t)) / 255;
2382    let bb = ((a.b() as u16 * inv) + (b.b() as u16 * t)) / 255;
2383    Rgb565::new(r as u8, g as u8, bb as u8)
2384}
2385
2386#[inline]
2387fn normalize_angle_deg(mut deg: f32) -> f32 {
2388    while deg < 0.0 {
2389        deg += 360.0;
2390    }
2391    while deg >= 360.0 {
2392        deg -= 360.0;
2393    }
2394    deg
2395}
2396
2397#[inline]
2398fn ccw_distance_deg(from: f32, to: f32) -> f32 {
2399    let mut d = normalize_angle_deg(to) - normalize_angle_deg(from);
2400    if d < 0.0 {
2401        d += 360.0;
2402    }
2403    d
2404}
2405
2406fn apply_blend_mode(src: Rgb565, mode: BlendMode, backdrop: Rgb565) -> Rgb565 {
2407    match mode {
2408        BlendMode::Normal => src,
2409        BlendMode::Add => Rgb565::new(
2410            src.r().saturating_add(backdrop.r()),
2411            src.g().saturating_add(backdrop.g()),
2412            src.b().saturating_add(backdrop.b()),
2413        ),
2414        BlendMode::Multiply => Rgb565::new(
2415            ((src.r() as u16 * backdrop.r() as u16) / 31) as u8,
2416            ((src.g() as u16 * backdrop.g() as u16) / 63) as u8,
2417            ((src.b() as u16 * backdrop.b() as u16) / 31) as u8,
2418        ),
2419        BlendMode::Screen => Rgb565::new(
2420            (31 - ((31 - src.r() as u16) * (31 - backdrop.r() as u16) / 31)) as u8,
2421            (63 - ((63 - src.g() as u16) * (63 - backdrop.g() as u16) / 63)) as u8,
2422            (31 - ((31 - src.b() as u16) * (31 - backdrop.b() as u16) / 31)) as u8,
2423        ),
2424    }
2425}
2426
2427fn in_rounded_rect(x: i32, y: i32, rect: Rect, radius: u8) -> bool {
2428    if rect.is_empty() {
2429        return false;
2430    }
2431    let radius = radius as i32;
2432    if radius <= 0 {
2433        return rect.contains(x, y);
2434    }
2435
2436    let left = rect.x;
2437    let top = rect.y;
2438    let right = rect.right() - 1;
2439    let bottom = rect.bottom() - 1;
2440    let inner_left = left + radius;
2441    let inner_right = right - radius;
2442    let inner_top = top + radius;
2443    let inner_bottom = bottom - radius;
2444
2445    if (x >= inner_left && x <= inner_right) || (y >= inner_top && y <= inner_bottom) {
2446        return rect.contains(x, y);
2447    }
2448
2449    let (cx, cy) = if x < inner_left && y < inner_top {
2450        (inner_left, inner_top)
2451    } else if x > inner_right && y < inner_top {
2452        (inner_right, inner_top)
2453    } else if x < inner_left && y > inner_bottom {
2454        (inner_left, inner_bottom)
2455    } else if x > inner_right && y > inner_bottom {
2456        (inner_right, inner_bottom)
2457    } else {
2458        return rect.contains(x, y);
2459    };
2460
2461    let dx = x - cx;
2462    let dy = y - cy;
2463    dx * dx + dy * dy <= radius * radius
2464}
2465
2466fn line_len_at(text: &str, start: usize, max_chars: usize, wrap: TextWrap) -> (usize, bool) {
2467    let mut len = 0;
2468    let limit = match wrap {
2469        TextWrap::None => usize::MAX,
2470        TextWrap::Character => max_chars.max(1),
2471        TextWrap::Word => max_chars.max(1),
2472    };
2473    let mut last_ws_break = None;
2474
2475    for ch in text.chars().skip(start) {
2476        if ch == '\n' {
2477            return (len, true);
2478        }
2479        if matches!(wrap, TextWrap::Word) && ch.is_whitespace() {
2480            last_ws_break = Some(len + 1);
2481        }
2482        if len >= limit {
2483            if matches!(wrap, TextWrap::Word) {
2484                if let Some(idx) = last_ws_break {
2485                    return (idx, false);
2486                }
2487            }
2488            return (len, false);
2489        }
2490        len += 1;
2491    }
2492
2493    (len, false)
2494}
2495
2496fn count_lines(text: &str, max_chars: usize, wrap: TextWrap) -> usize {
2497    if text.is_empty() {
2498        return 1;
2499    }
2500    let char_count = text.chars().count();
2501    let mut lines = 0;
2502    let mut start = 0;
2503    while start < char_count {
2504        let (len, consumed_newline) = line_len_at(text, start, max_chars, wrap);
2505        lines += 1;
2506        start += len + usize::from(consumed_newline);
2507        if len == 0 && !consumed_newline {
2508            break;
2509        }
2510    }
2511    lines
2512}
2513
2514fn widest_line(text: &str, max_chars: usize, wrap: TextWrap) -> usize {
2515    let char_count = text.chars().count();
2516    let mut widest = 0;
2517    let mut start = 0;
2518    while start < char_count {
2519        let (len, consumed_newline) = line_len_at(text, start, max_chars, wrap);
2520        widest = widest.max(len);
2521        start += len + usize::from(consumed_newline);
2522        if len == 0 && !consumed_newline {
2523            break;
2524        }
2525    }
2526    widest
2527}
2528
2529fn kerning_adjust(prev: Option<char>, next: char, enabled: bool) -> i32 {
2530    if !enabled {
2531        return 0;
2532    }
2533    match (prev, next) {
2534        (Some('A'), 'V') | (Some('A'), 'W') | (Some('T'), 'o') | (Some('L'), 'T') => -1,
2535        _ => 0,
2536    }
2537}
2538
2539#[cfg(test)]
2540mod tests {
2541    use super::*;
2542
2543    #[test]
2544    fn test_transform2d_is_identity() {
2545        let id = Transform2D::IDENTITY;
2546        assert!(id.is_identity());
2547        assert_eq!(id.apply(10, 20), (10, 20));
2548
2549        let tr = Transform2D::translation(5.0, 10.0);
2550        assert!(!tr.is_identity());
2551        assert_eq!(tr.apply(10, 20), (15, 30));
2552    }
2553
2554    #[test]
2555    fn test_fill_circle_scanline_spans_correctness() {
2556        let mut buf = crate::test_buffer::TestBuffer::new(50, 50);
2557        let mut ctx = RenderCtx::new(&mut buf, Rect::new(0, 0, 50, 50));
2558
2559        // Draw a circle of radius 10 at center (25, 25)
2560        ctx.fill_circle(25, 25, 10, Rgb565::RED).unwrap();
2561
2562        // Center pixel must be red
2563        assert_eq!(buf.pixel_at(25, 25), Some(Rgb565::RED));
2564
2565        // Points inside radius 10 must be red (e.g. 25 + 7, 25 + 7 => dist^2 = 98 <= 100)
2566        assert_eq!(buf.pixel_at(32, 32), Some(Rgb565::RED));
2567
2568        // Points outside radius 10 must remain black (e.g. 25 + 11, 25)
2569        assert_eq!(buf.pixel_at(37, 25), Some(Rgb565::BLACK));
2570        assert_eq!(buf.pixel_at(25, 37), Some(Rgb565::BLACK));
2571    }
2572}