| 1 |
//! This example shows basic usage of wgpu-hal by rendering |
| 2 |
//! a ton of moving sprites, each with a separate texture and draw call. |
| 3 |
extern crate wgpu_hal as hal; |
| 4 |
|
| 5 |
use hal::{ |
| 6 |
Adapter as _, CommandEncoder as _, Device as _, Instance as _, Queue as _, Surface as _, |
| 7 |
}; |
| 8 |
use raw_window_handle::{HasDisplayHandle, HasWindowHandle}; |
| 9 |
use winit::{ |
| 10 |
event::{ElementState, Event, KeyEvent, WindowEvent}, |
| 11 |
event_loop::ControlFlow, |
| 12 |
keyboard::{Key, NamedKey}, |
| 13 |
}; |
| 14 |
|
| 15 |
use std::{ |
| 16 |
borrow::{Borrow, Cow}, |
| 17 |
iter, ptr, |
| 18 |
time::Instant, |
| 19 |
}; |
| 20 |
|
| 21 |
const MAX_BUNNIES: usize = 1 << 20; |
| 22 |
const BUNNY_SIZE: f32 = 0.15 * 256.0; |
| 23 |
const GRAVITY: f32 = -9.8 * 100.0; |
| 24 |
const MAX_VELOCITY: f32 = 750.0; |
| 25 |
const DESIRED_MAX_LATENCY: u32 = 2; |
| 26 |
|
| 27 |
#[repr(C)] |
| 28 |
#[derive(Clone, Copy)] |
| 29 |
struct Globals { |
| 30 |
mvp: [[f32; 4]; 4], |
| 31 |
size: [f32; 2], |
| 32 |
pad: [f32; 2], |
| 33 |
} |
| 34 |
|
| 35 |
#[repr(C, align(256))] |
| 36 |
#[derive(Clone, Copy)] |
| 37 |
struct Locals { |
| 38 |
position: [f32; 2], |
| 39 |
velocity: [f32; 2], |
| 40 |
color: u32, |
| 41 |
_pad: u32, |
| 42 |
} |
| 43 |
|
| 44 |
struct ExecutionContext<A: hal::Api> { |
| 45 |
encoder: A::CommandEncoder, |
| 46 |
fence: A::Fence, |
| 47 |
fence_value: hal::FenceValue, |
| 48 |
used_views: Vec<A::TextureView>, |
| 49 |
used_cmd_bufs: Vec<A::CommandBuffer>, |
| 50 |
frames_recorded: usize, |
| 51 |
} |
| 52 |
|
| 53 |
impl<A: hal::Api> ExecutionContext<A> { |
| 54 |
unsafe fn wait_and_clear(&mut self, device: &A::Device) { |
| 55 |
device.wait(&self.fence, self.fence_value, !0).unwrap(); |
| 56 |
self.encoder.reset_all(self.used_cmd_bufs.drain(..)); |
| 57 |
for view in self.used_views.drain(..) { |
| 58 |
device.destroy_texture_view(view); |
| 59 |
} |
| 60 |
self.frames_recorded = 0; |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
#[allow(dead_code)] |
| 65 |
struct Example<A: hal::Api> { |
| 66 |
instance: A::Instance, |
| 67 |
adapter: A::Adapter, |
| 68 |
surface: A::Surface, |
| 69 |
surface_format: wgpu_types::TextureFormat, |
| 70 |
device: A::Device, |
| 71 |
queue: A::Queue, |
| 72 |
global_group: A::BindGroup, |
| 73 |
local_group: A::BindGroup, |
| 74 |
global_group_layout: A::BindGroupLayout, |
| 75 |
local_group_layout: A::BindGroupLayout, |
| 76 |
pipeline_layout: A::PipelineLayout, |
| 77 |
shader: A::ShaderModule, |
| 78 |
pipeline: A::RenderPipeline, |
| 79 |
bunnies: Vec<Locals>, |
| 80 |
local_buffer: A::Buffer, |
| 81 |
local_alignment: u32, |
| 82 |
global_buffer: A::Buffer, |
| 83 |
sampler: A::Sampler, |
| 84 |
texture: A::Texture, |
| 85 |
texture_view: A::TextureView, |
| 86 |
contexts: Vec<ExecutionContext<A>>, |
| 87 |
context_index: usize, |
| 88 |
extent: [u32; 2], |
| 89 |
start: Instant, |
| 90 |
} |
| 91 |
|
| 92 |
impl<A: hal::Api> Example<A> { |
| 93 |
fn init(window: &winit::window::Window) -> Result<Self, Box<dyn std::error::Error>> { |
| 94 |
let instance_desc = hal::InstanceDescriptor { |
| 95 |
name: "example", |
| 96 |
flags: wgpu_types::InstanceFlags::from_build_config().with_env(), |
| 97 |
memory_budget_thresholds: wgpu_types::MemoryBudgetThresholds::default(), |
| 98 |
// Can't rely on having DXC available, so use FXC instead |
| 99 |
backend_options: wgpu_types::BackendOptions::default(), |
| 100 |
}; |
| 101 |
let instance = unsafe { A::Instance::init(&instance_desc)? }; |
| 102 |
let surface = { |
| 103 |
let raw_window_handle = window.window_handle()?.as_raw(); |
| 104 |
let raw_display_handle = window.display_handle()?.as_raw(); |
| 105 |
|
| 106 |
unsafe { |
| 107 |
instance |
| 108 |
.create_surface(raw_display_handle, raw_window_handle) |
| 109 |
.unwrap() |
| 110 |
} |
| 111 |
}; |
| 112 |
|
| 113 |
let (adapter, capabilities) = unsafe { |
| 114 |
let mut adapters = instance.enumerate_adapters(Some(&surface)); |
| 115 |
if adapters.is_empty() { |
| 116 |
return Err("no adapters found".into()); |
| 117 |
} |
| 118 |
let exposed = adapters.swap_remove(0); |
| 119 |
(exposed.adapter, exposed.capabilities) |
| 120 |
}; |
| 121 |
|
| 122 |
let surface_caps = unsafe { adapter.surface_capabilities(&surface) } |
| 123 |
.ok_or("failed to get surface capabilities")?; |
| 124 |
log::info!("Surface caps: {:#?}", surface_caps); |
| 125 |
|
| 126 |
let hal::OpenDevice { device, queue } = unsafe { |
| 127 |
adapter |
| 128 |
.open( |
| 129 |
wgpu_types::Features::empty(), |
| 130 |
&wgpu_types::Limits::default(), |
| 131 |
&wgpu_types::MemoryHints::default(), |
| 132 |
) |
| 133 |
.unwrap() |
| 134 |
}; |
| 135 |
|
| 136 |
let window_size: (u32, u32) = window.inner_size().into(); |
| 137 |
let surface_config = hal::SurfaceConfiguration { |
| 138 |
maximum_frame_latency: DESIRED_MAX_LATENCY.clamp( |
| 139 |
*surface_caps.maximum_frame_latency.start(), |
| 140 |
*surface_caps.maximum_frame_latency.end(), |
| 141 |
), |
| 142 |
present_mode: wgpu_types::PresentMode::Fifo, |
| 143 |
composite_alpha_mode: wgpu_types::CompositeAlphaMode::Opaque, |
| 144 |
format: wgpu_types::TextureFormat::Bgra8UnormSrgb, |
| 145 |
extent: wgpu_types::Extent3d { |
| 146 |
width: window_size.0, |
| 147 |
height: window_size.1, |
| 148 |
depth_or_array_layers: 1, |
| 149 |
}, |
| 150 |
usage: wgpu_types::TextureUses::COLOR_TARGET, |
| 151 |
view_formats: vec![], |
| 152 |
}; |
| 153 |
unsafe { |
| 154 |
surface.configure(&device, &surface_config).unwrap(); |
| 155 |
}; |
| 156 |
|
| 157 |
let naga_shader = { |
| 158 |
let shader_file = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 159 |
.join("examples") |
| 160 |
.join("halmark") |
| 161 |
.join("shader.wgsl"); |
| 162 |
let source = std::fs::read_to_string(shader_file).unwrap(); |
| 163 |
let module = naga::front::wgsl::Frontend::new().parse(&source).unwrap(); |
| 164 |
let info = naga::valid::Validator::new( |
| 165 |
naga::valid::ValidationFlags::all(), |
| 166 |
naga::valid::Capabilities::empty(), |
| 167 |
) |
| 168 |
.validate(&module) |
| 169 |
.unwrap(); |
| 170 |
hal::NagaShader { |
| 171 |
module: Cow::Owned(module), |
| 172 |
info, |
| 173 |
debug_source: None, |
| 174 |
} |
| 175 |
}; |
| 176 |
let shader_desc = hal::ShaderModuleDescriptor { |
| 177 |
label: None, |
| 178 |
runtime_checks: wgpu_types::ShaderRuntimeChecks::checked(), |
| 179 |
}; |
| 180 |
let shader = unsafe { |
| 181 |
device |
| 182 |
.create_shader_module(&shader_desc, hal::ShaderInput::Naga(naga_shader)) |
| 183 |
.unwrap() |
| 184 |
}; |
| 185 |
|
| 186 |
let global_bgl_desc = hal::BindGroupLayoutDescriptor { |
| 187 |
label: None, |
| 188 |
flags: hal::BindGroupLayoutFlags::empty(), |
| 189 |
entries: &[ |
| 190 |
wgpu_types::BindGroupLayoutEntry { |
| 191 |
binding: 0, |
| 192 |
visibility: wgpu_types::ShaderStages::VERTEX, |
| 193 |
ty: wgpu_types::BindingType::Buffer { |
| 194 |
ty: wgpu_types::BufferBindingType::Uniform, |
| 195 |
has_dynamic_offset: false, |
| 196 |
min_binding_size: wgpu_types::BufferSize::new(size_of::<Globals>() as _), |
| 197 |
}, |
| 198 |
count: None, |
| 199 |
}, |
| 200 |
wgpu_types::BindGroupLayoutEntry { |
| 201 |
binding: 1, |
| 202 |
visibility: wgpu_types::ShaderStages::FRAGMENT, |
| 203 |
ty: wgpu_types::BindingType::Texture { |
| 204 |
sample_type: wgpu_types::TextureSampleType::Float { filterable: true }, |
| 205 |
view_dimension: wgpu_types::TextureViewDimension::D2, |
| 206 |
multisampled: false, |
| 207 |
}, |
| 208 |
count: None, |
| 209 |
}, |
| 210 |
wgpu_types::BindGroupLayoutEntry { |
| 211 |
binding: 2, |
| 212 |
visibility: wgpu_types::ShaderStages::FRAGMENT, |
| 213 |
ty: wgpu_types::BindingType::Sampler(wgpu_types::SamplerBindingType::Filtering), |
| 214 |
count: None, |
| 215 |
}, |
| 216 |
], |
| 217 |
}; |
| 218 |
|
| 219 |
let global_group_layout = |
| 220 |
unsafe { device.create_bind_group_layout(&global_bgl_desc).unwrap() }; |
| 221 |
|
| 222 |
let local_bgl_desc = hal::BindGroupLayoutDescriptor { |
| 223 |
label: None, |
| 224 |
flags: hal::BindGroupLayoutFlags::empty(), |
| 225 |
entries: &[wgpu_types::BindGroupLayoutEntry { |
| 226 |
binding: 0, |
| 227 |
visibility: wgpu_types::ShaderStages::VERTEX, |
| 228 |
ty: wgpu_types::BindingType::Buffer { |
| 229 |
ty: wgpu_types::BufferBindingType::Uniform, |
| 230 |
has_dynamic_offset: true, |
| 231 |
min_binding_size: wgpu_types::BufferSize::new(size_of::<Locals>() as _), |
| 232 |
}, |
| 233 |
count: None, |
| 234 |
}], |
| 235 |
}; |
| 236 |
let local_group_layout = |
| 237 |
unsafe { device.create_bind_group_layout(&local_bgl_desc).unwrap() }; |
| 238 |
|
| 239 |
let pipeline_layout_desc = hal::PipelineLayoutDescriptor { |
| 240 |
label: None, |
| 241 |
flags: hal::PipelineLayoutFlags::empty(), |
| 242 |
bind_group_layouts: &[&global_group_layout, &local_group_layout], |
| 243 |
push_constant_ranges: &[], |
| 244 |
}; |
| 245 |
let pipeline_layout = unsafe { |
| 246 |
device |
| 247 |
.create_pipeline_layout(&pipeline_layout_desc) |
| 248 |
.unwrap() |
| 249 |
}; |
| 250 |
|
| 251 |
let constants = naga::back::PipelineConstants::default(); |
| 252 |
let pipeline_desc = hal::RenderPipelineDescriptor { |
| 253 |
label: None, |
| 254 |
layout: &pipeline_layout, |
| 255 |
vertex_stage: hal::ProgrammableStage { |
| 256 |
module: &shader, |
| 257 |
entry_point: "vs_main", |
| 258 |
constants: &constants, |
| 259 |
zero_initialize_workgroup_memory: true, |
| 260 |
}, |
| 261 |
vertex_buffers: &[], |
| 262 |
fragment_stage: Some(hal::ProgrammableStage { |
| 263 |
module: &shader, |
| 264 |
entry_point: "fs_main", |
| 265 |
constants: &constants, |
| 266 |
zero_initialize_workgroup_memory: true, |
| 267 |
}), |
| 268 |
primitive: wgpu_types::PrimitiveState { |
| 269 |
topology: wgpu_types::PrimitiveTopology::TriangleStrip, |
| 270 |
..wgpu_types::PrimitiveState::default() |
| 271 |
}, |
| 272 |
depth_stencil: None, |
| 273 |
multisample: wgpu_types::MultisampleState::default(), |
| 274 |
color_targets: &[Some(wgpu_types::ColorTargetState { |
| 275 |
format: surface_config.format, |
| 276 |
blend: Some(wgpu_types::BlendState::ALPHA_BLENDING), |
| 277 |
write_mask: wgpu_types::ColorWrites::default(), |
| 278 |
})], |
| 279 |
multiview: None, |
| 280 |
cache: None, |
| 281 |
}; |
| 282 |
let pipeline = unsafe { device.create_render_pipeline(&pipeline_desc).unwrap() }; |
| 283 |
|
| 284 |
let texture_data = [0xFFu8; 4]; |
| 285 |
|
| 286 |
let staging_buffer_desc = hal::BufferDescriptor { |
| 287 |
label: Some("stage"), |
| 288 |
size: texture_data.len() as wgpu_types::BufferAddress, |
| 289 |
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::COPY_SRC, |
| 290 |
memory_flags: hal::MemoryFlags::TRANSIENT | hal::MemoryFlags::PREFER_COHERENT, |
| 291 |
}; |
| 292 |
let staging_buffer = unsafe { device.create_buffer(&staging_buffer_desc).unwrap() }; |
| 293 |
unsafe { |
| 294 |
let mapping = device |
| 295 |
.map_buffer(&staging_buffer, 0..staging_buffer_desc.size) |
| 296 |
.unwrap(); |
| 297 |
ptr::copy_nonoverlapping( |
| 298 |
texture_data.as_ptr(), |
| 299 |
mapping.ptr.as_ptr(), |
| 300 |
texture_data.len(), |
| 301 |
); |
| 302 |
device.unmap_buffer(&staging_buffer); |
| 303 |
assert!(mapping.is_coherent); |
| 304 |
} |
| 305 |
|
| 306 |
let texture_desc = hal::TextureDescriptor { |
| 307 |
label: None, |
| 308 |
size: wgpu_types::Extent3d { |
| 309 |
width: 1, |
| 310 |
height: 1, |
| 311 |
depth_or_array_layers: 1, |
| 312 |
}, |
| 313 |
mip_level_count: 1, |
| 314 |
sample_count: 1, |
| 315 |
dimension: wgpu_types::TextureDimension::D2, |
| 316 |
format: wgpu_types::TextureFormat::Rgba8UnormSrgb, |
| 317 |
usage: wgpu_types::TextureUses::COPY_DST | wgpu_types::TextureUses::RESOURCE, |
| 318 |
memory_flags: hal::MemoryFlags::empty(), |
| 319 |
view_formats: vec![], |
| 320 |
}; |
| 321 |
let texture = unsafe { device.create_texture(&texture_desc).unwrap() }; |
| 322 |
|
| 323 |
let cmd_encoder_desc = hal::CommandEncoderDescriptor { |
| 324 |
label: None, |
| 325 |
queue: &queue, |
| 326 |
}; |
| 327 |
let mut cmd_encoder = unsafe { device.create_command_encoder(&cmd_encoder_desc).unwrap() }; |
| 328 |
unsafe { cmd_encoder.begin_encoding(Some("init")).unwrap() }; |
| 329 |
{ |
| 330 |
let buffer_barrier = hal::BufferBarrier { |
| 331 |
buffer: &staging_buffer, |
| 332 |
usage: hal::StateTransition { |
| 333 |
from: wgpu_types::BufferUses::empty(), |
| 334 |
to: wgpu_types::BufferUses::COPY_SRC, |
| 335 |
}, |
| 336 |
}; |
| 337 |
let texture_barrier1 = hal::TextureBarrier { |
| 338 |
texture: &texture, |
| 339 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 340 |
usage: hal::StateTransition { |
| 341 |
from: wgpu_types::TextureUses::UNINITIALIZED, |
| 342 |
to: wgpu_types::TextureUses::COPY_DST, |
| 343 |
}, |
| 344 |
}; |
| 345 |
let texture_barrier2 = hal::TextureBarrier { |
| 346 |
texture: &texture, |
| 347 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 348 |
usage: hal::StateTransition { |
| 349 |
from: wgpu_types::TextureUses::COPY_DST, |
| 350 |
to: wgpu_types::TextureUses::RESOURCE, |
| 351 |
}, |
| 352 |
}; |
| 353 |
let copy = hal::BufferTextureCopy { |
| 354 |
buffer_layout: wgpu_types::TexelCopyBufferLayout { |
| 355 |
offset: 0, |
| 356 |
bytes_per_row: Some(4), |
| 357 |
rows_per_image: None, |
| 358 |
}, |
| 359 |
texture_base: hal::TextureCopyBase { |
| 360 |
origin: wgpu_types::Origin3d::ZERO, |
| 361 |
mip_level: 0, |
| 362 |
array_layer: 0, |
| 363 |
aspect: hal::FormatAspects::COLOR, |
| 364 |
}, |
| 365 |
size: hal::CopyExtent { |
| 366 |
width: 1, |
| 367 |
height: 1, |
| 368 |
depth: 1, |
| 369 |
}, |
| 370 |
}; |
| 371 |
unsafe { |
| 372 |
cmd_encoder.transition_buffers(iter::once(buffer_barrier)); |
| 373 |
cmd_encoder.transition_textures(iter::once(texture_barrier1)); |
| 374 |
cmd_encoder.copy_buffer_to_texture(&staging_buffer, &texture, iter::once(copy)); |
| 375 |
cmd_encoder.transition_textures(iter::once(texture_barrier2)); |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
let sampler_desc = hal::SamplerDescriptor { |
| 380 |
label: None, |
| 381 |
address_modes: [wgpu_types::AddressMode::ClampToEdge; 3], |
| 382 |
mag_filter: wgpu_types::FilterMode::Linear, |
| 383 |
min_filter: wgpu_types::FilterMode::Nearest, |
| 384 |
mipmap_filter: wgpu_types::FilterMode::Nearest, |
| 385 |
lod_clamp: 0.0..32.0, |
| 386 |
compare: None, |
| 387 |
anisotropy_clamp: 1, |
| 388 |
border_color: None, |
| 389 |
}; |
| 390 |
let sampler = unsafe { device.create_sampler(&sampler_desc).unwrap() }; |
| 391 |
|
| 392 |
let globals = Globals { |
| 393 |
// cgmath::ortho() projection |
| 394 |
mvp: [ |
| 395 |
[2.0 / window_size.0 as f32, 0.0, 0.0, 0.0], |
| 396 |
[0.0, 2.0 / window_size.1 as f32, 0.0, 0.0], |
| 397 |
[0.0, 0.0, 1.0, 0.0], |
| 398 |
[-1.0, -1.0, 0.0, 1.0], |
| 399 |
], |
| 400 |
size: [BUNNY_SIZE; 2], |
| 401 |
pad: [0.0; 2], |
| 402 |
}; |
| 403 |
|
| 404 |
let global_buffer_desc = hal::BufferDescriptor { |
| 405 |
label: Some("global"), |
| 406 |
size: size_of::<Globals>() as wgpu_types::BufferAddress, |
| 407 |
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM, |
| 408 |
memory_flags: hal::MemoryFlags::PREFER_COHERENT, |
| 409 |
}; |
| 410 |
let global_buffer = unsafe { |
| 411 |
let buffer = device.create_buffer(&global_buffer_desc).unwrap(); |
| 412 |
let mapping = device |
| 413 |
.map_buffer(&buffer, 0..global_buffer_desc.size) |
| 414 |
.unwrap(); |
| 415 |
ptr::copy_nonoverlapping( |
| 416 |
&globals as *const Globals as *const u8, |
| 417 |
mapping.ptr.as_ptr(), |
| 418 |
size_of::<Globals>(), |
| 419 |
); |
| 420 |
device.unmap_buffer(&buffer); |
| 421 |
assert!(mapping.is_coherent); |
| 422 |
buffer |
| 423 |
}; |
| 424 |
|
| 425 |
let local_alignment = wgpu_types::math::align_to( |
| 426 |
size_of::<Locals>() as u32, |
| 427 |
capabilities.limits.min_uniform_buffer_offset_alignment, |
| 428 |
); |
| 429 |
let local_buffer_desc = hal::BufferDescriptor { |
| 430 |
label: Some("local"), |
| 431 |
size: (MAX_BUNNIES as wgpu_types::BufferAddress) |
| 432 |
* (local_alignment as wgpu_types::BufferAddress), |
| 433 |
usage: wgpu_types::BufferUses::MAP_WRITE | wgpu_types::BufferUses::UNIFORM, |
| 434 |
memory_flags: hal::MemoryFlags::PREFER_COHERENT, |
| 435 |
}; |
| 436 |
let local_buffer = unsafe { device.create_buffer(&local_buffer_desc).unwrap() }; |
| 437 |
|
| 438 |
let view_desc = hal::TextureViewDescriptor { |
| 439 |
label: None, |
| 440 |
format: texture_desc.format, |
| 441 |
dimension: wgpu_types::TextureViewDimension::D2, |
| 442 |
usage: wgpu_types::TextureUses::RESOURCE, |
| 443 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 444 |
}; |
| 445 |
let texture_view = unsafe { device.create_texture_view(&texture, &view_desc).unwrap() }; |
| 446 |
|
| 447 |
let global_group = { |
| 448 |
let global_buffer_binding = hal::BufferBinding { |
| 449 |
buffer: &global_buffer, |
| 450 |
offset: 0, |
| 451 |
size: None, |
| 452 |
}; |
| 453 |
let texture_binding = hal::TextureBinding { |
| 454 |
view: &texture_view, |
| 455 |
usage: wgpu_types::TextureUses::RESOURCE, |
| 456 |
}; |
| 457 |
let global_group_desc = hal::BindGroupDescriptor { |
| 458 |
label: Some("global"), |
| 459 |
layout: &global_group_layout, |
| 460 |
buffers: &[global_buffer_binding], |
| 461 |
samplers: &[&sampler], |
| 462 |
textures: &[texture_binding], |
| 463 |
acceleration_structures: &[], |
| 464 |
entries: &[ |
| 465 |
hal::BindGroupEntry { |
| 466 |
binding: 0, |
| 467 |
resource_index: 0, |
| 468 |
count: 1, |
| 469 |
}, |
| 470 |
hal::BindGroupEntry { |
| 471 |
binding: 1, |
| 472 |
resource_index: 0, |
| 473 |
count: 1, |
| 474 |
}, |
| 475 |
hal::BindGroupEntry { |
| 476 |
binding: 2, |
| 477 |
resource_index: 0, |
| 478 |
count: 1, |
| 479 |
}, |
| 480 |
], |
| 481 |
}; |
| 482 |
unsafe { device.create_bind_group(&global_group_desc).unwrap() } |
| 483 |
}; |
| 484 |
|
| 485 |
let local_group = { |
| 486 |
let local_buffer_binding = hal::BufferBinding { |
| 487 |
buffer: &local_buffer, |
| 488 |
offset: 0, |
| 489 |
size: wgpu_types::BufferSize::new(size_of::<Locals>() as _), |
| 490 |
}; |
| 491 |
let local_group_desc = hal::BindGroupDescriptor { |
| 492 |
label: Some("local"), |
| 493 |
layout: &local_group_layout, |
| 494 |
buffers: &[local_buffer_binding], |
| 495 |
samplers: &[], |
| 496 |
textures: &[], |
| 497 |
acceleration_structures: &[], |
| 498 |
entries: &[hal::BindGroupEntry { |
| 499 |
binding: 0, |
| 500 |
resource_index: 0, |
| 501 |
count: 1, |
| 502 |
}], |
| 503 |
}; |
| 504 |
unsafe { device.create_bind_group(&local_group_desc).unwrap() } |
| 505 |
}; |
| 506 |
|
| 507 |
let init_fence_value = 1; |
| 508 |
let fence = unsafe { |
| 509 |
let mut fence = device.create_fence().unwrap(); |
| 510 |
let init_cmd = cmd_encoder.end_encoding().unwrap(); |
| 511 |
queue |
| 512 |
.submit(&[&init_cmd], &[], (&mut fence, init_fence_value)) |
| 513 |
.unwrap(); |
| 514 |
device.wait(&fence, init_fence_value, !0).unwrap(); |
| 515 |
device.destroy_buffer(staging_buffer); |
| 516 |
cmd_encoder.reset_all(iter::once(init_cmd)); |
| 517 |
fence |
| 518 |
}; |
| 519 |
|
| 520 |
Ok(Example { |
| 521 |
instance, |
| 522 |
surface, |
| 523 |
surface_format: surface_config.format, |
| 524 |
adapter, |
| 525 |
device, |
| 526 |
queue, |
| 527 |
pipeline_layout, |
| 528 |
shader, |
| 529 |
pipeline, |
| 530 |
global_group, |
| 531 |
local_group, |
| 532 |
global_group_layout, |
| 533 |
local_group_layout, |
| 534 |
bunnies: Vec::new(), |
| 535 |
local_buffer, |
| 536 |
local_alignment, |
| 537 |
global_buffer, |
| 538 |
sampler, |
| 539 |
texture, |
| 540 |
texture_view, |
| 541 |
contexts: vec![ExecutionContext { |
| 542 |
encoder: cmd_encoder, |
| 543 |
fence, |
| 544 |
fence_value: init_fence_value + 1, |
| 545 |
used_views: Vec::new(), |
| 546 |
used_cmd_bufs: Vec::new(), |
| 547 |
frames_recorded: 0, |
| 548 |
}], |
| 549 |
context_index: 0, |
| 550 |
extent: [window_size.0, window_size.1], |
| 551 |
start: Instant::now(), |
| 552 |
}) |
| 553 |
} |
| 554 |
|
| 555 |
fn is_empty(&self) -> bool { |
| 556 |
self.bunnies.is_empty() |
| 557 |
} |
| 558 |
|
| 559 |
fn exit(mut self) { |
| 560 |
unsafe { |
| 561 |
{ |
| 562 |
let ctx = &mut self.contexts[self.context_index]; |
| 563 |
self.queue |
| 564 |
.submit(&[], &[], (&mut ctx.fence, ctx.fence_value)) |
| 565 |
.unwrap(); |
| 566 |
} |
| 567 |
|
| 568 |
for mut ctx in self.contexts { |
| 569 |
ctx.wait_and_clear(&self.device); |
| 570 |
drop(ctx.encoder); |
| 571 |
self.device.destroy_fence(ctx.fence); |
| 572 |
} |
| 573 |
|
| 574 |
self.device.destroy_bind_group(self.local_group); |
| 575 |
self.device.destroy_bind_group(self.global_group); |
| 576 |
self.device.destroy_buffer(self.local_buffer); |
| 577 |
self.device.destroy_buffer(self.global_buffer); |
| 578 |
self.device.destroy_texture_view(self.texture_view); |
| 579 |
self.device.destroy_texture(self.texture); |
| 580 |
self.device.destroy_sampler(self.sampler); |
| 581 |
self.device.destroy_shader_module(self.shader); |
| 582 |
self.device.destroy_render_pipeline(self.pipeline); |
| 583 |
self.device |
| 584 |
.destroy_bind_group_layout(self.local_group_layout); |
| 585 |
self.device |
| 586 |
.destroy_bind_group_layout(self.global_group_layout); |
| 587 |
self.device.destroy_pipeline_layout(self.pipeline_layout); |
| 588 |
|
| 589 |
self.surface.unconfigure(&self.device); |
| 590 |
drop(self.queue); |
| 591 |
drop(self.device); |
| 592 |
drop(self.surface); |
| 593 |
drop(self.adapter); |
| 594 |
} |
| 595 |
} |
| 596 |
|
| 597 |
fn update(&mut self, event: winit::event::WindowEvent) { |
| 598 |
if let winit::event::WindowEvent::KeyboardInput { |
| 599 |
event: |
| 600 |
KeyEvent { |
| 601 |
logical_key: Key::Named(NamedKey::Space), |
| 602 |
state: ElementState::Pressed, |
| 603 |
.. |
| 604 |
}, |
| 605 |
.. |
| 606 |
} = event |
| 607 |
{ |
| 608 |
let spawn_count = 64 + self.bunnies.len() / 2; |
| 609 |
let elapsed = self.start.elapsed(); |
| 610 |
let color = elapsed.as_nanos() as u32; |
| 611 |
println!( |
| 612 |
"Spawning {} bunnies, total at {}", |
| 613 |
spawn_count, |
| 614 |
self.bunnies.len() + spawn_count |
| 615 |
); |
| 616 |
for i in 0..spawn_count { |
| 617 |
let random = ((elapsed.as_nanos() * (i + 1) as u128) & 0xFF) as f32 / 255.0; |
| 618 |
let speed = random * MAX_VELOCITY - (MAX_VELOCITY * 0.5); |
| 619 |
self.bunnies.push(Locals { |
| 620 |
position: [0.0, 0.5 * (self.extent[1] as f32)], |
| 621 |
velocity: [speed, 0.0], |
| 622 |
color, |
| 623 |
_pad: 0, |
| 624 |
}); |
| 625 |
} |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
fn render(&mut self) { |
| 630 |
let delta = 0.01; |
| 631 |
for bunny in self.bunnies.iter_mut() { |
| 632 |
bunny.position[0] += bunny.velocity[0] * delta; |
| 633 |
bunny.position[1] += bunny.velocity[1] * delta; |
| 634 |
bunny.velocity[1] += GRAVITY * delta; |
| 635 |
if (bunny.velocity[0] > 0.0 |
| 636 |
&& bunny.position[0] + 0.5 * BUNNY_SIZE > self.extent[0] as f32) |
| 637 |
|| (bunny.velocity[0] < 0.0 && bunny.position[0] - 0.5 * BUNNY_SIZE < 0.0) |
| 638 |
{ |
| 639 |
bunny.velocity[0] *= -1.0; |
| 640 |
} |
| 641 |
if bunny.velocity[1] < 0.0 && bunny.position[1] < 0.5 * BUNNY_SIZE { |
| 642 |
bunny.velocity[1] *= -1.0; |
| 643 |
} |
| 644 |
} |
| 645 |
|
| 646 |
if !self.bunnies.is_empty() { |
| 647 |
let size = self.bunnies.len() * self.local_alignment as usize; |
| 648 |
unsafe { |
| 649 |
let mapping = self |
| 650 |
.device |
| 651 |
.map_buffer(&self.local_buffer, 0..size as wgpu_types::BufferAddress) |
| 652 |
.unwrap(); |
| 653 |
ptr::copy_nonoverlapping( |
| 654 |
self.bunnies.as_ptr() as *const u8, |
| 655 |
mapping.ptr.as_ptr(), |
| 656 |
size, |
| 657 |
); |
| 658 |
assert!(mapping.is_coherent); |
| 659 |
self.device.unmap_buffer(&self.local_buffer); |
| 660 |
} |
| 661 |
} |
| 662 |
|
| 663 |
let ctx = &mut self.contexts[self.context_index]; |
| 664 |
|
| 665 |
let surface_tex = unsafe { |
| 666 |
self.surface |
| 667 |
.acquire_texture(None, &ctx.fence) |
| 668 |
.unwrap() |
| 669 |
.unwrap() |
| 670 |
.texture |
| 671 |
}; |
| 672 |
|
| 673 |
let target_barrier0 = hal::TextureBarrier { |
| 674 |
texture: surface_tex.borrow(), |
| 675 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 676 |
usage: hal::StateTransition { |
| 677 |
from: wgpu_types::TextureUses::UNINITIALIZED, |
| 678 |
to: wgpu_types::TextureUses::COLOR_TARGET, |
| 679 |
}, |
| 680 |
}; |
| 681 |
unsafe { |
| 682 |
ctx.encoder.begin_encoding(Some("frame")).unwrap(); |
| 683 |
ctx.encoder.transition_textures(iter::once(target_barrier0)); |
| 684 |
} |
| 685 |
|
| 686 |
let surface_view_desc = hal::TextureViewDescriptor { |
| 687 |
label: None, |
| 688 |
format: self.surface_format, |
| 689 |
dimension: wgpu_types::TextureViewDimension::D2, |
| 690 |
usage: wgpu_types::TextureUses::COLOR_TARGET, |
| 691 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 692 |
}; |
| 693 |
let surface_tex_view = unsafe { |
| 694 |
self.device |
| 695 |
.create_texture_view(surface_tex.borrow(), &surface_view_desc) |
| 696 |
.unwrap() |
| 697 |
}; |
| 698 |
let pass_desc = hal::RenderPassDescriptor { |
| 699 |
label: None, |
| 700 |
extent: wgpu_types::Extent3d { |
| 701 |
width: self.extent[0], |
| 702 |
height: self.extent[1], |
| 703 |
depth_or_array_layers: 1, |
| 704 |
}, |
| 705 |
sample_count: 1, |
| 706 |
color_attachments: &[Some(hal::ColorAttachment { |
| 707 |
target: hal::Attachment { |
| 708 |
view: &surface_tex_view, |
| 709 |
usage: wgpu_types::TextureUses::COLOR_TARGET, |
| 710 |
}, |
| 711 |
depth_slice: None, |
| 712 |
resolve_target: None, |
| 713 |
ops: hal::AttachmentOps::STORE, |
| 714 |
clear_value: wgpu_types::Color { |
| 715 |
r: 0.1, |
| 716 |
g: 0.2, |
| 717 |
b: 0.3, |
| 718 |
a: 1.0, |
| 719 |
}, |
| 720 |
})], |
| 721 |
depth_stencil_attachment: None, |
| 722 |
multiview: None, |
| 723 |
timestamp_writes: None, |
| 724 |
occlusion_query_set: None, |
| 725 |
}; |
| 726 |
unsafe { |
| 727 |
ctx.encoder.begin_render_pass(&pass_desc).unwrap(); |
| 728 |
ctx.encoder.set_render_pipeline(&self.pipeline); |
| 729 |
ctx.encoder |
| 730 |
.set_bind_group(&self.pipeline_layout, 0, &self.global_group, &[]); |
| 731 |
} |
| 732 |
|
| 733 |
for i in 0..self.bunnies.len() { |
| 734 |
let offset = (i as wgpu_types::DynamicOffset) |
| 735 |
* (self.local_alignment as wgpu_types::DynamicOffset); |
| 736 |
unsafe { |
| 737 |
ctx.encoder |
| 738 |
.set_bind_group(&self.pipeline_layout, 1, &self.local_group, &[offset]); |
| 739 |
ctx.encoder.draw(0, 4, 0, 1); |
| 740 |
} |
| 741 |
} |
| 742 |
|
| 743 |
ctx.frames_recorded += 1; |
| 744 |
|
| 745 |
let target_barrier1 = hal::TextureBarrier { |
| 746 |
texture: surface_tex.borrow(), |
| 747 |
range: wgpu_types::ImageSubresourceRange::default(), |
| 748 |
usage: hal::StateTransition { |
| 749 |
from: wgpu_types::TextureUses::COLOR_TARGET, |
| 750 |
to: wgpu_types::TextureUses::PRESENT, |
| 751 |
}, |
| 752 |
}; |
| 753 |
unsafe { |
| 754 |
ctx.encoder.end_render_pass(); |
| 755 |
ctx.encoder.transition_textures(iter::once(target_barrier1)); |
| 756 |
} |
| 757 |
|
| 758 |
unsafe { |
| 759 |
let cmd_buf = ctx.encoder.end_encoding().unwrap(); |
| 760 |
self.queue |
| 761 |
.submit( |
| 762 |
&[&cmd_buf], |
| 763 |
&[&surface_tex], |
| 764 |
(&mut ctx.fence, ctx.fence_value), |
| 765 |
) |
| 766 |
.unwrap(); |
| 767 |
self.queue.present(&self.surface, surface_tex).unwrap(); |
| 768 |
ctx.used_cmd_bufs.push(cmd_buf); |
| 769 |
ctx.used_views.push(surface_tex_view); |
| 770 |
}; |
| 771 |
|
| 772 |
log::debug!("Context switch from {}", self.context_index); |
| 773 |
let old_fence_value = ctx.fence_value; |
| 774 |
if self.contexts.len() == 1 { |
| 775 |
let hal_desc = hal::CommandEncoderDescriptor { |
| 776 |
label: None, |
| 777 |
queue: &self.queue, |
| 778 |
}; |
| 779 |
self.contexts.push(unsafe { |
| 780 |
ExecutionContext { |
| 781 |
encoder: self.device.create_command_encoder(&hal_desc).unwrap(), |
| 782 |
fence: self.device.create_fence().unwrap(), |
| 783 |
fence_value: 0, |
| 784 |
used_views: Vec::new(), |
| 785 |
used_cmd_bufs: Vec::new(), |
| 786 |
frames_recorded: 0, |
| 787 |
} |
| 788 |
}); |
| 789 |
} |
| 790 |
self.context_index = (self.context_index + 1) % self.contexts.len(); |
| 791 |
let next = &mut self.contexts[self.context_index]; |
| 792 |
unsafe { |
| 793 |
next.wait_and_clear(&self.device); |
| 794 |
} |
| 795 |
next.fence_value = old_fence_value + 1; |
| 796 |
} |
| 797 |
} |
| 798 |
|
| 799 |
cfg_if::cfg_if! { |
| 800 |
// Apple + Metal |
| 801 |
if #[cfg(all(target_vendor = "apple", feature = "metal"))] { |
| 802 |
type Api = hal::api::Metal; |
| 803 |
} |
| 804 |
// Wasm + Vulkan |
| 805 |
else if #[cfg(all(not(target_arch = "wasm32"), feature = "vulkan"))] { |
| 806 |
type Api = hal::api::Vulkan; |
| 807 |
} |
| 808 |
// Windows + DX12 |
| 809 |
else if #[cfg(all(windows, feature = "dx12"))] { |
| 810 |
type Api = hal::api::Dx12; |
| 811 |
} |
| 812 |
// Anything + GLES |
| 813 |
else if #[cfg(feature = "gles")] { |
| 814 |
type Api = hal::api::Gles; |
| 815 |
} |
| 816 |
// Fallback |
| 817 |
else { |
| 818 |
type Api = hal::api::Noop; |
| 819 |
} |
| 820 |
} |
| 821 |
|
| 822 |
fn main() { |
| 823 |
env_logger::init(); |
| 824 |
|
| 825 |
let event_loop = winit::event_loop::EventLoop::new().unwrap(); |
| 826 |
let window = winit::window::WindowBuilder::new() |
| 827 |
.with_title("hal-bunnymark") |
| 828 |
.build(&event_loop) |
| 829 |
.unwrap(); |
| 830 |
|
| 831 |
let example_result = Example::<Api>::init(&window); |
| 832 |
let mut example = Some(example_result.expect("Selected backend is not supported")); |
| 833 |
|
| 834 |
println!("Press space to spawn bunnies."); |
| 835 |
|
| 836 |
let mut last_frame_inst = Instant::now(); |
| 837 |
let (mut frame_count, mut accum_time) = (0, 0.0); |
| 838 |
|
| 839 |
event_loop |
| 840 |
.run(move |event, target| { |
| 841 |
let _ = &window; // force ownership by the closure |
| 842 |
target.set_control_flow(ControlFlow::Poll); |
| 843 |
|
| 844 |
match event { |
| 845 |
Event::LoopExiting => { |
| 846 |
example.take().unwrap().exit(); |
| 847 |
} |
| 848 |
Event::WindowEvent { event, .. } => match event { |
| 849 |
WindowEvent::KeyboardInput { |
| 850 |
event: |
| 851 |
KeyEvent { |
| 852 |
logical_key: Key::Named(NamedKey::Escape), |
| 853 |
state: ElementState::Pressed, |
| 854 |
.. |
| 855 |
}, |
| 856 |
.. |
| 857 |
} |
| 858 |
| WindowEvent::CloseRequested => target.exit(), |
| 859 |
WindowEvent::RedrawRequested => { |
| 860 |
let ex = example.as_mut().unwrap(); |
| 861 |
{ |
| 862 |
accum_time += last_frame_inst.elapsed().as_secs_f32(); |
| 863 |
last_frame_inst = Instant::now(); |
| 864 |
frame_count += 1; |
| 865 |
if frame_count == 100 && !ex.is_empty() { |
| 866 |
println!( |
| 867 |
"Avg frame time {}ms", |
| 868 |
accum_time * 1000.0 / frame_count as f32 |
| 869 |
); |
| 870 |
accum_time = 0.0; |
| 871 |
frame_count = 0; |
| 872 |
} |
| 873 |
} |
| 874 |
ex.render(); |
| 875 |
window.request_redraw(); |
| 876 |
} |
| 877 |
_ => { |
| 878 |
example.as_mut().unwrap().update(event); |
| 879 |
} |
| 880 |
}, |
| 881 |
_ => {} |
| 882 |
} |
| 883 |
}) |
| 884 |
.unwrap(); |
| 885 |
} |