run cargo fmt

This commit is contained in:
Tristam MacDonald 2019-03-05 20:41:24 -08:00
parent 643a34fec3
commit 1fe59e71db
22 changed files with 1030 additions and 1004 deletions

View File

@ -43,21 +43,22 @@ fn main() {
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[
wgpu::ColorStateDescriptor {
format: wgpu::TextureFormat::Bgra8Unorm,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
},
],
color_states: &[wgpu::ColorStateDescriptor {
format: wgpu::TextureFormat::Bgra8Unorm,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[],
sample_count: 1,
});
use wgpu::winit::{ControlFlow, Event, ElementState, EventsLoop, KeyboardInput, Window, WindowEvent, VirtualKeyCode};
use wgpu::winit::{
ControlFlow, ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window,
WindowEvent,
};
let mut events_loop = EventsLoop::new();
let window = Window::new(&events_loop).unwrap();
@ -67,35 +68,40 @@ fn main() {
.to_physical(window.get_hidpi_factor());
let surface = instance.create_surface(&window);
let mut swap_chain = device.create_swap_chain(&surface, &wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width as u32,
height: size.height as u32,
});
let mut swap_chain = device.create_swap_chain(
&surface,
&wgpu::SwapChainDescriptor {
usage: wgpu::TextureUsageFlags::OUTPUT_ATTACHMENT,
format: wgpu::TextureFormat::Bgra8Unorm,
width: size.width as u32,
height: size.height as u32,
},
);
events_loop.run_forever(|event| {
match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input: KeyboardInput { virtual_keycode: Some(code), state: ElementState::Pressed, .. },
input:
KeyboardInput {
virtual_keycode: Some(code),
state: ElementState::Pressed,
..
},
..
} => match code {
VirtualKeyCode::Escape => {
return ControlFlow::Break
}
VirtualKeyCode::Escape => return ControlFlow::Break,
_ => {}
}
WindowEvent::CloseRequested => {
return ControlFlow::Break
}
},
WindowEvent::CloseRequested => return ControlFlow::Break,
_ => {}
}
},
_ => {}
}
let frame = swap_chain.get_next_texture();
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
@ -110,9 +116,7 @@ fn main() {
rpass.draw(0..3, 0..1);
}
device
.get_queue()
.submit(&[encoder.finish()]);
device.get_queue().submit(&[encoder.finish()]);
ControlFlow::Continue
});

View File

