Skip to content

Commit

Permalink
Merge pull request #140 from artursapek/artur/canvas
Browse files Browse the repository at this point in the history
Mesh2D primitive for rendering arbitrary geometry in `iced_wgpu`
  • Loading branch information
hecrj authored Jan 3, 2020
2 parents 26de688 + dc094df commit e4de213
Show file tree
Hide file tree
Showing 9 changed files with 512 additions and 2 deletions.
209 changes: 209 additions & 0 deletions examples/geometry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
//! 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, Hasher, Layout, Length, MouseCursor, Point, Size,
Widget,
};
use iced_wgpu::{
triangle::{Mesh2D, Vertex2D},
Primitive, Renderer,
};

pub struct Rainbow;

impl Rainbow {
pub fn new() -> Self {
Self
}
}

impl<Message> Widget<Message, Renderer> for Rainbow {
fn width(&self) -> Length {
Length::Fill
}

fn height(&self) -> Length {
Length::Shrink
}

fn layout(
&self,
_renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
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) {}

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::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,
)
}
}

impl<'a, Message> Into<Element<'a, Message, Renderer>> for Rainbow {
fn into(self) -> Element<'a, Message, Renderer> {
Element::new(self)
}
}
}

use iced::{
scrollable, Align, Column, Container, Element, Length, Sandbox, Scrollable,
Settings, Text,
};
use rainbow::Rainbow;

pub fn main() {
Example::run(Settings::default())
}

struct Example {
scroll: scrollable::State,
}

impl Sandbox for Example {
type Message = ();

fn new() -> Self {
Example {
scroll: scrollable::State::new(),
}
}

fn title(&self) -> String {
String::from("Custom 2D geometry - Iced")
}

fn update(&mut self, _: ()) {}

fn view(&mut self) -> Element<()> {
let content = Column::new()
.padding(20)
.spacing(20)
.max_width(500)
.align_items(Align::Start)
.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).width(Length::Fill).center_x());

Container::new(scrollable)
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.into()
}
}
2 changes: 2 additions & 0 deletions wgpu/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
#![deny(unused_results)]
#![deny(unsafe_code)]
#![deny(rust_2018_idioms)]
pub mod triangle;

mod image;
mod primitive;
mod quad;
Expand Down
7 changes: 7 additions & 0 deletions wgpu/src/primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ use iced_native::{
Vector, VerticalAlignment,
};

use crate::triangle;
use std::sync::Arc;

/// A rendering primitive.
#[derive(Debug, Clone)]
pub enum Primitive {
Expand Down Expand Up @@ -63,6 +66,10 @@ pub enum Primitive {
/// The content of the clip
content: Box<Primitive>,
},
/// A low-level primitive to render a mesh of triangles.
///
/// It can be used to render many kinds of geometry freely.
Mesh2D(Arc<triangle::Mesh2D>),
}

impl Default for Primitive {
Expand Down
32 changes: 30 additions & 2 deletions wgpu/src/renderer.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use crate::{image, quad, text, Image, Primitive, Quad, Transformation};
use crate::{
image, quad, text, triangle, Image, Primitive, Quad, Transformation,
};
use iced_native::{
renderer::{Debugger, Windowed},
Background, Color, Layout, MouseCursor, Point, Rectangle, Vector, Widget,
};

use std::sync::Arc;
use wgpu::{
Adapter, BackendBit, CommandEncoderDescriptor, Device, DeviceDescriptor,
Extensions, Limits, PowerPreference, Queue, RequestAdapterOptions,
Expand All @@ -24,13 +26,15 @@ pub struct Renderer {
quad_pipeline: quad::Pipeline,
image_pipeline: crate::image::Pipeline,
text_pipeline: text::Pipeline,
triangle_pipeline: crate::triangle::Pipeline,
}

struct Layer<'a> {
bounds: Rectangle<u32>,
offset: Vector<u32>,
quads: Vec<Quad>,
images: Vec<Image>,
meshes: Vec<Arc<triangle::Mesh2D>>,
text: Vec<wgpu_glyph::Section<'a>>,
}

Expand All @@ -42,6 +46,7 @@ impl<'a> Layer<'a> {
quads: Vec::new(),
images: Vec::new(),
text: Vec::new(),
meshes: Vec::new(),
}
}
}
Expand All @@ -64,13 +69,15 @@ 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 triangle_pipeline = triangle::Pipeline::new(&mut device);

Self {
device,
queue,
quad_pipeline,
image_pipeline,
text_pipeline,
triangle_pipeline,
}
}

Expand Down Expand Up @@ -244,6 +251,9 @@ impl Renderer {
scale: [bounds.width, bounds.height],
});
}
Primitive::Mesh2D(mesh) => {
layer.meshes.push(mesh.clone());
}
Primitive::Clip {
bounds,
offset,
Expand Down Expand Up @@ -322,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,
Expand Down
8 changes: 8 additions & 0 deletions wgpu/src/shader/triangle.frag
Original file line number Diff line number Diff line change
@@ -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;
}
Binary file added wgpu/src/shader/triangle.frag.spv
Binary file not shown.
17 changes: 17 additions & 0 deletions wgpu/src/shader/triangle.vert
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#version 450

layout(location = 0) in vec2 i_Position;
layout(location = 1) in vec4 i_Color;

layout(location = 0) out vec4 o_Color;

layout (set = 0, binding = 0) uniform Globals {
mat4 u_Transform;
float u_Scale;
};

void main() {
vec2 p_Position = i_Position * u_Scale;
gl_Position = u_Transform * vec4(p_Position, 0.0, 1.0);
o_Color = i_Color;
}
Binary file added wgpu/src/shader/triangle.vert.spv
Binary file not shown.
Loading

0 comments on commit e4de213

Please sign in to comment.