summaryrefslogtreecommitdiffstats
path: root/graphics
diff options
context:
space:
mode:
Diffstat (limited to 'graphics')
-rw-r--r--graphics/Cargo.toml2
-rw-r--r--graphics/src/gradient.rs30
-rw-r--r--graphics/src/gradient/linear.rs178
-rw-r--r--graphics/src/layer.rs126
-rw-r--r--graphics/src/layer/image.rs23
-rw-r--r--graphics/src/layer/mesh.rs51
-rw-r--r--graphics/src/layer/quad.rs30
-rw-r--r--graphics/src/layer/text.rs26
-rw-r--r--graphics/src/lib.rs1
-rw-r--r--graphics/src/primitive.rs5
-rw-r--r--graphics/src/transformation.rs8
-rw-r--r--graphics/src/triangle.rs10
-rw-r--r--graphics/src/widget/canvas.rs21
-rw-r--r--graphics/src/widget/canvas/fill.rs59
-rw-r--r--graphics/src/widget/canvas/frame.rs138
-rw-r--r--graphics/src/widget/canvas/stroke.rs41
16 files changed, 550 insertions, 199 deletions
diff --git a/graphics/Cargo.toml b/graphics/Cargo.toml
index 49d4d9c6..ff6fcd4a 100644
--- a/graphics/Cargo.toml
+++ b/graphics/Cargo.toml
@@ -19,7 +19,7 @@ font-icons = []
opengl = []
[dependencies]
-glam = "0.10"
+glam = "0.21.3"
raw-window-handle = "0.4"
thiserror = "1.0"
diff --git a/graphics/src/gradient.rs b/graphics/src/gradient.rs
new file mode 100644
index 00000000..da0f911d
--- /dev/null
+++ b/graphics/src/gradient.rs
@@ -0,0 +1,30 @@
+//! For creating a Gradient.
+mod linear;
+
+pub use crate::gradient::linear::{Linear, Location, Position};
+use crate::Color;
+
+#[derive(Debug, Clone, PartialEq)]
+/// A fill which transitions colors progressively along a direction, either linearly, radially (TBD),
+/// or conically (TBD).
+pub enum Gradient {
+ /// A linear gradient interpolates colors along a direction from its [`start`] to its [`end`]
+ /// point.
+ Linear(Linear),
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+/// A point along the gradient vector where the specified [`color`] is unmixed.
+pub struct ColorStop {
+ /// Offset along the gradient vector.
+ pub offset: f32,
+ /// The color of the gradient at the specified [`offset`].
+ pub color: Color,
+}
+
+impl Gradient {
+ /// Creates a new linear [`linear::Builder`].
+ pub fn linear(position: impl Into<Position>) -> linear::Builder {
+ linear::Builder::new(position.into())
+ }
+}
diff --git a/graphics/src/gradient/linear.rs b/graphics/src/gradient/linear.rs
new file mode 100644
index 00000000..a9cfd55d
--- /dev/null
+++ b/graphics/src/gradient/linear.rs
@@ -0,0 +1,178 @@
+//! Linear gradient builder & definition.
+use crate::gradient::{ColorStop, Gradient};
+use crate::{Color, Point, Size};
+
+/// A linear gradient that can be used in the style of [`super::Fill`] or [`super::Stroke`].
+#[derive(Debug, Clone, PartialEq)]
+pub struct Linear {
+ /// The point where the linear gradient begins.
+ pub start: Point,
+ /// The point where the linear gradient ends.
+ pub end: Point,
+ /// [`ColorStop`]s along the linear gradient path.
+ pub color_stops: Vec<ColorStop>,
+}
+
+#[derive(Debug)]
+/// The position of the gradient within its bounds.
+pub enum Position {
+ /// The gradient will be positioned with respect to two points.
+ Absolute {
+ /// The starting point of the gradient.
+ start: Point,
+ /// The ending point of the gradient.
+ end: Point,
+ },
+ /// The gradient will be positioned relative to the provided bounds.
+ Relative {
+ /// The top left position of the bounds.
+ top_left: Point,
+ /// The width & height of the bounds.
+ size: Size,
+ /// The start [Location] of the gradient.
+ start: Location,
+ /// The end [Location] of the gradient.
+ end: Location,
+ },
+}
+
+impl Into<Position> for (Point, Point) {
+ fn into(self) -> Position {
+ Position::Absolute {
+ start: self.0,
+ end: self.1,
+ }
+ }
+}
+
+#[derive(Debug)]
+/// The location of a relatively-positioned gradient.
+pub enum Location {
+ /// Top left.
+ TopLeft,
+ /// Top.
+ Top,
+ /// Top right.
+ TopRight,
+ /// Right.
+ Right,
+ /// Bottom right.
+ BottomRight,
+ /// Bottom.
+ Bottom,
+ /// Bottom left.
+ BottomLeft,
+ /// Left.
+ Left,
+}
+
+impl Location {
+ fn to_absolute(&self, top_left: Point, size: Size) -> Point {
+ match self {
+ Location::TopLeft => top_left,
+ Location::Top => {
+ Point::new(top_left.x + size.width / 2.0, top_left.y)
+ }
+ Location::TopRight => {
+ Point::new(top_left.x + size.width, top_left.y)
+ }
+ Location::Right => Point::new(
+ top_left.x + size.width,
+ top_left.y + size.height / 2.0,
+ ),
+ Location::BottomRight => {
+ Point::new(top_left.x + size.width, top_left.y + size.height)
+ }
+ Location::Bottom => Point::new(
+ top_left.x + size.width / 2.0,
+ top_left.y + size.height,
+ ),
+ Location::BottomLeft => {
+ Point::new(top_left.x, top_left.y + size.height)
+ }
+ Location::Left => {
+ Point::new(top_left.x, top_left.y + size.height / 2.0)
+ }
+ }
+ }
+}
+
+/// A [`Linear`] builder.
+#[derive(Debug)]
+pub struct Builder {
+ start: Point,
+ end: Point,
+ stops: Vec<ColorStop>,
+ valid: bool,
+}
+
+impl Builder {
+ /// Creates a new [`Builder`].
+ pub fn new(position: Position) -> Self {
+ let (start, end) = match position {
+ Position::Absolute { start, end } => (start, end),
+ Position::Relative {
+ top_left,
+ size,
+ start,
+ end,
+ } => (
+ start.to_absolute(top_left, size),
+ end.to_absolute(top_left, size),
+ ),
+ };
+
+ Self {
+ start,
+ end,
+ stops: vec![],
+ valid: true,
+ }
+ }
+
+ /// Adds a new stop, defined by an offset and a color, to the gradient.
+ ///
+ /// `offset` must be between `0.0` and `1.0` or the gradient cannot be built.
+ ///
+ /// Note: when using the [Glow] backend, any color stop added after the 16th
+ /// will not be displayed.
+ ///
+ /// On [backend::Wgpu] backend this limitation does not exist (technical limit is 524,288 stops).
+ pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
+ if offset.is_finite() && (0.0..=1.0).contains(&offset) {
+ match self.stops.binary_search_by(|stop| {
+ stop.offset.partial_cmp(&offset).unwrap()
+ }) {
+ Ok(_) => {
+ //the offset already exists in the gradient
+ self.valid = false;
+ }
+ Err(index) => {
+ self.stops.insert(index, ColorStop { offset, color })
+ }
+ }
+ } else {
+ self.valid = false;
+ }
+ self
+ }
+
+ /// Builds the linear [`Gradient`] of this [`Builder`].
+ ///
+ /// Returns `Err` if no stops were added to the builder or
+ /// if stops not between 0.0 and 1.0 were added.
+ pub fn build(self) -> Result<Gradient, &'static str> {
+ if self.stops.is_empty() || !self.valid {
+ return Err("Valid gradient conditions: \
+ 1) Must contain at least one color stop. \
+ 2) Every color stop offset must be unique. \
+ 3) Every color stop must be within the range of 0.0..=1.0");
+ }
+
+ Ok(Gradient::Linear(Linear {
+ start: self.start,
+ end: self.end,
+ color_stops: self.stops,
+ }))
+ }
+}
diff --git a/graphics/src/layer.rs b/graphics/src/layer.rs
index af545713..56a42a9d 100644
--- a/graphics/src/layer.rs
+++ b/graphics/src/layer.rs
@@ -1,15 +1,20 @@
//! Organize rendering primitives into a flattened list of layers.
+pub mod mesh;
+mod quad;
+mod text;
+mod image;
+
use crate::alignment;
-use crate::triangle;
use crate::{
Background, Font, Point, Primitive, Rectangle, Size, Vector, Viewport,
};
-
-use iced_native::image;
-use iced_native::svg;
+pub use crate::layer::image::Image;
+pub use crate::layer::mesh::Mesh;
+pub use crate::layer::quad::Quad;
+pub use crate::layer::text::Text;
/// A group of primitives that should be clipped together.
-#[derive(Debug, Clone)]
+#[derive(Debug)]
pub struct Layer<'a> {
/// The clipping bounds of the [`Layer`].
pub bounds: Rectangle,
@@ -159,7 +164,11 @@ impl<'a> Layer<'a> {
border_color: border_color.into_linear(),
});
}
- Primitive::Mesh2D { buffers, size } => {
+ Primitive::Mesh2D {
+ buffers,
+ size,
+ style,
+ } => {
let layer = &mut layers[current_layer];
let bounds = Rectangle::new(
@@ -169,11 +178,14 @@ impl<'a> Layer<'a> {
// Only draw visible content
if let Some(clip_bounds) = layer.bounds.intersection(&bounds) {
- layer.meshes.push(Mesh {
- origin: Point::new(translation.x, translation.y),
- buffers,
- clip_bounds,
- });
+ layer.meshes.push(
+ Mesh {
+ origin: Point::new(translation.x, translation.y),
+ buffers,
+ clip_bounds,
+ style,
+ }
+ );
}
}
Primitive::Clip { bounds, content } => {
@@ -232,94 +244,4 @@ impl<'a> Layer<'a> {
}
}
}
-}
-
-/// A colored rectangle with a border.
-///
-/// This type can be directly uploaded to GPU memory.
-#[derive(Debug, Clone, Copy)]
-#[repr(C)]
-pub struct Quad {
- /// The position of the [`Quad`].
- pub position: [f32; 2],
-
- /// The size of the [`Quad`].
- pub size: [f32; 2],
-
- /// The color of the [`Quad`], in __linear RGB__.
- pub color: [f32; 4],
-
- /// The border color of the [`Quad`], in __linear RGB__.
- pub border_color: [f32; 4],
-
- /// The border radius of the [`Quad`].
- pub border_radius: f32,
-
- /// The border width of the [`Quad`].
- pub border_width: f32,
-}
-
-/// A mesh of triangles.
-#[derive(Debug, Clone, Copy)]
-pub struct Mesh<'a> {
- /// The origin of the vertices of the [`Mesh`].
- pub origin: Point,
-
- /// The vertex and index buffers of the [`Mesh`].
- pub buffers: &'a triangle::Mesh2D,
-
- /// The clipping bounds of the [`Mesh`].
- pub clip_bounds: Rectangle<f32>,
-}
-
-/// A paragraph of text.
-#[derive(Debug, Clone, Copy)]
-pub struct Text<'a> {
- /// The content of the [`Text`].
- pub content: &'a str,
-
- /// The layout bounds of the [`Text`].
- pub bounds: Rectangle,
-
- /// The color of the [`Text`], in __linear RGB_.
- pub color: [f32; 4],
-
- /// The size of the [`Text`].
- pub size: f32,
-
- /// The font of the [`Text`].
- pub font: Font,
-
- /// The horizontal alignment of the [`Text`].
- pub horizontal_alignment: alignment::Horizontal,
-
- /// The vertical alignment of the [`Text`].
- pub vertical_alignment: alignment::Vertical,
-}
-
-/// A raster or vector image.
-#[derive(Debug, Clone)]
-pub enum Image {
- /// A raster image.
- Raster {
- /// The handle of a raster image.
- handle: image::Handle,
-
- /// The bounds of the image.
- bounds: Rectangle,
- },
- /// A vector image.
- Vector {
- /// The handle of a vector image.
- handle: svg::Handle,
-
- /// The bounds of the image.
- bounds: Rectangle,
- },
-}
-
-#[allow(unsafe_code)]
-unsafe impl bytemuck::Zeroable for Quad {}
-
-#[allow(unsafe_code)]
-unsafe impl bytemuck::Pod for Quad {}
+} \ No newline at end of file
diff --git a/graphics/src/layer/image.rs b/graphics/src/layer/image.rs
new file mode 100644
index 00000000..cbba7888
--- /dev/null
+++ b/graphics/src/layer/image.rs
@@ -0,0 +1,23 @@
+use iced_native::{image, svg};
+use crate::Rectangle;
+
+/// A raster or vector image.
+#[derive(Debug, Clone)]
+pub enum Image {
+ /// A raster image.
+ Raster {
+ /// The handle of a raster image.
+ handle: image::Handle,
+
+ /// The bounds of the image.
+ bounds: Rectangle,
+ },
+ /// A vector image.
+ Vector {
+ /// The handle of a vector image.
+ handle: svg::Handle,
+
+ /// The bounds of the image.
+ bounds: Rectangle,
+ },
+}
diff --git a/graphics/src/layer/mesh.rs b/graphics/src/layer/mesh.rs
new file mode 100644
index 00000000..0946317e
--- /dev/null
+++ b/graphics/src/layer/mesh.rs
@@ -0,0 +1,51 @@
+//! A collection of triangle primitives.
+
+use crate::{Color, Point, Rectangle, triangle};
+use crate::gradient::Gradient;
+
+/// A mesh of triangles.
+#[derive(Debug, Clone, Copy)]
+pub struct Mesh<'a> {
+ /// The origin of the vertices of the [`Mesh`].
+ pub origin: Point,
+
+ /// The vertex and index buffers of the [`Mesh`].
+ pub buffers: &'a triangle::Mesh2D,
+
+ /// The clipping bounds of the [`Mesh`].
+ pub clip_bounds: Rectangle<f32>,
+
+ /// The shader of the [`Mesh`].
+ pub style: &'a Style,
+}
+
+#[derive(Debug, Clone)]
+/// Supported shaders for primitives.
+pub enum Style {
+ /// Fill a primitive with a solid color.
+ Solid(Color),
+ /// Fill a primitive with an interpolated color.
+ Gradient(Gradient)
+}
+
+impl <'a> Into<Style> for Gradient {
+ fn into(self) -> Style {
+ match self {
+ Gradient::Linear(linear) => {
+ Style::Gradient(Gradient::Linear(linear))
+ }
+ }
+ }
+}
+
+/// Returns the number of total vertices & total indices of all [`Mesh`]es.
+pub fn attribute_count_of<'a>(meshes: &'a [Mesh<'a>]) -> (usize, usize) {
+ meshes
+ .iter()
+ .map(|Mesh { buffers, .. }| {
+ (buffers.vertices.len(), buffers.indices.len())
+ })
+ .fold((0, 0), |(total_v, total_i), (v, i)| {
+ (total_v + v, total_i + i)
+ })
+}
diff --git a/graphics/src/layer/quad.rs b/graphics/src/layer/quad.rs
new file mode 100644
index 00000000..4def8427
--- /dev/null
+++ b/graphics/src/layer/quad.rs
@@ -0,0 +1,30 @@
+/// A colored rectangle with a border.
+///
+/// This type can be directly uploaded to GPU memory.
+#[derive(Debug, Clone, Copy)]
+#[repr(C)]
+pub struct Quad {
+ /// The position of the [`Quad`].
+ pub position: [f32; 2],
+
+ /// The size of the [`Quad`].
+ pub size: [f32; 2],
+
+ /// The color of the [`Quad`], in __linear RGB__.
+ pub color: [f32; 4],
+
+ /// The border color of the [`Quad`], in __linear RGB__.
+ pub border_color: [f32; 4],
+
+ /// The border radius of the [`Quad`].
+ pub border_radius: f32,
+
+ /// The border width of the [`Quad`].
+ pub border_width: f32,
+}
+
+#[allow(unsafe_code)]
+unsafe impl bytemuck::Zeroable for Quad {}
+
+#[allow(unsafe_code)]
+unsafe impl bytemuck::Pod for Quad {}
diff --git a/graphics/src/layer/text.rs b/graphics/src/layer/text.rs
new file mode 100644
index 00000000..74f7a676
--- /dev/null
+++ b/graphics/src/layer/text.rs
@@ -0,0 +1,26 @@
+use crate::{alignment, Font, Rectangle};
+
+/// A paragraph of text.
+#[derive(Debug, Clone, Copy)]
+pub struct Text<'a> {
+ /// The content of the [`Text`].
+ pub content: &'a str,
+
+ /// The layout bounds of the [`Text`].
+ pub bounds: Rectangle,
+
+ /// The color of the [`Text`], in __linear RGB_.
+ pub color: [f32; 4],
+
+ /// The size of the [`Text`].
+ pub size: f32,
+
+ /// The font of the [`Text`].
+ pub font: Font,
+
+ /// The horizontal alignment of the [`Text`].
+ pub horizontal_alignment: alignment::Horizontal,
+
+ /// The vertical alignment of the [`Text`].
+ pub vertical_alignment: alignment::Vertical,
+}
diff --git a/graphics/src/lib.rs b/graphics/src/lib.rs
index 11082472..0d29416c 100644
--- a/graphics/src/lib.rs
+++ b/graphics/src/lib.rs
@@ -35,6 +35,7 @@ pub mod renderer;
pub mod triangle;
pub mod widget;
pub mod window;
+pub mod gradient;
pub use antialiasing::Antialiasing;
pub use backend::Backend;
diff --git a/graphics/src/primitive.rs b/graphics/src/primitive.rs
index 5f7a344d..5cb0ef23 100644
--- a/graphics/src/primitive.rs
+++ b/graphics/src/primitive.rs
@@ -2,7 +2,7 @@ use iced_native::image;
use iced_native::svg;
use iced_native::{Background, Color, Font, Rectangle, Size, Vector};
-use crate::alignment;
+use crate::{alignment, layer::mesh};
use crate::triangle;
use std::sync::Arc;
@@ -88,6 +88,9 @@ pub enum Primitive {
///
/// Any geometry that falls out of this region will be clipped.
size: Size,
+
+ /// The shader of the mesh
+ style: mesh::Style,
},
/// A cached primitive.
///
diff --git a/graphics/src/transformation.rs b/graphics/src/transformation.rs
index 2a19caed..116b3058 100644
--- a/graphics/src/transformation.rs
+++ b/graphics/src/transformation.rs
@@ -8,7 +8,7 @@ pub struct Transformation(Mat4);
impl Transformation {
/// Get the identity transformation.
pub fn identity() -> Transformation {
- Transformation(Mat4::identity())
+ Transformation(Mat4::IDENTITY)
}
/// Creates an orthographic projection.
@@ -51,3 +51,9 @@ impl From<Transformation> for [f32; 16] {
*t.as_ref()
}
}
+
+impl Into<Mat4> for Transformation {
+ fn into(self) -> Mat4 {
+ self.0
+ }
+}
diff --git a/graphics/src/triangle.rs b/graphics/src/triangle.rs
index 05028f51..f019d55d 100644
--- a/graphics/src/triangle.rs
+++ b/graphics/src/triangle.rs
@@ -6,20 +6,14 @@ use bytemuck::{Pod, Zeroable};
pub struct Mesh2D {
/// The vertices of the mesh
pub vertices: Vec<Vertex2D>,
-
/// The list of vertex indices that defines the triangles of the mesh.
- ///
- /// Therefore, this list should always have a length that is a multiple of
- /// 3.
pub indices: Vec<u32>,
}
-/// A two-dimensional vertex with some color in __linear__ RGBA.
+/// A two-dimensional vertex.
#[derive(Copy, Clone, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct Vertex2D {
- /// The vertex position
+ /// The vertex position in 2D space.
pub position: [f32; 2],
- /// The vertex color in __linear__ RGBA.
- pub color: [f32; 4],
}
diff --git a/graphics/src/widget/canvas.rs b/graphics/src/widget/canvas.rs
index b4afd998..ea2efcc1 100644
--- a/graphics/src/widget/canvas.rs
+++ b/graphics/src/widget/canvas.rs
@@ -9,12 +9,12 @@ pub mod path;
mod cache;
mod cursor;
-mod fill;
-mod frame;
mod geometry;
mod program;
-mod stroke;
mod text;
+pub mod fill;
+pub mod stroke;
+pub(crate) mod frame;
pub use cache::Cache;
pub use cursor::Cursor;
@@ -28,6 +28,7 @@ pub use stroke::{LineCap, LineDash, LineJoin, Stroke};
pub use text::Text;
use crate::{Backend, Primitive, Renderer};
+pub use crate::gradient::{self, Gradient};
use iced_native::layout::{self, Layout};
use iced_native::mouse;
@@ -45,16 +46,12 @@ use std::marker::PhantomData;
/// If you want to get a quick overview, here's how we can draw a simple circle:
///
/// ```no_run
-/// # mod iced {
-/// # pub mod widget {
-/// # pub use iced_graphics::widget::canvas;
-/// # }
-/// # pub use iced_native::{Color, Rectangle, Theme};
-/// # }
-/// use iced::widget::canvas::{self, Canvas, Cursor, Fill, Frame, Geometry, Path, Program};
-/// use iced::{Color, Rectangle, Theme};
-///
/// // First, we define the data we need for drawing
+/// use iced_graphics::{Color, Rectangle};
+/// use iced_graphics::widget::Canvas;
+/// use iced_graphics::widget::canvas::{Cursor, Frame, Geometry, Path, Program};
+/// use iced_style::Theme;
+///
/// #[derive(Debug)]
/// struct Circle {
/// radius: f32,
diff --git a/graphics/src/widget/canvas/fill.rs b/graphics/src/widget/canvas/fill.rs
index 56495435..34cc5e50 100644
--- a/graphics/src/widget/canvas/fill.rs
+++ b/graphics/src/widget/canvas/fill.rs
@@ -1,12 +1,17 @@
+//! Fill [crate::widget::canvas::Geometry] with a certain style.
+
+use crate::gradient::Gradient;
+use crate::layer::mesh;
use iced_native::Color;
+use crate::widget::canvas::frame::Transform;
/// The style used to fill geometry.
-#[derive(Debug, Clone, Copy)]
-pub struct Fill {
- /// The color used to fill geometry.
+#[derive(Debug, Clone)]
+pub struct Fill<'a> {
+ /// The color or gradient of the fill.
///
- /// By default, it is set to `BLACK`.
- pub color: Color,
+ /// By default, it is set to [`FillStyle::Solid`] `BLACK`.
+ pub style: Style<'a>,
/// The fill rule defines how to determine what is inside and what is
/// outside of a shape.
@@ -19,24 +24,56 @@ pub struct Fill {
pub rule: FillRule,
}
-impl Default for Fill {
- fn default() -> Fill {
+impl<'a> Default for Fill<'a> {
+ fn default() -> Fill<'a> {
Fill {
- color: Color::BLACK,
+ style: Style::Solid(Color::BLACK),
rule: FillRule::NonZero,
}
}
}
-impl From<Color> for Fill {
- fn from(color: Color) -> Fill {
+impl<'a> From<Color> for Fill<'a> {
+ fn from(color: Color) -> Fill<'a> {
Fill {
- color,
+ style: Style::Solid(color),
..Fill::default()
}
}
}
+impl<'a> Into<Fill<'a>> for &'a Gradient {
+ fn into(self) -> Fill<'a> {
+ Fill {
+ style: Style::Gradient(self),
+ ..Default::default()
+ }
+ }
+}
+
+/// The style of a [`Fill`].
+#[derive(Debug, Clone)]
+pub enum Style<'a> {
+ /// A solid color
+ Solid(Color),
+ /// A color gradient
+ Gradient(&'a Gradient),
+}
+
+impl<'a> Style<'a> {
+ /// Converts a fill's [Style] to a [mesh::Style] for use in the renderer's shader.
+ pub(crate) fn as_mesh_style(&self, transform: &Transform) -> mesh::Style {
+ match self {
+ Style::Solid(color) => {
+ mesh::Style::Solid(*color)
+ },
+ Style::Gradient(gradient) => mesh::Style::Gradient(
+ transform.transform_gradient((*gradient).clone()),
+ ),
+ }
+ }
+}
+
/// The fill rule defines how to determine what is inside and what is outside of
/// a shape.
///
diff --git a/graphics/src/widget/canvas/frame.rs b/graphics/src/widget/canvas/frame.rs
index 516539ca..3ba72179 100644
--- a/graphics/src/widget/canvas/frame.rs
+++ b/graphics/src/widget/canvas/frame.rs
@@ -1,10 +1,13 @@
+use lyon::geom::euclid::Point2D;
use std::borrow::Cow;
use iced_native::{Point, Rectangle, Size, Vector};
+use crate::gradient::Gradient;
+use crate::layer::mesh;
use crate::triangle;
-use crate::widget::canvas::path;
-use crate::widget::canvas::{Fill, Geometry, Path, Stroke, Text};
+use crate::triangle::Vertex2D;
+use crate::widget::canvas::{path, Fill, Geometry, Path, Stroke, Text};
use crate::Primitive;
use lyon::tessellation;
@@ -15,7 +18,7 @@ use lyon::tessellation;
#[allow(missing_debug_implementations)]
pub struct Frame {
size: Size,
- buffers: lyon::tessellation::VertexBuffers<triangle::Vertex2D, u32>,
+ buffers: Vec<(tessellation::VertexBuffers<Vertex2D, u32>, mesh::Style)>,
primitives: Vec<Primitive>,
transforms: Transforms,
fill_tessellator: tessellation::FillTessellator,
@@ -29,11 +32,33 @@ struct Transforms {
}
#[derive(Debug, Clone, Copy)]
-struct Transform {
+pub(crate) struct Transform {
raw: lyon::math::Transform,
is_identity: bool,
}
+impl Transform {
+ /// Transforms the given [Point] by the transformation matrix.
+ fn transform_point(&self, point: &mut Point) {
+ let transformed =
+ self.raw.transform_point(Point2D::new(point.x, point.y));
+ point.x = transformed.x;
+ point.y = transformed.y;
+ }
+
+ pub(crate) fn transform_gradient(
+ &self,
+ mut gradient: Gradient,
+ ) -> Gradient {
+ let (start, end) = match &mut gradient {
+ Gradient::Linear(linear) => (&mut linear.start, &mut linear.end),
+ };
+ self.transform_point(start);
+ self.transform_point(end);
+ gradient
+ }
+}
+
impl Frame {
/// Creates a new empty [`Frame`] with the given dimensions.
///
@@ -42,7 +67,7 @@ impl Frame {
pub fn new(size: Size) -> Frame {
Frame {
size,
- buffers: lyon::tessellation::VertexBuffers::new(),
+ buffers: Vec::new(),
primitives: Vec::new(),
transforms: Transforms {
previous: Vec::new(),
@@ -82,18 +107,18 @@ impl Frame {
/// Draws the given [`Path`] on the [`Frame`] by filling it with the
/// provided style.
- pub fn fill(&mut self, path: &Path, fill: impl Into<Fill>) {
- let Fill { color, rule } = fill.into();
+ pub fn fill<'a>(&mut self, path: &Path, fill: impl Into<Fill<'a>>) {
+ let Fill { style, rule } = fill.into();
+
+ let mut buf = tessellation::VertexBuffers::new();
- let mut buffers = tessellation::BuffersBuilder::new(
- &mut self.buffers,
- FillVertex(color.into_linear()),
- );
+ let mut buffers =
+ tessellation::BuffersBuilder::new(&mut buf, Vertex2DBuilder);
let options =
tessellation::FillOptions::default().with_fill_rule(rule.into());
- let result = if self.transforms.current.is_identity {
+ if self.transforms.current.is_identity {
self.fill_tessellator.tessellate_path(
path.raw(),
&options,
@@ -107,25 +132,27 @@ impl Frame {
&options,
&mut buffers,
)
- };
+ }
+ .expect("Tessellate path.");
- result.expect("Tessellate path");
+ self.buffers
+ .push((buf, style.as_mesh_style(&self.transforms.current)));
}
/// Draws an axis-aligned rectangle given its top-left corner coordinate and
/// its `Size` on the [`Frame`] by filling it with the provided style.
- pub fn fill_rectangle(
+ pub fn fill_rectangle<'a>(
&mut self,
top_left: Point,
size: Size,
- fill: impl Into<Fill>,
+ fill: impl Into<Fill<'a>>,
) {
- let Fill { color, rule } = fill.into();
+ let Fill { style, rule } = fill.into();
+
+ let mut buf = tessellation::VertexBuffers::new();
- let mut buffers = tessellation::BuffersBuilder::new(
- &mut self.buffers,
- FillVertex(color.into_linear()),
- );
+ let mut buffers =
+ tessellation::BuffersBuilder::new(&mut buf, Vertex2DBuilder);
let top_left =
self.transforms.current.raw.transform_point(
@@ -147,6 +174,9 @@ impl Frame {
&mut buffers,
)
.expect("Fill rectangle");
+
+ self.buffers
+ .push((buf, style.as_mesh_style(&self.transforms.current)));
}
/// Draws the stroke of the given [`Path`] on the [`Frame`] with the
@@ -154,10 +184,10 @@ impl Frame {
pub fn stroke<'a>(&mut self, path: &Path, stroke: impl Into<Stroke<'a>>) {
let stroke = stroke.into();
- let mut buffers = tessellation::BuffersBuilder::new(
- &mut self.buffers,
- StrokeVertex(stroke.color.into_linear()),
- );
+ let mut buf = tessellation::VertexBuffers::new();
+
+ let mut buffers =
+ tessellation::BuffersBuilder::new(&mut buf, Vertex2DBuilder);
let mut options = tessellation::StrokeOptions::default();
options.line_width = stroke.width;
@@ -171,7 +201,7 @@ impl Frame {
Cow::Owned(path::dashed(path, stroke.line_dash))
};
- let result = if self.transforms.current.is_identity {
+ if self.transforms.current.is_identity {
self.stroke_tessellator.tessellate_path(
path.raw(),
&options,
@@ -185,9 +215,11 @@ impl Frame {
&options,
&mut buffers,
)
- };
+ }
+ .expect("Stroke path");
- result.expect("Stroke path");
+ self.buffers
+ .push((buf, stroke.style.as_mesh_style(&self.transforms.current)))
}
/// Draws the characters of the given [`Text`] on the [`Frame`], filling
@@ -206,8 +238,6 @@ impl Frame {
///
/// [`Canvas`]: crate::widget::Canvas
pub fn fill_text(&mut self, text: impl Into<Text>) {
- use std::f32;
-
let text = text.into();
let position = if self.transforms.current.is_identity {
@@ -304,7 +334,7 @@ impl Frame {
self.transforms.current.is_identity = false;
}
- /// Applies a rotation to the current transform of the [`Frame`].
+ /// Applies a rotation in radians to the current transform of the [`Frame`].
#[inline]
pub fn rotate(&mut self, angle: f32) {
self.transforms.current.raw = self
@@ -331,52 +361,44 @@ impl Frame {
}
fn into_primitives(mut self) -> Vec<Primitive> {
- if !self.buffers.indices.is_empty() {
- self.primitives.push(Primitive::Mesh2D {
- buffers: triangle::Mesh2D {
- vertices: self.buffers.vertices,
- indices: self.buffers.indices,
- },
- size: self.size,
- });
+ for (buffer, style) in self.buffers {
+ if !buffer.indices.is_empty() {
+ self.primitives.push(Primitive::Mesh2D {
+ buffers: triangle::Mesh2D {
+ vertices: buffer.vertices,
+ indices: buffer.indices,
+ },
+ size: self.size,
+ style,
+ })
+ }
}
self.primitives
}
}
-struct FillVertex([f32; 4]);
+struct Vertex2DBuilder;
-impl lyon::tessellation::FillVertexConstructor<triangle::Vertex2D>
- for FillVertex
-{
- fn new_vertex(
- &mut self,
- vertex: lyon::tessellation::FillVertex<'_>,
- ) -> triangle::Vertex2D {
+impl tessellation::FillVertexConstructor<Vertex2D> for Vertex2DBuilder {
+ fn new_vertex(&mut self, vertex: tessellation::FillVertex<'_>) -> Vertex2D {
let position = vertex.position();
- triangle::Vertex2D {
+ Vertex2D {
position: [position.x, position.y],
- color: self.0,
}
}
}
-struct StrokeVertex([f32; 4]);
-
-impl lyon::tessellation::StrokeVertexConstructor<triangle::Vertex2D>
- for StrokeVertex
-{
+impl tessellation::StrokeVertexConstructor<Vertex2D> for Vertex2DBuilder {
fn new_vertex(
&mut self,
- vertex: lyon::tessellation::StrokeVertex<'_, '_>,
- ) -> triangle::Vertex2D {
+ vertex: tessellation::StrokeVertex<'_, '_>,
+ ) -> Vertex2D {
let position = vertex.position();
- triangle::Vertex2D {
+ Vertex2D {
position: [position.x, position.y],
- color: self.0,
}
}
}
diff --git a/graphics/src/widget/canvas/stroke.rs b/graphics/src/widget/canvas/stroke.rs
index 6accc2fb..2f02a2f3 100644
--- a/graphics/src/widget/canvas/stroke.rs
+++ b/graphics/src/widget/canvas/stroke.rs
@@ -1,10 +1,17 @@
+//! Create lines from a [crate::widget::canvas::Path] and assigns them various attributes/styles.
+
+use crate::gradient::Gradient;
+use crate::layer::mesh;
+use crate::widget::canvas::frame::Transform;
use iced_native::Color;
/// The style of a stroke.
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone)]
pub struct Stroke<'a> {
- /// The color of the stroke.
- pub color: Color,
+ /// The color or gradient of the stroke.
+ ///
+ /// By default, it is set to [`StrokeStyle::Solid`] `BLACK`.
+ pub style: Style<'a>,
/// The distance between the two edges of the stroke.
pub width: f32,
/// The shape to be used at the end of open subpaths when they are stroked.
@@ -19,7 +26,10 @@ pub struct Stroke<'a> {
impl<'a> Stroke<'a> {
/// Sets the color of the [`Stroke`].
pub fn with_color(self, color: Color) -> Self {
- Stroke { color, ..self }
+ Stroke {
+ style: Style::Solid(color),
+ ..self
+ }
}
/// Sets the width of the [`Stroke`].
@@ -41,7 +51,7 @@ impl<'a> Stroke<'a> {
impl<'a> Default for Stroke<'a> {
fn default() -> Self {
Stroke {
- color: Color::BLACK,
+ style: Style::Solid(Color::BLACK),
width: 1.0,
line_cap: LineCap::default(),
line_join: LineJoin::default(),
@@ -50,6 +60,27 @@ impl<'a> Default for Stroke<'a> {
}
}
+/// The style of a [`Stroke`].
+#[derive(Debug, Clone, Copy)]
+pub enum Style<'a> {
+ /// A solid color
+ Solid(Color),
+ /// A color gradient
+ Gradient(&'a Gradient),
+}
+
+impl<'a> Style<'a> {
+ /// Converts a fill's [Style] to a [mesh::Style] for use in the renderer's shader.
+ pub(crate) fn as_mesh_style(&self, transform: &Transform) -> mesh::Style {
+ match self {
+ Style::Solid(color) => mesh::Style::Solid(*color),
+ Style::Gradient(gradient) => mesh::Style::Gradient(
+ transform.transform_gradient((*gradient).clone()),
+ ),
+ }
+ }
+}
+
/// The shape used at the end of open subpaths when they are stroked.
#[derive(Debug, Clone, Copy)]
pub enum LineCap {