@ -1,6 +1,5 @@
mod framework;
#[derive(Clone, Copy)]
struct Vertex {
_pos: [f32; 4],
@ -17,41 +16,41 @@ fn vertex(pos: [i8; 3], tc: [i8; 2]) -> Vertex {
fn create_vertices() -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
// top (0, 0, 1)
vertex([-1, -1, 1], [0, 0]),
vertex([ 1, -1, 1], [1, 0]),
vertex([ 1, 1, 1], [1, 1]),
vertex([-1, 1, 1], [0, 1]),
vertex([-1, -1, 1], [0, 0]),
vertex([1, -1, 1], [1, 0]),
vertex([1, 1, 1], [1, 1]),
vertex([-1, 1, 1], [0, 1]),
// bottom (0, 0, -1)
vertex([-1, 1, -1], [1, 0]),
vertex([ 1, 1, -1], [0, 0]),
vertex([ 1, -1, -1], [0, 1]),
vertex([-1, 1, -1], [1, 0]),
vertex([1, 1, -1], [0, 0]),
vertex([1, -1, -1], [0, 1]),
vertex([-1, -1, -1], [1, 1]),
// right (1, 0, 0)
vertex([ 1, -1, -1], [0, 0]),
vertex([ 1, 1, -1], [1, 0]),
vertex([ 1, 1, 1], [1, 1]),
vertex([ 1, -1, 1], [0, 1]),
vertex([1, -1, -1], [0, 0]),
vertex([1, 1, -1], [1, 0]),
vertex([1, 1, 1], [1, 1]),
vertex([1, -1, 1], [0, 1]),
// left (-1, 0, 0)
vertex([-1, -1, 1], [1, 0]),
vertex([-1, 1, 1], [0, 0]),
vertex([-1, 1, -1], [0, 1]),
vertex([-1, -1, 1], [1, 0]),
vertex([-1, 1, 1], [0, 0]),
vertex([-1, 1, -1], [0, 1]),
vertex([-1, -1, -1], [1, 1]),
// front (0, 1, 0)
vertex([ 1, 1, -1], [1, 0]),
vertex([-1, 1, -1], [0, 0]),
vertex([-1, 1, 1], [0, 1]),
vertex([ 1, 1, 1], [1, 1]),
vertex([1, 1, -1], [1, 0]),
vertex([-1, 1, -1], [0, 0]),
vertex([-1, 1, 1], [0, 1]),
vertex([1, 1, 1], [1, 1]),
// back (0, -1, 0)
vertex([ 1, -1, 1], [0, 0]),
vertex([-1, -1, 1], [1, 0]),
vertex([1, -1, 1], [0, 0]),
vertex([-1, -1, 1], [1, 0]),
vertex([-1, -1, -1], [1, 1]),
vertex([ 1, -1, -1], [0, 1]),
vertex([1, -1, -1], [0, 1]),
];
let index_data: &[u16] = &[
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
12, 13, 14, 14, 15, 12, // left
16, 17, 18, 18, 19, 16, // front
20, 21, 22, 22, 23, 20, // back
@ -63,13 +62,13 @@ fn create_vertices() -> (Vec<Vertex>, Vec<u16>) {
fn create_texels(size: usize) -> Vec<u8> {
use std::iter;
(0 .. size * size)
(0..size * size)
.flat_map(|id| {
// get high five for recognizing this ;)
let cx = 3.0*(id % size) as f32 / (size - 1) as f32 - 2.0;
let cy = 2.0*(id / size) as f32 / (size - 1) as f32 - 1.0;
let cx = 3.0 * (id % size) as f32 / (size - 1) as f32 - 2.0;
let cy = 2.0 * (id / size) as f32 / (size - 1) as f32 - 1.0;
let (mut x, mut y, mut count) = (cx, cy, 0);
while count < 0xFF && x*x + y*y < 4.0 {
while count < 0xFF && x * x + y * y < 4.0 {
let old_x = x;
x = x * x - y * y + cx;
y = 2.0 * old_x * y + cy;
@ -108,19 +107,18 @@ impl framework::Example for Example {
fn init(sc_desc: &wgpu::SwapChainDescriptor, device: &mut wgpu::Device) -> Self {
use std::mem;
let mut init_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
todo: 0,
});
let mut init_encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
// Create the vertex and index buffers
let vertex_size = mem::size_of::<Vertex>();
let (vertex_data, index_data) = create_vertices();
let vertex_buf =
device.create_buffer_mapped(vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
let vertex_buf = device
.create_buffer_mapped(vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&vertex_data);
let index_buf =
device.create_buffer_mapped(index_data.len(), wgpu::BufferUsageFlags::INDEX)
let index_buf = device
.create_buffer_mapped(index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&index_data);
// Create pipeline layout
@ -163,8 +161,8 @@ impl framework::Example for Example {
usage: wgpu::TextureUsageFlags::SAMPLED | wgpu::TextureUsageFlags::TRANSFER_DST,
});
let texture_view = texture.create_default_view();
let temp_buf =
device.create_buffer_mapped(texels.len(), wgpu::BufferUsageFlags::TRANSFER_SRC)
let temp_buf = device
.create_buffer_mapped(texels.len(), wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(&texels);
init_encoder.copy_buffer_to_texture(
wgpu::BufferCopyView {
@ -202,8 +200,11 @@ impl framework::Example for Example {
});
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let uniform_buf =
device.create_buffer_mapped(16, wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST)
let uniform_buf = device
.create_buffer_mapped(
16,
wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
)
.fill_from_slice(mx_ref);
// Create bind group
@ -214,7 +215,7 @@ impl framework::Example for Example {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0 .. 64,
range: 0..64,
},
},
wgpu::Binding {
@ -252,34 +253,30 @@ impl framework::Example for Example {
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[
wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
},
],
color_states: &[wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[
wgpu::VertexBufferDescriptor {
stride: vertex_size as u32,
step_mode: wgpu::InputStepMode::Vertex,
attributes: &[
wgpu::VertexAttributeDescriptor {
attribute_index: 0,
format: wgpu::VertexFormat::Float4,
offset: 0,
},
wgpu::VertexAttributeDescriptor {
attribute_index: 1,
format: wgpu::VertexFormat::Float2,
offset: 4 * 4,
},
],
},
],
vertex_buffers: &[wgpu::VertexBufferDescriptor {
stride: vertex_size as u32,
step_mode: wgpu::InputStepMode::Vertex,
attributes: &[
wgpu::VertexAttributeDescriptor {
attribute_index: 0,
format: wgpu::VertexFormat::Float4,
offset: 0,
},
wgpu::VertexAttributeDescriptor {
attribute_index: 1,
format: wgpu::VertexFormat::Float2,
offset: 4 * 4,
},
],
}],
sample_count: 1,
});
@ -304,24 +301,31 @@ impl framework::Example for Example {
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let temp_buf =
device.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
let temp_buf = device
.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(mx_ref);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.uniform_buf, 0, 64);
device.get_queue().submit(&[encoder.finish()]);
}
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let mut rpass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 },
clear_color: wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
}],
depth_stencil_attachment: None,
});
@ -329,12 +333,10 @@ impl framework::Example for Example {
rpass.set_bind_group(0, &self.bind_group);
rpass.set_index_buffer(&self.index_buf, 0);
rpass.set_vertex_buffers(&[(&self.vertex_buf, 0)]);
rpass.draw_indexed(0 .. self.index_count as u32, 0, 0..1);
rpass.draw_indexed(0..self.index_count as u32, 0, 0..1);
}
device
.get_queue()
.submit(&[encoder.finish()]);
device.get_queue().submit(&[encoder.finish()]);
}
}

View File

@ -1,14 +1,11 @@
use log::info;
#[allow(dead_code)]
pub fn cast_slice<T>(data: &[T]) -> &[u8] {
use std::mem::size_of;
use std::slice::from_raw_parts;
unsafe {
from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>())
}
unsafe { from_raw_parts(data.as_ptr() as *const u8, data.len() * size_of::<T>()) }
}
#[allow(dead_code)]
@ -51,7 +48,7 @@ pub trait Example {
pub fn run<E: Example>(title: &str) {
use wgpu::winit::{
Event, ElementState, EventsLoop, KeyboardInput, Window, WindowEvent, VirtualKeyCode
ElementState, Event, EventsLoop, KeyboardInput, VirtualKeyCode, Window, WindowEvent,
};
info!("Initializing the device...");
@ -90,37 +87,36 @@ pub fn run<E: Example>(title: &str) {
info!("Entering render loop...");
let mut running = true;
while running {
events_loop.poll_events(|event| {
match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
let physical = size.to_physical(window.get_hidpi_factor());
info!("Resizing to {:?}", physical);
sc_desc.width = physical.width as u32;
sc_desc.height = physical.height as u32;
swap_chain = device.create_swap_chain(&surface, &sc_desc);
example.resize(&sc_desc, &mut device);
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input: KeyboardInput {
events_loop.poll_events(|event| match event {
Event::WindowEvent {
event: WindowEvent::Resized(size),
..
} => {
let physical = size.to_physical(window.get_hidpi_factor());
info!("Resizing to {:?}", physical);
sc_desc.width = physical.width as u32;
sc_desc.height = physical.height as u32;
swap_chain = device.create_swap_chain(&surface, &sc_desc);
example.resize(&sc_desc, &mut device);
}
Event::WindowEvent { event, .. } => match event {
WindowEvent::KeyboardInput {
input:
KeyboardInput {
virtual_keycode: Some(VirtualKeyCode::Escape),
state: ElementState::Pressed,
..
},
..
} |
WindowEvent::CloseRequested => {
running = false;
}
_ => {
example.update(event);
}
..
}
_ => ()
}
| WindowEvent::CloseRequested => {
running = false;
}
_ => {
example.update(event);
}
},
_ => (),
});
let frame = swap_chain.get_next_texture();

View File

@ -4,7 +4,6 @@ use std::rc::Rc;
mod framework;
#[derive(Clone, Copy)]
struct Vertex {
_pos: [i8; 4],
@ -21,41 +20,41 @@ fn vertex(pos: [i8; 3], nor: [i8; 3]) -> Vertex {
fn create_cube() -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
// top (0, 0, 1)
vertex([-1, -1, 1], [0, 0, 1]),
vertex([ 1, -1, 1], [0, 0, 1]),
vertex([ 1, 1, 1], [0, 0, 1]),
vertex([-1, 1, 1], [0, 0, 1]),
vertex([-1, -1, 1], [0, 0, 1]),
vertex([1, -1, 1], [0, 0, 1]),
vertex([1, 1, 1], [0, 0, 1]),
vertex([-1, 1, 1], [0, 0, 1]),
// bottom (0, 0, -1)
vertex([-1, 1, -1], [0, 0, -1]),
vertex([ 1, 1, -1], [0, 0, -1]),
vertex([ 1, -1, -1], [0, 0, -1]),
vertex([-1, 1, -1], [0, 0, -1]),
vertex([1, 1, -1], [0, 0, -1]),
vertex([1, -1, -1], [0, 0, -1]),
vertex([-1, -1, -1], [0, 0, -1]),
// right (1, 0, 0)
vertex([ 1, -1, -1], [1, 0, 0]),
vertex([ 1, 1, -1], [1, 0, 0]),
vertex([ 1, 1, 1], [1, 0, 0]),
vertex([ 1, -1, 1], [1, 0, 0]),
vertex([1, -1, -1], [1, 0, 0]),
vertex([1, 1, -1], [1, 0, 0]),
vertex([1, 1, 1], [1, 0, 0]),
vertex([1, -1, 1], [1, 0, 0]),
// left (-1, 0, 0)
vertex([-1, -1, 1], [-1, 0, 0]),
vertex([-1, 1, 1], [-1, 0, 0]),
vertex([-1, 1, -1], [-1, 0, 0]),
vertex([-1, -1, 1], [-1, 0, 0]),
vertex([-1, 1, 1], [-1, 0, 0]),
vertex([-1, 1, -1], [-1, 0, 0]),
vertex([-1, -1, -1], [-1, 0, 0]),
// front (0, 1, 0)
vertex([ 1, 1, -1], [0, 1, 0]),
vertex([-1, 1, -1], [0, 1, 0]),
vertex([-1, 1, 1], [0, 1, 0]),
vertex([ 1, 1, 1], [0, 1, 0]),
vertex([1, 1, -1], [0, 1, 0]),
vertex([-1, 1, -1], [0, 1, 0]),
vertex([-1, 1, 1], [0, 1, 0]),
vertex([1, 1, 1], [0, 1, 0]),
// back (0, -1, 0)
vertex([ 1, -1, 1], [0, -1, 0]),
vertex([-1, -1, 1], [0, -1, 0]),
vertex([1, -1, 1], [0, -1, 0]),
vertex([-1, -1, 1], [0, -1, 0]),
vertex([-1, -1, -1], [0, -1, 0]),
vertex([ 1, -1, -1], [0, -1, 0]),
vertex([1, -1, -1], [0, -1, 0]),
];
let index_data: &[u16] = &[
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
0, 1, 2, 2, 3, 0, // top
4, 5, 6, 6, 7, 4, // bottom
8, 9, 10, 10, 11, 8, // right
12, 13, 14, 14, 15, 12, // left
16, 17, 18, 18, 19, 16, // front
20, 21, 22, 22, 23, 20, // back
@ -66,21 +65,17 @@ fn create_cube() -> (Vec<Vertex>, Vec<u16>) {
fn create_plane(size: i8) -> (Vec<Vertex>, Vec<u16>) {
let vertex_data = [
vertex([ size, -size, 0], [0, 0, 1]),
vertex([ size, size, 0], [0, 0, 1]),
vertex([-size, -size, 0], [0, 0, 1]),
vertex([-size, size, 0], [0, 0, 1]),
vertex([size, -size, 0], [0, 0, 1]),
vertex([size, size, 0], [0, 0, 1]),
vertex([-size, -size, 0], [0, 0, 1]),
vertex([-size, size, 0], [0, 0, 1]),
];
let index_data: &[u16] = &[
0, 1, 2,
2, 1, 3
];
let index_data: &[u16] = &[0, 1, 2, 2, 1, 3];
(vertex_data.to_vec(), index_data.to_vec())
}
struct Entity {
mx_world: cgmath::Matrix4<f32>,
rotation_speed: f32,
@ -110,13 +105,9 @@ struct LightRaw {
impl Light {
fn to_raw(&self) -> LightRaw {
use cgmath::{EuclideanSpace, Deg, Point3, Vector3, Matrix4, PerspectiveFov};
use cgmath::{Deg, EuclideanSpace, Matrix4, PerspectiveFov, Point3, Vector3};
let mx_view = Matrix4::look_at(
self.pos,
Point3::origin(),
-Vector3::unit_z(),
);
let mx_view = Matrix4::look_at(self.pos, Point3::origin(), -Vector3::unit_z());
let projection = PerspectiveFov {
fovy: Deg(self.fov).into(),
aspect: 1.0,
@ -194,22 +185,24 @@ impl framework::Example for Example {
let vertex_size = mem::size_of::<Vertex>();
let (cube_vertex_data, cube_index_data) = create_cube();
let cube_vertex_buf = Rc::new(
device.create_buffer_mapped(cube_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&cube_vertex_data)
device
.create_buffer_mapped(cube_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&cube_vertex_data),
);
let cube_index_buf = Rc::new(
device.create_buffer_mapped(cube_index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&cube_index_data)
device
.create_buffer_mapped(cube_index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&cube_index_data),
);
let (plane_vertex_data, plane_index_data) = create_plane(7);
let plane_vertex_buf =
device.create_buffer_mapped(plane_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
let plane_vertex_buf = device
.create_buffer_mapped(plane_vertex_data.len(), wgpu::BufferUsageFlags::VERTEX)
.fill_from_slice(&plane_vertex_data);
let plane_index_buf =
device.create_buffer_mapped(plane_index_data.len(), wgpu::BufferUsageFlags::INDEX)
let plane_index_buf = device
.create_buffer_mapped(plane_index_data.len(), wgpu::BufferUsageFlags::INDEX)
.fill_from_slice(&plane_index_data);
let entity_uniform_size = mem::size_of::<EntityUniforms>() as u32;
@ -218,30 +211,27 @@ impl framework::Example for Example {
usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
});
let local_bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
let local_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0,
visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
],
});
}],
});
let mut entities = vec![{
use cgmath::SquareMatrix;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &local_bind_group_layout,
bindings: &[
wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &plane_uniform_buf,
range: 0 .. entity_uniform_size,
},
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &plane_uniform_buf,
range: 0..entity_uniform_size,
},
],
}],
});
Entity {
mx_world: cgmath::Matrix4::identity(),
@ -289,14 +279,11 @@ impl framework::Example for Example {
];
for cube in &cube_descs {
use cgmath::{Deg, Decomposed, Quaternion, Rotation3, InnerSpace};
use cgmath::{Decomposed, Deg, InnerSpace, Quaternion, Rotation3};
let transform = Decomposed {
disp: cube.offset.clone(),
rot: Quaternion::from_axis_angle(
cube.offset.normalize(),
Deg(cube.angle),
),
rot: Quaternion::from_axis_angle(cube.offset.normalize(), Deg(cube.angle)),
scale: cube.scale,
};
let uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
@ -312,15 +299,13 @@ impl framework::Example for Example {
index_count: cube_index_data.len(),
bind_group: device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &local_bind_group_layout,
bindings: &[
wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0 .. entity_uniform_size,
},
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..entity_uniform_size,
},
],
}],
}),
uniform_buf,
});
@ -351,36 +336,50 @@ impl framework::Example for Example {
let shadow_view = shadow_texture.create_default_view();
let mut shadow_target_views = (0..2)
.map(|i| Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor {
format: Self::SHADOW_FORMAT,
dimension: wgpu::TextureViewDimension::D2,
aspect: wgpu::TextureAspectFlags::DEPTH,
base_mip_level: 0,
level_count: 1,
base_array_layer: i as u32,
array_count: 1,
})))
.map(|i| {
Some(shadow_texture.create_view(&wgpu::TextureViewDescriptor {
format: Self::SHADOW_FORMAT,
dimension: wgpu::TextureViewDimension::D2,
aspect: wgpu::TextureAspectFlags::DEPTH,
base_mip_level: 0,
level_count: 1,
base_array_layer: i as u32,
array_count: 1,
}))
})
.collect::<Vec<_>>();
let lights = vec![
Light {
pos: cgmath::Point3::new(7.0, -5.0, 10.0),
color: wgpu::Color { r: 0.5, g: 1.0, b: 0.5, a: 1.0 },
color: wgpu::Color {
r: 0.5,
g: 1.0,
b: 0.5,
a: 1.0,
},
fov: 60.0,
depth: 1.0 .. 20.0,
depth: 1.0..20.0,
target_view: shadow_target_views[0].take().unwrap(),
},
Light {
pos: cgmath::Point3::new(-5.0, 7.0, 10.0),
color: wgpu::Color { r: 1.0, g: 0.5, b: 0.5, a: 1.0 },
color: wgpu::Color {
r: 1.0,
g: 0.5,
b: 0.5,
a: 1.0,
},
fov: 45.0,
depth: 1.0 .. 20.0,
depth: 1.0..20.0,
target_view: shadow_target_views[1].take().unwrap(),
},
];
let light_uniform_size = (Self::MAX_LIGHTS * mem::size_of::<LightRaw>()) as u32;
let light_uniform_buf = device.create_buffer(&wgpu::BufferDescriptor {
size: light_uniform_size,
usage: wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_SRC | wgpu::BufferUsageFlags::TRANSFER_DST,
usage: wgpu::BufferUsageFlags::UNIFORM
| wgpu::BufferUsageFlags::TRANSFER_SRC
| wgpu::BufferUsageFlags::TRANSFER_DST,
});
let vb_desc = wgpu::VertexBufferDescriptor {
@ -402,20 +401,16 @@ impl framework::Example for Example {
let shadow_pass = {
// Create pipeline layout
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding {
binding: 0, // global
visibility: wgpu::ShaderStageFlags::VERTEX,
ty: wgpu::BindingType::UniformBuffer,
},
],
});
}],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[
&bind_group_layout,
&local_bind_group_layout,
],
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
});
let uniform_size = mem::size_of::<ShadowUniforms>() as u32;
@ -427,20 +422,19 @@ impl framework::Example for Example {
// Create bind group
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
layout: &bind_group_layout,
bindings: &[
wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0 .. uniform_size,
},
bindings: &[wgpu::Binding {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0..uniform_size,
},
],
}],
});
// Create the render pipeline
let vs_bytes = framework::load_glsl("shadow-bake.vert", framework::ShaderStage::Vertex);
let fs_bytes = framework::load_glsl("shadow-bake.frag", framework::ShaderStage::Fragment);
let fs_bytes =
framework::load_glsl("shadow-bake.frag", framework::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes);
@ -486,35 +480,35 @@ impl framework::Example for Example {
let forward_pass = {
// Create pipeline layout
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
binding: 0, // global
visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 1, // lights
visibility: wgpu::ShaderStageFlags::VERTEX | wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 2,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::SampledTexture,
},
wgpu::BindGroupLayoutBinding {
binding: 3,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::Sampler,
},
],
});
let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[
wgpu::BindGroupLayoutBinding {
binding: 0, // global
visibility: wgpu::ShaderStageFlags::VERTEX
| wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 1, // lights
visibility: wgpu::ShaderStageFlags::VERTEX
| wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::UniformBuffer,
},
wgpu::BindGroupLayoutBinding {
binding: 2,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::SampledTexture,
},
wgpu::BindGroupLayoutBinding {
binding: 3,
visibility: wgpu::ShaderStageFlags::FRAGMENT,
ty: wgpu::BindingType::Sampler,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
bind_group_layouts: &[
&bind_group_layout,
&local_bind_group_layout,
],
bind_group_layouts: &[&bind_group_layout, &local_bind_group_layout],
});
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
@ -523,8 +517,11 @@ impl framework::Example for Example {
num_lights: [lights.len() as u32, 0, 0, 0],
};
let uniform_size = mem::size_of::<ForwardUniforms>() as u32;
let uniform_buf =
device.create_buffer_mapped(1, wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST)
let uniform_buf = device
.create_buffer_mapped(
1,
wgpu::BufferUsageFlags::UNIFORM | wgpu::BufferUsageFlags::TRANSFER_DST,
)
.fill_from_slice(&[forward_uniforms]);
// Create bind group
@ -535,14 +532,14 @@ impl framework::Example for Example {
binding: 0,
resource: wgpu::BindingResource::Buffer {
buffer: &uniform_buf,
range: 0 .. uniform_size,
range: 0..uniform_size,
},
},
wgpu::Binding {
binding: 1,
resource: wgpu::BindingResource::Buffer {
buffer: &light_uniform_buf,
range: 0 .. light_uniform_size,
range: 0..light_uniform_size,
},
},
wgpu::Binding {
@ -557,8 +554,10 @@ impl framework::Example for Example {
});
// Create the render pipeline
let vs_bytes = framework::load_glsl("shadow-forward.vert", framework::ShaderStage::Vertex);
let fs_bytes = framework::load_glsl("shadow-forward.frag", framework::ShaderStage::Fragment);
let vs_bytes =
framework::load_glsl("shadow-forward.vert", framework::ShaderStage::Vertex);
let fs_bytes =
framework::load_glsl("shadow-forward.frag", framework::ShaderStage::Fragment);
let vs_module = device.create_shader_module(&vs_bytes);
let fs_module = device.create_shader_module(&fs_bytes);
@ -580,14 +579,12 @@ impl framework::Example for Example {
depth_bias_clamp: 0.0,
},
primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[
wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
},
],
color_states: &[wgpu::ColorStateDescriptor {
format: sc_desc.format,
color: wgpu::BlendDescriptor::REPLACE,
alpha: wgpu::BlendDescriptor::REPLACE,
write_mask: wgpu::ColorWriteFlags::ALL,
}],
depth_stencil_state: Some(wgpu::DepthStencilStateDescriptor {
format: Self::DEPTH_FORMAT,
depth_write_enabled: true,
@ -640,11 +637,12 @@ impl framework::Example for Example {
{
let mx_total = Self::generate_matrix(sc_desc.width as f32 / sc_desc.height as f32);
let mx_ref: &[f32; 16] = mx_total.as_ref();
let temp_buf =
device.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
let temp_buf = device
.create_buffer_mapped(16, wgpu::BufferUsageFlags::TRANSFER_SRC)
.fill_from_slice(mx_ref);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
encoder.copy_buffer_to_buffer(&temp_buf, 0, &self.forward_pass.uniform_buf, 0, 64);
device.get_queue().submit(&[encoder.finish()]);
}
@ -664,42 +662,61 @@ impl framework::Example for Example {
}
fn render(&mut self, frame: &wgpu::SwapChainOutput, device: &mut wgpu::Device) {
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
let mut encoder =
device.create_command_encoder(&wgpu::CommandEncoderDescriptor { todo: 0 });
{
let size = mem::size_of::<EntityUniforms>() as u32;
let temp_buf_data =
device.create_buffer_mapped(self.entities.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
let temp_buf_data = device
.create_buffer_mapped(self.entities.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
for (i, entity) in self.entities.iter_mut().enumerate() {
if entity.rotation_speed != 0.0 {
let rotation = cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed));
let rotation =
cgmath::Matrix4::from_angle_x(cgmath::Deg(entity.rotation_speed));
entity.mx_world = entity.mx_world * rotation;
}
temp_buf_data.data[i] = EntityUniforms {
model: entity.mx_world.clone(),
color: [entity.color.r, entity.color.g, entity.color.b, entity.color.a],
color: [
entity.color.r,
entity.color.g,
entity.color.b,
entity.color.a,
],
};
}
let temp_buf = temp_buf_data.finish();
for (i, entity) in self.entities.iter().enumerate() {
encoder.copy_buffer_to_buffer(&temp_buf, i as u32 * size, &entity.uniform_buf, 0, size);
encoder.copy_buffer_to_buffer(
&temp_buf,
i as u32 * size,
&entity.uniform_buf,
0,
size,
);
}
}
if self.lights_are_dirty {
self.lights_are_dirty = false;
let size = (self.lights.len() * mem::size_of::<LightRaw>()) as u32;
let temp_buf_data =
device.create_buffer_mapped(self.lights.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
let temp_buf_data = device
.create_buffer_mapped(self.lights.len(), wgpu::BufferUsageFlags::TRANSFER_SRC);
for (i, light) in self.lights.iter().enumerate() {
temp_buf_data.data[i] = light.to_raw();
}
encoder.copy_buffer_to_buffer(&temp_buf_data.finish(), 0, &self.light_uniform_buf, 0, size);
encoder.copy_buffer_to_buffer(
&temp_buf_data.finish(),
0,
&self.light_uniform_buf,
0,
size,
);
}
for (i, light) in self.lights.iter().enumerate() {
// The light uniform buffer already has the projection,
// let's just copy it over to the shadow uniform buffer.
@ -730,7 +747,7 @@ impl framework::Example for Example {
pass.set_bind_group(1, &entity.bind_group);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0..1);
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
}
}
@ -741,7 +758,12 @@ impl framework::Example for Example {
attachment: &frame.view,
load_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color { r: 0.1, g: 0.2, b: 0.3, a: 1.0 },
clear_color: wgpu::Color {
r: 0.1,
g: 0.2,
b: 0.3,
a: 1.0,
},
}],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachmentDescriptor {
attachment: &self.forward_depth,
@ -760,13 +782,11 @@ impl framework::Example for Example {
pass.set_bind_group(1, &entity.bind_group);
pass.set_index_buffer(&entity.index_buf, 0);
pass.set_vertex_buffers(&[(&entity.vertex_buf, 0)]);
pass.draw_indexed(0 .. entity.index_count as u32, 0, 0..1);
pass.draw_indexed(0..entity.index_count as u32, 0, 0..1);
}
}
device
.get_queue()
.submit(&[encoder.finish()]);
device.get_queue().submit(&[encoder.finish()]);
}
}

View File

@ -1,12 +1,8 @@
use crate::track::TrackerSet;
use crate::{
LifeGuard,
BindGroupLayoutId, BufferId, SamplerId, TextureViewId,
};
use crate::{BindGroupLayoutId, BufferId, LifeGuard, SamplerId, TextureViewId};
use bitflags::bitflags;
bitflags! {
#[repr(transparent)]
pub struct ShaderStageFlags: u32 {

View File

@ -110,7 +110,10 @@ impl<B: hal::Backend> CommandAllocator<B> {
pub fn maintain(&self, last_done: SubmissionIndex) {
let mut inner = self.inner.lock();
for i in (0..inner.pending.len()).rev() {
let index = inner.pending[i].life_guard.submission_index.load(Ordering::Acquire);
let index = inner.pending[i]
.life_guard
.submission_index
.load(Ordering::Acquire);
if index <= last_done {
let cmd_buf = inner.pending.swap_remove(i);
inner.recycle(cmd_buf);

View File

@ -1,8 +1,4 @@
use crate::{
BindGroupHandle, Stored,
BindGroupId, BindGroupLayoutId, PipelineLayoutId,
};
use crate::{BindGroupHandle, BindGroupId, BindGroupLayoutId, PipelineLayoutId, Stored};
pub struct BindGroupPair {
layout_id: BindGroupLayoutId,
@ -17,10 +13,14 @@ pub struct BindGroupEntry {
impl BindGroupEntry {
fn provide(&mut self, bind_group_id: BindGroupId, bind_group: &BindGroupHandle) -> bool {
if let Some(BindGroupPair { ref layout_id, ref group_id }) = self.provided {
if let Some(BindGroupPair {
ref layout_id,
ref group_id,
}) = self.provided
{
if group_id.value == bind_group_id {
assert_eq!(*layout_id, bind_group.layout_id);
return false
return false;
}
}
@ -36,14 +36,17 @@ impl BindGroupEntry {
}
pub fn expect_layout(
&mut self, bind_group_layout_id: BindGroupLayoutId,
&mut self,
bind_group_layout_id: BindGroupLayoutId,
) -> Option<BindGroupId> {
let some = Some(bind_group_layout_id);
if self.expected_layout_id != some {
self.expected_layout_id = some;
match self.provided {
Some(BindGroupPair { layout_id, ref group_id })
if layout_id == bind_group_layout_id => Some(group_id.value),
Some(BindGroupPair {
layout_id,
ref group_id,
}) if layout_id == bind_group_layout_id => Some(group_id.value),
Some(_) | None => None,
}
} else {
@ -66,7 +69,10 @@ impl Binder {
}
pub(crate) fn provide_entry(
&mut self, index: usize, bind_group_id: BindGroupId, bind_group: &BindGroupHandle
&mut self,
index: usize,
bind_group_id: BindGroupId,
bind_group: &BindGroupHandle,
) -> Option<PipelineLayoutId> {
self.ensure_length(index + 1);
if self.entries[index].provide(bind_group_id, bind_group) {

View File

@ -1,9 +1,8 @@
use crate::command::bind::{Binder};
use crate::command::bind::Binder;
use crate::hub::HUB;
use crate::track::{Stitch, TrackerSet};
use crate::{
Stored, CommandBuffer,
BindGroupId, CommandBufferId, ComputePassId, ComputePipelineId,
BindGroupId, CommandBuffer, CommandBufferId, ComputePassId, ComputePipelineId, Stored,
};
use hal;
@ -11,7 +10,6 @@ use hal::command::RawCommandBuffer;
use std::iter;
pub struct ComputePass<B: hal::Backend> {
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
@ -36,9 +34,8 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandB
//TODO: transitions?
HUB.command_buffers
.write()
[pass.cmb_id.value].raw
HUB.command_buffers.write()[pass.cmb_id.value]
.raw
.push(pass.raw);
pass.cmb_id.value
}
@ -46,10 +43,7 @@ pub extern "C" fn wgpu_compute_pass_end_pass(pass_id: ComputePassId) -> CommandB
#[no_mangle]
pub extern "C" fn wgpu_compute_pass_dispatch(pass_id: ComputePassId, x: u32, y: u32, z: u32) {
unsafe {
HUB.compute_passes
.write()
[pass_id].raw
.dispatch([x, y, z]);
HUB.compute_passes.write()[pass_id].raw.dispatch([x, y, z]);
}
}
@ -76,7 +70,10 @@ pub extern "C" fn wgpu_compute_pass_set_bind_group(
&*HUB.textures.read(),
);
if let Some(pipeline_layout_id) = pass.binder.provide_entry(index as usize, bind_group_id, bind_group) {
if let Some(pipeline_layout_id) =
pass.binder
.provide_entry(index as usize, bind_group_id, bind_group)
{
let pipeline_layout_guard = HUB.pipeline_layouts.read();
unsafe {
pass.raw.bind_compute_descriptor_sets(
@ -104,7 +101,7 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline(
}
if pass.binder.pipeline_layout_id == Some(pipeline.layout_id.clone()) {
return
return;
}
let pipeline_layout_guard = HUB.pipeline_layouts.read();
@ -112,9 +109,12 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline(
let bing_group_guard = HUB.bind_groups.read();
pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone());
pass.binder.ensure_length(pipeline_layout.bind_group_layout_ids.len());
pass.binder
.ensure_length(pipeline_layout.bind_group_layout_ids.len());
for (index, (entry, &bgl_id)) in pass.binder.entries
for (index, (entry, &bgl_id)) in pass
.binder
.entries
.iter_mut()
.zip(&pipeline_layout.bind_group_layout_ids)
.enumerate()
@ -126,7 +126,7 @@ pub extern "C" fn wgpu_compute_pass_set_pipeline(
&pipeline_layout.raw,
index,
iter::once(desc_set),
&[]
&[],
);
}
}

View File

@ -9,35 +9,29 @@ pub use self::compute::*;
pub use self::render::*;
pub use self::transfer::*;
use crate::conv;
use crate::device::{
FramebufferKey, RenderPassKey, RenderPassContext,
all_buffer_stages, all_image_stages,
all_buffer_stages, all_image_stages, FramebufferKey, RenderPassContext, RenderPassKey,
};
use crate::hub::{HUB, Storage};
use crate::hub::{Storage, HUB};
use crate::resource::TexturePlacement;
use crate::swap_chain::{SwapChainLink, SwapImageEpoch};
use crate::track::{DummyUsage, Stitch, TrackerSet};
use crate::conv;
use crate::{
BufferHandle, TextureHandle,
CommandBufferId, CommandEncoderId, DeviceId,
TextureViewId,
TextureUsageFlags, Color,
LifeGuard, Stored,
CommandBufferHandle,
BufferHandle, Color, CommandBufferHandle, CommandBufferId, CommandEncoderId, DeviceId,
LifeGuard, Stored, TextureHandle, TextureUsageFlags, TextureViewId,
};
#[cfg(feature = "local")]
use crate::{RenderPassId, ComputePassId};
use crate::{ComputePassId, RenderPassId};
use back::Backend;
use hal::command::RawCommandBuffer;
use hal::{Device as _Device};
use hal::Device as _Device;
use log::trace;
use std::collections::hash_map::Entry;
use std::{iter, slice};
use std::thread::ThreadId;
use std::{iter, slice};
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
@ -78,7 +72,6 @@ pub struct RenderPassDescriptor {
pub depth_stencil_attachment: *const RenderPassDepthStencilAttachmentDescriptor<TextureViewId>,
}
pub struct CommandBuffer<B: hal::Backend> {
pub(crate) raw: Vec<B::CommandBuffer>,
is_recording: bool,
@ -98,19 +91,22 @@ impl CommandBufferHandle {
buffer_guard: &Storage<BufferHandle>,
texture_guard: &Storage<TextureHandle>,
) {
let buffer_barriers = base.buffers
.consume_by_replace(&head.buffers, stitch)
.map(|(id, transit)| {
let b = &buffer_guard[id];
trace!("transit buffer {:?} {:?}", id, transit);
hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(transit.start) .. conv::map_buffer_state(transit.end),
target: &b.raw,
range: None .. None,
families: None,
}
});
let texture_barriers = base.textures
let buffer_barriers =
base.buffers
.consume_by_replace(&head.buffers, stitch)
.map(|(id, transit)| {
let b = &buffer_guard[id];
trace!("transit buffer {:?} {:?}", id, transit);
hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(transit.start)
..conv::map_buffer_state(transit.end),
target: &b.raw,
range: None..None,
families: None,
}
});
let texture_barriers = base
.textures
.consume_by_replace(&head.textures, stitch)
.map(|(id, transit)| {
let t = &texture_guard[id];
@ -124,14 +120,12 @@ impl CommandBufferHandle {
families: None,
}
});
base.views
.consume_by_extend(&head.views)
.unwrap();
base.views.consume_by_extend(&head.views).unwrap();
let stages = all_buffer_stages() | all_image_stages();
unsafe {
raw.pipeline_barrier(
stages .. stages,
stages..stages,
hal::memory::Dependencies::empty(),
buffer_barriers.chain(texture_barriers),
);
@ -150,10 +144,7 @@ pub struct CommandEncoderDescriptor {
pub extern "C" fn wgpu_command_encoder_finish(
command_encoder_id: CommandEncoderId,
) -> CommandBufferId {
HUB.command_buffers
.write()
[command_encoder_id]
.is_recording = false; //TODO: check for the old value
HUB.command_buffers.write()[command_encoder_id].is_recording = false; //TODO: check for the old value
command_encoder_id
}
@ -176,15 +167,9 @@ pub fn command_encoder_begin_render_pass(
}
let mut extent = None;
let color_attachments = unsafe {
slice::from_raw_parts(
desc.color_attachments,
desc.color_attachments_length,
)
};
let depth_stencil_attachment = unsafe {
desc.depth_stencil_attachment.as_ref()
};
let color_attachments =
unsafe { slice::from_raw_parts(desc.color_attachments, desc.color_attachments_length) };
let depth_stencil_attachment = unsafe { desc.depth_stencil_attachment.as_ref() };
let rp_key = {
let trackers = &mut cmb.trackers;
@ -197,7 +182,9 @@ pub fn command_encoder_begin_render_pass(
} else {
extent = Some(view.extent);
}
trackers.views.query(at.attachment, &view.life_guard.ref_count, DummyUsage);
trackers
.views
.query(at.attachment, &view.life_guard.ref_count, DummyUsage);
let query = trackers.textures.query(
view.texture_id.value,
&view.texture_id.ref_count,
@ -220,17 +207,13 @@ pub fn command_encoder_begin_render_pass(
let view = &view_guard[at.attachment];
if view.is_owned_by_swap_chain {
let link = match HUB.textures
.read()
[view.texture_id.value].placement
{
let link = match HUB.textures.read()[view.texture_id.value].placement {
TexturePlacement::SwapChain(ref link) => SwapChainLink {
swap_chain_id: link.swap_chain_id.clone(),
epoch: *link.epoch.lock(),
image_index: link.image_index,
},
TexturePlacement::Memory(_) |
TexturePlacement::Void => unreachable!()
TexturePlacement::Memory(_) | TexturePlacement::Void => unreachable!(),
};
swap_chain_links.push(link);
}
@ -240,7 +223,9 @@ pub fn command_encoder_begin_render_pass(
} else {
extent = Some(view.extent);
}
trackers.views.query(at.attachment, &view.life_guard.ref_count, DummyUsage);
trackers
.views
.query(at.attachment, &view.life_guard.ref_count, DummyUsage);
let query = trackers.textures.query(
view.texture_id.value,
&view.texture_id.ref_count,
@ -297,21 +282,14 @@ pub fn command_encoder_begin_render_pass(
let mut framebuffer_cache = device.framebuffers.lock();
let fb_key = FramebufferKey {
colors: color_attachments
.iter()
.map(|at| at.attachment)
.collect(),
depth_stencil: depth_stencil_attachment
.map(|at| at.attachment),
colors: color_attachments.iter().map(|at| at.attachment).collect(),
depth_stencil: depth_stencil_attachment.map(|at| at.attachment),
};
let framebuffer = match framebuffer_cache.entry(fb_key) {
Entry::Occupied(e) => e.into_mut(),
Entry::Vacant(e) => {
let fb = {
let attachments = e
.key()
.all()
.map(|&id| &view_guard[id].raw);
let attachments = e.key().all().map(|&id| &view_guard[id].raw);
unsafe {
device
@ -355,10 +333,13 @@ pub fn command_encoder_begin_render_pass(
hal::command::SubpassContents::Inline,
);
current_comb.set_scissors(0, iter::once(&rect));
current_comb.set_viewports(0, iter::once(hal::pso::Viewport {
rect,
depth: 0.0 .. 1.0,
}));
current_comb.set_viewports(
0,
iter::once(hal::pso::Viewport {
rect,
depth: 0.0..1.0,
}),
);
}
let context = RenderPassContext {
@ -366,8 +347,7 @@ pub fn command_encoder_begin_render_pass(
.iter()
.map(|at| view_guard[at.attachment].format)
.collect(),
depth_stencil: depth_stencil_attachment
.map(|at| view_guard[at.attachment].format),
depth_stencil: depth_stencil_attachment.map(|at| view_guard[at.attachment].format),
};
RenderPass::new(

View File

@ -1,18 +1,16 @@
use crate::command::bind::Binder;
use crate::device::RenderPassContext;
use crate::hub::HUB;
use crate::resource::{BufferUsageFlags};
use crate::resource::BufferUsageFlags;
use crate::track::{Stitch, TrackerSet};
use crate::{
CommandBuffer, Stored,
BindGroupId, BufferId, CommandBufferId, RenderPassId, RenderPipelineId,
BindGroupId, BufferId, CommandBuffer, CommandBufferId, RenderPassId, RenderPipelineId, Stored,
};
use hal::command::RawCommandBuffer;
use std::{iter, slice};
pub struct RenderPass<B: hal::Backend> {
raw: B::CommandBuffer,
cmb_id: Stored<CommandBufferId>,
@ -70,18 +68,18 @@ pub extern "C" fn wgpu_render_pass_end_pass(pass_id: RenderPassId) -> CommandBuf
#[no_mangle]
pub extern "C" fn wgpu_render_pass_set_index_buffer(
pass_id: RenderPassId, buffer_id: BufferId, offset: u32
pass_id: RenderPassId,
buffer_id: BufferId,
offset: u32,
) {
let mut pass_guard = HUB.render_passes.write();
let buffer_guard = HUB.buffers.read();
let pass = &mut pass_guard[pass_id];
let buffer = pass.trackers.buffers
.get_with_extended_usage(
&*buffer_guard,
buffer_id,
BufferUsageFlags::INDEX,
)
let buffer = pass
.trackers
.buffers
.get_with_extended_usage(&*buffer_guard, buffer_id, BufferUsageFlags::INDEX)
.unwrap();
let view = hal::buffer::IndexBufferView {
@ -104,21 +102,14 @@ pub extern "C" fn wgpu_render_pass_set_vertex_buffers(
) {
let mut pass_guard = HUB.render_passes.write();
let buffer_guard = HUB.buffers.read();
let buffers = unsafe {
slice::from_raw_parts(buffer_ptr, count)
};
let offsets = unsafe {
slice::from_raw_parts(offset_ptr, count)
};
let buffers = unsafe { slice::from_raw_parts(buffer_ptr, count) };
let offsets = unsafe { slice::from_raw_parts(offset_ptr, count) };
let pass = &mut pass_guard[pass_id];
for &id in buffers {
pass.trackers.buffers
.get_with_extended_usage(
&*buffer_guard,
id,
BufferUsageFlags::VERTEX,
)
pass.trackers
.buffers
.get_with_extended_usage(&*buffer_guard, id, BufferUsageFlags::VERTEX)
.unwrap();
}
@ -141,13 +132,10 @@ pub extern "C" fn wgpu_render_pass_draw(
first_instance: u32,
) {
unsafe {
HUB.render_passes
.write()
[pass_id].raw
.draw(
first_vertex .. first_vertex + vertex_count,
first_instance .. first_instance + instance_count,
);
HUB.render_passes.write()[pass_id].raw.draw(
first_vertex..first_vertex + vertex_count,
first_instance..first_instance + instance_count,
);
}
}
@ -161,14 +149,11 @@ pub extern "C" fn wgpu_render_pass_draw_indexed(
first_instance: u32,
) {
unsafe {
HUB.render_passes
.write()
[pass_id].raw
.draw_indexed(
first_index .. first_index + index_count,
base_vertex,
first_instance .. first_instance + instance_count,
);
HUB.render_passes.write()[pass_id].raw.draw_indexed(
first_index..first_index + index_count,
base_vertex,
first_instance..first_instance + instance_count,
);
}
}
@ -185,7 +170,10 @@ pub extern "C" fn wgpu_render_pass_set_bind_group(
pass.trackers.consume_by_extend(&bind_group.used);
if let Some(pipeline_layout_id) = pass.binder.provide_entry(index as usize, bind_group_id, bind_group) {
if let Some(pipeline_layout_id) =
pass.binder
.provide_entry(index as usize, bind_group_id, bind_group)
{
let pipeline_layout_guard = HUB.pipeline_layouts.read();
let pipeline_layout = &pipeline_layout_guard[pipeline_layout_id];
unsafe {
@ -209,15 +197,17 @@ pub extern "C" fn wgpu_render_pass_set_pipeline(
let pipeline_guard = HUB.render_pipelines.read();
let pipeline = &pipeline_guard[pipeline_id];
assert_eq!(pass.context, pipeline.pass_context,
"The render pipeline is not compatible with the pass!");
assert_eq!(
pass.context, pipeline.pass_context,
"The render pipeline is not compatible with the pass!"
);
unsafe {
pass.raw.bind_graphics_pipeline(&pipeline.raw);
}
if pass.binder.pipeline_layout_id == Some(pipeline.layout_id.clone()) {
return
return;
}
let pipeline_layout_guard = HUB.pipeline_layouts.read();
@ -225,9 +215,12 @@ pub extern "C" fn wgpu_render_pass_set_pipeline(
let bind_group_guard = HUB.bind_groups.read();
pass.binder.pipeline_layout_id = Some(pipeline.layout_id.clone());
pass.binder.ensure_length(pipeline_layout.bind_group_layout_ids.len());
pass.binder
.ensure_length(pipeline_layout.bind_group_layout_ids.len());
for (index, (entry, &bgl_id)) in pass.binder.entries
for (index, (entry, &bgl_id)) in pass
.binder
.entries
.iter_mut()
.zip(&pipeline_layout.bind_group_layout_ids)
.enumerate()
@ -239,7 +232,7 @@ pub extern "C" fn wgpu_render_pass_set_pipeline(
&pipeline_layout.raw,
index,
iter::once(desc_set),
&[]
&[],
);
}
}

View File

@ -1,19 +1,16 @@
use crate::conv;
use crate::device::{all_buffer_stages, all_image_stages};
use crate::hub::HUB;
use crate::resource::TexturePlacement;
use crate::swap_chain::SwapChainLink;
use crate::conv;
use crate::{
BufferId, CommandBufferId, TextureId,
BufferUsageFlags, TextureUsageFlags,
Extent3d, Origin3d,
BufferId, BufferUsageFlags, CommandBufferId, Extent3d, Origin3d, TextureId, TextureUsageFlags,
};
use hal::command::RawCommandBuffer;
use std::iter;
const BITS_PER_BYTE: u32 = 8;
#[repr(C)]
@ -36,7 +33,7 @@ pub struct TextureCopyView {
#[no_mangle]
pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer(
command_buffer_id: CommandBufferId,
src: BufferId,
src: BufferId,
src_offset: u32,
dst: BufferId,
dst_offset: u32,
@ -46,32 +43,28 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer(
let cmb = &mut cmb_guard[command_buffer_id];
let buffer_guard = HUB.buffers.read();
let (src_buffer, src_usage) = cmb.trackers.buffers
.get_with_replaced_usage(
&*buffer_guard,
src,
BufferUsageFlags::TRANSFER_SRC,
)
let (src_buffer, src_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(&*buffer_guard, src, BufferUsageFlags::TRANSFER_SRC)
.unwrap();
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ,
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ,
target: &src_buffer.raw,
families: None,
range: None .. None,
range: None..None,
});
let (dst_buffer, dst_usage) = cmb.trackers.buffers
.get_with_replaced_usage(
&*buffer_guard,
dst,
BufferUsageFlags::TRANSFER_DST,
)
let (dst_buffer, dst_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(&*buffer_guard, dst, BufferUsageFlags::TRANSFER_DST)
.unwrap();
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE,
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE,
target: &dst_buffer.raw,
families: None,
range: None .. None,
range: None..None,
});
let region = hal::command::BufferCopy {
@ -82,15 +75,11 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_buffer(
let cmb_raw = cmb.raw.last_mut().unwrap();
unsafe {
cmb_raw.pipeline_barrier(
all_buffer_stages() .. all_buffer_stages(),
all_buffer_stages()..all_buffer_stages(),
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
cmb_raw.copy_buffer(
&src_buffer.raw,
&dst_buffer.raw,
iter::once(region),
);
cmb_raw.copy_buffer(&src_buffer.raw, &dst_buffer.raw, iter::once(region));
}
}
@ -106,7 +95,9 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let buffer_guard = HUB.buffers.read();
let texture_guard = HUB.textures.read();
let (src_buffer, src_usage) = cmb.trackers.buffers
let (src_buffer, src_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(
&*buffer_guard,
source.buffer,
@ -114,13 +105,15 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
)
.unwrap();
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_READ,
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_READ,
target: &src_buffer.raw,
families: None,
range: None .. None,
range: None..None,
});
let (dst_texture, dst_usage) = cmb.trackers.textures
let (dst_texture, dst_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
destination.texture,
@ -130,7 +123,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let aspects = dst_texture.full_range.aspects;
let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects);
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects) .. dst_texture_state,
states: conv::map_texture_state(old, aspects)..dst_texture_state,
target: &dst_texture.raw,
families: None,
range: dst_texture.full_range.clone(),
@ -145,7 +138,9 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
}
let bytes_per_texel = conv::map_texture_format(dst_texture.format)
.surface_desc().bits as u32 / BITS_PER_BYTE;
.surface_desc()
.bits as u32
/ BITS_PER_BYTE;
let buffer_width = source.row_pitch / bytes_per_texel;
assert_eq!(source.row_pitch % bytes_per_texel, 0);
let region = hal::command::BufferImageCopy {
@ -155,7 +150,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
image_layers: hal::image::SubresourceLayers {
aspects, //TODO
level: destination.level as hal::image::Level,
layers: destination.slice as u16 .. destination.slice as u16 + 1,
layers: destination.slice as u16..destination.slice as u16 + 1,
},
image_offset: conv::map_origin(destination.origin),
image_extent: conv::map_extent(copy_size),
@ -164,7 +159,7 @@ pub extern "C" fn wgpu_command_buffer_copy_buffer_to_texture(
let stages = all_buffer_stages() | all_image_stages();
unsafe {
cmb_raw.pipeline_barrier(
stages .. stages,
stages..stages,
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
@ -189,7 +184,9 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let buffer_guard = HUB.buffers.read();
let texture_guard = HUB.textures.read();
let (src_texture, src_usage) = cmb.trackers.textures
let (src_texture, src_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
source.texture,
@ -199,7 +196,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let aspects = src_texture.full_range.aspects;
let src_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_SRC, aspects);
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects) .. src_texture_state,
states: conv::map_texture_state(old, aspects)..src_texture_state,
target: &src_texture.raw,
families: None,
range: src_texture.full_range.clone(),
@ -210,7 +207,9 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
TexturePlacement::Memory(_) => (),
}
let (dst_buffer, dst_usage) = cmb.trackers.buffers
let (dst_buffer, dst_usage) = cmb
.trackers
.buffers
.get_with_replaced_usage(
&*buffer_guard,
destination.buffer,
@ -218,14 +217,16 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
)
.unwrap();
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Buffer {
states: conv::map_buffer_state(old) .. hal::buffer::Access::TRANSFER_WRITE,
states: conv::map_buffer_state(old)..hal::buffer::Access::TRANSFER_WRITE,
target: &dst_buffer.raw,
families: None,
range: None .. None,
range: None..None,
});
let bytes_per_texel = conv::map_texture_format(src_texture.format)
.surface_desc().bits as u32 / BITS_PER_BYTE;
.surface_desc()
.bits as u32
/ BITS_PER_BYTE;
let buffer_width = destination.row_pitch / bytes_per_texel;
assert_eq!(destination.row_pitch % bytes_per_texel, 0);
let region = hal::command::BufferImageCopy {
@ -235,7 +236,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
image_layers: hal::image::SubresourceLayers {
aspects, //TODO
level: source.level as hal::image::Level,
layers: source.slice as u16 .. source.slice as u16 + 1,
layers: source.slice as u16..source.slice as u16 + 1,
},
image_offset: conv::map_origin(source.origin),
image_extent: conv::map_extent(copy_size),
@ -244,7 +245,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_buffer(
let stages = all_buffer_stages() | all_image_stages();
unsafe {
cmb_raw.pipeline_barrier(
stages .. stages,
stages..stages,
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);
@ -268,14 +269,18 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let cmb = &mut cmb_guard[command_buffer_id];
let texture_guard = HUB.textures.read();
let (src_texture, src_usage) = cmb.trackers.textures
let (src_texture, src_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
source.texture,
TextureUsageFlags::TRANSFER_SRC,
)
.unwrap();
let (dst_texture, dst_usage) = cmb.trackers.textures
let (dst_texture, dst_usage) = cmb
.trackers
.textures
.get_with_replaced_usage(
&*texture_guard,
destination.texture,
@ -288,13 +293,13 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let dst_texture_state = conv::map_texture_state(TextureUsageFlags::TRANSFER_DST, aspects);
let src_barrier = src_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects) .. src_texture_state,
states: conv::map_texture_state(old, aspects)..src_texture_state,
target: &src_texture.raw,
families: None,
range: src_texture.full_range.clone(),
});
let dst_barrier = dst_usage.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, aspects) .. dst_texture_state,
states: conv::map_texture_state(old, aspects)..dst_texture_state,
target: &dst_texture.raw,
families: None,
range: dst_texture.full_range.clone(),
@ -312,13 +317,13 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
src_subresource: hal::image::SubresourceLayers {
aspects,
level: source.level as hal::image::Level,
layers: source.slice as u16 .. source.slice as u16 + 1,
layers: source.slice as u16..source.slice as u16 + 1,
},
src_offset: conv::map_origin(source.origin),
dst_subresource: hal::image::SubresourceLayers {
aspects,
level: destination.level as hal::image::Level,
layers: destination.slice as u16 .. destination.slice as u16 + 1,
layers: destination.slice as u16..destination.slice as u16 + 1,
},
dst_offset: conv::map_origin(destination.origin),
extent: conv::map_extent(copy_size),
@ -326,7 +331,7 @@ pub extern "C" fn wgpu_command_buffer_copy_texture_to_texture(
let cmb_raw = cmb.raw.last_mut().unwrap();
unsafe {
cmb_raw.pipeline_barrier(
all_image_stages() .. all_image_stages(),
all_image_stages()..all_image_stages(),
hal::memory::Dependencies::empty(),
src_barrier.into_iter().chain(dst_barrier),
);

View File

@ -1,15 +1,11 @@
use crate::{
binding_model, command, pipeline, resource, Color,
Extent3d, Origin3d,
};
use crate::{binding_model, command, pipeline, resource, Color, Extent3d, Origin3d};
pub fn map_buffer_usage(
usage: resource::BufferUsageFlags,
) -> (hal::buffer::Usage, hal::memory::Properties) {
use crate::resource::BufferUsageFlags as W;
use hal::buffer::Usage as U;
use hal::memory::Properties as P;
use crate::resource::BufferUsageFlags as W;
let mut hal_memory = P::empty();
if usage.contains(W::MAP_READ) {
@ -46,8 +42,8 @@ pub fn map_texture_usage(
usage: resource::TextureUsageFlags,
aspects: hal::format::Aspects,
) -> hal::image::Usage {
use hal::image::Usage as U;
use crate::resource::TextureUsageFlags as W;
use hal::image::Usage as U;
let mut value = U::empty();
if usage.contains(W::TRANSFER_SRC) {
@ -121,8 +117,8 @@ pub fn map_extent(extent: Extent3d) -> hal::image::Extent {
}
pub fn map_primitive_topology(primitive_topology: pipeline::PrimitiveTopology) -> hal::Primitive {
use hal::Primitive as H;
use crate::pipeline::PrimitiveTopology::*;
use hal::Primitive as H;
match primitive_topology {
PointList => H::PointList,
LineList => H::LineList,
@ -136,8 +132,8 @@ pub fn map_color_state_descriptor(
desc: &pipeline::ColorStateDescriptor,
) -> hal::pso::ColorBlendDesc {
let color_mask = desc.write_mask;
let blend_state = if desc.color != pipeline::BlendDescriptor::REPLACE ||
desc.alpha != pipeline::BlendDescriptor::REPLACE
let blend_state = if desc.color != pipeline::BlendDescriptor::REPLACE
|| desc.alpha != pipeline::BlendDescriptor::REPLACE
{
hal::pso::BlendState::On {
color: map_blend_descriptor(&desc.color),
@ -150,8 +146,8 @@ pub fn map_color_state_descriptor(
}
fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMask {
use hal::pso::ColorMask as H;
use crate::pipeline::ColorWriteFlags as F;
use hal::pso::ColorMask as H;
let mut value = H::empty();
if flags.contains(F::RED) {
@ -170,8 +166,8 @@ fn map_color_write_flags(flags: pipeline::ColorWriteFlags) -> hal::pso::ColorMas
}
fn map_blend_descriptor(blend_desc: &pipeline::BlendDescriptor) -> hal::pso::BlendOp {
use hal::pso::BlendOp as H;
use crate::pipeline::BlendOperation::*;
use hal::pso::BlendOp as H;
match blend_desc.operation {
Add => H::Add {
src: map_blend_factor(blend_desc.src_factor),
@ -191,8 +187,8 @@ fn map_blend_descriptor(blend_desc: &pipeline::BlendDescriptor) -> hal::pso::Ble
}
fn map_blend_factor(blend_factor: pipeline::BlendFactor) -> hal::pso::Factor {
use hal::pso::Factor as H;
use crate::pipeline::BlendFactor::*;
use hal::pso::Factor as H;
match blend_factor {
Zero => H::Zero,
One => H::One,
@ -214,7 +210,9 @@ pub fn map_depth_stencil_state_descriptor(
desc: &pipeline::DepthStencilStateDescriptor,
) -> hal::pso::DepthStencilDesc {
hal::pso::DepthStencilDesc {
depth: if desc.depth_write_enabled || desc.depth_compare != resource::CompareFunction::Always {
depth: if desc.depth_write_enabled
|| desc.depth_compare != resource::CompareFunction::Always
{
hal::pso::DepthTest::On {
fun: map_compare_function(desc.depth_compare),
write: desc.depth_write_enabled,
@ -223,13 +221,22 @@ pub fn map_depth_stencil_state_descriptor(
hal::pso::DepthTest::Off
},
depth_bounds: false, // TODO
stencil: if desc.stencil_read_mask != !0 || desc.stencil_write_mask != !0 ||
desc.stencil_front != pipeline::StencilStateFaceDescriptor::IGNORE ||
desc.stencil_back != pipeline::StencilStateFaceDescriptor::IGNORE
stencil: if desc.stencil_read_mask != !0
|| desc.stencil_write_mask != !0
|| desc.stencil_front != pipeline::StencilStateFaceDescriptor::IGNORE
|| desc.stencil_back != pipeline::StencilStateFaceDescriptor::IGNORE
{
hal::pso::StencilTest::On {
front: map_stencil_face(&desc.stencil_front, desc.stencil_read_mask, desc.stencil_write_mask),
back: map_stencil_face(&desc.stencil_back, desc.stencil_read_mask, desc.stencil_write_mask),
front: map_stencil_face(
&desc.stencil_front,
desc.stencil_read_mask,
desc.stencil_write_mask,
),
back: map_stencil_face(
&desc.stencil_back,
desc.stencil_read_mask,
desc.stencil_write_mask,
),
}
} else {
hal::pso::StencilTest::Off
@ -254,8 +261,8 @@ fn map_stencil_face(
}
pub fn map_compare_function(compare_function: resource::CompareFunction) -> hal::pso::Comparison {
use hal::pso::Comparison as H;
use crate::resource::CompareFunction::*;
use hal::pso::Comparison as H;
match compare_function {
Never => H::Never,
Less => H::Less,
@ -269,8 +276,8 @@ pub fn map_compare_function(compare_function: resource::CompareFunction) -> hal:
}
fn map_stencil_operation(stencil_operation: pipeline::StencilOperation) -> hal::pso::StencilOp {
use hal::pso::StencilOp as H;
use crate::pipeline::StencilOperation::*;
use hal::pso::StencilOp as H;
match stencil_operation {
Keep => H::Keep,
Zero => H::Zero,
@ -284,8 +291,8 @@ fn map_stencil_operation(stencil_operation: pipeline::StencilOperation) -> hal::
}
pub fn map_texture_format(texture_format: resource::TextureFormat) -> hal::format::Format {
use hal::format::Format as H;
use crate::resource::TextureFormat::*;
use hal::format::Format as H;
match texture_format {
// Normal 8 bit formats
R8Unorm => H::R8Unorm,
@ -355,8 +362,8 @@ pub fn map_texture_format(texture_format: resource::TextureFormat) -> hal::forma
}
pub fn map_vertex_format(vertex_format: pipeline::VertexFormat) -> hal::format::Format {
use hal::format::Format as H;
use crate::pipeline::VertexFormat::*;
use hal::format::Format as H;
match vertex_format {
Uchar => H::R8Uint,
Uchar2 => H::Rg8Uint,
@ -379,7 +386,7 @@ pub fn map_vertex_format(vertex_format: pipeline::VertexFormat) -> hal::format::
Ushort2 => H::Rg16Uint,
Ushort3 => H::Rgb16Uint,
Ushort4 => H::Rgba16Uint,
Short => H::R16Int,
Short => H::R16Int,
Short2 => H::Rg16Int,
Short3 => H::Rgb16Int,
Short4 => H::Rgba16Int,
@ -417,11 +424,15 @@ fn checked_u32_as_u16(value: u32) -> u16 {
pub fn map_texture_dimension_size(
dimension: resource::TextureDimension,
Extent3d { width, height, depth }: Extent3d,
Extent3d {
width,
height,
depth,
}: Extent3d,
array_size: u32,
) -> hal::image::Kind {
use hal::image::Kind as H;
use crate::resource::TextureDimension::*;
use hal::image::Kind as H;
match dimension {
D1 => {
assert_eq!(height, 1);
@ -442,8 +453,8 @@ pub fn map_texture_dimension_size(
pub fn map_texture_view_dimension(
dimension: resource::TextureViewDimension,
) -> hal::image::ViewKind {
use hal::image::ViewKind as H;
use crate::resource::TextureViewDimension::*;
use hal::image::ViewKind as H;
match dimension {
D1 => H::D1,
D2 => H::D2,
@ -455,8 +466,8 @@ pub fn map_texture_view_dimension(
}
pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::format::Aspects {
use hal::format::Aspects;
use crate::resource::TextureAspectFlags as Taf;
use hal::format::Aspects;
let mut flags = Aspects::empty();
if aspect.contains(Taf::COLOR) {
@ -472,8 +483,8 @@ pub fn map_texture_aspect_flags(aspect: resource::TextureAspectFlags) -> hal::fo
}
pub fn map_buffer_state(usage: resource::BufferUsageFlags) -> hal::buffer::State {
use hal::buffer::Access as A;
use crate::resource::BufferUsageFlags as W;
use hal::buffer::Access as A;
let mut access = A::empty();
if usage.contains(W::TRANSFER_SRC) {
@ -502,8 +513,8 @@ pub fn map_texture_state(
usage: resource::TextureUsageFlags,
aspects: hal::format::Aspects,
) -> hal::image::State {
use hal::image::{Access as A, Layout as L};
use crate::resource::TextureUsageFlags as W;
use hal::image::{Access as A, Layout as L};
let is_color = aspects.contains(hal::format::Aspects::COLOR);
let layout = match usage {
@ -568,8 +579,8 @@ pub fn map_filter(filter: resource::FilterMode) -> hal::image::Filter {
}
pub fn map_wrap(address: resource::AddressMode) -> hal::image::WrapMode {
use hal::image::WrapMode as W;
use crate::resource::AddressMode as Am;
use hal::image::WrapMode as W;
match address {
Am::ClampToEdge => W::Clamp,
Am::Repeat => W::Tile,
@ -579,7 +590,7 @@ pub fn map_wrap(address: resource::AddressMode) -> hal::image::WrapMode {
}
pub fn map_rasterization_state_descriptor(
desc: &pipeline::RasterizationStateDescriptor
desc: &pipeline::RasterizationStateDescriptor,
) -> hal::pso::Rasterizer {
hal::pso::Rasterizer {
depth_clamping: false,
@ -593,7 +604,10 @@ pub fn map_rasterization_state_descriptor(
pipeline::FrontFace::Ccw => hal::pso::FrontFace::CounterClockwise,
pipeline::FrontFace::Cw => hal::pso::FrontFace::Clockwise,
},
depth_bias: if desc.depth_bias != 0 || desc.depth_bias_slope_scale != 0.0 || desc.depth_bias_clamp != 0.0 {
depth_bias: if desc.depth_bias != 0
|| desc.depth_bias_slope_scale != 0.0
|| desc.depth_bias_clamp != 0.0
{
Some(hal::pso::State::Static(hal::pso::DepthBias {
const_factor: desc.depth_bias as f32,
slope_factor: desc.depth_bias_slope_scale,

File diff suppressed because it is too large Load Diff

View File

@ -1,24 +1,21 @@
use crate::{
AdapterHandle, BindGroupLayoutHandle, BindGroupHandle,
CommandBufferHandle, DeviceHandle, InstanceHandle,
RenderPassHandle, ComputePassHandle,
PipelineLayoutHandle, RenderPipelineHandle, ComputePipelineHandle, ShaderModuleHandle,
BufferHandle, SamplerHandle, TextureHandle, TextureViewHandle,
SurfaceHandle,
AdapterHandle, BindGroupHandle, BindGroupLayoutHandle, BufferHandle, CommandBufferHandle,
ComputePassHandle, ComputePipelineHandle, DeviceHandle, InstanceHandle, PipelineLayoutHandle,
RenderPassHandle, RenderPipelineHandle, SamplerHandle, ShaderModuleHandle, SurfaceHandle,
TextureHandle, TextureViewHandle,
};
use lazy_static::lazy_static;
use parking_lot::RwLock;
#[cfg(feature = "local")]
use parking_lot::Mutex;
use parking_lot::RwLock;
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use vec_map::VecMap;
use std::ops;
use std::sync::Arc;
pub(crate) type Index = u32;
pub(crate) type Epoch = u32;
#[derive(Clone, Copy, Debug, Hash, PartialEq)]
@ -55,9 +52,7 @@ pub struct IdentityManager {
impl IdentityManager {
pub fn alloc(&mut self) -> Id {
match self.free.pop() {
Some(index) => {
Id(index, self.epochs[index as usize])
}
Some(index) => Id(index, self.epochs[index as usize]),
None => {
let id = Id(self.epochs.len() as Index, 1);
self.epochs.push(id.1);
@ -104,7 +99,7 @@ impl<T> Storage<T> {
pub fn contains(&self, id: Id) -> bool {
match self.map.get(id.0 as usize) {
Some(&(_, epoch)) if epoch == id.1 => true,
_ => false
_ => false,
}
}
}
@ -120,9 +115,7 @@ impl<T> Default for Registry<T> {
Registry {
#[cfg(feature = "local")]
identity: Mutex::new(IdentityManager::default()),
data: RwLock::new(Storage {
map: VecMap::new(),
}),
data: RwLock::new(Storage { map: VecMap::new() }),
}
}
}

View File

@ -1,17 +1,13 @@
use crate::hub::HUB;
use crate::{
AdapterHandle, DeviceHandle, SurfaceHandle,
AdapterId, InstanceId,
};
use crate::{AdapterHandle, AdapterId, DeviceHandle, InstanceId, SurfaceHandle};
#[cfg(feature = "local")]
use crate::{DeviceId, SurfaceId};
#[cfg(feature = "remote")]
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use hal::{self, Instance as _Instance, PhysicalDevice as _PhysicalDevice};
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
#[cfg_attr(feature = "remote", derive(Serialize, Deserialize))]
@ -56,10 +52,7 @@ pub extern "C" fn wgpu_instance_create_surface_from_winit(
instance_id: InstanceId,
window: &winit::Window,
) -> SurfaceId {
let raw = HUB.instances
.read()
[instance_id]
.create_surface(window);
let raw = HUB.instances.read()[instance_id].create_surface(window);
let surface = SurfaceHandle::new(raw);
HUB.surfaces.register_local(surface)
}
@ -74,11 +67,7 @@ pub fn instance_create_surface_from_xlib(
unimplemented!();
#[cfg(all(unix, feature = "gfx-backend-vulkan"))]
SurfaceHandle::new(HUB.instances
.read()
[instance_id]
.create_surface_from_xlib(display, window)
)
SurfaceHandle::new(HUB.instances.read()[instance_id].create_surface_from_xlib(display, window))
}
#[cfg(feature = "local")]
@ -101,11 +90,7 @@ pub fn instance_create_surface_from_macos_layer(
unimplemented!();
#[cfg(feature = "gfx-backend-metal")]
SurfaceHandle::new(HUB.instances
.read()
[instance_id]
.create_surface_from_layer(layer as *mut _)
)
SurfaceHandle::new(HUB.instances.read()[instance_id].create_surface_from_layer(layer as *mut _))
}
#[cfg(feature = "local")]
@ -128,16 +113,10 @@ pub fn instance_create_surface_from_windows_hwnd(
let raw = unimplemented!();
#[cfg(any(feature = "gfx-backend-dx11", feature = "gfx-backend-dx12"))]
let raw = HUB.instances
.read()
[instance_id]
.create_surface_from_hwnd(hwnd);
let raw = HUB.instances.read()[instance_id].create_surface_from_hwnd(hwnd);
#[cfg(all(target_os = "windows", feature = "gfx-backend-vulkan"))]
let raw = HUB.instances
.read()
[instance_id]
.create_surface_from_hwnd(hinstance, hwnd);
let raw = HUB.instances.read()[instance_id].create_surface_from_hwnd(hinstance, hwnd);
#[cfg_attr(not(target_os = "windows"), allow(unreachable_code))]
SurfaceHandle::new(raw)
@ -154,10 +133,7 @@ pub extern "C" fn wgpu_instance_create_surface_from_windows_hwnd(
HUB.surfaces.register_local(surface)
}
pub fn instance_get_adapter(
instance_id: InstanceId,
desc: &AdapterDescriptor,
) -> AdapterHandle {
pub fn instance_get_adapter(instance_id: InstanceId, desc: &AdapterDescriptor) -> AdapterHandle {
let instance_guard = HUB.instances.read();
let instance = &instance_guard[instance_id];
let (mut low, mut high, mut other) = (None, None, None);
@ -186,10 +162,7 @@ pub extern "C" fn wgpu_instance_get_adapter(
HUB.adapters.register_local(adapter)
}
pub fn adapter_create_device(
adapter_id: AdapterId,
_desc: &DeviceDescriptor,
) -> DeviceHandle {
pub fn adapter_create_device(adapter_id: AdapterId, _desc: &DeviceDescriptor) -> DeviceHandle {
let adapter_guard = HUB.adapters.read();
let adapter = &adapter_guard[adapter_id];
let (raw, queue_group) = adapter.open_with::<_, hal::General>(1, |_qf| true).unwrap();

View File

@ -34,12 +34,12 @@ mod track;
pub use self::binding_model::*;
pub use self::command::*;
pub use self::device::*;
#[cfg(feature = "remote")]
pub use self::hub::{Id, IdentityManager, Registry, HUB};
pub use self::instance::*;
pub use self::pipeline::*;
pub use self::resource::*;
pub use self::swap_chain::*;
#[cfg(feature = "remote")]
pub use self::hub::{HUB, Id, IdentityManager, Registry};
use std::ptr;
use std::sync::atomic::{AtomicUsize, Ordering};
@ -53,7 +53,6 @@ pub struct RefCount(ptr::NonNull<AtomicUsize>);
unsafe impl Send for RefCount {}
unsafe impl Sync for RefCount {}
impl RefCount {
const MAX: usize = 1 << 24;
@ -99,7 +98,6 @@ struct Stored<T> {
ref_count: RefCount,
}
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct Color {

View File

@ -1,8 +1,6 @@
use crate::device::RenderPassContext;
use crate::resource;
use crate::{
ByteArray, PipelineLayoutId, ShaderModuleId,
};
use crate::{ByteArray, PipelineLayoutId, ShaderModuleId};
use bitflags::bitflags;
@ -147,7 +145,7 @@ pub enum VertexFormat {
Ushort2 = 18,
Ushort3 = 19,
Ushort4 = 20,
Short = 21,
Short = 21,
Short2 = 22,
Short3 = 23,
Short4 = 24,
@ -175,7 +173,7 @@ pub enum VertexFormat {
Int2 = 46,
Int3 = 47,
Int4 = 48,
}
}
#[repr(C)]
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]

View File

@ -1,9 +1,8 @@
use crate::{
Extent3d, LifeGuard, RefCount, Stored,
DeviceId, TextureId,
BufferMapReadCallback, BufferMapWriteCallback,
};
use crate::swap_chain::{SwapChainLink, SwapImageEpoch};
use crate::{
BufferMapReadCallback, BufferMapWriteCallback, DeviceId, Extent3d, LifeGuard, RefCount, Stored,
TextureId,
};
use bitflags::bitflags;
use hal;
@ -176,8 +175,9 @@ impl<B: hal::Backend> TexturePlacement<B> {
pub fn as_swap_chain(&self) -> &SwapChainLink<Mutex<SwapImageEpoch>> {
match *self {
TexturePlacement::SwapChain(ref link) => link,
TexturePlacement::Memory(_) |
TexturePlacement::Void => panic!("Expected swap chain link!"),
TexturePlacement::Memory(_) | TexturePlacement::Void => {
panic!("Expected swap chain link!")
}
}
}
}

View File

@ -1,11 +1,8 @@
use crate::{
Extent3d, Stored,
DeviceId, SwapChainId, TextureId, TextureViewId,
};
use crate::{conv, resource};
use crate::device::all_image_stages;
use crate::hub::HUB;
use crate::track::{TrackPermit};
use crate::track::TrackPermit;
use crate::{conv, resource};
use crate::{DeviceId, Extent3d, Stored, SwapChainId, TextureId, TextureViewId};
use hal;
use hal::{Device as _Device, Swapchain as _Swapchain};
@ -14,7 +11,6 @@ use parking_lot::Mutex;
use std::{iter, mem};
pub type SwapImageEpoch = u16;
pub(crate) struct SwapChainLink<E> {
@ -96,20 +92,17 @@ pub struct SwapChainOutput {
}
#[no_mangle]
pub extern "C" fn wgpu_swap_chain_get_next_texture(
swap_chain_id: SwapChainId,
) -> SwapChainOutput {
pub extern "C" fn wgpu_swap_chain_get_next_texture(swap_chain_id: SwapChainId) -> SwapChainOutput {
let (image_index, device_id, descriptor) = {
let mut surface_guard = HUB.surfaces.write();
let swap_chain = surface_guard
[swap_chain_id].swap_chain
.as_mut()
.unwrap();
let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap();
let sync = hal::FrameSync::Semaphore(&swap_chain.sem_available);
let result = unsafe {
swap_chain.raw.acquire_image(!0, sync)
};
(result.ok(), swap_chain.device_id.value, swap_chain.desc.clone())
let result = unsafe { swap_chain.raw.acquire_image(!0, sync) };
(
result.ok(),
swap_chain.device_id.value,
swap_chain.desc.clone(),
)
};
#[cfg(not(feature = "local"))]
@ -125,10 +118,7 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(
}
let mut surface_guard = HUB.surfaces.write();
let swap_chain = surface_guard
[swap_chain_id].swap_chain
.as_mut()
.unwrap();
let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap();
let image_index = match image_index {
Some(index) => index,
@ -141,8 +131,11 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(
let device_guard = HUB.devices.read();
let device = &device_guard[device_id];
assert_ne!(swap_chain.acquired.len(), swap_chain.acquired.capacity(),
"Unable to acquire any more swap chain images before presenting");
assert_ne!(
swap_chain.acquired.len(),
swap_chain.acquired.capacity(),
"Unable to acquire any more swap chain images before presenting"
);
swap_chain.acquired.push(image_index);
let frame = &mut swap_chain.frames[image_index as usize];
@ -151,7 +144,10 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(
}
mem::swap(&mut frame.sem_available, &mut swap_chain.sem_available);
HUB.textures.read()[frame.texture_id.value].placement.as_swap_chain().bump_epoch();
HUB.textures.read()[frame.texture_id.value]
.placement
.as_swap_chain()
.bump_epoch();
SwapChainOutput {
texture_id: frame.texture_id.value,
@ -160,14 +156,9 @@ pub extern "C" fn wgpu_swap_chain_get_next_texture(
}
#[no_mangle]
pub extern "C" fn wgpu_swap_chain_present(
swap_chain_id: SwapChainId,
) {
pub extern "C" fn wgpu_swap_chain_present(swap_chain_id: SwapChainId) {
let mut surface_guard = HUB.surfaces.write();
let swap_chain = surface_guard
[swap_chain_id].swap_chain
.as_mut()
.unwrap();
let swap_chain = surface_guard[swap_chain_id].swap_chain.as_mut().unwrap();
let image_index = swap_chain.acquired.remove(0);
let frame = &mut swap_chain.frames[image_index as usize];
@ -182,7 +173,8 @@ pub extern "C" fn wgpu_swap_chain_present(
//TODO: support for swapchain being sampled or read by the shader?
trace!("transit {:?} to present", frame.texture_id.value);
let barrier = device.trackers
let barrier = device
.trackers
.lock()
.textures
.transit(
@ -194,8 +186,11 @@ pub extern "C" fn wgpu_swap_chain_present(
.unwrap()
.into_source()
.map(|old| hal::memory::Barrier::Image {
states: conv::map_texture_state(old, hal::format::Aspects::COLOR) ..
(hal::image::Access::COLOR_ATTACHMENT_WRITE, hal::image::Layout::Present),
states: conv::map_texture_state(old, hal::format::Aspects::COLOR)
..(
hal::image::Access::COLOR_ATTACHMENT_WRITE,
hal::image::Layout::Present,
),
target: &texture.raw,
families: None,
range: texture.full_range.clone(),
@ -204,7 +199,7 @@ pub extern "C" fn wgpu_swap_chain_present(
let err = unsafe {
frame.comb.begin(false);
frame.comb.pipeline_barrier(
all_image_stages() .. hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT,
all_image_stages()..hal::pso::PipelineStage::COLOR_ATTACHMENT_OUTPUT,
hal::memory::Dependencies::empty(),
barrier,
);

View File

@ -1,9 +1,6 @@
use crate::hub::{NewId, Id, Index, Epoch, Storage};
use crate::hub::{Epoch, Id, Index, NewId, Storage};
use crate::resource::{BufferUsageFlags, TextureUsageFlags};
use crate::{
RefCount,
BufferId, TextureId, TextureViewId,
};
use crate::{BufferId, RefCount, TextureId, TextureViewId};
use bitflags::bitflags;
use hal::backend::FastHashMap;
@ -14,7 +11,6 @@ use std::marker::PhantomData;
use std::mem;
use std::ops::{BitOr, Range};
#[derive(Clone, Debug, PartialEq)]
#[allow(unused)]
pub enum Tracktion<T> {
@ -27,10 +23,8 @@ pub enum Tracktion<T> {
impl<T> Tracktion<T> {
pub fn into_source(self) -> Option<T> {
match self {
Tracktion::Init |
Tracktion::Keep => None,
Tracktion::Extend { old } |
Tracktion::Replace { old } => Some(old),
Tracktion::Init | Tracktion::Keep => None,
Tracktion::Extend { old } | Tracktion::Replace { old } => Some(old),
}
}
}
@ -125,15 +119,9 @@ impl TrackerSet {
}
pub fn consume_by_extend(&mut self, other: &Self) {
self.buffers
.consume_by_extend(&other.buffers)
.unwrap();
self.textures
.consume_by_extend(&other.textures)
.unwrap();
self.views
.consume_by_extend(&other.views)
.unwrap();
self.buffers.consume_by_extend(&other.buffers).unwrap();
self.textures.consume_by_extend(&other.textures).unwrap();
self.views.consume_by_extend(&other.views).unwrap();
}
}
@ -224,8 +212,10 @@ impl<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I
other: &'a Self,
stitch: Stitch,
) -> impl 'a + Iterator<Item = (I, Range<U>)> {
other.map.iter().flat_map(move |(&index, new)| {
match self.map.entry(index) {
other
.map
.iter()
.flat_map(move |(&index, new)| match self.map.entry(index) {
Entry::Vacant(e) => {
e.insert(new.clone());
None
@ -240,11 +230,10 @@ impl<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I
Stitch::Init => new.init,
Stitch::Last => new.last,
};
Some((I::new(index, new.epoch), old .. state))
Some((I::new(index, new.epoch), old..state))
}
}
}
})
})
}
/// Consume another tacker, adding it's transitions to `self`.
@ -262,7 +251,7 @@ impl<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I
let extended = old | new.last;
if extended.is_exclusive() {
let id = I::new(index, new.epoch);
return Err((id, old .. new.last));
return Err((id, old..new.last));
}
e.get_mut().last = extended;
}
@ -274,7 +263,9 @@ impl<I: NewId, U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<I
/// Return an iterator over used resources keys.
pub fn used<'a>(&'a self) -> impl 'a + Iterator<Item = I> {
self.map.iter().map(|(&index, track)| I::new(index, track.epoch))
self.map
.iter()
.map(|(&index, track)| I::new(index, track.epoch))
}
}
@ -310,11 +301,15 @@ impl<U: Copy + GenericUsage + BitOr<Output = U> + PartialEq> Tracker<Id, U> {
) -> Result<(&'a T, Option<U>), U> {
let item = &storage[id];
self.transit(id, item.borrow(), usage, TrackPermit::REPLACE)
.map(|tracktion| (item, match tracktion {
Tracktion::Init |
Tracktion::Keep => None,
Tracktion::Extend { ..} => unreachable!(),
Tracktion::Replace { old } => Some(old),
}))
.map(|tracktion| {
(
item,
match tracktion {
Tracktion::Init | Tracktion::Keep => None,
Tracktion::Extend { .. } => unreachable!(),
Tracktion::Replace { old } => Some(old),
},
)
})
}
}

View File

@ -1,10 +1,9 @@
use ipc_channel::ipc::IpcSender;
use parking_lot::Mutex;
use serde::{Serialize, Deserialize};
use serde::{Deserialize, Serialize};
use wgpu_native as wgn;
#[derive(Serialize, Deserialize)]
pub enum InstanceMessage {
InstanceGetAdapter(wgn::InstanceId, wgn::AdapterDescriptor, wgn::AdapterId),
@ -41,7 +40,6 @@ impl Client {
}
}
#[no_mangle]
pub extern "C" fn wgpu_instance_get_adapter(
client: &Client,
@ -49,7 +47,11 @@ pub extern "C" fn wgpu_instance_get_adapter(
desc: &wgn::AdapterDescriptor,
) -> wgn::AdapterId {
let id = client.identity.lock().adapters.alloc();
let msg = GlobalMessage::Instance(InstanceMessage::InstanceGetAdapter(instance_id, desc.clone(), id));
let msg = GlobalMessage::Instance(InstanceMessage::InstanceGetAdapter(
instance_id,
desc.clone(),
id,
));
client.channel.send(msg).unwrap();
id
}
@ -61,7 +63,11 @@ pub extern "C" fn wgpu_adapter_create_device(
desc: &wgn::DeviceDescriptor,
) -> wgn::DeviceId {
let id = client.identity.lock().devices.alloc();
let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice(adapter_id, desc.clone(), id));
let msg = GlobalMessage::Instance(InstanceMessage::AdapterCreateDevice(
adapter_id,
desc.clone(),
id,
));
client.channel.send(msg).unwrap();
id
}

View File

@ -10,22 +10,19 @@ use std::slice;
pub use wgn::winit;
pub use wgn::{
AdapterDescriptor, BindGroupLayoutBinding, BindingType,
BlendDescriptor, BlendOperation, BlendFactor, BufferMapAsyncStatus, ColorWriteFlags,
RasterizationStateDescriptor, CullMode, FrontFace,
BufferDescriptor, BufferUsageFlags,
IndexFormat, InputStepMode, ShaderAttributeIndex, VertexAttributeDescriptor, VertexFormat,
Color, CommandEncoderDescriptor,
ColorStateDescriptor, DepthStencilStateDescriptor, StencilStateFaceDescriptor, StencilOperation,
DeviceDescriptor, Extensions, Extent3d, LoadOp, Origin3d, PowerPreference, PrimitiveTopology,
RenderPassColorAttachmentDescriptor, RenderPassDepthStencilAttachmentDescriptor,
ShaderModuleDescriptor, ShaderStageFlags, StoreOp, SwapChainDescriptor,
SamplerDescriptor, AddressMode, FilterMode, BorderColor, CompareFunction,
TextureDescriptor, TextureDimension, TextureFormat, TextureUsageFlags,
TextureViewDescriptor, TextureViewDimension, TextureAspectFlags,
AdapterDescriptor, AddressMode, BindGroupLayoutBinding, BindingType, BlendDescriptor,
BlendFactor, BlendOperation, BorderColor, BufferDescriptor, BufferMapAsyncStatus,
BufferUsageFlags, Color, ColorStateDescriptor, ColorWriteFlags, CommandEncoderDescriptor,
CompareFunction, CullMode, DepthStencilStateDescriptor, DeviceDescriptor, Extensions, Extent3d,
FilterMode, FrontFace, IndexFormat, InputStepMode, LoadOp, Origin3d, PowerPreference,
PrimitiveTopology, RasterizationStateDescriptor, RenderPassColorAttachmentDescriptor,
RenderPassDepthStencilAttachmentDescriptor, SamplerDescriptor, ShaderAttributeIndex,
ShaderModuleDescriptor, ShaderStageFlags, StencilOperation, StencilStateFaceDescriptor,
StoreOp, SwapChainDescriptor, TextureAspectFlags, TextureDescriptor, TextureDimension,
TextureFormat, TextureUsageFlags, TextureViewDescriptor, TextureViewDimension,
VertexAttributeDescriptor, VertexFormat,
};
//TODO: avoid heap allocating vectors during resource creation.
#[derive(Default)]
struct Temp {
@ -34,7 +31,6 @@ struct Temp {
command_buffers: Vec<wgn::CommandBufferId>,
}
pub struct Instance {
id: wgn::InstanceId,
}
@ -127,7 +123,6 @@ pub struct Queue<'a> {
temp: &'a mut Temp,
}
pub enum BindingResource<'a> {
Buffer {
buffer: &'a Buffer,
@ -239,7 +234,9 @@ pub struct CreateBufferMapped<'a, T> {
}
impl<'a, T> CreateBufferMapped<'a, T>
where T: Copy {
where
T: Copy,
{
pub fn fill_from_slice(self, slice: &[T]) -> Buffer {
self.data.copy_from_slice(slice);
self.finish()
@ -247,9 +244,7 @@ impl<'a, T> CreateBufferMapped<'a, T>
pub fn finish(self) -> Buffer {
wgn::wgpu_buffer_unmap(self.id);
Buffer {
id: self.id,
}
Buffer { id: self.id }
}
}
@ -414,7 +409,8 @@ impl Device {
primitive_topology: desc.primitive_topology,
color_states: temp_color_states.as_ptr(),
color_states_length: temp_color_states.len(),
depth_stencil_state: desc.depth_stencil_state
depth_stencil_state: desc
.depth_stencil_state
.as_ref()
.map_or(ptr::null(), |p| p as *const _),
vertex_buffer_state: wgn::VertexBufferStateDescriptor {
@ -451,22 +447,28 @@ impl Device {
}
}
pub fn create_buffer_mapped<'a, T>(&self, count: usize, usage: BufferUsageFlags) -> CreateBufferMapped<'a, T>
where T: 'static + Copy {
pub fn create_buffer_mapped<'a, T>(
&self,
count: usize,
usage: BufferUsageFlags,
) -> CreateBufferMapped<'a, T>
where
T: 'static + Copy,
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
let desc = BufferDescriptor{
let desc = BufferDescriptor {
size: type_size * count as u32,
usage,
};
let mut ptr : *mut u8 = std::ptr::null_mut();
let mut ptr: *mut u8 = std::ptr::null_mut();
let id = wgn::wgpu_device_create_buffer_mapped(self.id, &desc, &mut ptr as *mut *mut u8);
let data = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, count) };
CreateBufferMapped{id, data}
CreateBufferMapped { id, data }
}
pub fn create_texture(&self, desc: &TextureDescriptor) -> Texture {
@ -502,15 +504,19 @@ pub enum BufferMapAsyncResult<T> {
Error,
}
struct BufferMapReadAsyncUserData<T,F>
where F: FnOnce(BufferMapAsyncResult<&[T]>) {
struct BufferMapReadAsyncUserData<T, F>
where
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
size: u32,
callback: F,
phantom: std::marker::PhantomData<T>,
}
struct BufferMapWriteAsyncUserData<T, F>
where F: FnOnce(BufferMapAsyncResult<&mut [T]>) {
where
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
size: u32,
callback: F,
phantom: std::marker::PhantomData<T>,
@ -522,15 +528,29 @@ impl Buffer {
}
pub fn map_read_async<T, F>(&self, start: u32, size: u32, callback: F)
where T: 'static + Copy, F: FnOnce(BufferMapAsyncResult<&[T]>) {
where
T: 'static + Copy,
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
assert_eq!(size % type_size, 0);
extern "C" fn buffer_map_read_callback_wrapper<T, F>(status: wgn::BufferMapAsyncStatus, data: *const u8, userdata: *mut u8)
where F: FnOnce(BufferMapAsyncResult<&[T]>) {
let userdata = unsafe { Box::from_raw(userdata as *mut BufferMapReadAsyncUserData<T, F>) };
let data = unsafe { slice::from_raw_parts(data as *const T, userdata.size as usize / std::mem::size_of::<T>()) };
extern "C" fn buffer_map_read_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *const u8,
userdata: *mut u8,
) where
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
let userdata =
unsafe { Box::from_raw(userdata as *mut BufferMapReadAsyncUserData<T, F>) };
let data = unsafe {
slice::from_raw_parts(
data as *const T,
userdata.size as usize / std::mem::size_of::<T>(),
)
};
if let wgn::BufferMapAsyncStatus::Success = status {
(userdata.callback)(BufferMapAsyncResult::Success::<&[T]>(data));
} else {
@ -538,20 +558,44 @@ impl Buffer {
}
}
let userdata = Box::new(BufferMapReadAsyncUserData{size, callback, phantom: std::marker::PhantomData});
wgn::wgpu_buffer_map_read_async(self.id, start, size, buffer_map_read_callback_wrapper::<T, F>, Box::into_raw(userdata) as *mut u8);
let userdata = Box::new(BufferMapReadAsyncUserData {
size,
callback,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_read_async(
self.id,
start,
size,
buffer_map_read_callback_wrapper::<T, F>,
Box::into_raw(userdata) as *mut u8,
);
}
pub fn map_write_async<T, F>(&self, start: u32, size: u32, callback: F)
where T: 'static + Copy, F: FnOnce(BufferMapAsyncResult<&mut [T]>) {
where
T: 'static + Copy,
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
let type_size = std::mem::size_of::<T>() as u32;
assert_ne!(type_size, 0);
assert_eq!(size % type_size, 0);
extern "C" fn buffer_map_write_callback_wrapper<T, F>(status: wgn::BufferMapAsyncStatus, data: *mut u8, userdata: *mut u8)
where F: FnOnce(BufferMapAsyncResult<&mut [T]>) {
let userdata = unsafe { Box::from_raw(userdata as *mut BufferMapWriteAsyncUserData<T, F>) };
let data = unsafe { slice::from_raw_parts_mut(data as *mut T, userdata.size as usize / std::mem::size_of::<T>()) };
extern "C" fn buffer_map_write_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *mut u8,
userdata: *mut u8,
) where
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
let userdata =
unsafe { Box::from_raw(userdata as *mut BufferMapWriteAsyncUserData<T, F>) };
let data = unsafe {
slice::from_raw_parts_mut(
data as *mut T,
userdata.size as usize / std::mem::size_of::<T>(),
)
};
if let wgn::BufferMapAsyncStatus::Success = status {
(userdata.callback)(BufferMapAsyncResult::Success::<&mut [T]>(data));
} else {
@ -559,8 +603,18 @@ impl Buffer {
}
}
let userdata = Box::new(BufferMapWriteAsyncUserData{size, callback, phantom: std::marker::PhantomData});
wgn::wgpu_buffer_map_write_async(self.id, start, size, buffer_map_write_callback_wrapper::<T, F>, Box::into_raw(userdata) as *mut u8);
let userdata = Box::new(BufferMapWriteAsyncUserData {
size,
callback,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_write_async(
self.id,
start,
size,
buffer_map_write_callback_wrapper::<T, F>,
Box::into_raw(userdata) as *mut u8,
);
}
pub fn unmap(&self) {
@ -800,9 +854,9 @@ impl<'a> Drop for ComputePass<'a> {
impl<'a> Queue<'a> {
pub fn submit(&mut self, command_buffers: &[CommandBuffer]) {
self.temp.command_buffers.clear();
self.temp.command_buffers.extend(
command_buffers.iter().map(|cb| cb.id)
);
self.temp
.command_buffers
.extend(command_buffers.iter().map(|cb| cb.id));
wgn::wgpu_queue_submit(
self.id,