From 0d620b7701f427ed0091f3640ab9ca0e116eb412 Mon Sep 17 00:00:00 2001 From: Artur Sapek Date: Wed, 1 Jan 2020 15:44:32 -0700 Subject: [PATCH 1/3] Implement Geometry2D primitive --- core/src/geometry.rs | 20 +++ core/src/lib.rs | 2 + examples/geometry.rs | 227 ++++++++++++++++++++++++++++++++ native/src/lib.rs | 2 +- native/src/widget/geometry.rs | 0 wgpu/src/geometry.rs | 215 ++++++++++++++++++++++++++++++ wgpu/src/lib.rs | 1 + wgpu/src/primitive.rs | 7 +- wgpu/src/renderer.rs | 33 ++++- wgpu/src/shader/geom2d.frag | 8 ++ wgpu/src/shader/geom2d.frag.spv | Bin 0 -> 372 bytes wgpu/src/shader/geom2d.vert | 17 +++ wgpu/src/shader/geom2d.vert.spv | Bin 0 -> 1468 bytes 13 files changed, 528 insertions(+), 4 deletions(-) create mode 100644 core/src/geometry.rs create mode 100644 examples/geometry.rs create mode 100644 native/src/widget/geometry.rs create mode 100644 wgpu/src/geometry.rs create mode 100644 wgpu/src/shader/geom2d.frag create mode 100644 wgpu/src/shader/geom2d.frag.spv create mode 100644 wgpu/src/shader/geom2d.vert create mode 100644 wgpu/src/shader/geom2d.vert.spv diff --git a/core/src/geometry.rs b/core/src/geometry.rs new file mode 100644 index 00000000..f04ce42e --- /dev/null +++ b/core/src/geometry.rs @@ -0,0 +1,20 @@ +/// A two-dimensional vertex which has a color +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct Vertex2D { + /// The vertex position + pub position: [f32; 2], + /// The vertex color in rgba + pub color: [f32; 4], +} + +/// A set of [`Vertex2D`] and indices for drawing some 2D geometry on the GPU. +/// +/// [`Vertex2D`]: struct.Vertex2D.html +#[derive(Clone, Debug)] +pub struct Geometry2D { + /// The vertices for this geometry + pub vertices: Vec, + /// The indices for this geometry + pub indices: Vec, +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 821b09c1..881f56c9 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -23,6 +23,7 @@ mod length; mod point; mod rectangle; mod vector; +mod geometry; pub use align::{Align, HorizontalAlignment, VerticalAlignment}; pub use background::Background; @@ -32,6 +33,7 @@ pub use length::Length; pub use point::Point; pub use rectangle::Rectangle; pub use vector::Vector; +pub use geometry::{Vertex2D, Geometry2D}; #[cfg(feature = "command")] mod command; diff --git a/examples/geometry.rs b/examples/geometry.rs new file mode 100644 index 00000000..feb7684e --- /dev/null +++ b/examples/geometry.rs @@ -0,0 +1,227 @@ +//! This example showcases a simple native custom widget that renders using +//! arbitrary low-level geometry. +mod rainbow { + // For now, to implement a custom native widget you will need to add + // `iced_native` and `iced_wgpu` to your dependencies. + // + // Then, you simply need to define your widget type and implement the + // `iced_native::Widget` trait with the `iced_wgpu::Renderer`. + // + // Of course, you can choose to make the implementation renderer-agnostic, + // if you wish to, by creating your own `Renderer` trait, which could be + // implemented by `iced_wgpu` and other renderers. + use iced_native::{ + layout, Element, Geometry2D, Hasher, Layout, Length, + MouseCursor, Point, Size, Vertex2D, Widget, + }; + use iced_wgpu::{Primitive, Renderer}; + + pub struct Rainbow { + dimen: u16, + } + + impl Rainbow { + pub fn new(dimen: u16) -> Self { + Self { dimen } + } + } + + impl Widget for Rainbow { + fn width(&self) -> Length { + Length::Shrink + } + + fn height(&self) -> Length { + Length::Shrink + } + + fn layout( + &self, + _renderer: &Renderer, + _limits: &layout::Limits, + ) -> layout::Node { + layout::Node::new(Size::new( + f32::from(self.dimen), + f32::from(self.dimen), + )) + } + + fn hash_layout(&self, state: &mut Hasher) { + use std::hash::Hash; + + self.dimen.hash(state); + } + + fn draw( + &self, + _renderer: &mut Renderer, + layout: Layout<'_>, + cursor_position: Point, + ) -> (Primitive, MouseCursor) { + let b = layout.bounds(); + + // R O Y G B I V + let color_r = [1.0, 0.0, 0.0, 1.0]; + let color_o = [1.0, 0.5, 0.0, 1.0]; + let color_y = [1.0, 1.0, 0.0, 1.0]; + let color_g = [0.0, 1.0, 0.0, 1.0]; + let color_gb = [0.0, 1.0, 0.5, 1.0]; + let color_b = [0.0, 0.2, 1.0, 1.0]; + let color_i = [0.5, 0.0, 1.0, 1.0]; + let color_v = [0.75, 0.0, 0.5, 1.0]; + + let posn_center = { + if b.contains(cursor_position) { + [cursor_position.x, cursor_position.y] + } else { + [b.x + (b.width / 2.0), b.y + (b.height / 2.0)] + } + }; + + let posn_tl = [b.x, b.y]; + let posn_t = [b.x + (b.width / 2.0), b.y]; + let posn_tr = [b.x + b.width, b.y]; + let posn_r = [b.x + b.width, b.y + (b.height / 2.0)]; + let posn_br = [b.x + b.width, b.y + b.height]; + let posn_b = [b.x + (b.width / 2.0), b.y + b.height]; + let posn_bl = [b.x, b.y + b.height]; + let posn_l = [b.x, b.y + (b.height / 2.0)]; + + ( + Primitive::Geometry2D { + geometry: Geometry2D { + vertices: vec![ + Vertex2D { + position: posn_center, + color: [1.0, 1.0, 1.0, 1.0], + }, + Vertex2D { + position: posn_tl, + color: color_r, + }, + Vertex2D { + position: posn_t, + color: color_o, + }, + Vertex2D { + position: posn_tr, + color: color_y, + }, + Vertex2D { + position: posn_r, + color: color_g, + }, + Vertex2D { + position: posn_br, + color: color_gb, + }, + Vertex2D { + position: posn_b, + color: color_b, + }, + Vertex2D { + position: posn_bl, + color: color_i, + }, + Vertex2D { + position: posn_l, + color: color_v, + }, + ], + indices: vec![ + 0, 1, 2, // TL + 0, 2, 3, // T + 0, 3, 4, // TR + 0, 4, 5, // R + 0, 5, 6, // BR + 0, 6, 7, // B + 0, 7, 8, // BL + 0, 8, 1, // L + ], + }, + }, + MouseCursor::OutOfBounds, + ) + } + } + + impl<'a, Message> Into> for Rainbow { + fn into(self) -> Element<'a, Message, Renderer> { + Element::new(self) + } + } +} + +use iced::{ + scrollable, settings::Window, Align, Column, Container, Element, + Length, Sandbox, Scrollable, Settings, Text, +}; +use rainbow::Rainbow; + +pub fn main() { + Example::run(Settings { + window: Window { + size: (660, 660), + resizable: true, + decorations: true, + }, + }) +} + +struct Example { + dimen: u16, + scroll: scrollable::State, +} + +#[derive(Debug, Clone, Copy)] +enum Message {} + +impl Sandbox for Example { + type Message = Message; + + fn new() -> Self { + Example { + dimen: 500, + scroll: scrollable::State::new(), + } + } + + fn title(&self) -> String { + String::from("Custom 2D geometry - Iced") + } + + fn update(&mut self, _: Message) {} + + fn view(&mut self) -> Element { + let content = Column::new() + .padding(20) + .spacing(20) + .max_width(500) + .align_items(Align::Start) + .push(Rainbow::new(self.dimen)) + .push( + Text::new(String::from("In this example we draw a custom widget Rainbow, using the \ + Geometry2D primitive. This primitive supplies a list of triangles, expressed as vertices and indices.")) + .width(Length::Shrink), + ) + .push( + Text::new(String::from("Move your cursor over it, and see the center vertex follow you!")) + .width(Length::Shrink), + ) + .push( + Text::new(String::from("Every Vertex2D defines its own color. You could use the \ + Geometry2D primitive to render virtually any two-dimensional geometry for your widget.")) + .width(Length::Shrink), + ); + + let scrollable = + Scrollable::new(&mut self.scroll).push(Container::new(content)); + + Container::new(scrollable) + .width(Length::Fill) + .height(Length::Fill) + .center_x() + .center_y() + .into() + } +} diff --git a/native/src/lib.rs b/native/src/lib.rs index 8dcacb2b..6f6af159 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -55,7 +55,7 @@ mod user_interface; pub use iced_core::{ Align, Background, Color, Command, Font, HorizontalAlignment, Length, - Point, Rectangle, Vector, VerticalAlignment, + Point, Rectangle, Vector, VerticalAlignment, Geometry2D, Vertex2D, }; pub use clipboard::Clipboard; diff --git a/native/src/widget/geometry.rs b/native/src/widget/geometry.rs new file mode 100644 index 00000000..e69de29b diff --git a/wgpu/src/geometry.rs b/wgpu/src/geometry.rs new file mode 100644 index 00000000..f79e9c43 --- /dev/null +++ b/wgpu/src/geometry.rs @@ -0,0 +1,215 @@ +use crate::Transformation; +use iced_native::{Geometry2D, Rectangle, Vertex2D}; +use std::mem; + +#[derive(Debug)] +pub struct Pipeline { + pipeline: wgpu::RenderPipeline, + constants: wgpu::BindGroup, + constants_buffer: wgpu::Buffer, +} + +impl Pipeline { + pub fn new(device: &mut wgpu::Device) -> Pipeline { + let constant_layout = + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + bindings: &[wgpu::BindGroupLayoutBinding { + binding: 0, + visibility: wgpu::ShaderStage::VERTEX, + ty: wgpu::BindingType::UniformBuffer { dynamic: false }, + }], + }); + + let constants_buffer = device + .create_buffer_mapped( + 1, + wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, + ) + .fill_from_slice(&[Uniforms::default()]); + + let constant_bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { + layout: &constant_layout, + bindings: &[wgpu::Binding { + binding: 0, + resource: wgpu::BindingResource::Buffer { + buffer: &constants_buffer, + range: 0..std::mem::size_of::() as u64, + }, + }], + }); + + let layout = + device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + bind_group_layouts: &[&constant_layout], + }); + + let vs = include_bytes!("shader/geom2d.vert.spv"); + let vs_module = device.create_shader_module( + &wgpu::read_spirv(std::io::Cursor::new(&vs[..])) + .expect("Read quad vertex shader as SPIR-V"), + ); + + let fs = include_bytes!("shader/geom2d.frag.spv"); + let fs_module = device.create_shader_module( + &wgpu::read_spirv(std::io::Cursor::new(&fs[..])) + .expect("Read quad fragment shader as SPIR-V"), + ); + + let pipeline = + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + layout: &layout, + vertex_stage: wgpu::ProgrammableStageDescriptor { + module: &vs_module, + entry_point: "main", + }, + fragment_stage: Some(wgpu::ProgrammableStageDescriptor { + module: &fs_module, + entry_point: "main", + }), + rasterization_state: Some(wgpu::RasterizationStateDescriptor { + front_face: wgpu::FrontFace::Cw, + cull_mode: wgpu::CullMode::None, + depth_bias: 0, + depth_bias_slope_scale: 0.0, + depth_bias_clamp: 0.0, + }), + primitive_topology: wgpu::PrimitiveTopology::TriangleList, + color_states: &[wgpu::ColorStateDescriptor { + format: wgpu::TextureFormat::Bgra8UnormSrgb, + color_blend: wgpu::BlendDescriptor { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha_blend: wgpu::BlendDescriptor { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + write_mask: wgpu::ColorWrite::ALL, + }], + depth_stencil_state: None, + index_format: wgpu::IndexFormat::Uint16, + vertex_buffers: &[wgpu::VertexBufferDescriptor { + stride: mem::size_of::() as u64, + step_mode: wgpu::InputStepMode::Vertex, + attributes: &[ + // Position + wgpu::VertexAttributeDescriptor { + shader_location: 0, + format: wgpu::VertexFormat::Float2, + offset: 0, + }, + // Color + wgpu::VertexAttributeDescriptor { + shader_location: 1, + format: wgpu::VertexFormat::Float4, + offset: 4 * 2, + }, + ], + }], + sample_count: 1, + sample_mask: !0, + alpha_to_coverage_enabled: false, + }); + + Pipeline { + pipeline, + constants: constant_bind_group, + constants_buffer, + } + } + + pub fn draw( + &mut self, + device: &mut wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + transformation: Transformation, + scale: f32, + geometries: &Vec, + bounds: Rectangle, + ) { + let uniforms = Uniforms { + transform: transformation.into(), + scale, + }; + + let constants_buffer = device + .create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC) + .fill_from_slice(&[uniforms]); + + encoder.copy_buffer_to_buffer( + &constants_buffer, + 0, + &self.constants_buffer, + 0, + std::mem::size_of::() as u64, + ); + + for geom in geometries { + let vertices_buffer = device + .create_buffer_mapped( + geom.vertices.len(), + wgpu::BufferUsage::VERTEX, + ) + .fill_from_slice(&geom.vertices); + + let indices_buffer = device + .create_buffer_mapped( + geom.indices.len(), + wgpu::BufferUsage::INDEX, + ) + .fill_from_slice(&geom.indices); + + let mut render_pass = + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[ + wgpu::RenderPassColorAttachmentDescriptor { + attachment: target, + resolve_target: None, + load_op: wgpu::LoadOp::Load, + store_op: wgpu::StoreOp::Store, + clear_color: wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.0, + a: 0.0, + }, + }, + ], + depth_stencil_attachment: None, + }); + + render_pass.set_pipeline(&self.pipeline); + render_pass.set_bind_group(0, &self.constants, &[]); + render_pass.set_index_buffer(&indices_buffer, 0); + render_pass.set_vertex_buffers(0, &[(&vertices_buffer, 0)]); + render_pass.set_scissor_rect( + bounds.x, + bounds.y, + bounds.width, + bounds.height, + ); + + render_pass.draw_indexed(0..geom.indices.len() as u32, 0, 0..1); + } + } +} + +#[repr(C)] +#[derive(Debug, Clone, Copy)] +struct Uniforms { + transform: [f32; 16], + scale: f32, +} + +impl Default for Uniforms { + fn default() -> Self { + Self { + transform: *Transformation::identity().as_ref(), + scale: 1.0, + } + } +} diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 9f9ed8db..7587be77 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -30,6 +30,7 @@ mod quad; mod renderer; mod text; mod transformation; +mod geometry; pub(crate) use crate::image::Image; pub(crate) use quad::Quad; diff --git a/wgpu/src/primitive.rs b/wgpu/src/primitive.rs index 6c61f800..06121262 100644 --- a/wgpu/src/primitive.rs +++ b/wgpu/src/primitive.rs @@ -1,6 +1,6 @@ use iced_native::{ image, svg, Background, Color, Font, HorizontalAlignment, Rectangle, - Vector, VerticalAlignment, + Vector, VerticalAlignment, Geometry2D, }; /// A rendering primitive. @@ -63,6 +63,11 @@ pub enum Primitive { /// The content of the clip content: Box, }, + /// A low-level geometry primitive + Geometry2D { + /// The vertices and indices of the geometry + geometry: Geometry2D, + }, } impl Default for Primitive { diff --git a/wgpu/src/renderer.rs b/wgpu/src/renderer.rs index 365ef1ef..3cfd746d 100644 --- a/wgpu/src/renderer.rs +++ b/wgpu/src/renderer.rs @@ -1,7 +1,10 @@ -use crate::{image, quad, text, Image, Primitive, Quad, Transformation}; +use crate::{ + geometry, image, quad, text, Image, Primitive, Quad, Transformation, +}; use iced_native::{ renderer::{Debugger, Windowed}, - Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget, + Background, Color, Geometry2D, Layout, MouseCursor, Point, Rectangle, + Vector, Widget, }; use wgpu::{ @@ -24,6 +27,7 @@ pub struct Renderer { quad_pipeline: quad::Pipeline, image_pipeline: crate::image::Pipeline, text_pipeline: text::Pipeline, + geometry_pipeline: crate::geometry::Pipeline, } struct Layer<'a> { @@ -31,6 +35,7 @@ struct Layer<'a> { offset: Vector, quads: Vec, images: Vec, + geometries: Vec, text: Vec>, } @@ -42,6 +47,7 @@ impl<'a> Layer<'a> { quads: Vec::new(), images: Vec::new(), text: Vec::new(), + geometries: Vec::new(), } } } @@ -64,6 +70,7 @@ impl Renderer { let text_pipeline = text::Pipeline::new(&mut device); let quad_pipeline = quad::Pipeline::new(&mut device); let image_pipeline = crate::image::Pipeline::new(&mut device); + let geometry_pipeline = geometry::Pipeline::new(&mut device); Self { device, @@ -71,6 +78,7 @@ impl Renderer { quad_pipeline, image_pipeline, text_pipeline, + geometry_pipeline, } } @@ -244,6 +252,9 @@ impl Renderer { scale: [bounds.width, bounds.height], }); } + Primitive::Geometry2D { geometry } => { + layer.geometries.push(geometry.clone()); + } Primitive::Clip { bounds, offset, @@ -401,6 +412,24 @@ impl Renderer { }, ); } + + if layer.geometries.len() > 0 { + let translated = transformation + * Transformation::translate( + -(layer.offset.x as f32) * dpi, + -(layer.offset.y as f32) * dpi, + ); + + self.geometry_pipeline.draw( + &mut self.device, + encoder, + target, + translated, + dpi, + &layer.geometries, + bounds, + ); + } } } diff --git a/wgpu/src/shader/geom2d.frag b/wgpu/src/shader/geom2d.frag new file mode 100644 index 00000000..e39c45e7 --- /dev/null +++ b/wgpu/src/shader/geom2d.frag @@ -0,0 +1,8 @@ +#version 450 + +layout(location = 0) in vec4 i_Color; +layout(location = 0) out vec4 o_Color; + +void main() { + o_Color = i_Color; +} diff --git a/wgpu/src/shader/geom2d.frag.spv b/wgpu/src/shader/geom2d.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..c0165bcac9ab1cd9ba6bc39cb74afb19590a49e0 GIT binary patch literal 372 zcmZQ(Qf6mhU}WH6;9%fofB-=TCI&_Z1_o{hHZbk(6YQf`T#}+^Vrl?V!N}8U}U@%wV^J_(z`)GF%)rFJz;K9>fq|8Qg#lSDD+4Ro zgo5~h{Nl`#%=|o%8de678JQ?zEDZb%3=Hl$`ALa6#SCl=Y+ydfzS8)RqQt!7wEUu6 z1~vv(usF#5rSZYZi8-kZtPIQyf*^$qAhX#Rq!}0((sSYiQj5Y;i%L=}KvE#{K;j@a zNDk&0HU@UEdXRZw@yxuE;LNI2kUE$g$ZzR6@y9@RkQm7SFfkAtBnFCqcLrv#c_4KlyFg(8^CO543Ih-yWTr3!6FB`Sf>RO$ zm@US@%)rLLz@Wguz#z`R!T|Cohz~MPfq{jAgMk4o1`-GHxfnpH93p1Tz`_9HgWLi# zAEcj`fdOnD$ZZk~EDU@M3=AMK5MK@&<{&YU9U${SVG6PflqNyuf%u^C1Br<;urLTg z-3BsW8_E}kx&fqLgaP6Yka-~W5>WM^a0RIc@gBo8tVls-W6Fun?i!_Z(4 zQm+X$A7nSkd=MWLcOdgY@;XpA!{kAHP+Wq-!Hj_w9Cx5F1sMs_^Miqj0hEqGW`W`i zRGNU|%oZA_Jm7MOfx(f1l>roHq6`e+ybKCUkQ$JC#TXbEK;nH2tl&5oXJB9e=>v(| zF))M67mygp43K|8X$BNmpl|@00rER2orA Date: Thu, 2 Jan 2020 19:25:00 +0100 Subject: [PATCH 2/3] Rename `Geometry2D` to `Mesh2D` and move it to `iced_wgpu` --- core/src/geometry.rs | 20 -- core/src/lib.rs | 2 - examples/geometry.rs | 194 ++++++++---------- native/src/lib.rs | 2 +- wgpu/src/lib.rs | 3 +- wgpu/src/primitive.rs | 14 +- wgpu/src/renderer.rs | 57 +++-- .../src/shader/{geom2d.frag => triangle.frag} | 0 .../{geom2d.frag.spv => triangle.frag.spv} | Bin 372 -> 372 bytes .../src/shader/{geom2d.vert => triangle.vert} | 0 .../{geom2d.vert.spv => triangle.vert.spv} | Bin 1468 -> 1468 bytes wgpu/src/{geometry.rs => triangle.rs} | 90 +++++--- 12 files changed, 184 insertions(+), 198 deletions(-) delete mode 100644 core/src/geometry.rs rename wgpu/src/shader/{geom2d.frag => triangle.frag} (100%) rename wgpu/src/shader/{geom2d.frag.spv => triangle.frag.spv} (82%) rename wgpu/src/shader/{geom2d.vert => triangle.vert} (100%) rename wgpu/src/shader/{geom2d.vert.spv => triangle.vert.spv} (95%) rename wgpu/src/{geometry.rs => triangle.rs} (75%) diff --git a/core/src/geometry.rs b/core/src/geometry.rs deleted file mode 100644 index f04ce42e..00000000 --- a/core/src/geometry.rs +++ /dev/null @@ -1,20 +0,0 @@ -/// A two-dimensional vertex which has a color -#[repr(C)] -#[derive(Copy, Clone, Debug)] -pub struct Vertex2D { - /// The vertex position - pub position: [f32; 2], - /// The vertex color in rgba - pub color: [f32; 4], -} - -/// A set of [`Vertex2D`] and indices for drawing some 2D geometry on the GPU. -/// -/// [`Vertex2D`]: struct.Vertex2D.html -#[derive(Clone, Debug)] -pub struct Geometry2D { - /// The vertices for this geometry - pub vertices: Vec, - /// The indices for this geometry - pub indices: Vec, -} diff --git a/core/src/lib.rs b/core/src/lib.rs index 881f56c9..821b09c1 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -23,7 +23,6 @@ mod length; mod point; mod rectangle; mod vector; -mod geometry; pub use align::{Align, HorizontalAlignment, VerticalAlignment}; pub use background::Background; @@ -33,7 +32,6 @@ pub use length::Length; pub use point::Point; pub use rectangle::Rectangle; pub use vector::Vector; -pub use geometry::{Vertex2D, Geometry2D}; #[cfg(feature = "command")] mod command; diff --git a/examples/geometry.rs b/examples/geometry.rs index feb7684e..ae6c9ca0 100644 --- a/examples/geometry.rs +++ b/examples/geometry.rs @@ -11,24 +11,25 @@ mod rainbow { // if you wish to, by creating your own `Renderer` trait, which could be // implemented by `iced_wgpu` and other renderers. use iced_native::{ - layout, Element, Geometry2D, Hasher, Layout, Length, - MouseCursor, Point, Size, Vertex2D, Widget, + layout, Element, Hasher, Layout, Length, MouseCursor, Point, Size, + Widget, + }; + use iced_wgpu::{ + triangle::{Mesh2D, Vertex2D}, + Primitive, Renderer, }; - use iced_wgpu::{Primitive, Renderer}; - pub struct Rainbow { - dimen: u16, - } + pub struct Rainbow; impl Rainbow { - pub fn new(dimen: u16) -> Self { - Self { dimen } + pub fn new() -> Self { + Self } } impl Widget for Rainbow { fn width(&self) -> Length { - Length::Shrink + Length::Fill } fn height(&self) -> Length { @@ -38,19 +39,14 @@ mod rainbow { fn layout( &self, _renderer: &Renderer, - _limits: &layout::Limits, + limits: &layout::Limits, ) -> layout::Node { - layout::Node::new(Size::new( - f32::from(self.dimen), - f32::from(self.dimen), - )) + let size = limits.width(Length::Fill).resolve(Size::ZERO); + + layout::Node::new(Size::new(size.width, size.width)) } - fn hash_layout(&self, state: &mut Hasher) { - use std::hash::Hash; - - self.dimen.hash(state); - } + fn hash_layout(&self, _state: &mut Hasher) {} fn draw( &self, @@ -88,58 +84,56 @@ mod rainbow { let posn_l = [b.x, b.y + (b.height / 2.0)]; ( - Primitive::Geometry2D { - geometry: Geometry2D { - vertices: vec![ - Vertex2D { - position: posn_center, - color: [1.0, 1.0, 1.0, 1.0], - }, - Vertex2D { - position: posn_tl, - color: color_r, - }, - Vertex2D { - position: posn_t, - color: color_o, - }, - Vertex2D { - position: posn_tr, - color: color_y, - }, - Vertex2D { - position: posn_r, - color: color_g, - }, - Vertex2D { - position: posn_br, - color: color_gb, - }, - Vertex2D { - position: posn_b, - color: color_b, - }, - Vertex2D { - position: posn_bl, - color: color_i, - }, - Vertex2D { - position: posn_l, - color: color_v, - }, - ], - indices: vec![ - 0, 1, 2, // TL - 0, 2, 3, // T - 0, 3, 4, // TR - 0, 4, 5, // R - 0, 5, 6, // BR - 0, 6, 7, // B - 0, 7, 8, // BL - 0, 8, 1, // L - ], - }, - }, + Primitive::Mesh2D(std::sync::Arc::new(Mesh2D { + vertices: vec![ + Vertex2D { + position: posn_center, + color: [1.0, 1.0, 1.0, 1.0], + }, + Vertex2D { + position: posn_tl, + color: color_r, + }, + Vertex2D { + position: posn_t, + color: color_o, + }, + Vertex2D { + position: posn_tr, + color: color_y, + }, + Vertex2D { + position: posn_r, + color: color_g, + }, + Vertex2D { + position: posn_br, + color: color_gb, + }, + Vertex2D { + position: posn_b, + color: color_b, + }, + Vertex2D { + position: posn_bl, + color: color_i, + }, + Vertex2D { + position: posn_l, + color: color_v, + }, + ], + indices: vec![ + 0, 1, 2, // TL + 0, 2, 3, // T + 0, 3, 4, // TR + 0, 4, 5, // R + 0, 5, 6, // BR + 0, 6, 7, // B + 0, 7, 8, // BL + 0, 8, 1, // L + ], + })), MouseCursor::OutOfBounds, ) } @@ -153,35 +147,24 @@ mod rainbow { } use iced::{ - scrollable, settings::Window, Align, Column, Container, Element, - Length, Sandbox, Scrollable, Settings, Text, + scrollable, Align, Column, Container, Element, Length, Sandbox, Scrollable, + Settings, Text, }; use rainbow::Rainbow; pub fn main() { - Example::run(Settings { - window: Window { - size: (660, 660), - resizable: true, - decorations: true, - }, - }) + Example::run(Settings::default()) } struct Example { - dimen: u16, scroll: scrollable::State, } -#[derive(Debug, Clone, Copy)] -enum Message {} - impl Sandbox for Example { - type Message = Message; + type Message = (); fn new() -> Self { Example { - dimen: 500, scroll: scrollable::State::new(), } } @@ -190,37 +173,36 @@ impl Sandbox for Example { String::from("Custom 2D geometry - Iced") } - fn update(&mut self, _: Message) {} + fn update(&mut self, _: ()) {} - fn view(&mut self) -> Element { + fn view(&mut self) -> Element<()> { let content = Column::new() .padding(20) .spacing(20) .max_width(500) .align_items(Align::Start) - .push(Rainbow::new(self.dimen)) - .push( - Text::new(String::from("In this example we draw a custom widget Rainbow, using the \ - Geometry2D primitive. This primitive supplies a list of triangles, expressed as vertices and indices.")) - .width(Length::Shrink), - ) - .push( - Text::new(String::from("Move your cursor over it, and see the center vertex follow you!")) - .width(Length::Shrink), - ) - .push( - Text::new(String::from("Every Vertex2D defines its own color. You could use the \ - Geometry2D primitive to render virtually any two-dimensional geometry for your widget.")) - .width(Length::Shrink), - ); + .push(Rainbow::new()) + .push(Text::new( + "In this example we draw a custom widget Rainbow, using \ + the Mesh2D primitive. This primitive supplies a list of \ + triangles, expressed as vertices and indices.", + )) + .push(Text::new( + "Move your cursor over it, and see the center vertex \ + follow you!", + )) + .push(Text::new( + "Every Vertex2D defines its own color. You could use the \ + Mesh2D primitive to render virtually any two-dimensional \ + geometry for your widget.", + )); - let scrollable = - Scrollable::new(&mut self.scroll).push(Container::new(content)); + let scrollable = Scrollable::new(&mut self.scroll) + .push(Container::new(content).width(Length::Fill).center_x()); Container::new(scrollable) .width(Length::Fill) .height(Length::Fill) - .center_x() .center_y() .into() } diff --git a/native/src/lib.rs b/native/src/lib.rs index 6f6af159..8dcacb2b 100644 --- a/native/src/lib.rs +++ b/native/src/lib.rs @@ -55,7 +55,7 @@ mod user_interface; pub use iced_core::{ Align, Background, Color, Command, Font, HorizontalAlignment, Length, - Point, Rectangle, Vector, VerticalAlignment, Geometry2D, Vertex2D, + Point, Rectangle, Vector, VerticalAlignment, }; pub use clipboard::Clipboard; diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 7587be77..972f56af 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -24,13 +24,14 @@ #![deny(unused_results)] #![deny(unsafe_code)] #![deny(rust_2018_idioms)] +pub mod triangle; + mod image; mod primitive; mod quad; mod renderer; mod text; mod transformation; -mod geometry; pub(crate) use crate::image::Image; pub(crate) use quad::Quad; diff --git a/wgpu/src/primitive.rs b/wgpu/src/primitive.rs index 06121262..815ba3b0 100644 --- a/wgpu/src/primitive.rs +++ b/wgpu/src/primitive.rs @@ -1,8 +1,11 @@ use iced_native::{ image, svg, Background, Color, Font, HorizontalAlignment, Rectangle, - Vector, VerticalAlignment, Geometry2D, + Vector, VerticalAlignment, }; +use crate::triangle; +use std::sync::Arc; + /// A rendering primitive. #[derive(Debug, Clone)] pub enum Primitive { @@ -63,11 +66,10 @@ pub enum Primitive { /// The content of the clip content: Box, }, - /// A low-level geometry primitive - Geometry2D { - /// The vertices and indices of the geometry - geometry: Geometry2D, - }, + /// A low-level primitive to render a mesh of triangles. + /// + /// It can be used to render many kinds of geometry freely. + Mesh2D(Arc), } impl Default for Primitive { diff --git a/wgpu/src/renderer.rs b/wgpu/src/renderer.rs index 3cfd746d..050daca9 100644 --- a/wgpu/src/renderer.rs +++ b/wgpu/src/renderer.rs @@ -1,12 +1,11 @@ use crate::{ - geometry, image, quad, text, Image, Primitive, Quad, Transformation, + image, quad, text, triangle, Image, Primitive, Quad, Transformation, }; use iced_native::{ renderer::{Debugger, Windowed}, - Background, Color, Geometry2D, Layout, MouseCursor, Point, Rectangle, - Vector, Widget, + Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget, }; - +use std::sync::Arc; use wgpu::{ Adapter, BackendBit, CommandEncoderDescriptor, Device, DeviceDescriptor, Extensions, Limits, PowerPreference, Queue, RequestAdapterOptions, @@ -27,7 +26,7 @@ pub struct Renderer { quad_pipeline: quad::Pipeline, image_pipeline: crate::image::Pipeline, text_pipeline: text::Pipeline, - geometry_pipeline: crate::geometry::Pipeline, + triangle_pipeline: crate::triangle::Pipeline, } struct Layer<'a> { @@ -35,7 +34,7 @@ struct Layer<'a> { offset: Vector, quads: Vec, images: Vec, - geometries: Vec, + meshes: Vec>, text: Vec>, } @@ -47,7 +46,7 @@ impl<'a> Layer<'a> { quads: Vec::new(), images: Vec::new(), text: Vec::new(), - geometries: Vec::new(), + meshes: Vec::new(), } } } @@ -70,7 +69,7 @@ impl Renderer { let text_pipeline = text::Pipeline::new(&mut device); let quad_pipeline = quad::Pipeline::new(&mut device); let image_pipeline = crate::image::Pipeline::new(&mut device); - let geometry_pipeline = geometry::Pipeline::new(&mut device); + let triangle_pipeline = triangle::Pipeline::new(&mut device); Self { device, @@ -78,7 +77,7 @@ impl Renderer { quad_pipeline, image_pipeline, text_pipeline, - geometry_pipeline, + triangle_pipeline, } } @@ -252,8 +251,8 @@ impl Renderer { scale: [bounds.width, bounds.height], }); } - Primitive::Geometry2D { geometry } => { - layer.geometries.push(geometry.clone()); + Primitive::Mesh2D(mesh) => { + layer.meshes.push(mesh.clone()); } Primitive::Clip { bounds, @@ -333,6 +332,24 @@ impl Renderer { ) { let bounds = layer.bounds * dpi; + if layer.meshes.len() > 0 { + let translated = transformation + * Transformation::translate( + -(layer.offset.x as f32) * dpi, + -(layer.offset.y as f32) * dpi, + ); + + self.triangle_pipeline.draw( + &mut self.device, + encoder, + target, + translated, + dpi, + &layer.meshes, + bounds, + ); + } + if layer.quads.len() > 0 { self.quad_pipeline.draw( &mut self.device, @@ -412,24 +429,6 @@ impl Renderer { }, ); } - - if layer.geometries.len() > 0 { - let translated = transformation - * Transformation::translate( - -(layer.offset.x as f32) * dpi, - -(layer.offset.y as f32) * dpi, - ); - - self.geometry_pipeline.draw( - &mut self.device, - encoder, - target, - translated, - dpi, - &layer.geometries, - bounds, - ); - } } } diff --git a/wgpu/src/shader/geom2d.frag b/wgpu/src/shader/triangle.frag similarity index 100% rename from wgpu/src/shader/geom2d.frag rename to wgpu/src/shader/triangle.frag diff --git a/wgpu/src/shader/geom2d.frag.spv b/wgpu/src/shader/triangle.frag.spv similarity index 82% rename from wgpu/src/shader/geom2d.frag.spv rename to wgpu/src/shader/triangle.frag.spv index c0165bcac9ab1cd9ba6bc39cb74afb19590a49e0..11201872ec63d8b77e22fbee6a8731f2f5ed96a2 100644 GIT binary patch delta 18 Zcmeyu^o5C&nMs+Qfq{{MeIsW!BLF8J15*G1 delta 18 Zcmeyu^o5C&nMs+Qfq{{MV@) delta 18 ZcmdnPy@#8VnMs+Qfq{{MV, + meshes: &Vec>, bounds: Rectangle, ) { let uniforms = Uniforms { @@ -148,39 +149,39 @@ impl Pipeline { std::mem::size_of::() as u64, ); - for geom in geometries { + let mut render_pass = + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + color_attachments: &[ + wgpu::RenderPassColorAttachmentDescriptor { + attachment: target, + resolve_target: None, + load_op: wgpu::LoadOp::Load, + store_op: wgpu::StoreOp::Store, + clear_color: wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.0, + a: 0.0, + }, + }, + ], + depth_stencil_attachment: None, + }); + + for mesh in meshes { let vertices_buffer = device .create_buffer_mapped( - geom.vertices.len(), + mesh.vertices.len(), wgpu::BufferUsage::VERTEX, ) - .fill_from_slice(&geom.vertices); + .fill_from_slice(&mesh.vertices); let indices_buffer = device .create_buffer_mapped( - geom.indices.len(), + mesh.indices.len(), wgpu::BufferUsage::INDEX, ) - .fill_from_slice(&geom.indices); - - let mut render_pass = - encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - color_attachments: &[ - wgpu::RenderPassColorAttachmentDescriptor { - attachment: target, - resolve_target: None, - load_op: wgpu::LoadOp::Load, - store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, - }, - }, - ], - depth_stencil_attachment: None, - }); + .fill_from_slice(&mesh.indices); render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, &self.constants, &[]); @@ -193,7 +194,7 @@ impl Pipeline { bounds.height, ); - render_pass.draw_indexed(0..geom.indices.len() as u32, 0, 0..1); + render_pass.draw_indexed(0..mesh.indices.len() as u32, 0, 0..1); } } } @@ -213,3 +214,26 @@ impl Default for Uniforms { } } } + +/// A two-dimensional vertex with some color in __linear__ RGBA. +#[repr(C)] +#[derive(Copy, Clone, Debug)] +pub struct Vertex2D { + /// The vertex position + pub position: [f32; 2], + /// The vertex color in __linear__ RGBA. + pub color: [f32; 4], +} + +/// A set of [`Vertex2D`] and indices representing a list of triangles. +/// +/// [`Vertex2D`]: struct.Vertex2D.html +#[derive(Clone, Debug)] +pub struct Mesh2D { + /// The vertices of the mesh + pub vertices: Vec, + /// 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, +} From dc094df214a4eab53d3fa8bdf8087fef5a37e9b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 2 Jan 2020 19:27:54 +0100 Subject: [PATCH 3/3] Remove empty `geometry` file in `iced_native` --- native/src/widget/geometry.rs | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 native/src/widget/geometry.rs diff --git a/native/src/widget/geometry.rs b/native/src/widget/geometry.rs deleted file mode 100644 index e69de29b..00000000