use std::collections::HashMap;
use std::rc::Rc;
use mgui_core::image::ImageData;
use mgui_core::paint::{BlendMode as CoreBlendMode, PaintCommand, TextureMode, Vertex};
use mgui_core::{Color, PaintList, Rect};
use tiny_skia::{
BlendMode, FillRule, FilterQuality, GradientStop, LinearGradient, Mask, Paint, PathBuilder, Pattern, Pixmap,
PixmapPaint, PremultipliedColorU8, RadialGradient, SpreadMode, Transform,
};
use crate::layers::{rounded_rect_path, to_skia_rect};
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct GlyphCacheKey {
pub generation: u64,
pub uv: [u32; 4],
pub color: [u32; 4],
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ImageTintKey {
pub texture_id: u32,
pub color: [u32; 4],
pub mask: bool,
}
enum ClipEntry {
Rect(Rect),
Path(tiny_skia::Path),
}
pub(crate) struct Raster<'a> {
pub target: &'a mut Pixmap,
pub dpr: f32,
clips: Vec<ClipEntry>,
mask: Option<Mask>,
pub textures: &'a HashMap<u32, (Rc<ImageData>, Pixmap)>,
pub glyph_cache: &'a mut HashMap<GlyphCacheKey, Pixmap>,
pub tint_cache: &'a mut HashMap<ImageTintKey, Pixmap>,
pub atlas_generation: u64,
blend: CoreBlendMode,
blend_stack: Vec<CoreBlendMode>,
}
impl<'a> Raster<'a> {
pub fn new(
target: &'a mut Pixmap,
dpr: f32,
textures: &'a HashMap<u32, (Rc<ImageData>, Pixmap)>,
glyph_cache: &'a mut HashMap<GlyphCacheKey, Pixmap>,
tint_cache: &'a mut HashMap<ImageTintKey, Pixmap>,
atlas_generation: u64,
) -> Self {
Self {
target,
dpr,
clips: Vec::new(),
mask: None,
textures,
glyph_cache,
tint_cache,
atlas_generation,
blend: CoreBlendMode::Normal,
blend_stack: Vec::new(),
}
}
pub fn run(&mut self, list: &PaintList) {
for cmd in &list.commands {
self.draw(cmd);
}
}
fn draw(&mut self, cmd: &PaintCommand) {
match cmd {
PaintCommand::PushBlendMode(mode) => {
self.blend_stack.push(self.blend);
self.blend = *mode;
}
PaintCommand::PopBlendMode => {
self.blend = self.blend_stack.pop().unwrap_or(CoreBlendMode::Normal);
}
PaintCommand::Rect { rect, color, radius } => self.fill_rounded_rect(*rect, *color, *radius),
PaintCommand::BoxShadow { rect, color, radius, blur_radius } => {
self.fill_box_shadow(*rect, *color, *radius, *blur_radius)
}
PaintCommand::InsetShadow { rect, color, radius, blur_radius } => {
self.fill_inset_shadow(*rect, *color, *radius, *blur_radius)
}
PaintCommand::BackdropBlur { rect, radius, blur_radius, tint } => {
self.fill_backdrop_blur(*rect, *radius, *blur_radius, *tint)
}
PaintCommand::LinearGradient { rect, start, end, from, to, corner_radius } => {
let stops = vec![GradientStop::new(0.0, sk_color(*from)), GradientStop::new(1.0, sk_color(*to))];
if let Some(shader) = LinearGradient::new(
tiny_skia::Point::from_xy(start.x, start.y),
tiny_skia::Point::from_xy(end.x, end.y),
stops,
SpreadMode::Pad,
Transform::identity(),
) {
self.fill_rounded_rect_shader(*rect, *corner_radius, shader);
}
}
PaintCommand::RadialGradient { rect, center, radial_radius, from, to, corner_radius } => {
let stops = vec![GradientStop::new(0.0, sk_color(*from)), GradientStop::new(1.0, sk_color(*to))];
let c = tiny_skia::Point::from_xy(center.x, center.y);
if let Some(shader) =
RadialGradient::new(c, c, radial_radius.max(0.001), stops, SpreadMode::Pad, Transform::identity())
{
self.fill_rounded_rect_shader(*rect, *corner_radius, shader);
}
}
PaintCommand::Triangles { vertices, indices } => self.fill_triangles(vertices, indices),
PaintCommand::PushClip(rect) => {
self.clips.push(ClipEntry::Rect(*rect));
self.rebuild_mask();
}
PaintCommand::PopClip | PaintCommand::PopClipPath => {
self.clips.pop();
self.rebuild_mask();
}
PaintCommand::PushClipRRect { rect, radius } => {
match rounded_rect_path(*rect, *radius) {
Some(path) => self.clips.push(ClipEntry::Path(path)),
None => self.clips.push(ClipEntry::Rect(Rect::new(0.0, 0.0, 0.0, 0.0))),
}
self.rebuild_mask();
}
PaintCommand::PushClipPath { vertices, indices } => {
match triangles_path(vertices, indices) {
Some(path) => self.clips.push(ClipEntry::Path(path)),
None => self.clips.push(ClipEntry::Rect(Rect::new(0.0, 0.0, 0.0, 0.0))),
}
self.rebuild_mask();
}
PaintCommand::MaskRect { rect, texture_id, uv, alpha } => {
self.fill_alpha_mask(*rect, *texture_id, *uv, *alpha)
}
PaintCommand::TexturedRect { rect, color, uv, texture_id, mode } => {
self.fill_textured(*rect, *color, *uv, *texture_id, *mode)
}
PaintCommand::Text { text, range, font_size, color, position, max_width } => {
let mut expanded = PaintList::new();
mgui_text::text::paint_text_span(
text,
*range,
*font_size,
*color,
*position,
&mut expanded,
*max_width,
);
for c in &expanded.commands {
self.draw(c);
}
}
}
}
fn rebuild_mask(&mut self) {
if self.clips.is_empty() {
self.mask = None;
return;
}
let (w, h) = (self.target.width(), self.target.height());
let Some(mut mask) = Mask::new(w, h) else {
self.mask = None;
return;
};
mask.data_mut().fill(255);
let transform = Transform::from_scale(self.dpr, self.dpr);
for entry in &self.clips {
match entry {
ClipEntry::Rect(rect) => {
let Some(r) = to_skia_rect(*rect) else {
mask.data_mut().fill(0);
continue;
};
let path = PathBuilder::from_rect(r);
mask.intersect_path(&path, FillRule::Winding, false, transform);
}
ClipEntry::Path(path) => {
mask.intersect_path(path, FillRule::Winding, true, transform);
}
}
}
self.mask = Some(mask);
}
fn fill_rounded_rect(&mut self, rect: Rect, color: Color, radius: f32) {
if rect.width <= 0.0 || rect.height <= 0.0 {
return;
}
let mut paint = Paint::default();
paint.set_color_rgba8(enc(color.r), enc(color.g), enc(color.b), enc(color.a));
paint.anti_alias = true;
paint.blend_mode = self.sk_blend();
self.fill_rounded_rect_with(rect, radius, &paint);
}
fn fill_rounded_rect_shader(&mut self, rect: Rect, radius: f32, shader: tiny_skia::Shader) {
if rect.width <= 0.0 || rect.height <= 0.0 {
return;
}
let paint = Paint { shader, blend_mode: self.sk_blend(), anti_alias: true, ..Default::default() };
self.fill_rounded_rect_with(rect, radius, &paint);
}
fn sk_blend(&self) -> BlendMode {
match self.blend {
CoreBlendMode::Normal => BlendMode::SourceOver,
CoreBlendMode::Multiply => BlendMode::Multiply,
CoreBlendMode::Screen => BlendMode::Screen,
CoreBlendMode::Add => BlendMode::Plus,
}
}
fn fill_rounded_rect_with(&mut self, rect: Rect, radius: f32, paint: &Paint) {
let transform = Transform::from_scale(self.dpr, self.dpr);
let Raster { target, mask, .. } = self;
if radius <= 0.0 {
if let Some(r) = to_skia_rect(rect) {
target.fill_rect(r, paint, transform, mask.as_ref());
}
} else if let Some(path) = rounded_rect_path(rect, radius) {
target.fill_path(&path, paint, FillRule::Winding, transform, mask.as_ref());
}
}
fn fill_box_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur: f32) {
if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
return;
}
let dpr = self.dpr;
let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
if x1 <= x0 || y1 <= y0 {
return;
}
let (pw, ph) = (x1 - x0, y1 - y0);
let Some(mut shadow) = Pixmap::new(pw, ph) else { return };
let half = (rect.width * 0.5, rect.height * 0.5);
let pad = blur.max(0.0) * 4.0;
let shape_half = ((half.0 - pad).max(0.0), (half.1 - pad).max(0.0));
let r = radius.max(0.0).min(shape_half.0.min(shape_half.1));
let data = shadow.data_mut();
for py in 0..ph {
for px in 0..pw {
let lx = (x0 + px) as f32 + 0.5;
let ly = (y0 + py) as f32 + 0.5;
let lx = lx / dpr - rect.x;
let ly = ly / dpr - rect.y;
let p = (lx - half.0, ly - half.1);
let q = (p.0.abs() - shape_half.0 + r, p.1.abs() - shape_half.1 + r);
let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
let d = q.0.max(q.1).min(0.0) + outside - r;
let coverage = if blur > 0.0 {
let dp = d.max(0.0);
(-(dp * dp) / (2.0 * blur * blur)).exp()
} else {
1.0 - smoothstep(-0.5, 0.5, d)
};
let alpha = (color.a * coverage).clamp(0.0, 1.0);
if alpha <= 0.001 {
continue;
}
let a = enc(alpha);
let cr = enc((color.r * alpha).min(1.0));
let cg = enc((color.g * alpha).min(1.0));
let cb = enc((color.b * alpha).min(1.0));
let i = ((py * pw + px) * 4) as usize;
data[i..i + 4].copy_from_slice(&[cr.min(a), cg.min(a), cb.min(a), a]);
}
}
let blend = self.sk_blend();
let Raster { target, mask, .. } = self;
target.draw_pixmap(
x0 as i32,
y0 as i32,
shadow.as_ref(),
&PixmapPaint { blend_mode: blend, ..PixmapPaint::default() },
Transform::identity(),
mask.as_ref(),
);
}
fn fill_inset_shadow(&mut self, rect: Rect, color: Color, radius: f32, blur: f32) {
if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
return;
}
let dpr = self.dpr;
let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
if x1 <= x0 || y1 <= y0 {
return;
}
let (pw, ph) = (x1 - x0, y1 - y0);
let Some(mut shadow) = Pixmap::new(pw, ph) else { return };
let half = (rect.width * 0.5, rect.height * 0.5);
let r = radius.max(0.0).min(half.0.min(half.1));
let data = shadow.data_mut();
for py in 0..ph {
for px in 0..pw {
let lx = ((x0 + px) as f32 + 0.5) / dpr - rect.x;
let ly = ((y0 + py) as f32 + 0.5) / dpr - rect.y;
let p = (lx - half.0, ly - half.1);
let q = (p.0.abs() - half.0 + r, p.1.abs() - half.1 + r);
let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
let d = q.0.max(q.1).min(0.0) + outside - r;
let inside = 1.0 - smoothstep(-0.5, 0.5, d);
if inside <= 0.0 {
continue;
}
let depth = (-d).max(0.0);
let coverage = if blur > 0.0 {
inside * (-(depth * depth) / (2.0 * blur * blur)).exp()
} else {
inside * (1.0 - smoothstep(0.0, 1.0, depth))
};
let alpha = (color.a * coverage).clamp(0.0, 1.0);
if alpha <= 0.001 {
continue;
}
let a = enc(alpha);
let cr = enc((color.r * alpha).min(1.0));
let cg = enc((color.g * alpha).min(1.0));
let cb = enc((color.b * alpha).min(1.0));
let i = ((py * pw + px) * 4) as usize;
data[i..i + 4].copy_from_slice(&[cr.min(a), cg.min(a), cb.min(a), a]);
}
}
let blend = self.sk_blend();
let Raster { target, mask, .. } = self;
target.draw_pixmap(
x0 as i32,
y0 as i32,
shadow.as_ref(),
&PixmapPaint { blend_mode: blend, ..PixmapPaint::default() },
Transform::identity(),
mask.as_ref(),
);
}
fn fill_backdrop_blur(&mut self, rect: Rect, radius: f32, blur: f32, tint: Color) {
if rect.width <= 0.0 || rect.height <= 0.0 {
return;
}
let dpr = self.dpr;
let (x0, y0, x1, y1) = shadow_pixel_bounds(rect, dpr, self.target.width(), self.target.height());
if x1 <= x0 || y1 <= y0 {
return;
}
let (pw, ph) = (x1 - x0, y1 - y0);
let Some(mut out) = Pixmap::new(pw, ph) else { return };
let snap = self.target.data().to_vec();
let (tw, th) = (self.target.width() as i32, self.target.height() as i32);
let step = blur.max(0.0) * dpr;
let half = (rect.width * 0.5, rect.height * 0.5);
let r = radius.max(0.0).min(half.0.min(half.1));
let tint_a = tint.a.clamp(0.0, 1.0);
let taps: [(f32, f32, f32); 13] = [
(0.0, 0.0, 0.20),
(0.5, 0.0, 0.12),
(-0.5, 0.0, 0.12),
(0.0, 0.5, 0.12),
(0.0, -0.5, 0.12),
(0.35, 0.35, 0.06),
(-0.35, 0.35, 0.06),
(0.35, -0.35, 0.06),
(-0.35, -0.35, 0.06),
(1.0, 0.0, 0.02),
(-1.0, 0.0, 0.02),
(0.0, 1.0, 0.02),
(0.0, -1.0, 0.02),
];
let data = out.data_mut();
for py in 0..ph {
for px in 0..pw {
let sx = x0 + px;
let sy = y0 + py;
let lx = (sx as f32 + 0.5) / dpr - rect.x;
let ly = (sy as f32 + 0.5) / dpr - rect.y;
let p = (lx - half.0, ly - half.1);
let q = (p.0.abs() - half.0 + r, p.1.abs() - half.1 + r);
let outside = (q.0.max(0.0).powi(2) + q.1.max(0.0).powi(2)).sqrt();
let d = q.0.max(q.1).min(0.0) + outside - r;
let mask = 1.0 - smoothstep(-0.5, 0.5, d);
if mask <= 0.0 {
continue;
}
let mut acc = [0.0f32; 4];
for &(dx, dy, w) in &taps {
let ox = (sx as f32 + dx * step).round() as i32;
let oy = (sy as f32 + dy * step).round() as i32;
let ox = ox.clamp(0, tw - 1);
let oy = oy.clamp(0, th - 1);
let i = ((oy * tw + ox) * 4) as usize;
for c in 0..4 {
acc[c] += snap[i + c] as f32 * w;
}
}
let a = (acc[3] / 255.0).clamp(0.0, 1.0);
let mut rgb = [0.0f32; 3];
if acc[3] > 0.001 {
for c in 0..3 {
rgb[c] = acc[c] / acc[3];
}
}
rgb[0] = rgb[0] * (1.0 - tint_a) + tint.r * tint_a;
rgb[1] = rgb[1] * (1.0 - tint_a) + tint.g * tint_a;
rgb[2] = rgb[2] * (1.0 - tint_a) + tint.b * tint_a;
let alpha = (a * mask).clamp(0.0, 1.0);
if alpha <= 0.001 {
continue;
}
let ab = enc(alpha);
let i = ((py * pw + px) * 4) as usize;
data[i..i + 4].copy_from_slice(&[
enc((rgb[0] * alpha).min(1.0)).min(ab),
enc((rgb[1] * alpha).min(1.0)).min(ab),
enc((rgb[2] * alpha).min(1.0)).min(ab),
ab,
]);
}
}
let Raster { target, mask, .. } = self;
target.draw_pixmap(
x0 as i32,
y0 as i32,
out.as_ref(),
&PixmapPaint::default(),
Transform::identity(),
mask.as_ref(),
);
}
fn fill_triangles(&mut self, vertices: &[Vertex], indices: &[u32]) {
let Some(path) = triangles_path(vertices, indices) else { return };
let color = vertices.first().map(|v| v.color).unwrap_or(Color::WHITE);
let mut paint = Paint::default();
paint.set_color_rgba8(enc(color.r), enc(color.g), enc(color.b), enc(color.a));
paint.anti_alias = true;
let transform = Transform::from_scale(self.dpr, self.dpr);
let Raster { target, mask, .. } = self;
target.fill_path(&path, &paint, FillRule::Winding, transform, mask.as_ref());
}
fn fill_textured(&mut self, rect: Rect, color: Color, uv: [f32; 4], texture_id: u32, mode: TextureMode) {
if rect.width <= 0.0 || rect.height <= 0.0 || color.a <= 0.0 {
return;
}
if texture_id == 0 {
self.fill_glyph(rect, color, uv);
} else {
self.fill_image(rect, color, uv, texture_id, mode);
}
}
fn fill_glyph(&mut self, rect: Rect, color: Color, uv: [f32; 4]) {
let generation = mgui_text::text::atlas_generation();
if generation != self.atlas_generation {
self.atlas_generation = generation;
self.glyph_cache.clear();
}
let key = GlyphCacheKey {
generation,
uv: uv.map(f32::to_bits),
color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
};
if let std::collections::hash_map::Entry::Vacant(entry) = self.glyph_cache.entry(key) {
let built = mgui_text::text::with_atlas(|aw, ah, data| build_glyph_pixmap(aw, ah, data, uv, color));
if let Some(pix) = built {
entry.insert(pix);
}
}
let Raster { target, mask, dpr, glyph_cache, .. } = self;
if let Some(src) = glyph_cache.get(&key) {
draw_pixmap_rect(target, src, rect, *dpr, mask.as_ref(), FilterQuality::Bilinear);
}
}
fn fill_alpha_mask(&mut self, rect: Rect, texture_id: u32, uv: [f32; 4], alpha: f32) {
if rect.width <= 0.0 || rect.height <= 0.0 || alpha <= 0.0 {
return;
}
let Some((_, src)) = self.textures.get(&texture_id) else { return };
let (x0, y0, x1, y1) = uv_pixels(uv, src.width() as f32, src.height() as f32);
let (uw, uh) = ((x1 - x0).max(1e-3), (y1 - y0).max(1e-3));
let sx = rect.width / uw;
let sy = rect.height / uh;
let pat = Transform::from_row(sx, 0.0, 0.0, sy, rect.x - x0 * sx, rect.y - y0 * sy);
let shader = Pattern::new(src.as_ref(), SpreadMode::Pad, FilterQuality::Bilinear, alpha.clamp(0.0, 1.0), pat);
let paint = Paint { shader, blend_mode: BlendMode::DestinationIn, anti_alias: true, ..Paint::default() };
let Some(r) = to_skia_rect(rect) else { return };
let dpr = self.dpr;
let Raster { target, mask, .. } = self;
target.fill_rect(r, &paint, Transform::from_scale(dpr, dpr), mask.as_ref());
}
fn fill_image(&mut self, rect: Rect, color: Color, uv: [f32; 4], texture_id: u32, mode: TextureMode) {
if !self.textures.contains_key(&texture_id) {
return;
}
if mode == TextureMode::Mask {
let key = ImageTintKey {
texture_id,
color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
mask: true,
};
if !self.tint_cache.contains_key(&key) {
if let Some((data, _)) = self.textures.get(&texture_id) {
if let Some(tinted) = mask_tint_pixmap(data, color) {
self.tint_cache.insert(key, tinted);
}
}
}
let Raster { target, mask, dpr, tint_cache, .. } = self;
if let Some(src) = tint_cache.get(&key) {
draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
}
return;
}
let white = color.r >= 1.0 - f32::EPSILON
&& color.g >= 1.0 - f32::EPSILON
&& color.b >= 1.0 - f32::EPSILON
&& color.a >= 1.0 - f32::EPSILON;
if !white {
let key = ImageTintKey {
texture_id,
color: [color.r.to_bits(), color.g.to_bits(), color.b.to_bits(), color.a.to_bits()],
mask: false,
};
if !self.tint_cache.contains_key(&key) {
if let Some((_, base)) = self.textures.get(&texture_id) {
if let Some(tinted) = tint_pixmap(base, color) {
self.tint_cache.insert(key, tinted);
}
}
}
let Raster { target, mask, dpr, tint_cache, .. } = self;
if let Some(src) = tint_cache.get(&key) {
draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
}
} else {
let Raster { target, mask, dpr, textures, .. } = self;
if let Some((_, src)) = textures.get(&texture_id) {
draw_image_rect(target, src, rect, uv, *dpr, mask.as_ref());
}
}
}
}
fn draw_pixmap_rect(
target: &mut Pixmap,
src: &Pixmap,
dest: Rect,
dpr: f32,
mask: Option<&Mask>,
quality: FilterQuality,
) {
if src.width() == 0 || src.height() == 0 {
return;
}
let sx = dest.width / src.width() as f32;
let sy = dest.height / src.height() as f32;
let pat = Transform::from_row(sx, 0.0, 0.0, sy, dest.x, dest.y);
fill_with_pattern(target, src, dest, pat, dpr, mask, quality, 1.0);
}
fn draw_image_rect(target: &mut Pixmap, src: &Pixmap, dest: Rect, uv: [f32; 4], dpr: f32, mask: Option<&Mask>) {
let sw = src.width() as f32;
let sh = src.height() as f32;
let (x0, y0, x1, y1) = uv_pixels(uv, sw, sh);
let (uw, uh) = ((x1 - x0).max(1e-3), (y1 - y0).max(1e-3));
let sx = dest.width / uw;
let sy = dest.height / uh;
let pat = Transform::from_row(sx, 0.0, 0.0, sy, dest.x - x0 * sx, dest.y - y0 * sy);
fill_with_pattern(target, src, dest, pat, dpr, mask, FilterQuality::Bilinear, 1.0);
}
#[allow(clippy::too_many_arguments)]
fn fill_with_pattern(
target: &mut Pixmap,
src: &Pixmap,
dest: Rect,
pattern_transform: Transform,
dpr: f32,
mask: Option<&Mask>,
quality: FilterQuality,
opacity: f32,
) {
let shader = Pattern::new(src.as_ref(), SpreadMode::Pad, quality, opacity, pattern_transform);
let paint = Paint { shader, anti_alias: true, ..Paint::default() };
let Some(rect) = to_skia_rect(dest) else { return };
target.fill_rect(rect, &paint, Transform::from_scale(dpr, dpr), mask);
}
fn build_glyph_pixmap(aw: u32, ah: u32, atlas: &[u8], uv: [f32; 4], color: Color) -> Option<Pixmap> {
let (x0, y0, x1, y1) = uv_pixels(uv, aw as f32, ah as f32);
let x0 = x0.round() as i64;
let y0 = y0.round() as i64;
let x1 = (x1.round() as i64).min(aw as i64).max(x0);
let y1 = (y1.round() as i64).min(ah as i64).max(y0);
let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
if w == 0 || h == 0 || atlas.len() < (aw * ah) as usize {
return None;
}
let mut pix = Pixmap::new(w, h)?;
let out = pix.data_mut();
for y in 0..h {
for x in 0..w {
let idx = (y0 as u32 + y) as usize * aw as usize + (x0 as u32 + x) as usize;
let coverage = atlas[idx] as f32 / 255.0;
let a = color.a * coverage;
let pa = enc(a);
let pr = enc(color.r * a).min(pa);
let pg = enc(color.g * a).min(pa);
let pb = enc(color.b * a).min(pa);
let i = ((y * w + x) * 4) as usize;
out[i..i + 4].copy_from_slice(&[pr, pg, pb, pa]);
}
}
Some(pix)
}
fn mask_tint_pixmap(data: &ImageData, color: Color) -> Option<Pixmap> {
let (w, h) = (data.width, data.height);
if w == 0 || h == 0 || data.rgba.len() < (w * h * 4) as usize {
return None;
}
let mut pix = Pixmap::new(w, h)?;
let out = pix.data_mut();
for i in 0..(w * h) as usize {
let coverage = data.rgba[i * 4] as f32 / 255.0;
let a = color.a * coverage;
let pa = enc(a);
let pr = enc(color.r * a).min(pa);
let pg = enc(color.g * a).min(pa);
let pb = enc(color.b * a).min(pa);
out[i * 4..i * 4 + 4].copy_from_slice(&[pr, pg, pb, pa]);
}
Some(pix)
}
fn tint_pixmap(base: &Pixmap, color: Color) -> Option<Pixmap> {
let mut out = Pixmap::new(base.width(), base.height())?;
for (dst, src) in out.pixels_mut().iter_mut().zip(base.pixels()) {
let a = (src.alpha() as f32 / 255.0 * color.a).clamp(0.0, 1.0);
let pa = enc(a);
let rgb = |v: u8, c: f32| enc((v as f32 / 255.0) * c * color.a).min(pa);
*dst = PremultipliedColorU8::from_rgba(
rgb(src.red(), color.r),
rgb(src.green(), color.g),
rgb(src.blue(), color.b),
pa,
)?;
}
Some(out)
}
fn uv_pixels(uv: [f32; 4], w: f32, h: f32) -> (f32, f32, f32, f32) {
(uv[0] * w, uv[1] * h, uv[2] * w, uv[3] * h)
}
fn triangles_path(vertices: &[Vertex], indices: &[u32]) -> Option<tiny_skia::Path> {
if vertices.is_empty() || indices.len() < 3 {
return None;
}
let mut pb = PathBuilder::new();
for tri in indices.chunks_exact(3) {
let (a, b, c) = (tri[0] as usize, tri[1] as usize, tri[2] as usize);
let (Some(a), Some(b), Some(c)) = (vertices.get(a), vertices.get(b), vertices.get(c)) else {
continue;
};
pb.move_to(a.x, a.y);
pb.line_to(b.x, b.y);
pb.line_to(c.x, c.y);
pb.close();
}
pb.finish()
}
fn shadow_pixel_bounds(rect: Rect, dpr: f32, w: u32, h: u32) -> (u32, u32, u32, u32) {
let x0 = ((rect.x * dpr).floor().max(0.0) as u32).min(w);
let y0 = ((rect.y * dpr).floor().max(0.0) as u32).min(h);
let x1 = ((rect.right() * dpr).ceil().max(0.0) as u32).min(w);
let y1 = ((rect.bottom() * dpr).ceil().max(0.0) as u32).min(h);
(x0, y0, x1.max(x0), y1.max(y0))
}
fn smoothstep(edge0: f32, edge1: f32, x: f32) -> f32 {
let t = ((x - edge0) / (edge1 - edge0)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
pub(crate) fn enc(v: f32) -> u8 {
(v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8
}
fn sk_color(c: Color) -> tiny_skia::Color {
tiny_skia::Color::from_rgba8(enc(c.r), enc(c.g), enc(c.b), enc(c.a))
}
pub(crate) fn pixmap_to_rgba(pix: &Pixmap) -> Vec<u8> {
let mut out = Vec::new();
pixmap_to_rgba_into(pix, &mut out);
out
}
pub(crate) fn pixmap_to_rgba_into(pix: &Pixmap, out: &mut Vec<u8>) {
let len = (pix.width() * pix.height() * 4) as usize;
out.clear();
out.resize(len, 0);
for (dst, p) in out.chunks_exact_mut(4).zip(pix.pixels()) {
let c = p.demultiply();
dst[0] = c.red();
dst[1] = c.green();
dst[2] = c.blue();
dst[3] = c.alpha();
}
}
pub(crate) fn image_to_pixmap(data: &ImageData) -> Option<Pixmap> {
if data.width == 0 || data.height == 0 || data.rgba.len() < (data.width * data.height * 4) as usize {
return None;
}
let mut pix = Pixmap::new(data.width, data.height)?;
for (dst, src) in pix.pixels_mut().iter_mut().zip(data.rgba.chunks_exact(4)) {
let c = tiny_skia::ColorU8::from_rgba(src[0], src[1], src[2], src[3]);
*dst = c.premultiply();
}
Some(pix)
}