use crate::geometry::{Color, Point, Rect, Transform, Vec2};
use crate::render::Renderer;
use crate::text::{RichSpan, TextLayout, layout_text};
use kurbo::BezPath;
use std::sync::Arc;
fn prelayout(spans: &[RichSpan], max_width: Option<f64>) -> Option<Arc<TextLayout>> {
if spans.is_empty() || spans.iter().all(|s| s.text.is_empty()) {
return None;
}
let layout = layout_text(spans, max_width);
(!layout.lines.is_empty()).then_some(layout)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ObjectFit {
#[default]
Contain,
Cover,
Fill,
None,
Tile,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ImageQuality {
Nearest,
#[default]
Bilinear,
Bicubic,
}
#[derive(Debug, Clone)]
pub struct SceneImage {
pub pixmap: crate::Pixmap,
pub object_fit: ObjectFit,
pub quality: ImageQuality,
}
impl SceneImage {
#[must_use]
pub fn from_pixmap(pixmap: crate::Pixmap) -> Self {
Self {
pixmap,
object_fit: ObjectFit::Contain,
quality: ImageQuality::default(),
}
}
#[must_use]
pub fn from_rgba8(
width: u32,
height: u32,
pixels: impl Into<std::sync::Arc<[u8]>>,
) -> Option<Self> {
crate::Pixmap::from_rgba8(width, height, pixels).map(Self::from_pixmap)
}
#[must_use]
pub fn from_png(bytes: &[u8]) -> Option<Self> {
crate::Pixmap::decode_png(bytes).map(Self::from_pixmap)
}
#[cfg(feature = "extra-image-codecs")]
#[must_use]
pub fn from_encoded(bytes: &[u8]) -> Option<Self> {
let dyn_img = image::load_from_memory(bytes).ok()?;
let rgba = dyn_img.to_rgba8();
let (w, h) = rgba.dimensions();
Self::from_rgba8(w, h, rgba.into_raw())
}
#[must_use]
pub fn width(&self) -> u32 {
self.pixmap.width()
}
#[must_use]
pub fn height(&self) -> u32 {
self.pixmap.height()
}
#[must_use]
pub fn with_object_fit(mut self, fit: ObjectFit) -> Self {
self.object_fit = fit;
self
}
#[must_use]
pub fn with_quality(mut self, quality: ImageQuality) -> Self {
self.quality = quality;
self
}
#[must_use]
pub fn preserve_aspect_ratio(&self) -> &'static str {
match self.object_fit {
ObjectFit::Contain => "xMidYMid meet",
ObjectFit::Cover => "xMidYMid slice",
ObjectFit::Fill => "none",
ObjectFit::None | ObjectFit::Tile => "none",
}
}
}
#[derive(Debug, Clone)]
pub struct Scene {
pub width: f64,
pub height: f64,
pub background: Color,
pub nodes: Vec<SceneNode>,
pub layers: Vec<Layer>,
pub title: Option<String>,
pub description: Option<String>,
pub scale: f64,
}
impl Default for Scene {
fn default() -> Self {
Self {
width: 0.0,
height: 0.0,
background: Color::WHITE,
nodes: Vec::new(),
layers: Vec::new(),
title: None,
description: None,
scale: 1.0,
}
}
}
impl Scene {
pub fn new(width: f64, height: f64) -> Self {
Self {
width,
height,
background: Color::WHITE,
nodes: Vec::new(),
layers: Vec::new(),
title: None,
description: None,
scale: 1.0,
}
}
#[must_use]
pub fn with_background(mut self, bg: Color) -> Self {
self.background = bg;
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
#[must_use]
pub fn with_scale(mut self, scale: f64) -> Self {
self.scale = scale;
self
}
pub fn push(&mut self, node: impl Into<SceneNode>) {
self.nodes.push(node.into());
}
pub fn push_node(&mut self, node: SceneNode) {
self.nodes.push(node);
}
pub fn push_group(&mut self, children: Vec<SceneNode>) {
self.nodes.push(SceneNode::group(children));
}
pub fn push_layer(&mut self, layer: Layer) {
self.layers.push(layer);
}
pub fn layers(&self) -> &[Layer] {
&self.layers
}
pub fn layer(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name == name)
}
pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.name == name)
}
pub fn render(&self, renderer: &mut dyn Renderer) {
renderer.render_scene(self);
}
pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
SceneNode::ordered(&self.nodes)
}
pub fn visit_nodes(&self, f: &mut impl FnMut(&SceneNode)) {
for node in &self.nodes {
node.visit(f);
}
for layer in &self.layers {
for node in &layer.nodes {
node.visit(f);
}
}
}
pub fn visit_nodes_mut(&mut self, f: &mut impl FnMut(&mut SceneNode)) {
for node in &mut self.nodes {
node.visit_mut(f);
}
for layer in &mut self.layers {
for node in &mut layer.nodes {
node.visit_mut(f);
}
}
}
pub fn root_lists(&self) -> impl Iterator<Item = (&[SceneNode], Option<Transform>)> {
std::iter::once((self.nodes.as_slice(), None)).chain(
self.layers
.iter()
.filter(|l| l.visible)
.map(|l| (l.nodes.as_slice(), l.transform)),
)
}
pub fn root_lists_mut(&mut self) -> impl Iterator<Item = &mut Vec<SceneNode>> {
std::iter::once(&mut self.nodes).chain(
self.layers
.iter_mut()
.filter(|l| l.visible)
.map(|l| &mut l.nodes),
)
}
}
#[derive(Debug, Clone)]
pub struct Layer {
pub name: String,
pub visible: bool,
pub opacity: f64,
pub transform: Option<Transform>,
pub blend_mode: BlendMode,
pub nodes: Vec<SceneNode>,
}
impl Layer {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
visible: true,
opacity: 1.0,
transform: None,
blend_mode: BlendMode::Normal,
nodes: Vec::new(),
}
}
pub fn with_nodes(mut self, nodes: Vec<SceneNode>) -> Self {
self.nodes = nodes;
self
}
pub fn push(&mut self, node: impl Into<SceneNode>) {
self.nodes.push(node.into());
}
pub fn push_node(&mut self, node: SceneNode) {
self.nodes.push(node);
}
pub fn push_group(&mut self, children: Vec<SceneNode>) {
self.nodes.push(SceneNode::group(children));
}
pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
SceneNode::ordered(&self.nodes)
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
#[must_use]
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
#[must_use]
pub fn with_opacity(mut self, opacity: f64) -> Self {
self.opacity = opacity.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_transform(mut self, t: Transform) -> Self {
self.transform = Some(t);
self
}
#[must_use]
pub fn with_blend_mode(mut self, mode: BlendMode) -> Self {
self.blend_mode = mode;
self
}
}
#[derive(Debug, Clone, Copy)]
pub struct NodeScope<'a> {
pub transform: Option<Transform>,
pub clip: Option<&'a Clip>,
pub filter: Option<&'a Filter>,
pub opacity: f64,
pub blend_mode: BlendMode,
pub mask: Option<&'a Mask>,
pub color_matrix: Option<ColorMatrix>,
pub antialias: Option<bool>,
pub name: Option<&'a str>,
}
impl NodeScope<'_> {
#[must_use]
pub fn is_identity(&self) -> bool {
self.transform.is_none()
&& self.clip.is_none()
&& self.filter.is_none()
&& self.opacity == 1.0
&& self.blend_mode.is_normal()
&& self.mask.is_none()
&& self.color_matrix.is_none()
&& self.antialias.is_none()
&& self.name.is_none()
}
}
impl SceneNode {
#[must_use]
pub fn scope(&self) -> NodeScope<'_> {
NodeScope {
transform: self.transform,
clip: self.clip.as_ref(),
filter: self.filter.as_ref(),
opacity: self.opacity,
blend_mode: self.blend_mode,
mask: self.mask.as_ref(),
color_matrix: self.color_matrix,
antialias: self.antialias,
name: self.name.as_deref(),
}
}
}
impl Layer {
#[must_use]
pub fn scope(&self) -> NodeScope<'_> {
NodeScope {
transform: self.transform,
clip: None,
filter: None,
opacity: self.opacity,
blend_mode: self.blend_mode,
mask: None,
color_matrix: None,
antialias: None,
name: (!self.name.is_empty()).then_some(self.name.as_str()),
}
}
}
#[derive(Debug, Clone)]
pub enum NodeKind {
Draw(Element),
Group(Vec<SceneNode>),
}
#[derive(Debug, Clone)]
pub struct SceneNode {
pub kind: NodeKind,
pub z_index: i32,
pub transform: Option<Transform>,
pub opacity: f64,
pub name: Option<String>,
pub visible: bool,
pub clip: Option<Clip>,
pub blend_mode: BlendMode,
pub mask: Option<Mask>,
pub filter: Option<Filter>,
pub color_matrix: Option<ColorMatrix>,
pub antialias: Option<bool>,
}
impl SceneNode {
fn with_defaults(kind: NodeKind) -> Self {
Self {
kind,
z_index: 0,
transform: None,
opacity: 1.0,
name: None,
visible: true,
clip: None,
blend_mode: BlendMode::Normal,
mask: None,
filter: None,
color_matrix: None,
antialias: None,
}
}
pub fn new(element: Element) -> Self {
Self::with_defaults(NodeKind::Draw(element))
}
pub fn group(children: Vec<SceneNode>) -> Self {
Self::with_defaults(NodeKind::Group(children))
}
pub fn ordered(nodes: &[SceneNode]) -> impl Iterator<Item = &SceneNode> {
let mut order: Vec<usize> = (0..nodes.len()).collect();
order.sort_by_key(|&i| nodes[i].z_index);
order.into_iter().map(move |i| &nodes[i])
}
#[must_use]
pub fn is_group(&self) -> bool {
matches!(self.kind, NodeKind::Group(_))
}
#[must_use]
pub fn element(&self) -> Option<&Element> {
match &self.kind {
NodeKind::Draw(element) => Some(element),
NodeKind::Group(_) => None,
}
}
pub fn element_mut(&mut self) -> Option<&mut Element> {
match &mut self.kind {
NodeKind::Draw(element) => Some(element),
NodeKind::Group(_) => None,
}
}
#[must_use]
pub fn into_element(self) -> Option<Element> {
match self.kind {
NodeKind::Draw(element) => Some(element),
NodeKind::Group(_) => None,
}
}
#[must_use]
pub fn children(&self) -> Option<&[SceneNode]> {
match &self.kind {
NodeKind::Group(children) => Some(children),
NodeKind::Draw(_) => None,
}
}
pub fn children_mut(&mut self) -> Option<&mut Vec<SceneNode>> {
match &mut self.kind {
NodeKind::Group(children) => Some(children),
NodeKind::Draw(_) => None,
}
}
pub fn visit(&self, f: &mut impl FnMut(&SceneNode)) {
f(self);
if let Some(children) = self.children() {
for child in children {
child.visit(f);
}
}
}
pub fn visit_mut(&mut self, f: &mut impl FnMut(&mut SceneNode)) {
f(self);
if let Some(children) = self.children_mut() {
for child in children.iter_mut() {
child.visit_mut(f);
}
}
}
#[must_use]
pub fn with_z(mut self, z: i32) -> Self {
self.z_index = z;
self
}
#[must_use]
pub fn with_transform(mut self, t: Transform) -> Self {
self.transform = Some(t);
self
}
#[must_use]
pub fn with_opacity(mut self, opacity: f64) -> Self {
self.opacity = opacity.clamp(0.0, 1.0);
self
}
#[must_use]
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub fn with_visible(mut self, visible: bool) -> Self {
self.visible = visible;
self
}
#[must_use]
pub fn with_clip(mut self, clip: Clip) -> Self {
self.clip = Some(clip);
self
}
#[must_use]
pub fn with_blend_mode(mut self, mode: BlendMode) -> Self {
self.blend_mode = mode;
self
}
#[must_use]
pub fn with_mask(mut self, mask: Mask) -> Self {
self.mask = Some(mask);
self
}
#[must_use]
pub fn with_filter(mut self, filter: Filter) -> Self {
self.filter = Some(filter);
self
}
#[must_use]
pub fn with_color_matrix(mut self, matrix: ColorMatrix) -> Self {
self.color_matrix = Some(matrix);
self
}
#[must_use]
pub fn with_antialias(mut self, enabled: bool) -> Self {
self.antialias = Some(enabled);
self
}
}
impl From<Element> for SceneNode {
fn from(element: Element) -> Self {
SceneNode::new(element)
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Clip {
Rect(Rect),
RoundedRect { rect: Rect, radius: f64 },
Circle { center: Point, radius: f64 },
Ellipse {
center: Point,
radii: Vec2,
rotation: f64,
},
Path(BezPath),
}
impl Clip {
#[must_use]
pub fn rect(rect: Rect) -> Self {
Self::Rect(rect)
}
#[must_use]
pub fn rounded_rect(rect: Rect, radius: f64) -> Self {
Self::RoundedRect { rect, radius }
}
#[must_use]
pub fn circle(center: Point, radius: f64) -> Self {
Self::Circle { center, radius }
}
#[must_use]
pub fn ellipse(center: Point, radii: Vec2, rotation: f64) -> Self {
Self::Ellipse {
center,
radii,
rotation,
}
}
#[must_use]
pub fn path(path: BezPath) -> Self {
Self::Path(path)
}
#[must_use]
pub fn to_bezpath(&self) -> BezPath {
use kurbo::Shape;
match self {
Clip::Rect(rect) => {
let mut p = BezPath::new();
p.move_to((rect.min_x(), rect.min_y()));
p.line_to((rect.max_x(), rect.min_y()));
p.line_to((rect.max_x(), rect.max_y()));
p.line_to((rect.min_x(), rect.max_y()));
p.close_path();
p
}
Clip::RoundedRect { rect, radius } => kurbo::RoundedRect::new(
rect.min_x(),
rect.min_y(),
rect.max_x(),
rect.max_y(),
*radius,
)
.to_path(0.1),
Clip::Circle { center, radius } => {
kurbo::Circle::new((center.x, center.y), *radius).to_path(0.1)
}
Clip::Ellipse {
center,
radii,
rotation,
} => kurbo::Ellipse::new((center.x, center.y), (radii.x, radii.y), *rotation)
.to_path(0.1),
Clip::Path(path) => path.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Mask {
pub shape: Clip,
pub fill: Fill,
}
impl Mask {
#[must_use]
pub fn new(shape: Clip) -> Self {
Self {
shape,
fill: Fill::Solid(Color::WHITE),
}
}
#[must_use]
pub fn with_fill(mut self, fill: impl Into<Fill>) -> Self {
self.fill = fill.into();
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Filter {
Blur {
std_dev: f64,
},
DropShadow {
dx: f64,
dy: f64,
std_dev: f64,
color: Color,
},
}
impl Filter {
#[must_use]
pub fn blur(std_dev: f64) -> Self {
Self::Blur { std_dev }
}
#[must_use]
pub fn drop_shadow(dx: f64, dy: f64, std_dev: f64, color: Color) -> Self {
Self::DropShadow {
dx,
dy,
std_dev,
color,
}
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FillStrokeStyle {
pub fill: Option<Fill>,
pub stroke: Option<Stroke>,
}
impl FillStrokeStyle {
#[must_use]
pub fn fill(color: Color) -> Self {
Self {
fill: Some(Fill::Solid(color)),
stroke: None,
}
}
#[must_use]
pub fn fill_gradient(gradient: impl Into<Fill>) -> Self {
Self {
fill: Some(gradient.into()),
stroke: None,
}
}
#[must_use]
pub fn stroke(color: Color, width: f64) -> Self {
Self {
fill: None,
stroke: Some(Stroke {
color,
width,
..Default::default()
}),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ImageFill {
pub image: crate::Pixmap,
pub tile: Rect,
}
impl ImageFill {
#[must_use]
pub fn new(image: crate::Pixmap, tile: Rect) -> Self {
Self { image, tile }
}
#[must_use]
pub fn natural(image: crate::Pixmap, at: Point) -> Self {
let (w, h) = (image.width() as f64, image.height() as f64);
Self {
image,
tile: Rect::new(at.x, at.y, at.x + w, at.y + h),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
Solid(Color),
LinearGradient(LinearGradient),
RadialGradient(RadialGradient),
SweepGradient(SweepGradient),
Image(ImageFill),
Sketch(SketchFill),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SketchFillStyle {
#[default]
Hachure,
CrossHatch,
Zigzag,
Dots,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SketchFill {
pub color: Color,
pub style: SketchFillStyle,
pub angle: f64,
pub gap: f64,
pub fill_weight: f64,
}
impl SketchFill {
#[must_use]
pub fn new(color: Color) -> Self {
Self {
color,
style: SketchFillStyle::Hachure,
angle: -41.0,
gap: 4.0,
fill_weight: 0.5,
}
}
#[must_use]
pub fn with_style(mut self, style: SketchFillStyle) -> Self {
self.style = style;
self
}
#[must_use]
pub fn with_angle(mut self, angle: f64) -> Self {
self.angle = angle;
self
}
#[must_use]
pub fn with_gap(mut self, gap: f64) -> Self {
self.gap = gap;
self
}
#[must_use]
pub fn with_fill_weight(mut self, weight: f64) -> Self {
self.fill_weight = weight;
self
}
#[must_use]
pub fn gap(&self) -> f64 {
if self.gap.is_finite() && self.gap > 0.05 {
self.gap
} else {
4.0
}
}
#[must_use]
pub fn weight(&self) -> f64 {
if self.fill_weight.is_finite() && self.fill_weight > 0.0 {
self.fill_weight.min(self.gap() * 0.5)
} else {
0.5
}
}
}
impl From<Color> for Fill {
fn from(c: Color) -> Self {
Self::Solid(c)
}
}
impl From<LinearGradient> for Fill {
fn from(g: LinearGradient) -> Self {
Self::LinearGradient(g)
}
}
impl From<RadialGradient> for Fill {
fn from(g: RadialGradient) -> Self {
Self::RadialGradient(g)
}
}
impl From<SweepGradient> for Fill {
fn from(g: SweepGradient) -> Self {
Self::SweepGradient(g)
}
}
impl From<ImageFill> for Fill {
fn from(g: ImageFill) -> Self {
Self::Image(g)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GradientSpread {
#[default]
Pad,
Repeat,
Reflect,
}
#[derive(Debug, Clone, PartialEq)]
pub struct LinearGradient {
pub start: Point,
pub end: Point,
pub stops: Vec<GradientStop>,
pub spread: GradientSpread,
}
impl LinearGradient {
#[must_use]
pub fn new(start: Point, end: Point, stops: Vec<GradientStop>) -> Self {
Self {
start,
end,
stops,
spread: GradientSpread::Pad,
}
}
#[must_use]
pub fn with_spread(mut self, spread: GradientSpread) -> Self {
self.spread = spread;
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct RadialGradient {
pub center: Point,
pub radius: f64,
pub stops: Vec<GradientStop>,
pub spread: GradientSpread,
}
impl RadialGradient {
#[must_use]
pub fn new(center: Point, radius: f64, stops: Vec<GradientStop>) -> Self {
Self {
center,
radius,
stops,
spread: GradientSpread::Pad,
}
}
#[must_use]
pub fn with_spread(mut self, spread: GradientSpread) -> Self {
self.spread = spread;
self
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct SweepGradient {
pub center: Point,
pub start_angle: f64,
pub end_angle: f64,
pub stops: Vec<GradientStop>,
pub spread: GradientSpread,
}
impl SweepGradient {
#[must_use]
pub fn new(center: Point, start_angle: f64, end_angle: f64, stops: Vec<GradientStop>) -> Self {
Self {
center,
start_angle,
end_angle,
stops,
spread: GradientSpread::Pad,
}
}
#[must_use]
pub fn full(center: Point, start_angle: f64, stops: Vec<GradientStop>) -> Self {
Self::new(
center,
start_angle,
start_angle + std::f64::consts::TAU,
stops,
)
}
#[must_use]
pub fn with_spread(mut self, spread: GradientSpread) -> Self {
self.spread = spread;
self
}
#[must_use]
pub fn ramp_t(&self, angle: f64) -> f64 {
let span = self.end_angle - self.start_angle;
if span.abs() < 1e-12 {
return 0.0;
}
let raw = (angle - self.start_angle) / span;
match self.spread {
GradientSpread::Pad => raw.clamp(0.0, 1.0),
GradientSpread::Repeat => raw.rem_euclid(1.0),
GradientSpread::Reflect => {
let m = raw.rem_euclid(2.0);
if m > 1.0 { 2.0 - m } else { m }
}
}
}
#[must_use]
pub fn sample(&self, angle: f64) -> Color {
sample_stops(&self.stops, self.ramp_t(angle))
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct GradientStop {
pub offset: f64,
pub color: Color,
}
#[must_use]
pub fn sample_stops(stops: &[GradientStop], t: f64) -> Color {
let Some(first) = stops.first() else {
return Color::default();
};
if t <= first.offset {
return first.color;
}
for w in stops.windows(2) {
let (a, b) = (&w[0], &w[1]);
if t >= a.offset && t <= b.offset {
let span = b.offset - a.offset;
let u = if span > 1e-12 {
(t - a.offset) / span
} else {
1.0
};
return lerp_color(a.color, b.color, u);
}
}
stops.last().map_or(first.color, |s| s.color)
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CornerRadii {
pub top_left: f64,
pub top_right: f64,
pub bottom_right: f64,
pub bottom_left: f64,
}
impl CornerRadii {
#[must_use]
pub const fn uniform(radius: f64) -> Self {
Self {
top_left: radius,
top_right: radius,
bottom_right: radius,
bottom_left: radius,
}
}
#[must_use]
pub const fn new(top_left: f64, top_right: f64, bottom_right: f64, bottom_left: f64) -> Self {
Self {
top_left,
top_right,
bottom_right,
bottom_left,
}
}
#[must_use]
pub fn is_uniform(&self) -> bool {
self.top_left == self.top_right
&& self.top_right == self.bottom_right
&& self.bottom_right == self.bottom_left
}
#[must_use]
pub fn uniform_value(&self) -> f64 {
self.top_left
}
#[must_use]
pub fn to_kurbo(self) -> kurbo::RoundedRectRadii {
kurbo::RoundedRectRadii::new(
self.top_left,
self.top_right,
self.bottom_right,
self.bottom_left,
)
}
}
impl From<f64> for CornerRadii {
fn from(radius: f64) -> Self {
Self::uniform(radius)
}
}
fn lerp_color(a: Color, b: Color, t: f64) -> Color {
let t = t.clamp(0.0, 1.0);
let ch = |x: u8, y: u8| {
let v = f64::from(x) + (f64::from(y) - f64::from(x)) * t;
v.round().clamp(0.0, 255.0) as u8
};
Color::rgba(ch(a.r, b.r), ch(a.g, b.g), ch(a.b, b.b), ch(a.a, b.a))
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorMatrix(pub [f64; 20]);
impl ColorMatrix {
pub const IDENTITY: Self = Self([
1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
]);
#[must_use]
pub fn from_rows(rows: [[f64; 5]; 4]) -> Self {
let mut m = [0.0; 20];
for (i, row) in rows.iter().enumerate() {
m[i * 5..i * 5 + 5].copy_from_slice(row);
}
Self(m)
}
#[must_use]
pub fn values(&self) -> &[f64; 20] {
&self.0
}
#[must_use]
pub fn is_identity(&self) -> bool {
*self == Self::IDENTITY
}
#[must_use]
pub fn then(self, next: Self) -> Self {
let (a, b) = (&self.0, &next.0);
let mut out = [0.0f64; 20];
for row in 0..4 {
for col in 0..5 {
let mut v = 0.0;
for k in 0..4 {
v += b[row * 5 + k] * a[k * 5 + col];
}
if col == 4 {
v += b[row * 5 + 4];
}
out[row * 5 + col] = v;
}
}
Self(out)
}
#[must_use]
pub fn apply(&self, c: Color) -> Color {
if self.is_identity() {
return c;
}
let m = &self.0;
let (r, g, b, a) = (
f64::from(c.r) / 255.0,
f64::from(c.g) / 255.0,
f64::from(c.b) / 255.0,
f64::from(c.a) / 255.0,
);
let ch = |row: usize| -> u8 {
let o = row * 5;
let v = m[o] * r + m[o + 1] * g + m[o + 2] * b + m[o + 3] * a + m[o + 4];
(v * 255.0).round().clamp(0.0, 255.0) as u8
};
Color::rgba(ch(0), ch(1), ch(2), ch(3))
}
#[must_use]
pub fn grayscale() -> Self {
Self::saturate(0.0)
}
#[must_use]
pub fn saturate(amount: f64) -> Self {
let s = amount;
let (lr, lg, lb) = (0.213, 0.715, 0.072);
let k = 1.0 - s;
Self::from_rows([
[lr * k + s, lg * k, lb * k, 0.0, 0.0],
[lr * k, lg * k + s, lb * k, 0.0, 0.0],
[lr * k, lg * k, lb * k + s, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0],
])
}
#[must_use]
pub fn hue_rotate(deg: f64) -> Self {
let (s, c) = deg.to_radians().sin_cos();
Self::from_rows([
[
0.213 + c * 0.787 - s * 0.213,
0.715 - c * 0.715 - s * 0.715,
0.072 - c * 0.072 + s * 0.928,
0.0,
0.0,
],
[
0.213 - c * 0.213 + s * 0.143,
0.715 + c * 0.285 + s * 0.140,
0.072 - c * 0.072 - s * 0.283,
0.0,
0.0,
],
[
0.213 - c * 0.213 - s * 0.787,
0.715 - c * 0.715 + s * 0.715,
0.072 + c * 0.928 + s * 0.072,
0.0,
0.0,
],
[0.0, 0.0, 0.0, 1.0, 0.0],
])
}
#[must_use]
pub fn brightness(factor: f64) -> Self {
Self::from_rows([
[factor, 0.0, 0.0, 0.0, 0.0],
[0.0, factor, 0.0, 0.0, 0.0],
[0.0, 0.0, factor, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0, 0.0],
])
}
#[must_use]
pub fn contrast(factor: f64) -> Self {
let t = (1.0 - factor) * 0.5;
Self::from_rows([
[factor, 0.0, 0.0, 0.0, t],
[0.0, factor, 0.0, 0.0, t],
[0.0, 0.0, factor, 0.0, t],
[0.0, 0.0, 0.0, 1.0, 0.0],
])
}
#[must_use]
pub fn tint(color: Color, amount: f64) -> Self {
let a = amount.clamp(0.0, 1.0);
let keep = 1.0 - a;
let (tr, tg, tb) = (
f64::from(color.r) / 255.0,
f64::from(color.g) / 255.0,
f64::from(color.b) / 255.0,
);
Self::from_rows([
[keep, 0.0, 0.0, 0.0, tr * a],
[0.0, keep, 0.0, 0.0, tg * a],
[0.0, 0.0, keep, 0.0, tb * a],
[0.0, 0.0, 0.0, 1.0, 0.0],
])
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Stroke {
pub color: Color,
pub width: f64,
pub line_cap: LineCap,
pub line_join: LineJoin,
pub dash_array: Vec<f64>,
pub dash_offset: f64,
pub miter_limit: f64,
}
impl Default for Stroke {
fn default() -> Self {
Self {
color: Color::default(),
width: 0.0,
line_cap: LineCap::default(),
line_join: LineJoin::default(),
dash_array: Vec::new(),
dash_offset: 0.0,
miter_limit: 10.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
#[default]
Butt,
Round,
Square,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineJoin {
#[default]
Miter,
Round,
Bevel,
}
impl Stroke {
#[must_use]
pub fn new(color: Color, width: f64) -> Self {
Self {
color,
width,
..Default::default()
}
}
#[must_use]
pub fn dashed(color: Color, width: f64, dash_array: Vec<f64>) -> Self {
Self {
color,
width,
dash_array,
..Default::default()
}
}
#[must_use]
pub fn to_kurbo(&self) -> kurbo::Stroke {
let cap = match self.line_cap {
LineCap::Butt => kurbo::Cap::Butt,
LineCap::Round => kurbo::Cap::Round,
LineCap::Square => kurbo::Cap::Square,
};
let join = match self.line_join {
LineJoin::Miter => kurbo::Join::Miter,
LineJoin::Round => kurbo::Join::Round,
LineJoin::Bevel => kurbo::Join::Bevel,
};
let mut k = kurbo::Stroke::new(self.width)
.with_join(join)
.with_caps(cap)
.with_miter_limit(self.miter_limit);
if !self.dash_array.is_empty() {
k.dash_pattern = self.dash_array.iter().copied().collect();
k.dash_offset = self.dash_offset;
}
k
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
Clear,
Copy,
Dest,
DestOver,
SrcIn,
DestIn,
SrcOut,
DestOut,
SrcAtop,
DestAtop,
Xor,
Plus,
PlusLighter,
}
impl BlendMode {
#[must_use]
pub fn is_normal(self) -> bool {
matches!(self, BlendMode::Normal)
}
#[must_use]
pub fn css_keyword(self) -> Option<&'static str> {
Some(match self {
BlendMode::Normal => return None,
BlendMode::Multiply => "multiply",
BlendMode::Screen => "screen",
BlendMode::Overlay => "overlay",
BlendMode::Darken => "darken",
BlendMode::Lighten => "lighten",
BlendMode::ColorDodge => "color-dodge",
BlendMode::ColorBurn => "color-burn",
BlendMode::HardLight => "hard-light",
BlendMode::SoftLight => "soft-light",
BlendMode::Difference => "difference",
BlendMode::Exclusion => "exclusion",
BlendMode::Hue => "hue",
BlendMode::Saturation => "saturation",
BlendMode::Color => "color",
BlendMode::Luminosity => "luminosity",
_ => return None,
})
}
#[must_use]
pub fn is_porter_duff(self) -> bool {
matches!(
self,
BlendMode::Clear
| BlendMode::Copy
| BlendMode::Dest
| BlendMode::DestOver
| BlendMode::SrcIn
| BlendMode::DestIn
| BlendMode::SrcOut
| BlendMode::DestOut
| BlendMode::SrcAtop
| BlendMode::DestAtop
| BlendMode::Xor
| BlendMode::Plus
| BlendMode::PlusLighter
)
}
}
#[derive(Debug, Clone)]
pub enum Element {
Rect {
rect: Rect,
style: FillStrokeStyle,
},
Circle {
center: Point,
radius: f64,
style: FillStrokeStyle,
},
Ellipse {
center: Point,
radii: Vec2,
rotation: f64,
style: FillStrokeStyle,
},
RoundedRect {
rect: Rect,
radii: CornerRadii,
style: FillStrokeStyle,
},
Line {
start: Point,
end: Point,
style: Stroke,
},
Polyline {
points: Vec<Point>,
style: Stroke,
},
Polygon {
points: Vec<Point>,
style: FillStrokeStyle,
},
Arc {
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
style: Stroke,
},
Pie {
center: Point,
radius: f64,
start_angle: f64,
sweep_angle: f64,
style: FillStrokeStyle,
},
Path {
path: BezPath,
style: FillStrokeStyle,
closed: bool,
},
Image {
image: SceneImage,
frame: Rect,
opacity: f64,
},
GradientPath {
path: BezPath,
gradient: LinearGradient,
stroke: Option<Stroke>,
},
Text {
spans: Vec<RichSpan>,
position: Point,
style: crate::text::TextStyle,
layout: Option<std::sync::Arc<TextLayout>>,
},
}
impl Element {
#[must_use]
pub fn rect(rect: Rect, style: FillStrokeStyle) -> Self {
Self::Rect { rect, style }
}
#[must_use]
pub fn circle(center: Point, radius: f64, style: FillStrokeStyle) -> Self {
Self::Circle {
center,
radius,
style,
}
}
#[must_use]
pub fn ellipse(center: Point, radii: Vec2, rotation: f64, style: FillStrokeStyle) -> Self {
Self::Ellipse {
center,
radii,
rotation,
style,
}
}
#[must_use]
pub fn rounded_rect(
rect: Rect,
radius: impl Into<CornerRadii>,
style: FillStrokeStyle,
) -> Self {
Self::RoundedRect {
rect,
radii: radius.into(),
style,
}
}
#[must_use]
pub fn line(start: Point, end: Point, style: Stroke) -> Self {
Self::Line { start, end, style }
}
#[must_use]
pub fn poly(points: Vec<Point>, style: Stroke) -> Self {
Self::Polyline { points, style }
}
#[must_use]
pub fn polygon(points: Vec<Point>, style: FillStrokeStyle) -> Self {
Self::Polygon { points, style }
}
#[must_use]
pub fn arc(
center: Point,
radii: Vec2,
start_angle: f64,
sweep_angle: f64,
style: Stroke,
) -> Self {
Self::Arc {
center,
radii,
start_angle,
sweep_angle,
style,
}
}
#[must_use]
pub fn pie(
center: Point,
radius: f64,
start_angle: f64,
sweep_angle: f64,
style: FillStrokeStyle,
) -> Self {
Self::Pie {
center,
radius,
start_angle,
sweep_angle,
style,
}
}
#[must_use]
pub fn text(
content: impl Into<String>,
position: Point,
style: crate::text::TextStyle,
) -> Self {
let spans = vec![RichSpan::new(content, style.clone())];
let layout = prelayout(&spans, style.max_width);
Self::Text {
spans,
position,
style,
layout,
}
}
#[must_use]
pub fn rich_text(spans: Vec<RichSpan>, position: Point, style: crate::text::TextStyle) -> Self {
let layout = prelayout(&spans, style.max_width);
Self::Text {
spans,
position,
style,
layout,
}
}
#[must_use]
pub fn image(image: SceneImage, frame: Rect) -> Self {
Self::Image {
image,
frame,
opacity: 1.0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rect_node(x: f64, z: i32) -> SceneNode {
SceneNode::new(Element::rect(
Rect::new(x, 0.0, x + 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_z(z)
}
fn rect_x(node: &SceneNode) -> f64 {
match node.element() {
Some(Element::Rect { rect, .. }) => rect.min_x(),
_ => panic!("expected rect"),
}
}
mod element {
use super::*;
#[test]
fn push_accepts_element_and_scene_node() {
let mut scene = Scene::new(100.0, 100.0);
scene.push(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
scene.push(SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
)));
assert_eq!(scene.nodes.len(), 2);
}
#[test]
fn builder_chaining() {
let node = SceneNode::new(Element::circle(
Point::new(1.0, 2.0),
3.0,
FillStrokeStyle::stroke(Color::BLACK, 1.0),
))
.with_z(7)
.with_transform(Transform::translate(1.0, 2.0))
.with_opacity(0.5)
.with_name("node-a")
.with_visible(false);
assert_eq!(node.z_index, 7);
assert_eq!(node.transform, Some(Transform::translate(1.0, 2.0)));
assert_eq!(node.opacity, 0.5);
assert_eq!(node.name.as_deref(), Some("node-a"));
assert!(!node.visible);
}
#[test]
fn node_defaults() {
let node = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
assert_eq!(node.opacity, 1.0);
assert!(node.name.is_none());
assert!(node.visible);
}
#[test]
fn from_element_conversion() {
let node: SceneNode = Element::line(
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Stroke::new(Color::BLACK, 1.0),
)
.into();
assert_eq!(node.z_index, 0);
assert!(node.transform.is_none());
}
#[test]
fn element_constructors() {
let r = Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(r, Element::Rect { .. }));
let c = Element::circle(
Point::new(1.0, 2.0),
3.0,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(c, Element::Circle { .. }));
let e = Element::ellipse(
Point::new(1.0, 2.0),
Vec2::new(4.0, 2.0),
0.1,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(e, Element::Ellipse { .. }));
let rr = Element::rounded_rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
3.0,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(rr, Element::RoundedRect { .. }));
let l = Element::line(
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(l, Element::Line { .. }));
let p = Element::poly(
vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)],
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(p, Element::Polyline { .. }));
let pg = Element::polygon(
vec![
Point::new(0.0, 0.0),
Point::new(1.0, 1.0),
Point::new(0.0, 1.0),
],
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(pg, Element::Polygon { .. }));
let a = Element::arc(
Point::new(0.0, 0.0),
Vec2::new(5.0, 5.0),
0.0,
std::f64::consts::FRAC_PI_2,
Stroke::new(Color::BLACK, 1.0),
);
assert!(matches!(a, Element::Arc { .. }));
let pie = Element::pie(
Point::new(0.0, 0.0),
5.0,
0.0,
std::f64::consts::FRAC_PI_2,
FillStrokeStyle::fill(Color::BLACK),
);
assert!(matches!(pie, Element::Pie { .. }));
let t = Element::text(
"hi",
Point::new(0.0, 0.0),
crate::text::TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
);
match t {
Element::Text {
spans,
position,
style,
layout,
} => {
assert_eq!(spans.len(), 1);
assert_eq!(spans[0].text, "hi");
assert_eq!(position, Point::new(0.0, 0.0));
assert_eq!(style.font_size, 12.0);
if let Some(l) = layout {
assert!(!l.lines.is_empty());
assert!(l.width > 0.0 && l.height > 0.0);
}
}
_ => panic!("expected text"),
}
let empty = Element::text(
"",
Point::new(0.0, 0.0),
crate::text::TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
);
match empty {
Element::Text { layout, .. } => assert!(layout.is_none()),
_ => panic!("expected text"),
}
}
#[test]
fn stroke_dash_and_miter_defaults() {
let s = Stroke::new(Color::BLACK, 2.0);
assert!(s.dash_array.is_empty());
assert_eq!(s.dash_offset, 0.0);
assert_eq!(s.miter_limit, 10.0);
let d = Stroke::dashed(Color::BLACK, 2.0, vec![4.0, 2.0]);
assert_eq!(d.dash_array, vec![4.0, 2.0]);
}
#[test]
fn radial_gradient_into_fill() {
let g = RadialGradient::new(
Point::new(0.0, 0.0),
10.0,
vec![
GradientStop {
offset: 0.0,
color: Color::BLACK,
},
GradientStop {
offset: 1.0,
color: Color::WHITE,
},
],
);
let style = FillStrokeStyle::fill_gradient(g);
assert!(matches!(style.fill, Some(Fill::RadialGradient(_))));
}
#[test]
fn rect_center_helper() {
assert_eq!(
Rect::new(2.0, 4.0, 12.0, 10.0).center(),
Point::new(7.0, 7.0)
);
}
#[test]
fn corner_radii_uniform_vs_per_corner() {
let u = CornerRadii::uniform(4.0);
assert!(u.is_uniform());
assert_eq!(u.uniform_value(), 4.0);
let el = Element::rounded_rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
4.0,
FillStrokeStyle::fill(Color::BLACK),
);
match el {
Element::RoundedRect { rect, radii, style } => {
assert_eq!(rect, Rect::new(0.0, 0.0, 10.0, 10.0));
assert_eq!(radii, u);
assert_eq!(style.fill, Some(Fill::Solid(Color::BLACK)));
}
_ => panic!("expected RoundedRect"),
}
let p = CornerRadii::new(6.0, 0.0, 0.0, 0.0);
assert!(!p.is_uniform());
assert_eq!(
p.to_kurbo(),
kurbo::RoundedRectRadii::new(6.0, 0.0, 0.0, 0.0)
);
}
#[test]
fn clip_constructors_and_bezpath() {
let c = Clip::circle(Point::new(1.0, 2.0), 5.0);
assert!(matches!(c, Clip::Circle { radius: 5.0, .. }));
let p = c.to_bezpath();
assert!(!p.is_empty());
let r = Clip::rect(Rect::new(0.0, 0.0, 10.0, 20.0));
assert!(matches!(r, Clip::Rect(_)));
assert!(!r.to_bezpath().is_empty());
let rr = Clip::rounded_rect(Rect::new(0.0, 0.0, 10.0, 10.0), 2.0);
assert!(matches!(rr, Clip::RoundedRect { .. }));
let e = Clip::ellipse(Point::new(0.0, 0.0), Vec2::new(3.0, 4.0), 0.0);
assert!(matches!(e, Clip::Ellipse { .. }));
let mut bp = BezPath::new();
bp.move_to((0.0, 0.0));
bp.line_to((1.0, 0.0));
let p2 = Clip::path(bp);
assert!(matches!(p2, Clip::Path(_)));
assert!(!p2.to_bezpath().is_empty());
}
#[test]
fn scene_node_clip_builder() {
let node = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 10.0, 10.0),
FillStrokeStyle::fill(Color::BLACK),
))
.with_clip(Clip::circle(Point::new(5.0, 5.0), 3.0));
assert!(node.clip.is_some());
let n = SceneNode::new(Element::rect(
Rect::new(0.0, 0.0, 1.0, 1.0),
FillStrokeStyle::fill(Color::BLACK),
));
assert!(n.clip.is_none());
}
}
mod ordering {
use super::*;
#[test]
fn iter_ordered_sorts_z_ascending() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_node(rect_node(0.0, 5));
scene.push_node(rect_node(0.0, -3));
scene.push_node(rect_node(0.0, 1));
let zs: Vec<i32> = scene.iter_ordered().map(|n| n.z_index).collect();
assert_eq!(zs, vec![-3, 1, 5]);
}
#[test]
fn ordered_is_stable_within_same_z() {
let nodes = vec![rect_node(10.0, 0), rect_node(20.0, 0), rect_node(30.0, 0)];
let xs: Vec<f64> = SceneNode::ordered(&nodes).map(rect_x).collect();
assert_eq!(xs, vec![10.0, 20.0, 30.0]);
}
#[test]
fn z_index_does_not_cross_root_lists() {
let mut scene = Scene::new(10.0, 10.0);
scene.push_node(rect_node(1.0, 100)); scene.push_layer(Layer::new("top").with_nodes(vec![rect_node(2.0, -100)]));
let drawn: Vec<f64> = scene
.root_lists()
.flat_map(|(nodes, _)| SceneNode::ordered(nodes).map(rect_x).collect::<Vec<_>>())
.collect();
assert_eq!(drawn, vec![1.0, 2.0], "layer 数组顺序优先于 z_index");
}
#[test]
fn layer_iter_ordered_sorts_within_layer() {
let layer = Layer::new("l").with_nodes(vec![
rect_node(0.0, 5),
rect_node(0.0, -2),
rect_node(0.0, 1),
]);
let zs: Vec<i32> = layer.iter_ordered().map(|n| n.z_index).collect();
assert_eq!(zs, vec![-2, 1, 5]);
}
}
mod scene {
use super::*;
#[test]
fn scene_metadata_defaults_and_builders() {
let scene = Scene::new(10.0, 20.0)
.with_title("图表")
.with_description("示例")
.with_scale(2.0);
assert_eq!(scene.title.as_deref(), Some("图表"));
assert_eq!(scene.description.as_deref(), Some("示例"));
assert_eq!(scene.scale, 2.0);
let d = Scene::default();
assert_eq!(d.scale, 1.0);
}
#[test]
fn scene_node_group_and_push_group() {
let group = SceneNode::group(vec![rect_node(0.0, 0), rect_node(0.0, 1)]);
assert_eq!(group.children().unwrap().len(), 2);
assert!(group.element().is_none(), "容器没有 leaf element");
let mut scene = Scene::new(10.0, 10.0);
scene.push_group(vec![rect_node(0.0, 0)]);
assert!(scene.nodes[0].is_group());
}
#[test]
fn container_accessors_and_traversal() {
let outer = SceneNode::group(vec![
rect_node(0.0, 0),
SceneNode::group(vec![rect_node(5.0, 0)]),
]);
assert!(outer.is_group());
assert_eq!(outer.children().map(|c| c.len()), Some(2));
assert!(!outer.children().unwrap()[0].is_group());
assert!(outer.children().unwrap()[1].is_group());
assert!(rect_node(0.0, 0).children().is_none());
let mut visited = 0usize;
outer.visit(&mut |_| visited += 1);
assert_eq!(visited, 4);
let mut outer = outer;
outer.children_mut().unwrap()[1]
.children_mut()
.unwrap()
.push(rect_node(9.0, 0));
assert_eq!(outer.children().unwrap()[1].children().unwrap().len(), 2);
}
#[test]
fn visit_mut_reaches_every_node() {
let mut outer = SceneNode::group(vec![rect_node(0.0, 0)]);
let mut seen = 0usize;
outer.visit_mut(&mut |_| seen += 1);
assert_eq!(seen, 2, "根容器 + 1 个子节点");
}
#[test]
fn scene_visit_nodes_covers_default_and_layers() {
let mut scene = Scene::new(20.0, 20.0);
scene.push(rect_node(0.0, 0)); scene.push_group(vec![rect_node(0.0, 0)]); scene.push_layer(Layer::new("L").with_nodes(vec![rect_node(0.0, 0)]));
let mut seen = 0usize;
scene.visit_nodes(&mut |_| seen += 1);
assert_eq!(seen, 1 + 1 + 1 + 1);
}
#[test]
fn scene_root_lists_skip_hidden_layers() {
let mut scene = Scene::new(20.0, 20.0);
scene.push(rect_node(0.0, 0));
scene.push_layer(Layer::new("a").with_nodes(vec![rect_node(0.0, 0)]));
scene.push_layer(
Layer::new("b")
.with_nodes(vec![rect_node(0.0, 0), rect_node(1.0, 0)])
.with_visible(false),
);
let sizes: Vec<usize> = scene.root_lists().map(|(n, _)| n.len()).collect();
assert_eq!(sizes, vec![1, 1], "默认层 + 可见层 a;隐藏层 b 被跳过");
}
#[test]
fn scene_push_layer_and_lookup() {
let mut scene = Scene::new(100.0, 100.0);
scene.push_layer(Layer::new("grid"));
scene.push_layer(Layer::new("data").with_nodes(vec![rect_node(0.0, 0)]));
assert_eq!(scene.layers().len(), 2);
assert!(scene.layer("data").is_some());
assert!(scene.layer("missing").is_none());
scene.layer_mut("grid").unwrap().visible = false;
assert!(!scene.layers[0].visible);
}
#[test]
fn scene_default_has_empty_layers() {
let scene = Scene::new(10.0, 10.0);
assert!(scene.layers.is_empty());
}
}
mod layer {
use super::*;
#[test]
fn layer_defaults_and_builders() {
let layer = Layer::new("data").with_nodes(vec![rect_node(0.0, 1)]);
assert_eq!(layer.name, "data");
assert!(layer.visible);
assert_eq!(layer.opacity, 1.0);
assert!(layer.transform.is_none());
assert_eq!(layer.nodes.len(), 1);
let l2 = Layer::new("x")
.with_visible(false)
.with_opacity(0.5)
.with_transform(Transform::translate(1.0, 2.0));
assert!(!l2.visible);
assert_eq!(l2.opacity, 0.5);
assert_eq!(l2.transform, Some(Transform::translate(1.0, 2.0)));
}
#[test]
fn layer_scope_matches_its_attributes() {
let layer = Layer::new("l").with_opacity(0.5);
let s = layer.scope();
assert_eq!(s.opacity, 0.5);
assert_eq!(s.blend_mode, BlendMode::Normal);
assert_eq!(s.name, Some("l"));
assert!(s.clip.is_none() && s.filter.is_none() && s.mask.is_none());
assert!(!s.is_identity());
assert!(Layer::new("").scope().is_identity());
}
}
mod gradient {
use super::*;
fn ramp() -> Vec<GradientStop> {
vec![
GradientStop {
offset: 0.0,
color: Color::rgb(0, 0, 0),
},
GradientStop {
offset: 1.0,
color: Color::rgb(255, 255, 255),
},
]
}
#[test]
fn sample_stops_interpolates_and_clamps() {
let s = ramp();
assert_eq!(sample_stops(&s, -1.0).r, 0);
assert_eq!(sample_stops(&s, 0.0).r, 0);
assert_eq!(sample_stops(&s, 0.5).r, 128);
assert_eq!(sample_stops(&s, 2.0).r, 255);
}
#[test]
fn sweep_ramp_honours_spread() {
use std::f64::consts::{FRAC_PI_2, PI, TAU};
let s = ramp();
let g = SweepGradient::new(Point::ZERO, 0.0, FRAC_PI_2, s.clone());
assert!(g.ramp_t(0.0).abs() < 1e-12);
assert!((g.ramp_t(FRAC_PI_2) - 1.0).abs() < 1e-12);
assert!((g.ramp_t(PI) - 1.0).abs() < 1e-12);
assert_eq!(g.sample(0.0).r, 0);
assert_eq!(g.sample(PI).r, 255);
let rep = g.clone().with_spread(GradientSpread::Repeat);
assert!(rep.ramp_t(PI).abs() < 1e-12);
let refl = g.with_spread(GradientSpread::Reflect);
assert!((refl.ramp_t(1.25 * PI) - 0.5).abs() < 1e-12);
let full = SweepGradient::full(Point::ZERO, 0.0, s);
assert!((full.end_angle - TAU).abs() < 1e-12);
assert!(matches!(Fill::from(full), Fill::SweepGradient(_)));
}
}
mod color_matrix {
use super::*;
#[test]
fn presets_and_apply() {
let c = Color::rgba(0x20, 0x40, 0x60, 0xff);
assert_eq!(ColorMatrix::IDENTITY.apply(c), c);
assert!(ColorMatrix::IDENTITY.is_identity());
assert!(ColorMatrix::saturate(1.0).is_identity());
assert_eq!(ColorMatrix::saturate(1.0).apply(c), c);
assert_eq!(ColorMatrix::hue_rotate(0.0).apply(c), c);
let g = ColorMatrix::grayscale().apply(c);
assert_eq!(g.r, g.g);
assert_eq!(g.g, g.b);
let lum = 0.213 * 32.0 + 0.715 * 64.0 + 0.072 * 96.0;
assert!((f64::from(g.r) - lum).abs() <= 1.0, "got {}", g.r);
assert_eq!(g.a, 255, "alpha 不受影响");
let b = ColorMatrix::brightness(0.5).apply(Color::rgb(0xff, 0x80, 0x00));
assert_eq!((b.r, b.g, b.b), (128, 64, 0));
}
#[test]
fn compose_in_order() {
let c = Color::rgb(0xff, 0x00, 0x00);
let tint_blue = ColorMatrix::tint(Color::rgb(0, 0, 255), 0.5);
let a = tint_blue.then(ColorMatrix::grayscale());
assert_eq!(a.apply(c).r, 36);
let b = ColorMatrix::grayscale().then(tint_blue);
let out = b.apply(c);
assert_eq!((out.r, out.g), (27, 27));
assert_eq!(out.b, 155);
assert_eq!(
a.apply(c),
ColorMatrix::grayscale().apply(tint_blue.apply(c))
);
}
#[test]
fn tint_blends_toward_the_colour() {
let out =
ColorMatrix::tint(Color::rgb(0, 0, 255), 0.5).apply(Color::rgb(0xff, 0x00, 0x00));
assert_eq!((out.r, out.g, out.b), (128, 0, 128));
assert_eq!(
ColorMatrix::tint(Color::WHITE, 0.0).apply(Color::BLACK),
Color::BLACK
);
assert_eq!(
ColorMatrix::tint(Color::rgb(0x11, 0x22, 0x33), 1.0).apply(Color::BLACK),
Color::rgb(0x11, 0x22, 0x33)
);
}
}
mod image {
use super::*;
fn img(w: u32, h: u32) -> SceneImage {
let px = vec![0u8; (w * h * 4) as usize];
SceneImage::from_rgba8(w, h, px).unwrap()
}
#[test]
fn preserve_aspect_ratio_mapping() {
let base = img(10, 10);
assert_eq!(base.preserve_aspect_ratio(), "xMidYMid meet");
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::Cover)
.preserve_aspect_ratio(),
"xMidYMid slice"
);
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::Fill)
.preserve_aspect_ratio(),
"none"
);
assert_eq!(
base.clone()
.with_object_fit(ObjectFit::None)
.preserve_aspect_ratio(),
"none"
);
}
#[test]
fn default_object_fit_is_contain() {
assert_eq!(img(1, 1).object_fit, ObjectFit::Contain);
}
#[test]
fn from_rgba8_validates_dimensions() {
assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 64]).is_some());
assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 63]).is_none());
}
#[test]
fn from_png_roundtrips() {
let pm = crate::Pixmap::from_rgba8(2, 2, vec![255u8; 16]).unwrap();
let png = pm.to_png();
let img = SceneImage::from_png(&png).expect("有效 PNG 应可解码");
assert_eq!(img.width(), 2);
assert_eq!(img.height(), 2);
assert_eq!(img.pixmap.pixels(), pm.pixels());
}
#[test]
fn image_element_constructs() {
let img = img(4, 4);
let el = Element::image(img, Rect::new(0.0, 0.0, 10.0, 10.0));
match &el {
Element::Image {
image,
frame,
opacity,
} => {
assert_eq!(image.width(), 4);
assert_eq!(image.height(), 4);
assert_eq!(frame.width(), 10.0);
assert_eq!(*opacity, 1.0);
}
_ => panic!("expected image"),
}
}
}
}