Cleaned up namespaces re: PR comments.

This commit is contained in:
bungoboingo 2022-10-18 15:18:37 -07:00
parent bb8d46a3fd
commit c4565759e4
13 changed files with 158 additions and 161 deletions

View file

@ -4,11 +4,9 @@ mod solid;
use crate::{program, Transformation}; use crate::{program, Transformation};
use glow::HasContext; use glow::HasContext;
use iced_graphics::layer::{mesh, mesh::attribute_count_of, Mesh}; use iced_graphics::layer::{mesh, Mesh};
use std::marker::PhantomData; use std::marker::PhantomData;
use crate::triangle::gradient::GradientProgram;
use crate::triangle::solid::SolidProgram;
pub use iced_graphics::triangle::{Mesh2D, Vertex2D}; pub use iced_graphics::triangle::{Mesh2D, Vertex2D};
#[derive(Debug)] #[derive(Debug)]
@ -16,13 +14,13 @@ pub(crate) struct Pipeline {
vertex_array: <glow::Context as HasContext>::VertexArray, vertex_array: <glow::Context as HasContext>::VertexArray,
vertices: Buffer<Vertex2D>, vertices: Buffer<Vertex2D>,
indices: Buffer<u32>, indices: Buffer<u32>,
programs: TrianglePrograms, programs: ProgramList,
} }
#[derive(Debug)] #[derive(Debug)]
struct TrianglePrograms { struct ProgramList {
solid: SolidProgram, solid: solid::Program,
gradient: GradientProgram, gradient: gradient::Program,
} }
impl Pipeline { impl Pipeline {
@ -65,9 +63,9 @@ impl Pipeline {
vertex_array, vertex_array,
vertices, vertices,
indices, indices,
programs: TrianglePrograms { programs: ProgramList {
solid: SolidProgram::new(gl, shader_version), solid: solid::Program::new(gl, shader_version),
gradient: GradientProgram::new(gl, shader_version), gradient: gradient::Program::new(gl, shader_version),
}, },
} }
} }
@ -87,7 +85,7 @@ impl Pipeline {
} }
//count the total amount of vertices & indices we need to handle //count the total amount of vertices & indices we need to handle
let (total_vertices, total_indices) = attribute_count_of(meshes); let (total_vertices, total_indices) = mesh::attribute_count_of(meshes);
// Then we ensure the current attribute buffers are big enough, resizing if necessary // Then we ensure the current attribute buffers are big enough, resizing if necessary
unsafe { unsafe {
@ -171,7 +169,7 @@ impl Pipeline {
/// A simple shader program. Uses [`triangle.vert`] for its vertex shader and only binds position /// A simple shader program. Uses [`triangle.vert`] for its vertex shader and only binds position
/// attribute location. /// attribute location.
pub(super) fn simple_triangle_program( pub(super) fn program(
gl: &glow::Context, gl: &glow::Context,
shader_version: &program::Version, shader_version: &program::Version,
fragment_shader: &'static str, fragment_shader: &'static str,

View file

@ -1,25 +1,25 @@
use crate::program::Version; use crate::program::Version;
use crate::triangle::{set_transform, simple_triangle_program}; use crate::triangle;
use glow::{Context, HasContext, NativeProgram}; use glow::{Context, HasContext, NativeProgram};
use iced_graphics::gradient::Gradient; use iced_graphics::gradient::Gradient;
use iced_graphics::gradient::Linear; use iced_graphics::gradient::Linear;
use iced_graphics::Transformation; use iced_graphics::Transformation;
#[derive(Debug)] #[derive(Debug)]
pub struct GradientProgram { pub struct Program {
pub program: <Context as HasContext>::Program, pub program: <Context as HasContext>::Program,
pub uniform_data: GradientUniformData, pub uniform_data: UniformData,
} }
#[derive(Debug)] #[derive(Debug)]
pub struct GradientUniformData { pub struct UniformData {
gradient: Gradient, gradient: Gradient,
transform: Transformation, transform: Transformation,
uniform_locations: GradientUniformLocations, uniform_locations: UniformLocations,
} }
#[derive(Debug)] #[derive(Debug)]
struct GradientUniformLocations { struct UniformLocations {
gradient_direction_location: <Context as HasContext>::UniformLocation, gradient_direction_location: <Context as HasContext>::UniformLocation,
color_stops_size_location: <Context as HasContext>::UniformLocation, color_stops_size_location: <Context as HasContext>::UniformLocation,
//currently the maximum number of stops is 16 due to lack of SSBO in GL2.1 //currently the maximum number of stops is 16 due to lack of SSBO in GL2.1
@ -27,9 +27,9 @@ struct GradientUniformLocations {
transform_location: <Context as HasContext>::UniformLocation, transform_location: <Context as HasContext>::UniformLocation,
} }
impl GradientProgram { impl Program {
pub fn new(gl: &Context, shader_version: &Version) -> Self { pub fn new(gl: &Context, shader_version: &Version) -> Self {
let program = simple_triangle_program( let program = triangle::program(
gl, gl,
shader_version, shader_version,
include_str!("../shader/common/gradient.frag"), include_str!("../shader/common/gradient.frag"),
@ -37,7 +37,7 @@ impl GradientProgram {
Self { Self {
program, program,
uniform_data: GradientUniformData::new(gl, program), uniform_data: UniformData::new(gl, program),
} }
} }
@ -48,7 +48,7 @@ impl GradientProgram {
transform: &Transformation, transform: &Transformation,
) { ) {
if transform != &self.uniform_data.transform { if transform != &self.uniform_data.transform {
set_transform( triangle::set_transform(
gl, gl,
self.uniform_data.uniform_locations.transform_location, self.uniform_data.uniform_locations.transform_location,
*transform, *transform,
@ -117,12 +117,11 @@ impl GradientProgram {
transform: &Transformation, transform: &Transformation,
) { ) {
unsafe { gl.use_program(Some(self.program)) } unsafe { gl.use_program(Some(self.program)) }
self.write_uniforms(gl, gradient, transform); self.write_uniforms(gl, gradient, transform);
} }
} }
impl GradientUniformData { impl UniformData {
fn new(gl: &Context, program: NativeProgram) -> Self { fn new(gl: &Context, program: NativeProgram) -> Self {
let gradient_direction_location = let gradient_direction_location =
unsafe { gl.get_uniform_location(program, "gradient_direction") } unsafe { gl.get_uniform_location(program, "gradient_direction") }
@ -141,14 +140,14 @@ impl GradientUniformData {
unsafe { gl.get_uniform_location(program, "u_Transform") } unsafe { gl.get_uniform_location(program, "u_Transform") }
.expect("Gradient - Get u_Transform."); .expect("Gradient - Get u_Transform.");
GradientUniformData { Self {
gradient: Gradient::Linear(Linear { gradient: Gradient::Linear(Linear {
start: Default::default(), start: Default::default(),
end: Default::default(), end: Default::default(),
color_stops: vec![], color_stops: vec![],
}), }),
transform: Transformation::identity(), transform: Transformation::identity(),
uniform_locations: GradientUniformLocations { uniform_locations: UniformLocations {
gradient_direction_location, gradient_direction_location,
color_stops_size_location, color_stops_size_location,
color_stops_location, color_stops_location,

View file

@ -1,24 +1,23 @@
use crate::program::Version; use crate::program::Version;
use crate::triangle::{set_transform, simple_triangle_program}; use crate::{triangle, Color};
use crate::Color;
use glow::{Context, HasContext, NativeProgram}; use glow::{Context, HasContext, NativeProgram};
use iced_graphics::Transformation; use iced_graphics::Transformation;
#[derive(Debug)] #[derive(Debug)]
pub struct SolidProgram { pub struct Program {
program: <Context as HasContext>::Program, program: <Context as HasContext>::Program,
uniform_data: SolidUniformData, uniform_data: UniformData,
} }
#[derive(Debug)] #[derive(Debug)]
struct SolidUniformData { struct UniformData {
pub color: Color, pub color: Color,
pub color_location: <Context as HasContext>::UniformLocation, pub color_location: <Context as HasContext>::UniformLocation,
pub transform: Transformation, pub transform: Transformation,
pub transform_location: <Context as HasContext>::UniformLocation, pub transform_location: <Context as HasContext>::UniformLocation,
} }
impl SolidUniformData { impl UniformData {
fn new(gl: &Context, program: NativeProgram) -> Self { fn new(gl: &Context, program: NativeProgram) -> Self {
Self { Self {
color: Color::TRANSPARENT, color: Color::TRANSPARENT,
@ -35,9 +34,9 @@ impl SolidUniformData {
} }
} }
impl SolidProgram { impl Program {
pub fn new(gl: &Context, shader_version: &Version) -> Self { pub fn new(gl: &Context, shader_version: &Version) -> Self {
let program = simple_triangle_program( let program = triangle::program(
gl, gl,
shader_version, shader_version,
include_str!("../shader/common/triangle.frag"), include_str!("../shader/common/triangle.frag"),
@ -45,7 +44,7 @@ impl SolidProgram {
Self { Self {
program, program,
uniform_data: SolidUniformData::new(gl, program), uniform_data: UniformData::new(gl, program),
} }
} }
@ -56,7 +55,11 @@ impl SolidProgram {
transform: &Transformation, transform: &Transformation,
) { ) {
if transform != &self.uniform_data.transform { if transform != &self.uniform_data.transform {
set_transform(gl, self.uniform_data.transform_location, *transform) triangle::set_transform(
gl,
self.uniform_data.transform_location,
*transform,
)
} }
if color != &self.uniform_data.color { if color != &self.uniform_data.color {

View file

@ -134,10 +134,13 @@ impl Builder {
/// ///
/// `offset` must be between `0.0` and `1.0` or the gradient cannot be built. /// `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 /// Note: when using the [`glow`] backend, any color stop added after the 16th
/// will not be displayed. /// will not be displayed.
/// ///
/// On [backend::Wgpu] backend this limitation does not exist (technical limit is 524,288 stops). /// 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 { pub fn add_stop(mut self, offset: f32, color: Color) -> Self {
if offset.is_finite() && (0.0..=1.0).contains(&offset) { if offset.is_finite() && (0.0..=1.0).contains(&offset) {
match self.stops.binary_search_by(|stop| { match self.stops.binary_search_by(|stop| {

View file

@ -7,6 +7,8 @@ pub struct Mesh2D {
/// The vertices of the mesh /// The vertices of the mesh
pub vertices: Vec<Vertex2D>, pub vertices: Vec<Vertex2D>,
/// The list of vertex indices that defines the triangles of the mesh. /// The list of vertex indices that defines the triangles of the mesh.
///
/// Therefore, this list should always have a length that is a multiple of 3.
pub indices: Vec<u32>, pub indices: Vec<u32>,
} }

View file

@ -56,7 +56,7 @@ impl<T: Pod + Zeroable> StaticBuffer<T> {
/// Returns whether or not the buffer needs to be recreated. This can happen whenever mesh data /// Returns whether or not the buffer needs to be recreated. This can happen whenever mesh data
/// changes & a redraw is requested. /// changes & a redraw is requested.
pub fn recreate_if_needed( pub fn resize(
&mut self, &mut self,
device: &wgpu::Device, device: &wgpu::Device,
new_count: usize, new_count: usize,

View file

@ -4,23 +4,23 @@ use encase::ShaderType;
use std::marker::PhantomData; use std::marker::PhantomData;
// Currently supported dynamic buffers. // Currently supported dynamic buffers.
enum DynamicBufferType { enum BufferType {
Uniform(encase::DynamicUniformBuffer<Vec<u8>>), Uniform(encase::DynamicUniformBuffer<Vec<u8>>),
Storage(encase::DynamicStorageBuffer<Vec<u8>>), Storage(encase::DynamicStorageBuffer<Vec<u8>>),
} }
impl DynamicBufferType { impl BufferType {
/// Writes the current value to its CPU buffer with proper alignment. /// Writes the current value to its CPU buffer with proper alignment.
pub(super) fn write<T: ShaderType + WriteInto>( pub(super) fn write<T: ShaderType + WriteInto>(
&mut self, &mut self,
value: &T, value: &T,
) -> wgpu::DynamicOffset { ) -> wgpu::DynamicOffset {
match self { match self {
DynamicBufferType::Uniform(buf) => buf BufferType::Uniform(buf) => buf
.write(value) .write(value)
.expect("Error when writing to dynamic uniform buffer.") .expect("Error when writing to dynamic uniform buffer.")
as u32, as u32,
DynamicBufferType::Storage(buf) => buf BufferType::Storage(buf) => buf
.write(value) .write(value)
.expect("Error when writing to dynamic storage buffer.") .expect("Error when writing to dynamic storage buffer.")
as u32, as u32,
@ -30,19 +30,19 @@ impl DynamicBufferType {
/// Returns bytearray of aligned CPU buffer. /// Returns bytearray of aligned CPU buffer.
pub(super) fn get_ref(&self) -> &Vec<u8> { pub(super) fn get_ref(&self) -> &Vec<u8> {
match self { match self {
DynamicBufferType::Uniform(buf) => buf.as_ref(), BufferType::Uniform(buf) => buf.as_ref(),
DynamicBufferType::Storage(buf) => buf.as_ref(), BufferType::Storage(buf) => buf.as_ref(),
} }
} }
/// Resets the CPU buffer. /// Resets the CPU buffer.
pub(super) fn clear(&mut self) { pub(super) fn clear(&mut self) {
match self { match self {
DynamicBufferType::Uniform(buf) => { BufferType::Uniform(buf) => {
buf.as_mut().clear(); buf.as_mut().clear();
buf.set_offset(0); buf.set_offset(0);
} }
DynamicBufferType::Storage(buf) => { BufferType::Storage(buf) => {
buf.as_mut().clear(); buf.as_mut().clear();
buf.set_offset(0); buf.set_offset(0);
} }
@ -51,21 +51,21 @@ impl DynamicBufferType {
} }
/// A dynamic buffer is any type of buffer which does not have a static offset. /// A dynamic buffer is any type of buffer which does not have a static offset.
pub(crate) struct DynamicBuffer<T: ShaderType> { pub(crate) struct Buffer<T: ShaderType> {
offsets: Vec<wgpu::DynamicOffset>, offsets: Vec<wgpu::DynamicOffset>,
cpu: DynamicBufferType, cpu: BufferType,
gpu: wgpu::Buffer, gpu: wgpu::Buffer,
label: &'static str, label: &'static str,
size: u64, size: u64,
_data: PhantomData<T>, _data: PhantomData<T>,
} }
impl<T: ShaderType + WriteInto> DynamicBuffer<T> { impl<T: ShaderType + WriteInto> Buffer<T> {
/// Creates a new dynamic uniform buffer. /// Creates a new dynamic uniform buffer.
pub fn uniform(device: &wgpu::Device, label: &'static str) -> Self { pub fn uniform(device: &wgpu::Device, label: &'static str) -> Self {
DynamicBuffer::new( Buffer::new(
device, device,
DynamicBufferType::Uniform(encase::DynamicUniformBuffer::new( BufferType::Uniform(encase::DynamicUniformBuffer::new(
Vec::new(), Vec::new(),
)), )),
label, label,
@ -75,9 +75,9 @@ impl<T: ShaderType + WriteInto> DynamicBuffer<T> {
/// Creates a new dynamic storage buffer. /// Creates a new dynamic storage buffer.
pub fn storage(device: &wgpu::Device, label: &'static str) -> Self { pub fn storage(device: &wgpu::Device, label: &'static str) -> Self {
DynamicBuffer::new( Buffer::new(
device, device,
DynamicBufferType::Storage(encase::DynamicStorageBuffer::new( BufferType::Storage(encase::DynamicStorageBuffer::new(
Vec::new(), Vec::new(),
)), )),
label, label,
@ -87,7 +87,7 @@ impl<T: ShaderType + WriteInto> DynamicBuffer<T> {
fn new( fn new(
device: &wgpu::Device, device: &wgpu::Device,
dynamic_buffer_type: DynamicBufferType, dynamic_buffer_type: BufferType,
label: &'static str, label: &'static str,
usage: wgpu::BufferUsages, usage: wgpu::BufferUsages,
) -> Self { ) -> Self {
@ -96,7 +96,7 @@ impl<T: ShaderType + WriteInto> DynamicBuffer<T> {
Self { Self {
offsets: Vec::new(), offsets: Vec::new(),
cpu: dynamic_buffer_type, cpu: dynamic_buffer_type,
gpu: DynamicBuffer::<T>::create_gpu_buffer( gpu: Buffer::<T>::create_gpu_buffer(
device, device,
label, label,
usage, usage,
@ -139,15 +139,15 @@ impl<T: ShaderType + WriteInto> DynamicBuffer<T> {
if self.size < new_size { if self.size < new_size {
let usages = match self.cpu { let usages = match self.cpu {
DynamicBufferType::Uniform(_) => { BufferType::Uniform(_) => {
wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST
} }
DynamicBufferType::Storage(_) => { BufferType::Storage(_) => {
wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST
} }
}; };
self.gpu = DynamicBuffer::<T>::create_gpu_buffer( self.gpu = Buffer::<T>::create_gpu_buffer(
device, self.label, usages, new_size, device, self.label, usages, new_size,
); );
self.size = new_size; self.size = new_size;

View file

@ -1,4 +1,4 @@
struct GradientUniforms { struct Uniforms {
transform: mat4x4<f32>, transform: mat4x4<f32>,
//xy = start, wz = end //xy = start, wz = end
position: vec4<f32>, position: vec4<f32>,
@ -12,7 +12,7 @@ struct Stop {
}; };
@group(0) @binding(0) @group(0) @binding(0)
var<uniform> uniforms: GradientUniforms; var<uniform> uniforms: Uniforms;
@group(0) @binding(1) @group(0) @binding(1)
var<storage, read> color_stops: array<Stop>; var<storage, read> color_stops: array<Stop>;
@ -33,7 +33,7 @@ fn vs_main(@location(0) input: vec2<f32>) -> VertexOutput {
//TODO: rewrite without branching //TODO: rewrite without branching
@fragment @fragment
fn fs_gradient(input: VertexOutput) -> @location(0) vec4<f32> { fn fs_main(input: VertexOutput) -> @location(0) vec4<f32> {
let start = uniforms.position.xy; let start = uniforms.position.xy;
let end = uniforms.position.zw; let end = uniforms.position.zw;
let start_stop = uniforms.stop_range.x; let start_stop = uniforms.stop_range.x;

View file

@ -0,0 +1,17 @@
struct Uniforms {
transform: mat4x4<f32>,
color: vec4<f32>
}
@group(0) @binding(0)
var<uniform> uniforms: Uniforms;
@vertex
fn vs_main(@location(0) input: vec2<f32>) -> @builtin(position) vec4<f32> {
return uniforms.transform * vec4<f32>(input.xy, 0.0, 1.0);
}
@fragment
fn fs_main() -> @location(0) vec4<f32> {
return uniforms.color;
}

View file

@ -1,17 +0,0 @@
struct SolidUniforms {
transform: mat4x4<f32>,
color: vec4<f32>
}
@group(0) @binding(0)
var<uniform> solid_uniforms: SolidUniforms;
@vertex
fn vs_main(@location(0) input: vec2<f32>) -> @builtin(position) vec4<f32> {
return solid_uniforms.transform * vec4<f32>(input.xy, 0.0, 1.0);
}
@fragment
fn fs_solid() -> @location(0) vec4<f32> {
return solid_uniforms.color;
}

View file

@ -3,12 +3,10 @@ use crate::{settings, Transformation};
use core::fmt; use core::fmt;
use std::fmt::Formatter; use std::fmt::Formatter;
use iced_graphics::layer::{Mesh, mesh, mesh::attribute_count_of}; use iced_graphics::layer::{Mesh, mesh};
use iced_graphics::Size; use iced_graphics::Size;
use crate::buffers::StaticBuffer; use crate::buffers::StaticBuffer;
use crate::triangle::gradient::GradientPipeline;
use crate::triangle::solid::SolidPipeline;
pub use iced_graphics::triangle::{Mesh2D, Vertex2D}; pub use iced_graphics::triangle::{Mesh2D, Vertex2D};
mod solid; mod solid;
@ -22,22 +20,22 @@ pub(crate) struct Pipeline {
vertex_buffer: StaticBuffer<Vertex2D>, vertex_buffer: StaticBuffer<Vertex2D>,
index_buffer: StaticBuffer<u32>, index_buffer: StaticBuffer<u32>,
index_strides: Vec<u32>, index_strides: Vec<u32>,
pipelines: TrianglePipelines, pipelines: PipelineList,
} }
/// Supported triangle pipelines for different fills. /// Supported triangle pipelines for different fills.
pub(crate) struct TrianglePipelines { pub(crate) struct PipelineList {
solid: SolidPipeline, solid: solid::Pipeline,
gradient: GradientPipeline, gradient: gradient::Pipeline,
} }
impl fmt::Debug for TrianglePipelines { impl fmt::Debug for PipelineList {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("TrianglePipelines").finish() f.debug_struct("TrianglePipelines").finish()
} }
} }
impl TrianglePipelines { impl PipelineList {
/// Resets each pipeline's buffers. /// Resets each pipeline's buffers.
fn clear(&mut self) { fn clear(&mut self) {
self.solid.buffer.clear(); self.solid.buffer.clear();
@ -78,9 +76,9 @@ impl Pipeline {
wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
), ),
index_strides: Vec::new(), index_strides: Vec::new(),
pipelines: TrianglePipelines { pipelines: PipelineList {
solid: SolidPipeline::new(device, format, antialiasing), solid: solid::Pipeline::new(device, format, antialiasing),
gradient: GradientPipeline::new(device, format, antialiasing), gradient: gradient::Pipeline::new(device, format, antialiasing),
}, },
} }
} }
@ -98,7 +96,7 @@ impl Pipeline {
meshes: &[Mesh<'_>], meshes: &[Mesh<'_>],
) { ) {
//count the total amount of vertices & indices we need to handle //count the total amount of vertices & indices we need to handle
let (total_vertices, total_indices) = attribute_count_of(meshes); let (total_vertices, total_indices) = mesh::attribute_count_of(meshes);
// Then we ensure the current attribute buffers are big enough, resizing if necessary. // Then we ensure the current attribute buffers are big enough, resizing if necessary.
@ -107,8 +105,8 @@ impl Pipeline {
//the majority of use cases. Therefore we will write GPU data every frame (for now). //the majority of use cases. Therefore we will write GPU data every frame (for now).
let _ = self let _ = self
.vertex_buffer .vertex_buffer
.recreate_if_needed(device, total_vertices); .resize(device, total_vertices);
let _ = self.index_buffer.recreate_if_needed(device, total_indices); let _ = self.index_buffer.resize(device, total_indices);
//prepare dynamic buffers & data store for writing //prepare dynamic buffers & data store for writing
self.index_strides.clear(); self.index_strides.clear();
@ -258,7 +256,7 @@ fn vertex_buffer_layout<'a>() -> wgpu::VertexBufferLayout<'a> {
} }
} }
fn default_fragment_target( fn fragment_target(
texture_format: wgpu::TextureFormat, texture_format: wgpu::TextureFormat,
) -> Option<wgpu::ColorTargetState> { ) -> Option<wgpu::ColorTargetState> {
Some(wgpu::ColorTargetState { Some(wgpu::ColorTargetState {
@ -268,7 +266,7 @@ fn default_fragment_target(
}) })
} }
fn default_triangle_primitive_state() -> wgpu::PrimitiveState { fn primitive_state() -> wgpu::PrimitiveState {
wgpu::PrimitiveState { wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::TriangleList, topology: wgpu::PrimitiveTopology::TriangleList,
front_face: wgpu::FrontFace::Cw, front_face: wgpu::FrontFace::Cw,
@ -276,7 +274,7 @@ fn default_triangle_primitive_state() -> wgpu::PrimitiveState {
} }
} }
fn default_multisample_state( fn multisample_state(
antialiasing: Option<settings::Antialiasing>, antialiasing: Option<settings::Antialiasing>,
) -> wgpu::MultisampleState { ) -> wgpu::MultisampleState {
wgpu::MultisampleState { wgpu::MultisampleState {

View file

@ -1,28 +1,25 @@
use crate::buffers::dynamic::DynamicBuffer; use crate::buffers::dynamic;
use crate::settings; use crate::settings;
use crate::triangle::{ use crate::triangle;
default_fragment_target, default_multisample_state,
default_triangle_primitive_state, vertex_buffer_layout,
};
use encase::ShaderType; use encase::ShaderType;
use glam::{IVec4, Vec4}; use glam::{IVec4, Vec4};
use iced_graphics::gradient::Gradient; use iced_graphics::gradient::Gradient;
use iced_graphics::Transformation; use iced_graphics::Transformation;
pub struct GradientPipeline { pub struct Pipeline {
pipeline: wgpu::RenderPipeline, pipeline: wgpu::RenderPipeline,
pub(super) uniform_buffer: DynamicBuffer<GradientUniforms>, pub(super) uniform_buffer: dynamic::Buffer<Uniforms>,
pub(super) storage_buffer: DynamicBuffer<GradientStorage>, pub(super) storage_buffer: dynamic::Buffer<Storage>,
color_stop_offset: i32, color_stop_offset: i32,
//Need to store these and then write them all at once //Need to store these and then write them all at once
//or else they will be padded to 256 and cause gaps in the storage buffer //or else they will be padded to 256 and cause gaps in the storage buffer
color_stops_pending_write: GradientStorage, color_stops_pending_write: Storage,
bind_group_layout: wgpu::BindGroupLayout, bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup, bind_group: wgpu::BindGroup,
} }
#[derive(Debug, ShaderType)] #[derive(Debug, ShaderType)]
pub(super) struct GradientUniforms { pub(super) struct Uniforms {
transform: glam::Mat4, transform: glam::Mat4,
//xy = start, zw = end //xy = start, zw = end
direction: Vec4, direction: Vec4,
@ -37,33 +34,33 @@ pub(super) struct ColorStop {
} }
#[derive(ShaderType)] #[derive(ShaderType)]
pub(super) struct GradientStorage { pub(super) struct Storage {
#[size(runtime)] #[size(runtime)]
pub color_stops: Vec<ColorStop>, pub color_stops: Vec<ColorStop>,
} }
impl GradientPipeline { impl Pipeline {
/// Creates a new [GradientPipeline] using `triangle_gradient.wgsl` shader. /// Creates a new [GradientPipeline] using `gradient.wgsl` shader.
pub(super) fn new( pub(super) fn new(
device: &wgpu::Device, device: &wgpu::Device,
format: wgpu::TextureFormat, format: wgpu::TextureFormat,
antialiasing: Option<settings::Antialiasing>, antialiasing: Option<settings::Antialiasing>,
) -> Self { ) -> Self {
let uniform_buffer = DynamicBuffer::uniform( let uniform_buffer = dynamic::Buffer::uniform(
device, device,
"iced_wgpu::triangle [GRADIENT] uniforms", "iced_wgpu::triangle::gradient uniforms",
); );
//Note: with a WASM target storage buffers are not supported. Will need to use UBOs & static //Note: with a WASM target storage buffers are not supported. Will need to use UBOs & static
// sized array (eg like the 32-sized array on OpenGL side right now) to make gradients work // sized array (eg like the 32-sized array on OpenGL side right now) to make gradients work
let storage_buffer = DynamicBuffer::storage( let storage_buffer = dynamic::Buffer::storage(
device, device,
"iced_wgpu::triangle [GRADIENT] storage", "iced_wgpu::triangle::gradient storage",
); );
let bind_group_layout = let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("iced_wgpu::triangle [GRADIENT] bind group layout"), label: Some("iced_wgpu::triangle::gradient bind group layout"),
entries: &[ entries: &[
wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
@ -71,7 +68,7 @@ impl GradientPipeline {
ty: wgpu::BindingType::Buffer { ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform, ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true, has_dynamic_offset: true,
min_binding_size: Some(GradientUniforms::min_size()), min_binding_size: Some(Uniforms::min_size()),
}, },
count: None, count: None,
}, },
@ -83,14 +80,14 @@ impl GradientPipeline {
read_only: true, read_only: true,
}, },
has_dynamic_offset: false, has_dynamic_offset: false,
min_binding_size: Some(GradientStorage::min_size()), min_binding_size: Some(Storage::min_size()),
}, },
count: None, count: None,
}, },
], ],
}); });
let bind_group = GradientPipeline::bind_group( let bind_group = Pipeline::bind_group(
device, device,
uniform_buffer.raw(), uniform_buffer.raw(),
storage_buffer.raw(), storage_buffer.raw(),
@ -99,7 +96,7 @@ impl GradientPipeline {
let layout = let layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("iced_wgpu::triangle [GRADIENT] pipeline layout"), label: Some("iced_wgpu::triangle::gradient pipeline layout"),
bind_group_layouts: &[&bind_group_layout], bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
@ -107,30 +104,30 @@ impl GradientPipeline {
let shader = let shader =
device.create_shader_module(wgpu::ShaderModuleDescriptor { device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some( label: Some(
"iced_wgpu::triangle [GRADIENT] create shader module", "iced_wgpu::triangle::gradient create shader module",
), ),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(
include_str!("../shader/triangle_gradient.wgsl"), include_str!("../shader/gradient.wgsl"),
)), )),
}); });
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("iced_wgpu::triangle [GRADIENT] pipeline"), label: Some("iced_wgpu::triangle::gradient pipeline"),
layout: Some(&layout), layout: Some(&layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_main", entry_point: "vs_main",
buffers: &[vertex_buffer_layout()], buffers: &[triangle::vertex_buffer_layout()],
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
module: &shader, module: &shader,
entry_point: "fs_gradient", entry_point: "fs_main",
targets: &[default_fragment_target(format)], targets: &[triangle::fragment_target(format)],
}), }),
primitive: default_triangle_primitive_state(), primitive: triangle::primitive_state(),
depth_stencil: None, depth_stencil: None,
multisample: default_multisample_state(antialiasing), multisample: triangle::multisample_state(antialiasing),
multiview: None, multiview: None,
}); });
@ -139,7 +136,7 @@ impl GradientPipeline {
uniform_buffer, uniform_buffer,
storage_buffer, storage_buffer,
color_stop_offset: 0, color_stop_offset: 0,
color_stops_pending_write: GradientStorage { color_stops_pending_write: Storage {
color_stops: vec![], color_stops: vec![],
}, },
bind_group_layout, bind_group_layout,
@ -155,7 +152,7 @@ impl GradientPipeline {
let end_offset = let end_offset =
(linear.color_stops.len() as i32) + start_offset - 1; (linear.color_stops.len() as i32) + start_offset - 1;
self.uniform_buffer.push(&GradientUniforms { self.uniform_buffer.push(&Uniforms {
transform: transform.into(), transform: transform.into(),
direction: Vec4::new( direction: Vec4::new(
linear.start.x, linear.start.x,
@ -194,7 +191,7 @@ impl GradientPipeline {
layout: &wgpu::BindGroupLayout, layout: &wgpu::BindGroupLayout,
) -> wgpu::BindGroup { ) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("iced_wgpu::triangle [GRADIENT] bind group"), label: Some("iced_wgpu::triangle::gradient bind group"),
layout, layout,
entries: &[ entries: &[
wgpu::BindGroupEntry { wgpu::BindGroupEntry {
@ -203,7 +200,7 @@ impl GradientPipeline {
wgpu::BufferBinding { wgpu::BufferBinding {
buffer: uniform_buffer, buffer: uniform_buffer,
offset: 0, offset: 0,
size: Some(GradientUniforms::min_size()), size: Some(Uniforms::min_size()),
}, },
), ),
}, },
@ -232,7 +229,7 @@ impl GradientPipeline {
if uniforms_resized || storage_resized { if uniforms_resized || storage_resized {
//recreate bind groups if any buffers were resized //recreate bind groups if any buffers were resized
self.bind_group = GradientPipeline::bind_group( self.bind_group = Pipeline::bind_group(
device, device,
self.uniform_buffer.raw(), self.uniform_buffer.raw(),
self.storage_buffer.raw(), self.storage_buffer.raw(),

View file

@ -1,27 +1,24 @@
use crate::buffers::dynamic::DynamicBuffer; use crate::buffers::dynamic;
use crate::triangle::{ use crate::triangle;
default_fragment_target, default_multisample_state,
default_triangle_primitive_state, vertex_buffer_layout,
};
use crate::{settings, Color}; use crate::{settings, Color};
use encase::ShaderType; use encase::ShaderType;
use glam::Vec4; use glam::Vec4;
use iced_graphics::Transformation; use iced_graphics::Transformation;
pub struct SolidPipeline { pub struct Pipeline {
pipeline: wgpu::RenderPipeline, pipeline: wgpu::RenderPipeline,
pub(super) buffer: DynamicBuffer<SolidUniforms>, pub(super) buffer: dynamic::Buffer<Uniforms>,
bind_group_layout: wgpu::BindGroupLayout, bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup, bind_group: wgpu::BindGroup,
} }
#[derive(Debug, Clone, Copy, ShaderType)] #[derive(Debug, Clone, Copy, ShaderType)]
pub(super) struct SolidUniforms { pub(super) struct Uniforms {
transform: glam::Mat4, transform: glam::Mat4,
color: Vec4, color: Vec4,
} }
impl SolidUniforms { impl Uniforms {
pub fn new(transform: Transformation, color: Color) -> Self { pub fn new(transform: Transformation, color: Color) -> Self {
Self { Self {
transform: transform.into(), transform: transform.into(),
@ -30,34 +27,34 @@ impl SolidUniforms {
} }
} }
impl SolidPipeline { impl Pipeline {
/// Creates a new [SolidPipeline] using `triangle_solid.wgsl` shader. /// Creates a new [SolidPipeline] using `solid.wgsl` shader.
pub fn new( pub fn new(
device: &wgpu::Device, device: &wgpu::Device,
format: wgpu::TextureFormat, format: wgpu::TextureFormat,
antialiasing: Option<settings::Antialiasing>, antialiasing: Option<settings::Antialiasing>,
) -> Self { ) -> Self {
let buffer = DynamicBuffer::uniform( let buffer = dynamic::Buffer::uniform(
device, device,
"iced_wgpu::triangle [SOLID] uniforms", "iced_wgpu::triangle::solid uniforms",
); );
let bind_group_layout = let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("iced_wgpu::triangle [SOLID] bind group layout"), label: Some("iced_wgpu::triangle::solid bind group layout"),
entries: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT, visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
ty: wgpu::BindingType::Buffer { ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform, ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: true, has_dynamic_offset: true,
min_binding_size: Some(SolidUniforms::min_size()), min_binding_size: Some(Uniforms::min_size()),
}, },
count: None, count: None,
}], }],
}); });
let bind_group = SolidPipeline::bind_group( let bind_group = Pipeline::bind_group(
device, device,
&buffer.raw(), &buffer.raw(),
&bind_group_layout, &bind_group_layout,
@ -65,36 +62,36 @@ impl SolidPipeline {
let layout = let layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("iced_wgpu::triangle [SOLID] pipeline layout"), label: Some("iced_wgpu::triangle::solid pipeline layout"),
bind_group_layouts: &[&bind_group_layout], bind_group_layouts: &[&bind_group_layout],
push_constant_ranges: &[], push_constant_ranges: &[],
}); });
let shader = let shader =
device.create_shader_module(wgpu::ShaderModuleDescriptor { device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("iced_wgpu::triangle [SOLID] create shader module"), label: Some("iced_wgpu::triangle::solid create shader module"),
source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed( source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Borrowed(
include_str!("../shader/triangle_solid.wgsl"), include_str!("../shader/solid.wgsl"),
)), )),
}); });
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("iced_wgpu::triangle [SOLID] pipeline"), label: Some("iced_wgpu::triangle::solid pipeline"),
layout: Some(&layout), layout: Some(&layout),
vertex: wgpu::VertexState { vertex: wgpu::VertexState {
module: &shader, module: &shader,
entry_point: "vs_main", entry_point: "vs_main",
buffers: &[vertex_buffer_layout()], buffers: &[triangle::vertex_buffer_layout()],
}, },
fragment: Some(wgpu::FragmentState { fragment: Some(wgpu::FragmentState {
module: &shader, module: &shader,
entry_point: "fs_solid", entry_point: "fs_main",
targets: &[default_fragment_target(format)], targets: &[triangle::fragment_target(format)],
}), }),
primitive: default_triangle_primitive_state(), primitive: triangle::primitive_state(),
depth_stencil: None, depth_stencil: None,
multisample: default_multisample_state(antialiasing), multisample: triangle::multisample_state(antialiasing),
multiview: None, multiview: None,
}); });
@ -112,14 +109,14 @@ impl SolidPipeline {
layout: &wgpu::BindGroupLayout, layout: &wgpu::BindGroupLayout,
) -> wgpu::BindGroup { ) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("iced_wgpu::triangle [SOLID] bind group"), label: Some("iced_wgpu::triangle::solid bind group"),
layout, layout,
entries: &[wgpu::BindGroupEntry { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
buffer, buffer,
offset: 0, offset: 0,
size: Some(SolidUniforms::min_size()), size: Some(Uniforms::min_size()),
}), }),
}], }],
}) })
@ -127,7 +124,7 @@ impl SolidPipeline {
/// Pushes a new solid uniform to the CPU buffer. /// Pushes a new solid uniform to the CPU buffer.
pub fn push(&mut self, transform: Transformation, color: &Color) { pub fn push(&mut self, transform: Transformation, color: &Color) {
self.buffer.push(&SolidUniforms::new(transform, *color)); self.buffer.push(&Uniforms::new(transform, *color));
} }
/// Writes the contents of the solid CPU buffer to the GPU buffer, resizing the GPU buffer /// Writes the contents of the solid CPU buffer to the GPU buffer, resizing the GPU buffer
@ -141,7 +138,7 @@ impl SolidPipeline {
let uniforms_resized = self.buffer.resize(device); let uniforms_resized = self.buffer.resize(device);
if uniforms_resized { if uniforms_resized {
self.bind_group = SolidPipeline::bind_group( self.bind_group = Pipeline::bind_group(
device, device,
self.buffer.raw(), self.buffer.raw(),
&self.bind_group_layout, &self.bind_group_layout,