summaryrefslogtreecommitdiffstats
path: root/graphics/src
diff options
context:
space:
mode:
authorLibravatar Casper Storm <casper.storm@lich.io>2022-12-13 09:31:57 +0100
committerLibravatar Casper Storm <casper.storm@lich.io>2022-12-13 09:31:57 +0100
commit2e6d90f141217bad83eacd392562c13d7485881f (patch)
treebaa2c507076073aed4fd24abc9c7a7949d85c039 /graphics/src
parentba95042fff378213f5029b2b164d79e768482a47 (diff)
parent02182eea45537c9eb5b2bddfdff822bb8a3d143d (diff)
downloadiced-2e6d90f141217bad83eacd392562c13d7485881f.tar.gz
iced-2e6d90f141217bad83eacd392562c13d7485881f.tar.bz2
iced-2e6d90f141217bad83eacd392562c13d7485881f.zip
Merge branch 'master' into feat/slider-orientation
Diffstat (limited to '')
-rw-r--r--graphics/src/backend.rs4
-rw-r--r--graphics/src/gradient.rs117
-rw-r--r--graphics/src/gradient/linear.rs112
-rw-r--r--graphics/src/image.rs10
-rw-r--r--graphics/src/image/raster.rs (renamed from wgpu/src/image/raster.rs)86
-rw-r--r--graphics/src/image/storage.rs31
-rw-r--r--graphics/src/image/vector.rs (renamed from wgpu/src/image/vector.rs)95
-rw-r--r--graphics/src/layer.rs140
-rw-r--r--graphics/src/layer/image.rs27
-rw-r--r--graphics/src/layer/mesh.rs93
-rw-r--r--graphics/src/layer/quad.rs30
-rw-r--r--graphics/src/layer/text.rs26
-rw-r--r--graphics/src/lib.rs3
-rw-r--r--graphics/src/primitive.rs29
-rw-r--r--graphics/src/renderer.rs21
-rw-r--r--graphics/src/transformation.rs8
-rw-r--r--graphics/src/triangle.rs22
-rw-r--r--graphics/src/widget/canvas.rs8
-rw-r--r--graphics/src/widget/canvas/fill.rs30
-rw-r--r--graphics/src/widget/canvas/frame.rs260
-rw-r--r--graphics/src/widget/canvas/stroke.rs18
-rw-r--r--graphics/src/widget/canvas/style.rs23
-rw-r--r--graphics/src/window/compositor.rs2
-rw-r--r--graphics/src/window/gl_compositor.rs2
24 files changed, 933 insertions, 264 deletions
diff --git a/graphics/src/backend.rs b/graphics/src/backend.rs
index 7e0af2cc..2f8e9fc3 100644
--- a/graphics/src/backend.rs
+++ b/graphics/src/backend.rs
@@ -66,11 +66,11 @@ pub trait Text {
/// A graphics backend that supports image rendering.
pub trait Image {
/// Returns the dimensions of the provided image.
- fn dimensions(&self, handle: &image::Handle) -> (u32, u32);
+ fn dimensions(&self, handle: &image::Handle) -> Size<u32>;
}
/// A graphics backend that supports SVG rendering.
pub trait Svg {
/// Returns the viewport dimensions of the provided SVG.
- fn viewport_dimensions(&self, handle: &svg::Handle) -> (u32, u32);
+ fn viewport_dimensions(&self, handle: &svg::Handle) -> Size<u32>;
}
diff --git a/graphics/src/gradient.rs b/graphics/src/gradient.rs
new file mode 100644
index 00000000..83f25238
--- /dev/null
+++ b/graphics/src/gradient.rs
@@ -0,0 +1,117 @@
+//! For creating a Gradient.
+pub mod linear;
+
+pub use linear::Linear;
+
+use crate::{Color, Point, Size};
+
+#[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),
+}
+
+impl Gradient {
+ /// Creates a new linear [`linear::Builder`].
+ pub fn linear(position: impl Into<Position>) -> linear::Builder {
+ linear::Builder::new(position.into())
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq)]
+/// A point along the gradient vector where the specified [`color`] is unmixed.
+///
+/// [`color`]: Self::color
+pub struct ColorStop {
+ /// Offset along the gradient vector.
+ pub offset: f32,
+
+ /// The color of the gradient at the specified [`offset`].
+ ///
+ /// [`offset`]: Self::offset
+ pub color: Color,
+}
+
+#[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 From<(Point, Point)> for Position {
+ fn from((start, end): (Point, Point)) -> Self {
+ Self::Absolute { start, end }
+ }
+}
+
+#[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)
+ }
+ }
+ }
+}
diff --git a/graphics/src/gradient/linear.rs b/graphics/src/gradient/linear.rs
new file mode 100644
index 00000000..c886db47
--- /dev/null
+++ b/graphics/src/gradient/linear.rs
@@ -0,0 +1,112 @@
+//! Linear gradient builder & definition.
+use crate::gradient::{ColorStop, Gradient, Position};
+use crate::{Color, Point};
+
+/// A linear gradient that can be used in the style of [`Fill`] or [`Stroke`].
+///
+/// [`Fill`]: crate::widget::canvas::Fill
+/// [`Stroke`]: crate::widget::canvas::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>,
+}
+
+/// A [`Linear`] builder.
+#[derive(Debug)]
+pub struct Builder {
+ start: Point,
+ end: Point,
+ stops: Vec<ColorStop>,
+ error: Option<BuilderError>,
+}
+
+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![],
+ error: None,
+ }
+ }
+
+ /// 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 the [`wgpu`] backend this limitation does not exist (technical limit is 524,288 stops).
+ ///
+ /// [`glow`]: https://docs.rs/iced_glow
+ /// [`wgpu`]: https://docs.rs/iced_wgpu
+ 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(_) => {
+ self.error = Some(BuilderError::DuplicateOffset(offset))
+ }
+ Err(index) => {
+ self.stops.insert(index, ColorStop { offset, color });
+ }
+ }
+ } else {
+ self.error = Some(BuilderError::InvalidOffset(offset))
+ };
+
+ self
+ }
+
+ /// Builds the linear [`Gradient`] of this [`Builder`].
+ ///
+ /// Returns `BuilderError` if gradient in invalid.
+ pub fn build(self) -> Result<Gradient, BuilderError> {
+ if self.stops.is_empty() {
+ Err(BuilderError::MissingColorStop)
+ } else if let Some(error) = self.error {
+ Err(error)
+ } else {
+ Ok(Gradient::Linear(Linear {
+ start: self.start,
+ end: self.end,
+ color_stops: self.stops,
+ }))
+ }
+ }
+}
+
+/// An error that happened when building a [`Linear`] gradient.
+#[derive(Debug, thiserror::Error)]
+pub enum BuilderError {
+ #[error("Gradients must contain at least one color stop.")]
+ /// Gradients must contain at least one color stop.
+ MissingColorStop,
+ #[error("Offset {0} must be a unique, finite number.")]
+ /// Offsets in a gradient must all be unique & finite.
+ DuplicateOffset(f32),
+ #[error("Offset {0} must be between 0.0..=1.0.")]
+ /// Offsets in a gradient must be between 0.0..=1.0.
+ InvalidOffset(f32),
+}
diff --git a/graphics/src/image.rs b/graphics/src/image.rs
new file mode 100644
index 00000000..04f4ff9d
--- /dev/null
+++ b/graphics/src/image.rs
@@ -0,0 +1,10 @@
+//! Render images.
+#[cfg(feature = "image_rs")]
+pub mod raster;
+
+#[cfg(feature = "svg")]
+pub mod vector;
+
+pub mod storage;
+
+pub use storage::Storage;
diff --git a/wgpu/src/image/raster.rs b/graphics/src/image/raster.rs
index 2b4d4af3..da46c30f 100644
--- a/wgpu/src/image/raster.rs
+++ b/graphics/src/image/raster.rs
@@ -1,43 +1,53 @@
-use crate::image::atlas::{self, Atlas};
+//! Raster image loading and caching.
+use crate::image::Storage;
+use crate::Size;
+
use iced_native::image;
-use std::collections::{HashMap, HashSet};
use bitflags::bitflags;
+use std::collections::{HashMap, HashSet};
+/// Entry in cache corresponding to an image handle
#[derive(Debug)]
-pub enum Memory {
- Host(::image_rs::ImageBuffer<::image_rs::Bgra<u8>, Vec<u8>>),
- Device(atlas::Entry),
+pub enum Memory<T: Storage> {
+ /// Image data on host
+ Host(::image_rs::ImageBuffer<::image_rs::Rgba<u8>, Vec<u8>>),
+ /// Storage entry
+ Device(T::Entry),
+ /// Image not found
NotFound,
+ /// Invalid image data
Invalid,
}
-impl Memory {
- pub fn dimensions(&self) -> (u32, u32) {
+impl<T: Storage> Memory<T> {
+ /// Width and height of image
+ pub fn dimensions(&self) -> Size<u32> {
+ use crate::image::storage::Entry;
+
match self {
- Memory::Host(image) => image.dimensions(),
+ Memory::Host(image) => {
+ let (width, height) = image.dimensions();
+
+ Size::new(width, height)
+ }
Memory::Device(entry) => entry.size(),
- Memory::NotFound => (1, 1),
- Memory::Invalid => (1, 1),
+ Memory::NotFound => Size::new(1, 1),
+ Memory::Invalid => Size::new(1, 1),
}
}
}
+/// Caches image raster data
#[derive(Debug)]
-pub struct Cache {
- map: HashMap<u64, Memory>,
+pub struct Cache<T: Storage> {
+ map: HashMap<u64, Memory<T>>,
hits: HashSet<u64>,
}
-impl Cache {
- pub fn new() -> Self {
- Self {
- map: HashMap::new(),
- hits: HashSet::new(),
- }
- }
-
- pub fn load(&mut self, handle: &image::Handle) -> &mut Memory {
+impl<T: Storage> Cache<T> {
+ /// Load image
+ pub fn load(&mut self, handle: &image::Handle) -> &mut Memory<T> {
if self.contains(handle) {
return self.get(handle).unwrap();
}
@@ -53,7 +63,7 @@ impl Cache {
})
.unwrap_or_else(Operation::empty);
- Memory::Host(operation.perform(image.to_bgra8()))
+ Memory::Host(operation.perform(image.to_rgba8()))
} else {
Memory::NotFound
}
@@ -65,12 +75,12 @@ impl Cache {
.ok()
.unwrap_or_else(Operation::empty);
- Memory::Host(operation.perform(image.to_bgra8()))
+ Memory::Host(operation.perform(image.to_rgba8()))
} else {
Memory::Invalid
}
}
- image::Data::Pixels {
+ image::Data::Rgba {
width,
height,
pixels,
@@ -91,19 +101,19 @@ impl Cache {
self.get(handle).unwrap()
}
+ /// Load image and upload raster data
pub fn upload(
&mut self,
handle: &image::Handle,
- device: &wgpu::Device,
- encoder: &mut wgpu::CommandEncoder,
- atlas: &mut Atlas,
- ) -> Option<&atlas::Entry> {
+ state: &mut T::State<'_>,
+ storage: &mut T,
+ ) -> Option<&T::Entry> {
let memory = self.load(handle);
if let Memory::Host(image) = memory {
let (width, height) = image.dimensions();
- let entry = atlas.upload(width, height, image, device, encoder)?;
+ let entry = storage.upload(width, height, image, state)?;
*memory = Memory::Device(entry);
}
@@ -115,7 +125,8 @@ impl Cache {
}
}
- pub fn trim(&mut self, atlas: &mut Atlas) {
+ /// Trim cache misses from cache
+ pub fn trim(&mut self, storage: &mut T, state: &mut T::State<'_>) {
let hits = &self.hits;
self.map.retain(|k, memory| {
@@ -123,7 +134,7 @@ impl Cache {
if !retain {
if let Memory::Device(entry) = memory {
- atlas.remove(entry);
+ storage.remove(entry, state);
}
}
@@ -133,13 +144,13 @@ impl Cache {
self.hits.clear();
}
- fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory> {
+ fn get(&mut self, handle: &image::Handle) -> Option<&mut Memory<T>> {
let _ = self.hits.insert(handle.id());
self.map.get_mut(&handle.id())
}
- fn insert(&mut self, handle: &image::Handle, memory: Memory) {
+ fn insert(&mut self, handle: &image::Handle, memory: Memory<T>) {
let _ = self.map.insert(handle.id(), memory);
}
@@ -148,6 +159,15 @@ impl Cache {
}
}
+impl<T: Storage> Default for Cache<T> {
+ fn default() -> Self {
+ Self {
+ map: HashMap::new(),
+ hits: HashSet::new(),
+ }
+ }
+}
+
bitflags! {
struct Operation: u8 {
const FLIP_HORIZONTALLY = 0b001;
diff --git a/graphics/src/image/storage.rs b/graphics/src/image/storage.rs
new file mode 100644
index 00000000..2098c7b2
--- /dev/null
+++ b/graphics/src/image/storage.rs
@@ -0,0 +1,31 @@
+//! Store images.
+use crate::Size;
+
+use std::fmt::Debug;
+
+/// Stores cached image data for use in rendering
+pub trait Storage {
+ /// The type of an [`Entry`] in the [`Storage`].
+ type Entry: Entry;
+
+ /// State provided to upload or remove a [`Self::Entry`].
+ type State<'a>;
+
+ /// Upload the image data of a [`Self::Entry`].
+ fn upload(
+ &mut self,
+ width: u32,
+ height: u32,
+ data: &[u8],
+ state: &mut Self::State<'_>,
+ ) -> Option<Self::Entry>;
+
+ /// Romve a [`Self::Entry`] from the [`Storage`].
+ fn remove(&mut self, entry: &Self::Entry, state: &mut Self::State<'_>);
+}
+
+/// An entry in some [`Storage`],
+pub trait Entry: Debug {
+ /// The [`Size`] of the [`Entry`].
+ fn size(&self) -> Size<u32>;
+}
diff --git a/wgpu/src/image/vector.rs b/graphics/src/image/vector.rs
index b08a0aa2..82d77aff 100644
--- a/wgpu/src/image/vector.rs
+++ b/graphics/src/image/vector.rs
@@ -1,46 +1,48 @@
-use crate::image::atlas::{self, Atlas};
+//! Vector image loading and caching
+use crate::image::Storage;
+use crate::Color;
use iced_native::svg;
+use iced_native::Size;
use std::collections::{HashMap, HashSet};
use std::fs;
+/// Entry in cache corresponding to an svg handle
pub enum Svg {
+ /// Parsed svg
Loaded(usvg::Tree),
+ /// Svg not found or failed to parse
NotFound,
}
impl Svg {
- pub fn viewport_dimensions(&self) -> (u32, u32) {
+ /// Viewport width and height
+ pub fn viewport_dimensions(&self) -> Size<u32> {
match self {
Svg::Loaded(tree) => {
let size = tree.svg_node().size;
- (size.width() as u32, size.height() as u32)
+ Size::new(size.width() as u32, size.height() as u32)
}
- Svg::NotFound => (1, 1),
+ Svg::NotFound => Size::new(1, 1),
}
}
}
+/// Caches svg vector and raster data
#[derive(Debug)]
-pub struct Cache {
+pub struct Cache<T: Storage> {
svgs: HashMap<u64, Svg>,
- rasterized: HashMap<(u64, u32, u32), atlas::Entry>,
+ rasterized: HashMap<(u64, u32, u32, ColorFilter), T::Entry>,
svg_hits: HashSet<u64>,
- rasterized_hits: HashSet<(u64, u32, u32)>,
+ rasterized_hits: HashSet<(u64, u32, u32, ColorFilter)>,
}
-impl Cache {
- pub fn new() -> Self {
- Self {
- svgs: HashMap::new(),
- rasterized: HashMap::new(),
- svg_hits: HashSet::new(),
- rasterized_hits: HashSet::new(),
- }
- }
+type ColorFilter = Option<[u8; 4]>;
+impl<T: Storage> Cache<T> {
+ /// Load svg
pub fn load(&mut self, handle: &svg::Handle) -> &Svg {
if self.svgs.contains_key(&handle.id()) {
return self.svgs.get(&handle.id()).unwrap();
@@ -73,15 +75,16 @@ impl Cache {
self.svgs.get(&handle.id()).unwrap()
}
+ /// Load svg and upload raster data
pub fn upload(
&mut self,
handle: &svg::Handle,
+ color: Option<Color>,
[width, height]: [f32; 2],
scale: f32,
- device: &wgpu::Device,
- encoder: &mut wgpu::CommandEncoder,
- texture_atlas: &mut Atlas,
- ) -> Option<&atlas::Entry> {
+ state: &mut T::State<'_>,
+ storage: &mut T,
+ ) -> Option<&T::Entry> {
let id = handle.id();
let (width, height) = (
@@ -89,15 +92,18 @@ impl Cache {
(scale * height).ceil() as u32,
);
+ let color = color.map(Color::into_rgba8);
+ let key = (id, width, height, color);
+
// TODO: Optimize!
// We currently rerasterize the SVG when its size changes. This is slow
// as heck. A GPU rasterizer like `pathfinder` may perform better.
// It would be cool to be able to smooth resize the `svg` example.
- if self.rasterized.contains_key(&(id, width, height)) {
+ if self.rasterized.contains_key(&key) {
let _ = self.svg_hits.insert(id);
- let _ = self.rasterized_hits.insert((id, width, height));
+ let _ = self.rasterized_hits.insert(key);
- return self.rasterized.get(&(id, width, height));
+ return self.rasterized.get(&key);
}
match self.load(handle) {
@@ -123,28 +129,32 @@ impl Cache {
)?;
let mut rgba = img.take();
- rgba.chunks_exact_mut(4).for_each(|rgba| rgba.swap(0, 2));
-
- let allocation = texture_atlas.upload(
- width,
- height,
- bytemuck::cast_slice(rgba.as_slice()),
- device,
- encoder,
- )?;
+
+ if let Some(color) = color {
+ rgba.chunks_exact_mut(4).for_each(|rgba| {
+ if rgba[3] > 0 {
+ rgba[0] = color[0];
+ rgba[1] = color[1];
+ rgba[2] = color[2];
+ }
+ });
+ }
+
+ let allocation = storage.upload(width, height, &rgba, state)?;
log::debug!("allocating {} {}x{}", id, width, height);
let _ = self.svg_hits.insert(id);
- let _ = self.rasterized_hits.insert((id, width, height));
- let _ = self.rasterized.insert((id, width, height), allocation);
+ let _ = self.rasterized_hits.insert(key);
+ let _ = self.rasterized.insert(key, allocation);
- self.rasterized.get(&(id, width, height))
+ self.rasterized.get(&key)
}
Svg::NotFound => None,
}
}
- pub fn trim(&mut self, atlas: &mut Atlas) {
+ /// Load svg and upload raster data
+ pub fn trim(&mut self, storage: &mut T, state: &mut T::State<'_>) {
let svg_hits = &self.svg_hits;
let rasterized_hits = &self.rasterized_hits;
@@ -153,7 +163,7 @@ impl Cache {
let retain = rasterized_hits.contains(k);
if !retain {
- atlas.remove(entry);
+ storage.remove(entry, state);
}
retain
@@ -163,6 +173,17 @@ impl Cache {
}
}
+impl<T: Storage> Default for Cache<T> {
+ fn default() -> Self {
+ Self {
+ svgs: HashMap::new(),
+ rasterized: HashMap::new(),
+ svg_hits: HashSet::new(),
+ rasterized_hits: HashSet::new(),
+ }
+ }
+}
+
impl std::fmt::Debug for Svg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
diff --git a/graphics/src/layer.rs b/graphics/src/layer.rs
index af545713..1d453caa 100644
--- a/graphics/src/layer.rs
+++ b/graphics/src/layer.rs
@@ -1,15 +1,22 @@
//! Organize rendering primitives into a flattened list of layers.
+mod image;
+mod quad;
+mod text;
+
+pub mod mesh;
+
+pub use image::Image;
+pub use mesh::Mesh;
+pub use quad::Quad;
+pub use text::Text;
+
use crate::alignment;
-use crate::triangle;
use crate::{
Background, Font, Point, Primitive, Rectangle, Size, Vector, Viewport,
};
-use iced_native::image;
-use iced_native::svg;
-
/// 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 +166,7 @@ impl<'a> Layer<'a> {
border_color: border_color.into_linear(),
});
}
- Primitive::Mesh2D { buffers, size } => {
+ Primitive::SolidMesh { buffers, size } => {
let layer = &mut layers[current_layer];
let bounds = Rectangle::new(
@@ -169,13 +176,35 @@ impl<'a> Layer<'a> {
// Only draw visible content
if let Some(clip_bounds) = layer.bounds.intersection(&bounds) {
- layer.meshes.push(Mesh {
+ layer.meshes.push(Mesh::Solid {
origin: Point::new(translation.x, translation.y),
buffers,
clip_bounds,
});
}
}
+ Primitive::GradientMesh {
+ buffers,
+ size,
+ gradient,
+ } => {
+ let layer = &mut layers[current_layer];
+
+ let bounds = Rectangle::new(
+ Point::new(translation.x, translation.y),
+ *size,
+ );
+
+ // Only draw visible content
+ if let Some(clip_bounds) = layer.bounds.intersection(&bounds) {
+ layer.meshes.push(Mesh::Gradient {
+ origin: Point::new(translation.x, translation.y),
+ buffers,
+ clip_bounds,
+ gradient,
+ });
+ }
+ }
Primitive::Clip { bounds, content } => {
let layer = &mut layers[current_layer];
let translated_bounds = *bounds + translation;
@@ -222,104 +251,19 @@ impl<'a> Layer<'a> {
bounds: *bounds + translation,
});
}
- Primitive::Svg { handle, bounds } => {
+ Primitive::Svg {
+ handle,
+ color,
+ bounds,
+ } => {
let layer = &mut layers[current_layer];
layer.images.push(Image::Vector {
handle: handle.clone(),
+ color: *color,
bounds: *bounds + translation,
});
}
}
}
}
-
-/// 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 {}
diff --git a/graphics/src/layer/image.rs b/graphics/src/layer/image.rs
new file mode 100644
index 00000000..3eff2397
--- /dev/null
+++ b/graphics/src/layer/image.rs
@@ -0,0 +1,27 @@
+use crate::{Color, Rectangle};
+
+use iced_native::{image, svg};
+
+/// 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 [`Color`] filter
+ color: Option<Color>,
+
+ /// 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..7661c5c9
--- /dev/null
+++ b/graphics/src/layer/mesh.rs
@@ -0,0 +1,93 @@
+//! A collection of triangle primitives.
+use crate::triangle;
+use crate::{Gradient, Point, Rectangle};
+
+/// A mesh of triangles.
+#[derive(Debug, Clone, Copy)]
+pub enum Mesh<'a> {
+ /// A mesh of triangles with a solid color.
+ Solid {
+ /// The origin of the vertices of the [`Mesh`].
+ origin: Point,
+
+ /// The vertex and index buffers of the [`Mesh`].
+ buffers: &'a triangle::Mesh2D<triangle::ColoredVertex2D>,
+
+ /// The clipping bounds of the [`Mesh`].
+ clip_bounds: Rectangle<f32>,
+ },
+ /// A mesh of triangles with a gradient color.
+ Gradient {
+ /// The origin of the vertices of the [`Mesh`].
+ origin: Point,
+
+ /// The vertex and index buffers of the [`Mesh`].
+ buffers: &'a triangle::Mesh2D<triangle::Vertex2D>,
+
+ /// The clipping bounds of the [`Mesh`].
+ clip_bounds: Rectangle<f32>,
+
+ /// The gradient to apply to the [`Mesh`].
+ gradient: &'a Gradient,
+ },
+}
+
+impl Mesh<'_> {
+ /// Returns the origin of the [`Mesh`].
+ pub fn origin(&self) -> Point {
+ match self {
+ Self::Solid { origin, .. } | Self::Gradient { origin, .. } => {
+ *origin
+ }
+ }
+ }
+
+ /// Returns the indices of the [`Mesh`].
+ pub fn indices(&self) -> &[u32] {
+ match self {
+ Self::Solid { buffers, .. } => &buffers.indices,
+ Self::Gradient { buffers, .. } => &buffers.indices,
+ }
+ }
+
+ /// Returns the clip bounds of the [`Mesh`].
+ pub fn clip_bounds(&self) -> Rectangle<f32> {
+ match self {
+ Self::Solid { clip_bounds, .. }
+ | Self::Gradient { clip_bounds, .. } => *clip_bounds,
+ }
+ }
+}
+
+/// The result of counting the attributes of a set of meshes.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct AttributeCount {
+ /// The total amount of solid vertices.
+ pub solid_vertices: usize,
+
+ /// The total amount of gradient vertices.
+ pub gradient_vertices: usize,
+
+ /// The total amount of indices.
+ pub indices: usize,
+}
+
+/// Returns the number of total vertices & total indices of all [`Mesh`]es.
+pub fn attribute_count_of<'a>(meshes: &'a [Mesh<'a>]) -> AttributeCount {
+ meshes
+ .iter()
+ .fold(AttributeCount::default(), |mut count, mesh| {
+ match mesh {
+ Mesh::Solid { buffers, .. } => {
+ count.solid_vertices += buffers.vertices.len();
+ count.indices += buffers.indices.len();
+ }
+ Mesh::Gradient { buffers, .. } => {
+ count.gradient_vertices += buffers.vertices.len();
+ count.indices += buffers.indices.len();
+ }
+ }
+
+ count
+ })
+}
diff --git a/graphics/src/layer/quad.rs b/graphics/src/layer/quad.rs
new file mode 100644
index 00000000..0d8bde9d
--- /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; 4],
+
+ /// 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..d39dd90c 100644
--- a/graphics/src/lib.rs
+++ b/graphics/src/lib.rs
@@ -29,6 +29,8 @@ mod viewport;
pub mod backend;
pub mod font;
+pub mod gradient;
+pub mod image;
pub mod layer;
pub mod overlay;
pub mod renderer;
@@ -39,6 +41,7 @@ pub mod window;
pub use antialiasing::Antialiasing;
pub use backend::Backend;
pub use error::Error;
+pub use gradient::Gradient;
pub use layer::Layer;
pub use primitive::Primitive;
pub use renderer::Renderer;
diff --git a/graphics/src/primitive.rs b/graphics/src/primitive.rs
index 5f7a344d..5a163a2f 100644
--- a/graphics/src/primitive.rs
+++ b/graphics/src/primitive.rs
@@ -3,6 +3,7 @@ use iced_native::svg;
use iced_native::{Background, Color, Font, Rectangle, Size, Vector};
use crate::alignment;
+use crate::gradient::Gradient;
use crate::triangle;
use std::sync::Arc;
@@ -41,7 +42,7 @@ pub enum Primitive {
/// The background of the quad
background: Background,
/// The border radius of the quad
- border_radius: f32,
+ border_radius: [f32; 4],
/// The border width of the quad
border_width: f32,
/// The border color of the quad
@@ -59,6 +60,9 @@ pub enum Primitive {
/// The path of the SVG file
handle: svg::Handle,
+ /// The [`Color`] filter
+ color: Option<Color>,
+
/// The bounds of the viewport
bounds: Rectangle,
},
@@ -77,17 +81,32 @@ pub enum Primitive {
/// The primitive to translate
content: Box<Primitive>,
},
- /// A low-level primitive to render a mesh of triangles.
+ /// A low-level primitive to render a mesh of triangles with a solid color.
+ ///
+ /// It can be used to render many kinds of geometry freely.
+ SolidMesh {
+ /// The vertices and indices of the mesh.
+ buffers: triangle::Mesh2D<triangle::ColoredVertex2D>,
+
+ /// The size of the drawable region of the mesh.
+ ///
+ /// Any geometry that falls out of this region will be clipped.
+ size: Size,
+ },
+ /// A low-level primitive to render a mesh of triangles with a gradient.
///
/// It can be used to render many kinds of geometry freely.
- Mesh2D {
- /// The vertex and index buffers of the mesh
- buffers: triangle::Mesh2D,
+ GradientMesh {
+ /// The vertices and indices of the mesh.
+ buffers: triangle::Mesh2D<triangle::Vertex2D>,
/// The size of the drawable region of the mesh.
///
/// Any geometry that falls out of this region will be clipped.
size: Size,
+
+ /// The [`Gradient`] to apply to the mesh.
+ gradient: Gradient,
},
/// A cached primitive.
///
diff --git a/graphics/src/renderer.rs b/graphics/src/renderer.rs
index cdbc4f40..aabdf7fc 100644
--- a/graphics/src/renderer.rs
+++ b/graphics/src/renderer.rs
@@ -6,7 +6,7 @@ use iced_native::layout;
use iced_native::renderer;
use iced_native::svg;
use iced_native::text::{self, Text};
-use iced_native::{Background, Element, Font, Point, Rectangle, Size};
+use iced_native::{Background, Color, Element, Font, Point, Rectangle, Size};
pub use iced_native::renderer::Style;
@@ -109,7 +109,7 @@ where
self.primitives.push(Primitive::Quad {
bounds: quad.bounds,
background: background.into(),
- border_radius: quad.border_radius,
+ border_radius: quad.border_radius.into(),
border_width: quad.border_width,
border_color: quad.border_color,
});
@@ -183,7 +183,7 @@ where
{
type Handle = image::Handle;
- fn dimensions(&self, handle: &image::Handle) -> (u32, u32) {
+ fn dimensions(&self, handle: &image::Handle) -> Size<u32> {
self.backend().dimensions(handle)
}
@@ -196,11 +196,20 @@ impl<B, T> svg::Renderer for Renderer<B, T>
where
B: Backend + backend::Svg,
{
- fn dimensions(&self, handle: &svg::Handle) -> (u32, u32) {
+ fn dimensions(&self, handle: &svg::Handle) -> Size<u32> {
self.backend().viewport_dimensions(handle)
}
- fn draw(&mut self, handle: svg::Handle, bounds: Rectangle) {
- self.draw_primitive(Primitive::Svg { handle, bounds })
+ fn draw(
+ &mut self,
+ handle: svg::Handle,
+ color: Option<Color>,
+ bounds: Rectangle,
+ ) {
+ self.draw_primitive(Primitive::Svg {
+ handle,
+ color,
+ bounds,
+ })
}
}
diff --git a/graphics/src/transformation.rs b/graphics/src/transformation.rs
index 2a19caed..cf0457a4 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 From<Transformation> for Mat4 {
+ fn from(transformation: Transformation) -> Self {
+ transformation.0
+ }
+}
diff --git a/graphics/src/triangle.rs b/graphics/src/triangle.rs
index 05028f51..f52b2339 100644
--- a/graphics/src/triangle.rs
+++ b/graphics/src/triangle.rs
@@ -3,23 +3,31 @@ use bytemuck::{Pod, Zeroable};
/// A set of [`Vertex2D`] and indices representing a list of triangles.
#[derive(Clone, Debug)]
-pub struct Mesh2D {
+pub struct Mesh2D<T> {
/// The vertices of the mesh
- pub vertices: Vec<Vertex2D>,
+ pub vertices: Vec<T>,
/// 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.
+ /// 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.
+}
+
+/// A two-dimensional vertex with a color.
+#[derive(Copy, Clone, Debug, Zeroable, Pod)]
+#[repr(C)]
+pub struct ColoredVertex2D {
+ /// The vertex position in 2D space.
+ pub position: [f32; 2],
+
+ /// The color of the vertex in __linear__ RGBA.
pub color: [f32; 4],
}
diff --git a/graphics/src/widget/canvas.rs b/graphics/src/widget/canvas.rs
index b4afd998..b070d0a6 100644
--- a/graphics/src/widget/canvas.rs
+++ b/graphics/src/widget/canvas.rs
@@ -3,19 +3,20 @@
//! A [`Canvas`] widget can be used to draw different kinds of 2D shapes in a
//! [`Frame`]. It can be used for animation, data visualization, game graphics,
//! and more!
-
pub mod event;
+pub mod fill;
pub mod path;
+pub mod stroke;
mod cache;
mod cursor;
-mod fill;
mod frame;
mod geometry;
mod program;
-mod stroke;
+mod style;
mod text;
+pub use crate::gradient::{self, Gradient};
pub use cache::Cache;
pub use cursor::Cursor;
pub use event::Event;
@@ -25,6 +26,7 @@ pub use geometry::Geometry;
pub use path::Path;
pub use program::Program;
pub use stroke::{LineCap, LineDash, LineJoin, Stroke};
+pub use style::Style;
pub use text::Text;
use crate::{Backend, Primitive, Renderer};
diff --git a/graphics/src/widget/canvas/fill.rs b/graphics/src/widget/canvas/fill.rs
index 56495435..e954ebb5 100644
--- a/graphics/src/widget/canvas/fill.rs
+++ b/graphics/src/widget/canvas/fill.rs
@@ -1,12 +1,15 @@
-use iced_native::Color;
+//! Fill [crate::widget::canvas::Geometry] with a certain style.
+use crate::{Color, Gradient};
+
+pub use crate::widget::canvas::Style;
/// The style used to fill geometry.
-#[derive(Debug, Clone, Copy)]
+#[derive(Debug, Clone)]
pub struct Fill {
- /// The color used to fill geometry.
+ /// The color or gradient of the fill.
///
- /// By default, it is set to `BLACK`.
- pub color: Color,
+ /// By default, it is set to [`Style::Solid`] with [`Color::BLACK`].
+ pub style: Style,
/// The fill rule defines how to determine what is inside and what is
/// outside of a shape.
@@ -20,9 +23,9 @@ pub struct Fill {
}
impl Default for Fill {
- fn default() -> Fill {
- Fill {
- color: Color::BLACK,
+ fn default() -> Self {
+ Self {
+ style: Style::Solid(Color::BLACK),
rule: FillRule::NonZero,
}
}
@@ -31,12 +34,21 @@ impl Default for Fill {
impl From<Color> for Fill {
fn from(color: Color) -> Fill {
Fill {
- color,
+ style: Style::Solid(color),
..Fill::default()
}
}
}
+impl From<Gradient> for Fill {
+ fn from(gradient: Gradient) -> Self {
+ Fill {
+ style: Style::Gradient(gradient),
+ ..Default::default()
+ }
+ }
+}
+
/// 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..d68548ae 100644
--- a/graphics/src/widget/canvas/frame.rs
+++ b/graphics/src/widget/canvas/frame.rs
@@ -1,13 +1,13 @@
-use std::borrow::Cow;
-
-use iced_native::{Point, Rectangle, Size, Vector};
-
+use crate::gradient::Gradient;
use crate::triangle;
-use crate::widget::canvas::path;
-use crate::widget::canvas::{Fill, Geometry, Path, Stroke, Text};
+use crate::widget::canvas::{path, Fill, Geometry, Path, Stroke, Style, Text};
use crate::Primitive;
+use iced_native::{Point, Rectangle, Size, Vector};
+
+use lyon::geom::euclid;
use lyon::tessellation;
+use std::borrow::Cow;
/// The frame of a [`Canvas`].
///
@@ -15,13 +15,91 @@ use lyon::tessellation;
#[allow(missing_debug_implementations)]
pub struct Frame {
size: Size,
- buffers: lyon::tessellation::VertexBuffers<triangle::Vertex2D, u32>,
+ buffers: BufferStack,
primitives: Vec<Primitive>,
transforms: Transforms,
fill_tessellator: tessellation::FillTessellator,
stroke_tessellator: tessellation::StrokeTessellator,
}
+enum Buffer {
+ Solid(tessellation::VertexBuffers<triangle::ColoredVertex2D, u32>),
+ Gradient(
+ tessellation::VertexBuffers<triangle::Vertex2D, u32>,
+ Gradient,
+ ),
+}
+
+struct BufferStack {
+ stack: Vec<Buffer>,
+}
+
+impl BufferStack {
+ fn new() -> Self {
+ Self { stack: Vec::new() }
+ }
+
+ fn get_mut(&mut self, style: &Style) -> &mut Buffer {
+ match style {
+ Style::Solid(_) => match self.stack.last() {
+ Some(Buffer::Solid(_)) => {}
+ _ => {
+ self.stack.push(Buffer::Solid(
+ tessellation::VertexBuffers::new(),
+ ));
+ }
+ },
+ Style::Gradient(gradient) => match self.stack.last() {
+ Some(Buffer::Gradient(_, last)) if gradient == last => {}
+ _ => {
+ self.stack.push(Buffer::Gradient(
+ tessellation::VertexBuffers::new(),
+ gradient.clone(),
+ ));
+ }
+ },
+ }
+
+ self.stack.last_mut().unwrap()
+ }
+
+ fn get_fill<'a>(
+ &'a mut self,
+ style: &Style,
+ ) -> Box<dyn tessellation::FillGeometryBuilder + 'a> {
+ match (style, self.get_mut(style)) {
+ (Style::Solid(color), Buffer::Solid(buffer)) => {
+ Box::new(tessellation::BuffersBuilder::new(
+ buffer,
+ TriangleVertex2DBuilder(color.into_linear()),
+ ))
+ }
+ (Style::Gradient(_), Buffer::Gradient(buffer, _)) => Box::new(
+ tessellation::BuffersBuilder::new(buffer, Vertex2DBuilder),
+ ),
+ _ => unreachable!(),
+ }
+ }
+
+ fn get_stroke<'a>(
+ &'a mut self,
+ style: &Style,
+ ) -> Box<dyn tessellation::StrokeGeometryBuilder + 'a> {
+ match (style, self.get_mut(style)) {
+ (Style::Solid(color), Buffer::Solid(buffer)) => {
+ Box::new(tessellation::BuffersBuilder::new(
+ buffer,
+ TriangleVertex2DBuilder(color.into_linear()),
+ ))
+ }
+ (Style::Gradient(_), Buffer::Gradient(buffer, _)) => Box::new(
+ tessellation::BuffersBuilder::new(buffer, Vertex2DBuilder),
+ ),
+ _ => unreachable!(),
+ }
+ }
+}
+
#[derive(Debug)]
struct Transforms {
previous: Vec<Transform>,
@@ -34,6 +112,35 @@ struct 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(euclid::Point2D::new(point.x, point.y));
+ point.x = transformed.x;
+ point.y = transformed.y;
+ }
+
+ fn transform_style(&self, style: Style) -> Style {
+ match style {
+ Style::Solid(color) => Style::Solid(color),
+ Style::Gradient(gradient) => {
+ Style::Gradient(self.transform_gradient(gradient))
+ }
+ }
+ }
+
+ 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 +149,7 @@ impl Frame {
pub fn new(size: Size) -> Frame {
Frame {
size,
- buffers: lyon::tessellation::VertexBuffers::new(),
+ buffers: BufferStack::new(),
primitives: Vec::new(),
transforms: Transforms {
previous: Vec::new(),
@@ -83,21 +190,20 @@ 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();
+ let Fill { style, rule } = fill.into();
- let mut buffers = tessellation::BuffersBuilder::new(
- &mut self.buffers,
- FillVertex(color.into_linear()),
- );
+ let mut buffer = self
+ .buffers
+ .get_fill(&self.transforms.current.transform_style(style));
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,
- &mut buffers,
+ buffer.as_mut(),
)
} else {
let path = path.transformed(&self.transforms.current.raw);
@@ -105,11 +211,10 @@ impl Frame {
self.fill_tessellator.tessellate_path(
path.raw(),
&options,
- &mut buffers,
+ buffer.as_mut(),
)
- };
-
- result.expect("Tessellate path");
+ }
+ .expect("Tessellate path.");
}
/// Draws an axis-aligned rectangle given its top-left corner coordinate and
@@ -120,12 +225,11 @@ impl Frame {
size: Size,
fill: impl Into<Fill>,
) {
- let Fill { color, rule } = fill.into();
+ let Fill { style, rule } = fill.into();
- let mut buffers = tessellation::BuffersBuilder::new(
- &mut self.buffers,
- FillVertex(color.into_linear()),
- );
+ let mut buffer = self
+ .buffers
+ .get_fill(&self.transforms.current.transform_style(style));
let top_left =
self.transforms.current.raw.transform_point(
@@ -144,7 +248,7 @@ impl Frame {
.tessellate_rectangle(
&lyon::math::Box2D::new(top_left, top_left + size),
&options,
- &mut buffers,
+ buffer.as_mut(),
)
.expect("Fill rectangle");
}
@@ -154,10 +258,9 @@ 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 buffer = self
+ .buffers
+ .get_stroke(&self.transforms.current.transform_style(stroke.style));
let mut options = tessellation::StrokeOptions::default();
options.line_width = stroke.width;
@@ -171,11 +274,11 @@ 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,
- &mut buffers,
+ buffer.as_mut(),
)
} else {
let path = path.transformed(&self.transforms.current.raw);
@@ -183,11 +286,10 @@ impl Frame {
self.stroke_tessellator.tessellate_path(
path.raw(),
&options,
- &mut buffers,
+ buffer.as_mut(),
)
- };
-
- result.expect("Stroke path");
+ }
+ .expect("Stroke path");
}
/// Draws the characters of the given [`Text`] on the [`Frame`], filling
@@ -206,8 +308,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 +404,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,51 +431,99 @@ 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 in self.buffers.stack {
+ match buffer {
+ Buffer::Solid(buffer) => {
+ if !buffer.indices.is_empty() {
+ self.primitives.push(Primitive::SolidMesh {
+ buffers: triangle::Mesh2D {
+ vertices: buffer.vertices,
+ indices: buffer.indices,
+ },
+ size: self.size,
+ })
+ }
+ }
+ Buffer::Gradient(buffer, gradient) => {
+ if !buffer.indices.is_empty() {
+ self.primitives.push(Primitive::GradientMesh {
+ buffers: triangle::Mesh2D {
+ vertices: buffer.vertices,
+ indices: buffer.indices,
+ },
+ size: self.size,
+ gradient,
+ })
+ }
+ }
+ }
}
self.primitives
}
}
-struct FillVertex([f32; 4]);
+struct Vertex2DBuilder;
-impl lyon::tessellation::FillVertexConstructor<triangle::Vertex2D>
- for FillVertex
+impl tessellation::FillVertexConstructor<triangle::Vertex2D>
+ for Vertex2DBuilder
{
fn new_vertex(
&mut self,
- vertex: lyon::tessellation::FillVertex<'_>,
+ vertex: tessellation::FillVertex<'_>,
) -> triangle::Vertex2D {
let position = vertex.position();
triangle::Vertex2D {
position: [position.x, position.y],
- color: self.0,
}
}
}
-struct StrokeVertex([f32; 4]);
-
-impl lyon::tessellation::StrokeVertexConstructor<triangle::Vertex2D>
- for StrokeVertex
+impl tessellation::StrokeVertexConstructor<triangle::Vertex2D>
+ for Vertex2DBuilder
{
fn new_vertex(
&mut self,
- vertex: lyon::tessellation::StrokeVertex<'_, '_>,
+ vertex: tessellation::StrokeVertex<'_, '_>,
) -> triangle::Vertex2D {
let position = vertex.position();
triangle::Vertex2D {
position: [position.x, position.y],
+ }
+ }
+}
+
+struct TriangleVertex2DBuilder([f32; 4]);
+
+impl tessellation::FillVertexConstructor<triangle::ColoredVertex2D>
+ for TriangleVertex2DBuilder
+{
+ fn new_vertex(
+ &mut self,
+ vertex: tessellation::FillVertex<'_>,
+ ) -> triangle::ColoredVertex2D {
+ let position = vertex.position();
+
+ triangle::ColoredVertex2D {
+ position: [position.x, position.y],
+ color: self.0,
+ }
+ }
+}
+
+impl tessellation::StrokeVertexConstructor<triangle::ColoredVertex2D>
+ for TriangleVertex2DBuilder
+{
+ fn new_vertex(
+ &mut self,
+ vertex: tessellation::StrokeVertex<'_, '_>,
+ ) -> triangle::ColoredVertex2D {
+ let position = vertex.position();
+
+ triangle::ColoredVertex2D {
+ 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..4c19251d 100644
--- a/graphics/src/widget/canvas/stroke.rs
+++ b/graphics/src/widget/canvas/stroke.rs
@@ -1,10 +1,15 @@
+//! Create lines from a [crate::widget::canvas::Path] and assigns them various attributes/styles.
+pub use crate::widget::canvas::Style;
+
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 a [`Style::Solid`] with [`Color::BLACK`].
+ pub style: Style,
/// 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 +24,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 +49,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(),
diff --git a/graphics/src/widget/canvas/style.rs b/graphics/src/widget/canvas/style.rs
new file mode 100644
index 00000000..6794f2e7
--- /dev/null
+++ b/graphics/src/widget/canvas/style.rs
@@ -0,0 +1,23 @@
+use crate::{Color, Gradient};
+
+/// The coloring style of some drawing.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Style {
+ /// A solid [`Color`].
+ Solid(Color),
+
+ /// A [`Gradient`] color.
+ Gradient(Gradient),
+}
+
+impl From<Color> for Style {
+ fn from(color: Color) -> Self {
+ Self::Solid(color)
+ }
+}
+
+impl From<Gradient> for Style {
+ fn from(gradient: Gradient) -> Self {
+ Self::Gradient(gradient)
+ }
+}
diff --git a/graphics/src/window/compositor.rs b/graphics/src/window/compositor.rs
index 52255666..db4ba45d 100644
--- a/graphics/src/window/compositor.rs
+++ b/graphics/src/window/compositor.rs
@@ -40,7 +40,7 @@ pub trait Compositor: Sized {
height: u32,
);
- /// Returns [`GraphicsInformation`] used by this [`Compositor`].
+ /// Returns [`Information`] used by this [`Compositor`].
fn fetch_information(&self) -> Information;
/// Presents the [`Renderer`] primitives to the next frame of the given [`Surface`].
diff --git a/graphics/src/window/gl_compositor.rs b/graphics/src/window/gl_compositor.rs
index 722e4d9c..a45a7ca1 100644
--- a/graphics/src/window/gl_compositor.rs
+++ b/graphics/src/window/gl_compositor.rs
@@ -54,7 +54,7 @@ pub trait GLCompositor: Sized {
/// Resizes the viewport of the [`GLCompositor`].
fn resize_viewport(&mut self, physical_size: Size<u32>);
- /// Returns [`GraphicsInformation`] used by this [`Compositor`].
+ /// Returns [`Information`] used by this [`GLCompositor`].
fn fetch_information(&self) -> Information;
/// Presents the primitives of the [`Renderer`] to the next frame of the