use arrayvec::ArrayVec;
use zerocopy::{AsBytes, FromBytes, LayoutVerified};
use std::convert::TryFrom;
use std::ffi::CString;
use std::ops::Range;
use std::ptr;
use std::slice;
use std::thread;
pub use wgn::{
AddressMode,
BlendDescriptor,
BlendFactor,
BlendOperation,
BufferAddress,
BufferDescriptor,
BufferMapAsyncStatus,
BufferUsage,
Color,
ColorStateDescriptor,
ColorWrite,
CommandEncoderDescriptor,
CommandBufferDescriptor,
CompareFunction,
CullMode,
DepthStencilStateDescriptor,
DeviceDescriptor,
Extensions,
Extent3d,
FilterMode,
FrontFace,
IndexFormat,
InputStepMode,
Limits,
LoadOp,
Origin3d,
PowerPreference,
PresentMode,
PrimitiveTopology,
RasterizationStateDescriptor,
RenderPassDepthStencilAttachmentDescriptor,
RequestAdapterOptions,
SamplerDescriptor,
ShaderLocation,
ShaderModuleDescriptor,
ShaderStage,
StencilOperation,
StencilStateFaceDescriptor,
StoreOp,
SwapChainDescriptor,
TextureAspect,
TextureDescriptor,
TextureDimension,
TextureFormat,
TextureUsage,
TextureViewDescriptor,
TextureViewDimension,
VertexAttributeDescriptor,
VertexFormat,
read_spirv,
};
#[cfg(feature = "gl")]
pub use wgn::glutin;
#[derive(Default)]
#[derive(Debug)]
struct Temp {
command_buffers: Vec<wgn::CommandBufferId>,
}
#[derive(Debug)]
pub struct Instance {
id: wgn::InstanceId,
}
#[derive(Debug)]
pub struct Adapter {
id: wgn::AdapterId,
}
#[derive(Debug)]
pub struct Device {
id: wgn::DeviceId,
temp: Temp,
}
#[derive(Debug)]
pub struct Buffer {
id: wgn::BufferId,
}
#[derive(Debug)]
pub struct Texture {
id: wgn::TextureId,
owned: bool,
}
#[derive(Debug)]
pub struct TextureView {
id: wgn::TextureViewId,
owned: bool,
}
#[derive(Debug)]
pub struct Sampler {
id: wgn::SamplerId,
}
#[derive(Debug)]
pub struct Surface {
id: wgn::SurfaceId,
}
#[derive(Debug)]
pub struct SwapChain {
id: wgn::SwapChainId,
}
#[derive(Debug)]
pub struct BindGroupLayout {
id: wgn::BindGroupLayoutId,
}
#[derive(Debug)]
pub struct BindGroup {
id: wgn::BindGroupId,
}
impl Drop for BindGroup {
fn drop(&mut self) {
wgn::wgpu_bind_group_destroy(self.id);
}
}
#[derive(Debug)]
pub struct ShaderModule {
id: wgn::ShaderModuleId,
}
#[derive(Debug)]
pub struct PipelineLayout {
id: wgn::PipelineLayoutId,
}
#[derive(Debug)]
pub struct RenderPipeline {
id: wgn::RenderPipelineId,
}
#[derive(Debug)]
pub struct ComputePipeline {
id: wgn::ComputePipelineId,
}
#[derive(Debug)]
pub struct CommandBuffer {
id: wgn::CommandBufferId,
}
#[derive(Debug)]
pub struct CommandEncoder {
id: wgn::CommandEncoderId,
}
#[derive(Debug)]
pub struct RenderPass<'a> {
id: wgn::RenderPassId,
_parent: &'a mut CommandEncoder,
}
#[derive(Debug)]
pub struct ComputePass<'a> {
id: wgn::ComputePassId,
_parent: &'a mut CommandEncoder,
}
#[derive(Debug)]
pub struct Queue<'a> {
id: wgn::QueueId,
temp: &'a mut Temp,
}
#[derive(Clone, Debug)]
pub enum BindingResource<'a> {
Buffer {
buffer: &'a Buffer,
range: Range<BufferAddress>,
},
Sampler(&'a Sampler),
TextureView(&'a TextureView),
}
#[derive(Clone, Debug)]
pub struct Binding<'a> {
pub binding: u32,
pub resource: BindingResource<'a>,
}
#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
pub enum BindingType {
UniformBuffer {
dynamic: bool,
},
StorageBuffer {
dynamic: bool,
readonly: bool,
},
Sampler,
SampledTexture {
multisampled: bool,
dimension: TextureViewDimension,
},
StorageTexture {
dimension: TextureViewDimension,
},
}
#[derive(Clone, Debug, Hash)]
pub struct BindGroupLayoutBinding {
pub binding: u32,
pub visibility: ShaderStage,
pub ty: BindingType,
}
#[derive(Clone, Debug)]
pub struct BindGroupLayoutDescriptor<'a> {
pub bindings: &'a [BindGroupLayoutBinding],
}
#[derive(Clone, Debug)]
pub struct BindGroupDescriptor<'a> {
pub layout: &'a BindGroupLayout,
pub bindings: &'a [Binding<'a>],
}
#[derive(Clone, Debug)]
pub struct PipelineLayoutDescriptor<'a> {
pub bind_group_layouts: &'a [&'a BindGroupLayout],
}
#[derive(Clone, Debug)]
pub struct ProgrammableStageDescriptor<'a> {
pub module: &'a ShaderModule,
pub entry_point: &'a str,
}
#[derive(Clone, Debug)]
pub struct VertexBufferDescriptor<'a> {
pub stride: BufferAddress,
pub step_mode: InputStepMode,
pub attributes: &'a [VertexAttributeDescriptor],
}
#[derive(Clone, Debug)]
pub struct RenderPipelineDescriptor<'a> {
pub layout: &'a PipelineLayout,
pub vertex_stage: ProgrammableStageDescriptor<'a>,
pub fragment_stage: Option<ProgrammableStageDescriptor<'a>>,
pub rasterization_state: Option<RasterizationStateDescriptor>,
pub primitive_topology: PrimitiveTopology,
pub color_states: &'a [ColorStateDescriptor],
pub depth_stencil_state: Option<DepthStencilStateDescriptor>,
pub index_format: IndexFormat,
pub vertex_buffers: &'a [VertexBufferDescriptor<'a>],
pub sample_count: u32,
pub sample_mask: u32,
pub alpha_to_coverage_enabled: bool,
}
#[derive(Clone, Debug)]
pub struct ComputePipelineDescriptor<'a> {
pub layout: &'a PipelineLayout,
pub compute_stage: ProgrammableStageDescriptor<'a>,
}
#[derive(Debug)]
pub struct RenderPassDescriptor<'a> {
pub color_attachments: &'a [RenderPassColorAttachmentDescriptor<'a>],
pub depth_stencil_attachment:
Option<RenderPassDepthStencilAttachmentDescriptor<&'a TextureView>>,
}
#[derive(Clone, Debug)]
pub struct RenderPassColorAttachmentDescriptor<'a> {
pub attachment: &'a TextureView,
pub resolve_target: Option<&'a TextureView>,
pub load_op: LoadOp,
pub store_op: StoreOp,
pub clear_color: Color,
}
#[derive(Debug)]
pub struct SwapChainOutput<'a> {
pub texture: Texture,
pub view: TextureView,
swap_chain_id: &'a wgn::SwapChainId,
}
#[derive(Clone, Debug)]
pub struct BufferCopyView<'a> {
pub buffer: &'a Buffer,
pub offset: BufferAddress,
pub row_pitch: u32,
pub image_height: u32,
}
impl<'a> BufferCopyView<'a> {
fn into_native(self) -> wgn::BufferCopyView {
wgn::BufferCopyView {
buffer: self.buffer.id,
offset: self.offset,
row_pitch: self.row_pitch,
image_height: self.image_height,
}
}
}
#[derive(Clone, Debug)]
pub struct TextureCopyView<'a> {
pub texture: &'a Texture,
pub mip_level: u32,
pub array_layer: u32,
pub origin: Origin3d,
}
impl<'a> TextureCopyView<'a> {
fn into_native(self) -> wgn::TextureCopyView {
wgn::TextureCopyView {
texture: self.texture.id,
mip_level: self.mip_level,
array_layer: self.array_layer,
origin: self.origin,
}
}
}
pub struct CreateBufferMapped<'a, T> {
id: wgn::BufferId,
pub data: &'a mut [T],
}
impl<'a, T> CreateBufferMapped<'a, T>
where
T: Copy,
{
pub fn fill_from_slice(self, slice: &[T]) -> Buffer {
self.data.copy_from_slice(slice);
self.finish()
}
pub fn finish(self) -> Buffer {
wgn::wgpu_buffer_unmap(self.id);
Buffer { id: self.id }
}
}
impl Instance {
#[cfg(not(feature = "gl"))]
pub fn new() -> Self {
Instance {
id: wgn::wgpu_create_instance(),
}
}
#[cfg(feature = "gl")]
pub fn new(windowed_context: wgn::glutin::RawContext<wgn::glutin::PossiblyCurrent>) -> Self {
Instance {
id: wgn::wgpu_create_gl_instance(windowed_context),
}
}
pub fn request_adapter(&self, options: &RequestAdapterOptions) -> Adapter {
Adapter {
id: wgn::wgpu_instance_request_adapter(self.id, Some(options)),
}
}
#[cfg(not(feature = "gl"))]
pub fn create_surface(&self, raw_handle: raw_window_handle::RawWindowHandle) -> Surface {
Surface {
id: wgn::wgpu_instance_create_surface(self.id, raw_handle),
}
}
#[cfg(not(feature = "gl"))]
pub fn create_surface_from_core_animation_layer(&self, layer: *mut std::ffi::c_void) -> Surface {
Surface {
id: wgn::wgpu_instance_create_surface_from_macos_layer(self.id, layer),
}
}
#[cfg(feature = "gl")]
pub fn get_surface(&self) -> Surface {
Surface {
id: wgn::wgpu_instance_get_gl_surface(self.id),
}
}
}
impl Adapter {
pub fn request_device(&self, desc: &DeviceDescriptor) -> Device {
Device {
id: wgn::wgpu_adapter_request_device(self.id, Some(desc)),
temp: Temp::default(),
}
}
}
impl Device {
pub fn poll(&self, force_wait: bool) {
wgn::wgpu_device_poll(self.id, force_wait);
}
pub fn create_shader_module(&self, spv: &[u32]) -> ShaderModule {
let desc = wgn::ShaderModuleDescriptor {
code: wgn::U32Array {
bytes: spv.as_ptr(),
length: spv.len(),
},
};
ShaderModule {
id: wgn::wgpu_device_create_shader_module(self.id, &desc),
}
}
pub fn get_queue(&mut self) -> Queue {
Queue {
id: wgn::wgpu_device_get_queue(self.id),
temp: &mut self.temp,
}
}
pub fn create_command_encoder(&self, desc: &CommandEncoderDescriptor) -> CommandEncoder {
CommandEncoder {
id: wgn::wgpu_device_create_command_encoder(self.id, desc),
}
}
pub fn create_bind_group(&self, desc: &BindGroupDescriptor) -> BindGroup {
let bindings = desc
.bindings
.into_iter()
.map(|binding| wgn::BindGroupBinding {
binding: binding.binding,
resource: match binding.resource {
BindingResource::Buffer {
ref buffer,
ref range,
} => wgn::BindingResource::Buffer(wgn::BufferBinding {
buffer: buffer.id,
offset: range.start,
size: range.end - range.start,
}),
BindingResource::Sampler(ref sampler) => {
wgn::BindingResource::Sampler(sampler.id)
}
BindingResource::TextureView(ref texture_view) => {
wgn::BindingResource::TextureView(texture_view.id)
}
},
})
.collect::<Vec<_>>();
BindGroup {
id: wgn::wgpu_device_create_bind_group(
self.id,
&wgn::BindGroupDescriptor {
layout: desc.layout.id,
bindings: bindings.as_ptr(),
bindings_length: bindings.len(),
},
),
}
}
pub fn create_bind_group_layout(&self, desc: &BindGroupLayoutDescriptor) -> BindGroupLayout {
let temp_layouts = desc.bindings
.iter()
.map(|bind| wgn::BindGroupLayoutBinding {
binding: bind.binding,
visibility: bind.visibility,
ty: match bind.ty {
BindingType::UniformBuffer { .. } => wgn::BindingType::UniformBuffer,
BindingType::StorageBuffer { readonly: false, .. } => wgn::BindingType::StorageBuffer,
BindingType::StorageBuffer { readonly: true, .. } => wgn::BindingType::ReadonlyStorageBuffer,
BindingType::Sampler => wgn::BindingType::Sampler,
BindingType::SampledTexture { .. } => wgn::BindingType::SampledTexture,
BindingType::StorageTexture { .. } => wgn::BindingType::StorageTexture,
},
dynamic: match bind.ty {
BindingType::UniformBuffer { dynamic } |
BindingType::StorageBuffer { dynamic, .. } => dynamic,
_ => false,
},
multisampled: match bind.ty {
BindingType::SampledTexture { multisampled, .. } => multisampled,
_ => false,
},
texture_dimension: match bind.ty {
BindingType::SampledTexture { dimension, .. } |
BindingType::StorageTexture { dimension } => dimension,
_ => TextureViewDimension::D2,
},
})
.collect::<Vec<_>>();
BindGroupLayout {
id: wgn::wgpu_device_create_bind_group_layout(
self.id,
&wgn::BindGroupLayoutDescriptor {
bindings: temp_layouts.as_ptr(),
bindings_length: temp_layouts.len(),
},
),
}
}
pub fn create_pipeline_layout(&self, desc: &PipelineLayoutDescriptor) -> PipelineLayout {
let temp_layouts = desc
.bind_group_layouts
.iter()
.map(|bgl| bgl.id)
.collect::<Vec<_>>();
PipelineLayout {
id: wgn::wgpu_device_create_pipeline_layout(
self.id,
&wgn::PipelineLayoutDescriptor {
bind_group_layouts: temp_layouts.as_ptr(),
bind_group_layouts_length: temp_layouts.len(),
},
),
}
}
pub fn create_render_pipeline(&self, desc: &RenderPipelineDescriptor) -> RenderPipeline {
let vertex_entry_point = CString::new(desc.vertex_stage.entry_point).unwrap();
let vertex_stage = wgn::ProgrammableStageDescriptor {
module: desc.vertex_stage.module.id,
entry_point: vertex_entry_point.as_ptr(),
};
let (_fragment_entry_point, fragment_stage) =
if let Some(fragment_stage) = &desc.fragment_stage {
let fragment_entry_point = CString::new(fragment_stage.entry_point).unwrap();
let fragment_stage = wgn::ProgrammableStageDescriptor {
module: fragment_stage.module.id,
entry_point: fragment_entry_point.as_ptr(),
};
(fragment_entry_point, Some(fragment_stage))
} else {
(CString::default(), None)
};
let temp_color_states = desc.color_states.to_vec();
let temp_vertex_buffers = desc
.vertex_buffers
.iter()
.map(|vbuf| wgn::VertexBufferDescriptor {
stride: vbuf.stride,
step_mode: vbuf.step_mode,
attributes: vbuf.attributes.as_ptr(),
attributes_length: vbuf.attributes.len(),
})
.collect::<Vec<_>>();
RenderPipeline {
id: wgn::wgpu_device_create_render_pipeline(
self.id,
&wgn::RenderPipelineDescriptor {
layout: desc.layout.id,
vertex_stage,
fragment_stage: fragment_stage
.as_ref()
.map_or(ptr::null(), |fs| fs as *const _),
rasterization_state: desc.rasterization_state
.as_ref()
.map_or(ptr::null(), |p| p as *const _),
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
.as_ref()
.map_or(ptr::null(), |p| p as *const _),
vertex_input: wgn::VertexInputDescriptor {
index_format: desc.index_format,
vertex_buffers: temp_vertex_buffers.as_ptr(),
vertex_buffers_length: temp_vertex_buffers.len(),
},
sample_count: desc.sample_count,
sample_mask: desc.sample_mask,
alpha_to_coverage_enabled: desc.alpha_to_coverage_enabled,
},
),
}
}
pub fn create_compute_pipeline(&self, desc: &ComputePipelineDescriptor) -> ComputePipeline {
let entry_point = CString::new(desc.compute_stage.entry_point).unwrap();
ComputePipeline {
id: wgn::wgpu_device_create_compute_pipeline(
self.id,
&wgn::ComputePipelineDescriptor {
layout: desc.layout.id,
compute_stage: wgn::ProgrammableStageDescriptor {
module: desc.compute_stage.module.id,
entry_point: entry_point.as_ptr(),
},
},
),
}
}
pub fn create_buffer(&self, desc: &BufferDescriptor) -> Buffer {
Buffer {
id: wgn::wgpu_device_create_buffer(self.id, desc),
}
}
pub fn create_buffer_mapped<'a, T>(
&'a self,
count: usize,
usage: BufferUsage,
) -> CreateBufferMapped<'a, T>
where
T: 'static + Copy,
{
let type_size = std::mem::size_of::<T>() as BufferAddress;
assert_ne!(type_size, 0);
let desc = BufferDescriptor {
size: (type_size * count as BufferAddress).max(1),
usage,
};
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 }
}
pub fn create_texture(&self, desc: &TextureDescriptor) -> Texture {
Texture {
id: wgn::wgpu_device_create_texture(self.id, desc),
owned: true,
}
}
pub fn create_sampler(&self, desc: &SamplerDescriptor) -> Sampler {
Sampler {
id: wgn::wgpu_device_create_sampler(self.id, desc),
}
}
pub fn create_swap_chain(&self, surface: &Surface, desc: &SwapChainDescriptor) -> SwapChain {
SwapChain {
id: wgn::wgpu_device_create_swap_chain(self.id, surface.id, desc),
}
}
}
impl Drop for Device {
fn drop(&mut self) {
wgn::wgpu_device_poll(self.id, true);
#[cfg(feature = "metal-auto-capture")]
wgn::wgpu_device_destroy(self.id);
}
}
pub struct BufferAsyncMapping<T> {
pub data: T,
buffer_id: wgn::BufferId,
}
pub type BufferMapAsyncResult<T> = Result<BufferAsyncMapping<T>, ()>;
impl<T> Drop for BufferAsyncMapping<T> {
fn drop(&mut self) {
wgn::wgpu_buffer_unmap(self.buffer_id);
}
}
struct BufferMapReadAsyncUserData<T, F>
where
T: FromBytes,
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
size: BufferAddress,
callback: F,
buffer_id: wgn::BufferId,
phantom: std::marker::PhantomData<T>,
}
struct BufferMapWriteAsyncUserData<T, F>
where
T: AsBytes + FromBytes,
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
size: BufferAddress,
callback: F,
buffer_id: wgn::BufferId,
phantom: std::marker::PhantomData<T>,
}
impl Buffer {
pub fn map_read_async<T, F>(&self, start: BufferAddress, size: BufferAddress, callback: F)
where
T: 'static + FromBytes,
F: FnOnce(BufferMapAsyncResult<&[T]>) + 'static,
{
extern "C" fn buffer_map_read_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *const u8,
user_data: *mut u8,
) where
T: FromBytes,
F: FnOnce(BufferMapAsyncResult<&[T]>),
{
let user_data =
unsafe { Box::from_raw(user_data as *mut BufferMapReadAsyncUserData<T, F>) };
let data: &[u8] = unsafe {
slice::from_raw_parts(data as *const u8, usize::try_from(user_data.size).unwrap())
};
let data = LayoutVerified::new_slice(data)
.expect("could not interpret bytes as &[T]")
.into_slice();
if let wgn::BufferMapAsyncStatus::Success = status {
(user_data.callback)(Ok(BufferAsyncMapping {
data,
buffer_id: user_data.buffer_id,
}));
} else {
(user_data.callback)(Err(()))
}
}
let user_data = Box::new(BufferMapReadAsyncUserData {
size,
callback,
buffer_id: self.id,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_read_async(
self.id,
start,
size,
buffer_map_read_callback_wrapper::<T, F>,
Box::into_raw(user_data) as *mut u8,
);
}
pub fn map_write_async<T, F>(&self, start: BufferAddress, size: BufferAddress, callback: F)
where
T: 'static + AsBytes + FromBytes,
F: FnOnce(BufferMapAsyncResult<&mut [T]>) + 'static,
{
extern "C" fn buffer_map_write_callback_wrapper<T, F>(
status: wgn::BufferMapAsyncStatus,
data: *mut u8,
user_data: *mut u8,
) where
T: AsBytes + FromBytes,
F: FnOnce(BufferMapAsyncResult<&mut [T]>),
{
let user_data =
unsafe { Box::from_raw(user_data as *mut BufferMapWriteAsyncUserData<T, F>) };
let data = unsafe {
slice::from_raw_parts_mut(data as *mut u8, usize::try_from(user_data.size).unwrap())
};
let data = LayoutVerified::new_slice(data)
.expect("could not interpret bytes as &mut [T]")
.into_mut_slice();
if let wgn::BufferMapAsyncStatus::Success = status {
(user_data.callback)(Ok(BufferAsyncMapping {
data,
buffer_id: user_data.buffer_id,
}));
} else {
(user_data.callback)(Err(()))
}
}
let user_data = Box::new(BufferMapWriteAsyncUserData {
size,
callback,
buffer_id: self.id,
phantom: std::marker::PhantomData,
});
wgn::wgpu_buffer_map_write_async(
self.id,
start,
size,
buffer_map_write_callback_wrapper::<T, F>,
Box::into_raw(user_data) as *mut u8,
);
}
pub fn unmap(&self) {
wgn::wgpu_buffer_unmap(self.id);
}
}
impl Drop for Buffer {
fn drop(&mut self) {
wgn::wgpu_buffer_destroy(self.id);
}
}
impl Texture {
pub fn create_view(&self, desc: &TextureViewDescriptor) -> TextureView {
TextureView {
id: wgn::wgpu_texture_create_view(self.id, Some(desc)),
owned: true,
}
}
pub fn create_default_view(&self) -> TextureView {
TextureView {
id: wgn::wgpu_texture_create_view(self.id, None),
owned: true,
}
}
}
impl Drop for Texture {
fn drop(&mut self) {
if self.owned {
wgn::wgpu_texture_destroy(self.id);
}
}
}
impl Drop for TextureView {
fn drop(&mut self) {
if self.owned {
wgn::wgpu_texture_view_destroy(self.id);
}
}
}
impl CommandEncoder {
pub fn finish(self) -> CommandBuffer {
CommandBuffer {
id: wgn::wgpu_command_encoder_finish(self.id, None),
}
}
pub fn begin_render_pass(&mut self, desc: &RenderPassDescriptor) -> RenderPass {
let colors = desc
.color_attachments
.iter()
.map(|ca| wgn::RenderPassColorAttachmentDescriptor {
attachment: ca.attachment.id,
resolve_target: ca.resolve_target.map_or(ptr::null(), |v| &v.id as *const _),
load_op: ca.load_op,
store_op: ca.store_op,
clear_color: ca.clear_color,
})
.collect::<ArrayVec<[_; 4]>>();
let depth_stencil = desc.depth_stencil_attachment.as_ref().map(|dsa| {
RenderPassDepthStencilAttachmentDescriptor {
attachment: dsa.attachment.id,
depth_load_op: dsa.depth_load_op,
depth_store_op: dsa.depth_store_op,
clear_depth: dsa.clear_depth,
stencil_load_op: dsa.stencil_load_op,
stencil_store_op: dsa.stencil_store_op,
clear_stencil: dsa.clear_stencil,
}
});
RenderPass {
id: wgn::wgpu_command_encoder_begin_render_pass(
self.id,
&wgn::RenderPassDescriptor {
color_attachments: colors.as_ptr(),
color_attachments_length: colors.len(),
depth_stencil_attachment: depth_stencil
.as_ref()
.map(|at| at as *const _)
.unwrap_or(ptr::null()),
},
),
_parent: self,
}
}
pub fn begin_compute_pass(&mut self) -> ComputePass {
ComputePass {
id: wgn::wgpu_command_encoder_begin_compute_pass(self.id),
_parent: self,
}
}
pub fn copy_buffer_to_buffer(
&mut self,
source: &Buffer,
source_offset: BufferAddress,
destination: &Buffer,
destination_offset: BufferAddress,
copy_size: BufferAddress,
) {
wgn::wgpu_command_encoder_copy_buffer_to_buffer(
self.id,
source.id,
source_offset,
destination.id,
destination_offset,
copy_size,
);
}
pub fn copy_buffer_to_texture(
&mut self,
source: BufferCopyView,
destination: TextureCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_encoder_copy_buffer_to_texture(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
pub fn copy_texture_to_buffer(
&mut self,
source: TextureCopyView,
destination: BufferCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_encoder_copy_texture_to_buffer(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
pub fn copy_texture_to_texture(
&mut self,
source: TextureCopyView,
destination: TextureCopyView,
copy_size: Extent3d,
) {
wgn::wgpu_command_encoder_copy_texture_to_texture(
self.id,
&source.into_native(),
&destination.into_native(),
copy_size,
);
}
}
impl<'a> RenderPass<'a> {
pub fn set_bind_group(
&mut self,
index: u32,
bind_group: &BindGroup,
offsets: &[BufferAddress],
) {
wgn::wgpu_render_pass_set_bind_group(
self.id,
index,
bind_group.id,
offsets.as_ptr(),
offsets.len(),
);
}
pub fn set_pipeline(&mut self, pipeline: &RenderPipeline) {
wgn::wgpu_render_pass_set_pipeline(self.id, pipeline.id);
}
pub fn set_blend_color(&mut self, color: Color) {
wgn::wgpu_render_pass_set_blend_color(self.id, &color);
}
pub fn set_index_buffer(&mut self, buffer: &Buffer, offset: BufferAddress) {
wgn::wgpu_render_pass_set_index_buffer(self.id, buffer.id, offset);
}
pub fn set_vertex_buffers(
&mut self,
start_slot: u32,
buffer_pairs: &[(&Buffer, BufferAddress)],
) {
let mut buffers = Vec::new();
let mut offsets = Vec::new();
for &(buffer, offset) in buffer_pairs {
buffers.push(buffer.id);
offsets.push(offset);
}
wgn::wgpu_render_pass_set_vertex_buffers(
self.id,
start_slot,
buffers.as_ptr(),
offsets.as_ptr(),
buffer_pairs.len(),
);
}
pub fn set_scissor_rect(&mut self, x: u32, y: u32, w: u32, h: u32) {
wgn::wgpu_render_pass_set_scissor_rect(self.id, x, y, w, h)
}
pub fn set_viewport(&mut self, x: f32, y: f32, w: f32, h: f32, min_depth: f32, max_depth: f32) {
wgn::wgpu_render_pass_set_viewport(self.id, x, y, w, h, min_depth, max_depth)
}
pub fn set_stencil_reference(&mut self, reference: u32) {
wgn::wgpu_render_pass_set_stencil_reference(self.id, reference)
}
pub fn draw(&mut self, vertices: Range<u32>, instances: Range<u32>) {
wgn::wgpu_render_pass_draw(
self.id,
vertices.end - vertices.start,
instances.end - instances.start,
vertices.start,
instances.start,
);
}
pub fn draw_indexed(&mut self, indices: Range<u32>, base_vertex: i32, instances: Range<u32>) {
wgn::wgpu_render_pass_draw_indexed(
self.id,
indices.end - indices.start,
instances.end - instances.start,
indices.start,
base_vertex,
instances.start,
);
}
}
impl<'a> Drop for RenderPass<'a> {
fn drop(&mut self) {
if !thread::panicking() {
wgn::wgpu_render_pass_end_pass(self.id);
}
}
}
impl<'a> ComputePass<'a> {
pub fn set_bind_group(
&mut self,
index: u32,
bind_group: &BindGroup,
offsets: &[BufferAddress],
) {
wgn::wgpu_compute_pass_set_bind_group(
self.id,
index,
bind_group.id,
offsets.as_ptr(),
offsets.len(),
);
}
pub fn set_pipeline(&mut self, pipeline: &ComputePipeline) {
wgn::wgpu_compute_pass_set_pipeline(self.id, pipeline.id);
}
pub fn dispatch(&mut self, x: u32, y: u32, z: u32) {
wgn::wgpu_compute_pass_dispatch(self.id, x, y, z);
}
}
impl<'a> Drop for ComputePass<'a> {
fn drop(&mut self) {
if !thread::panicking() {
wgn::wgpu_compute_pass_end_pass(self.id);
}
}
}
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));
wgn::wgpu_queue_submit(
self.id,
self.temp.command_buffers.as_ptr(),
command_buffers.len(),
);
}
}
impl<'a> Drop for SwapChainOutput<'a> {
fn drop(&mut self) {
if !thread::panicking() {
wgn::wgpu_swap_chain_present(*self.swap_chain_id);
}
}
}
impl SwapChain {
pub fn get_next_texture(&mut self) -> SwapChainOutput {
let output = wgn::wgpu_swap_chain_get_next_texture(self.id);
SwapChainOutput {
texture: Texture {
id: output.texture_id,
owned: false,
},
view: TextureView {
id: output.view_id,
owned: false,
},
swap_chain_id: &self.id,
}
}
}