Rename Geometry2D to Mesh2D and move it to iced_wgpu

This commit is contained in:
Héctor Ramón Jiménez 2020-01-02 19:25:00 +01:00
parent 0d620b7701
commit 5ca98b113e
12 changed files with 184 additions and 198 deletions

View File

@ -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<Vertex2D>,
/// The indices for this geometry
pub indices: Vec<u16>,
}

View File

@ -23,7 +23,6 @@ mod length;
mod point; mod point;
mod rectangle; mod rectangle;
mod vector; mod vector;
mod geometry;
pub use align::{Align, HorizontalAlignment, VerticalAlignment}; pub use align::{Align, HorizontalAlignment, VerticalAlignment};
pub use background::Background; pub use background::Background;
@ -33,7 +32,6 @@ pub use length::Length;
pub use point::Point; pub use point::Point;
pub use rectangle::Rectangle; pub use rectangle::Rectangle;
pub use vector::Vector; pub use vector::Vector;
pub use geometry::{Vertex2D, Geometry2D};
#[cfg(feature = "command")] #[cfg(feature = "command")]
mod command; mod command;

View File

@ -11,24 +11,25 @@ mod rainbow {
// if you wish to, by creating your own `Renderer` trait, which could be // if you wish to, by creating your own `Renderer` trait, which could be
// implemented by `iced_wgpu` and other renderers. // implemented by `iced_wgpu` and other renderers.
use iced_native::{ use iced_native::{
layout, Element, Geometry2D, Hasher, Layout, Length, layout, Element, Hasher, Layout, Length, MouseCursor, Point, Size,
MouseCursor, Point, Size, Vertex2D, Widget, Widget,
};
use iced_wgpu::{
triangle::{Mesh2D, Vertex2D},
Primitive, Renderer,
}; };
use iced_wgpu::{Primitive, Renderer};
pub struct Rainbow { pub struct Rainbow;
dimen: u16,
}
impl Rainbow { impl Rainbow {
pub fn new(dimen: u16) -> Self { pub fn new() -> Self {
Self { dimen } Self
} }
} }
impl<Message> Widget<Message, Renderer> for Rainbow { impl<Message> Widget<Message, Renderer> for Rainbow {
fn width(&self) -> Length { fn width(&self) -> Length {
Length::Shrink Length::Fill
} }
fn height(&self) -> Length { fn height(&self) -> Length {
@ -38,19 +39,14 @@ mod rainbow {
fn layout( fn layout(
&self, &self,
_renderer: &Renderer, _renderer: &Renderer,
_limits: &layout::Limits, limits: &layout::Limits,
) -> layout::Node { ) -> layout::Node {
layout::Node::new(Size::new( let size = limits.width(Length::Fill).resolve(Size::ZERO);
f32::from(self.dimen),
f32::from(self.dimen), layout::Node::new(Size::new(size.width, size.width))
))
} }
fn hash_layout(&self, state: &mut Hasher) { fn hash_layout(&self, _state: &mut Hasher) {}
use std::hash::Hash;
self.dimen.hash(state);
}
fn draw( fn draw(
&self, &self,
@ -88,58 +84,56 @@ mod rainbow {
let posn_l = [b.x, b.y + (b.height / 2.0)]; let posn_l = [b.x, b.y + (b.height / 2.0)];
( (
Primitive::Geometry2D { Primitive::Mesh2D(std::sync::Arc::new(Mesh2D {
geometry: Geometry2D { vertices: vec![
vertices: vec![ Vertex2D {
Vertex2D { position: posn_center,
position: posn_center, color: [1.0, 1.0, 1.0, 1.0],
color: [1.0, 1.0, 1.0, 1.0], },
}, Vertex2D {
Vertex2D { position: posn_tl,
position: posn_tl, color: color_r,
color: color_r, },
}, Vertex2D {
Vertex2D { position: posn_t,
position: posn_t, color: color_o,
color: color_o, },
}, Vertex2D {
Vertex2D { position: posn_tr,
position: posn_tr, color: color_y,
color: color_y, },
}, Vertex2D {
Vertex2D { position: posn_r,
position: posn_r, color: color_g,
color: color_g, },
}, Vertex2D {
Vertex2D { position: posn_br,
position: posn_br, color: color_gb,
color: color_gb, },
}, Vertex2D {
Vertex2D { position: posn_b,
position: posn_b, color: color_b,
color: color_b, },
}, Vertex2D {
Vertex2D { position: posn_bl,
position: posn_bl, color: color_i,
color: color_i, },
}, Vertex2D {
Vertex2D { position: posn_l,
position: posn_l, color: color_v,
color: color_v, },
}, ],
], indices: vec![
indices: vec![ 0, 1, 2, // TL
0, 1, 2, // TL 0, 2, 3, // T
0, 2, 3, // T 0, 3, 4, // TR
0, 3, 4, // TR 0, 4, 5, // R
0, 4, 5, // R 0, 5, 6, // BR
0, 5, 6, // BR 0, 6, 7, // B
0, 6, 7, // B 0, 7, 8, // BL
0, 7, 8, // BL 0, 8, 1, // L
0, 8, 1, // L ],
], })),
},
},
MouseCursor::OutOfBounds, MouseCursor::OutOfBounds,
) )
} }
@ -153,35 +147,24 @@ mod rainbow {
} }
use iced::{ use iced::{
scrollable, settings::Window, Align, Column, Container, Element, scrollable, Align, Column, Container, Element, Length, Sandbox, Scrollable,
Length, Sandbox, Scrollable, Settings, Text, Settings, Text,
}; };
use rainbow::Rainbow; use rainbow::Rainbow;
pub fn main() { pub fn main() {
Example::run(Settings { Example::run(Settings::default())
window: Window {
size: (660, 660),
resizable: true,
decorations: true,
},
})
} }
struct Example { struct Example {
dimen: u16,
scroll: scrollable::State, scroll: scrollable::State,
} }
#[derive(Debug, Clone, Copy)]
enum Message {}
impl Sandbox for Example { impl Sandbox for Example {
type Message = Message; type Message = ();
fn new() -> Self { fn new() -> Self {
Example { Example {
dimen: 500,
scroll: scrollable::State::new(), scroll: scrollable::State::new(),
} }
} }
@ -190,37 +173,36 @@ impl Sandbox for Example {
String::from("Custom 2D geometry - Iced") String::from("Custom 2D geometry - Iced")
} }
fn update(&mut self, _: Message) {} fn update(&mut self, _: ()) {}
fn view(&mut self) -> Element<Message> { fn view(&mut self) -> Element<()> {
let content = Column::new() let content = Column::new()
.padding(20) .padding(20)
.spacing(20) .spacing(20)
.max_width(500) .max_width(500)
.align_items(Align::Start) .align_items(Align::Start)
.push(Rainbow::new(self.dimen)) .push(Rainbow::new())
.push( .push(Text::new(
Text::new(String::from("In this example we draw a custom widget Rainbow, using the \ "In this example we draw a custom widget Rainbow, using \
Geometry2D primitive. This primitive supplies a list of triangles, expressed as vertices and indices.")) the Mesh2D primitive. This primitive supplies a list of \
.width(Length::Shrink), triangles, expressed as vertices and indices.",
) ))
.push( .push(Text::new(
Text::new(String::from("Move your cursor over it, and see the center vertex follow you!")) "Move your cursor over it, and see the center vertex \
.width(Length::Shrink), follow you!",
) ))
.push( .push(Text::new(
Text::new(String::from("Every Vertex2D defines its own color. You could use the \ "Every Vertex2D defines its own color. You could use the \
Geometry2D primitive to render virtually any two-dimensional geometry for your widget.")) Mesh2D primitive to render virtually any two-dimensional \
.width(Length::Shrink), geometry for your widget.",
); ));
let scrollable = let scrollable = Scrollable::new(&mut self.scroll)
Scrollable::new(&mut self.scroll).push(Container::new(content)); .push(Container::new(content).width(Length::Fill).center_x());
Container::new(scrollable) Container::new(scrollable)
.width(Length::Fill) .width(Length::Fill)
.height(Length::Fill) .height(Length::Fill)
.center_x()
.center_y() .center_y()
.into() .into()
} }

View File

@ -55,7 +55,7 @@ mod user_interface;
pub use iced_core::{ pub use iced_core::{
Align, Background, Color, Command, Font, HorizontalAlignment, Length, Align, Background, Color, Command, Font, HorizontalAlignment, Length,
Point, Rectangle, Vector, VerticalAlignment, Geometry2D, Vertex2D, Point, Rectangle, Vector, VerticalAlignment,
}; };
pub use clipboard::Clipboard; pub use clipboard::Clipboard;

View File

@ -24,13 +24,14 @@
#![deny(unused_results)] #![deny(unused_results)]
#![deny(unsafe_code)] #![deny(unsafe_code)]
#![deny(rust_2018_idioms)] #![deny(rust_2018_idioms)]
pub mod triangle;
mod image; mod image;
mod primitive; mod primitive;
mod quad; mod quad;
mod renderer; mod renderer;
mod text; mod text;
mod transformation; mod transformation;
mod geometry;
pub(crate) use crate::image::Image; pub(crate) use crate::image::Image;
pub(crate) use quad::Quad; pub(crate) use quad::Quad;

View File

@ -1,8 +1,11 @@
use iced_native::{ use iced_native::{
image, svg, Background, Color, Font, HorizontalAlignment, Rectangle, image, svg, Background, Color, Font, HorizontalAlignment, Rectangle,
Vector, VerticalAlignment, Geometry2D, Vector, VerticalAlignment,
}; };
use crate::triangle;
use std::sync::Arc;
/// A rendering primitive. /// A rendering primitive.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Primitive { pub enum Primitive {
@ -63,11 +66,10 @@ pub enum Primitive {
/// The content of the clip /// The content of the clip
content: Box<Primitive>, content: Box<Primitive>,
}, },
/// A low-level geometry primitive /// A low-level primitive to render a mesh of triangles.
Geometry2D { ///
/// The vertices and indices of the geometry /// It can be used to render many kinds of geometry freely.
geometry: Geometry2D, Mesh2D(Arc<triangle::Mesh2D>),
},
} }
impl Default for Primitive { impl Default for Primitive {

View File

@ -1,12 +1,11 @@
use crate::{ use crate::{
geometry, image, quad, text, Image, Primitive, Quad, Transformation, image, quad, text, triangle, Image, Primitive, Quad, Transformation,
}; };
use iced_native::{ use iced_native::{
renderer::{Debugger, Windowed}, renderer::{Debugger, Windowed},
Background, Color, Geometry2D, Layout, MouseCursor, Point, Rectangle, Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget,
Vector, Widget,
}; };
use std::sync::Arc;
use wgpu::{ use wgpu::{
Adapter, BackendBit, CommandEncoderDescriptor, Device, DeviceDescriptor, Adapter, BackendBit, CommandEncoderDescriptor, Device, DeviceDescriptor,
Extensions, Limits, PowerPreference, Queue, RequestAdapterOptions, Extensions, Limits, PowerPreference, Queue, RequestAdapterOptions,
@ -27,7 +26,7 @@ pub struct Renderer {
quad_pipeline: quad::Pipeline, quad_pipeline: quad::Pipeline,
image_pipeline: crate::image::Pipeline, image_pipeline: crate::image::Pipeline,
text_pipeline: text::Pipeline, text_pipeline: text::Pipeline,
geometry_pipeline: crate::geometry::Pipeline, triangle_pipeline: crate::triangle::Pipeline,
} }
struct Layer<'a> { struct Layer<'a> {
@ -35,7 +34,7 @@ struct Layer<'a> {
offset: Vector<u32>, offset: Vector<u32>,
quads: Vec<Quad>, quads: Vec<Quad>,
images: Vec<Image>, images: Vec<Image>,
geometries: Vec<Geometry2D>, meshes: Vec<Arc<triangle::Mesh2D>>,
text: Vec<wgpu_glyph::Section<'a>>, text: Vec<wgpu_glyph::Section<'a>>,
} }
@ -47,7 +46,7 @@ impl<'a> Layer<'a> {
quads: Vec::new(), quads: Vec::new(),
images: Vec::new(), images: Vec::new(),
text: 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 text_pipeline = text::Pipeline::new(&mut device);
let quad_pipeline = quad::Pipeline::new(&mut device); let quad_pipeline = quad::Pipeline::new(&mut device);
let image_pipeline = crate::image::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 { Self {
device, device,
@ -78,7 +77,7 @@ impl Renderer {
quad_pipeline, quad_pipeline,
image_pipeline, image_pipeline,
text_pipeline, text_pipeline,
geometry_pipeline, triangle_pipeline,
} }
} }
@ -252,8 +251,8 @@ impl Renderer {
scale: [bounds.width, bounds.height], scale: [bounds.width, bounds.height],
}); });
} }
Primitive::Geometry2D { geometry } => { Primitive::Mesh2D(mesh) => {
layer.geometries.push(geometry.clone()); layer.meshes.push(mesh.clone());
} }
Primitive::Clip { Primitive::Clip {
bounds, bounds,
@ -333,6 +332,24 @@ impl Renderer {
) { ) {
let bounds = layer.bounds * dpi; 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 { if layer.quads.len() > 0 {
self.quad_pipeline.draw( self.quad_pipeline.draw(
&mut self.device, &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,
);
}
} }
} }

View File

@ -1,9 +1,10 @@
//! Draw meshes of triangles.
use crate::Transformation; use crate::Transformation;
use iced_native::{Geometry2D, Rectangle, Vertex2D}; use iced_native::Rectangle;
use std::mem; use std::{mem, sync::Arc};
#[derive(Debug)] #[derive(Debug)]
pub struct Pipeline { pub(crate) struct Pipeline {
pipeline: wgpu::RenderPipeline, pipeline: wgpu::RenderPipeline,
constants: wgpu::BindGroup, constants: wgpu::BindGroup,
constants_buffer: wgpu::Buffer, constants_buffer: wgpu::Buffer,
@ -44,16 +45,16 @@ impl Pipeline {
bind_group_layouts: &[&constant_layout], bind_group_layouts: &[&constant_layout],
}); });
let vs = include_bytes!("shader/geom2d.vert.spv"); let vs = include_bytes!("shader/triangle.vert.spv");
let vs_module = device.create_shader_module( let vs_module = device.create_shader_module(
&wgpu::read_spirv(std::io::Cursor::new(&vs[..])) &wgpu::read_spirv(std::io::Cursor::new(&vs[..]))
.expect("Read quad vertex shader as SPIR-V"), .expect("Read triangle vertex shader as SPIR-V"),
); );
let fs = include_bytes!("shader/geom2d.frag.spv"); let fs = include_bytes!("shader/triangle.frag.spv");
let fs_module = device.create_shader_module( let fs_module = device.create_shader_module(
&wgpu::read_spirv(std::io::Cursor::new(&fs[..])) &wgpu::read_spirv(std::io::Cursor::new(&fs[..]))
.expect("Read quad fragment shader as SPIR-V"), .expect("Read triangle fragment shader as SPIR-V"),
); );
let pipeline = let pipeline =
@ -128,7 +129,7 @@ impl Pipeline {
target: &wgpu::TextureView, target: &wgpu::TextureView,
transformation: Transformation, transformation: Transformation,
scale: f32, scale: f32,
geometries: &Vec<Geometry2D>, meshes: &Vec<Arc<Mesh2D>>,
bounds: Rectangle<u32>, bounds: Rectangle<u32>,
) { ) {
let uniforms = Uniforms { let uniforms = Uniforms {
@ -148,39 +149,39 @@ impl Pipeline {
std::mem::size_of::<Uniforms>() as u64, std::mem::size_of::<Uniforms>() 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 let vertices_buffer = device
.create_buffer_mapped( .create_buffer_mapped(
geom.vertices.len(), mesh.vertices.len(),
wgpu::BufferUsage::VERTEX, wgpu::BufferUsage::VERTEX,
) )
.fill_from_slice(&geom.vertices); .fill_from_slice(&mesh.vertices);
let indices_buffer = device let indices_buffer = device
.create_buffer_mapped( .create_buffer_mapped(
geom.indices.len(), mesh.indices.len(),
wgpu::BufferUsage::INDEX, wgpu::BufferUsage::INDEX,
) )
.fill_from_slice(&geom.indices); .fill_from_slice(&mesh.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_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.constants, &[]); render_pass.set_bind_group(0, &self.constants, &[]);
@ -193,7 +194,7 @@ impl Pipeline {
bounds.height, 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<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<u16>,
}