pub struct BufferHandler { /* private fields */ }
Expand description

safe handler of GPU buffer Buffer

Implementations§

Creates a buffer handler from a slice.

Examples found in repository?
src/light.rs (line 28)
27
28
29
    pub fn buffer(&self, device: &Device) -> BufferHandler {
        BufferHandler::from_slice(&[self.light_info()], device, BufferUsages::UNIFORM)
    }
More examples
Hide additional examples
src/camera.rs (line 273)
272
273
274
    pub fn buffer(&self, as_rat: f64, device: &Device) -> BufferHandler {
        BufferHandler::from_slice(&[self.camera_info(as_rat)], device, BufferUsages::UNIFORM)
    }
src/scene.rs (line 179)
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
    pub fn lights_buffer(&self, device: &Device) -> BufferHandler {
        let mut light_vec: Vec<_> = self.studio.lights.iter().map(Light::light_info).collect();
        light_vec.resize(LIGHT_MAX, LightInfo::zeroed());
        BufferHandler::from_slice(&light_vec, device, BufferUsages::UNIFORM)
    }

    #[inline(always)]
    fn sampling_buffer(
        device: &Device,
        render_texture: RenderTextureConfig,
        sample_count: u32,
    ) -> Texture {
        device.create_texture(&TextureDescriptor {
            size: Extent3d {
                width: render_texture.canvas_size.0,
                height: render_texture.canvas_size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count,
            dimension: TextureDimension::D2,
            format: render_texture.format,
            usage: TextureUsages::RENDER_ATTACHMENT,
            label: None,
        })
    }

    #[inline(always)]
    fn depth_texture(device: &Device, size: (u32, u32), sample_count: u32) -> Texture {
        device.create_texture(&TextureDescriptor {
            size: Extent3d {
                width: size.0,
                height: size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count,
            dimension: TextureDimension::D2,
            format: TextureFormat::Depth32Float,
            usage: TextureUsages::RENDER_ATTACHMENT,
            label: None,
        })
    }

    fn backend_buffers(&self, device: &Device) -> (Option<Texture>, Option<Texture>) {
        let foward_depth = if self.backend_buffer.depth_test {
            Some(Self::depth_texture(
                device,
                self.render_texture.canvas_size,
                self.backend_buffer.sample_count,
            ))
        } else {
            None
        };
        let sampling_buffer = if self.backend_buffer.sample_count > 1 {
            Some(Self::sampling_buffer(
                device,
                self.render_texture,
                self.backend_buffer.sample_count,
            ))
        } else {
            None
        };
        (foward_depth, sampling_buffer)
    }
}

/// Mutable reference of `SceneDescriptor` in `Scene`.
///
/// When this struct is dropped, the backend buffers of scene will be updated.
#[derive(Debug)]
pub struct SceneDescriptorMut<'a>(&'a mut Scene);

impl<'a> std::ops::Deref for SceneDescriptorMut<'a> {
    type Target = SceneDescriptor;
    #[inline(always)]
    fn deref(&self) -> &SceneDescriptor { &self.0.scene_desc }
}

impl<'a> std::ops::DerefMut for SceneDescriptorMut<'a> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut SceneDescriptor { &mut self.0.scene_desc }
}

impl<'a> Drop for SceneDescriptorMut<'a> {
    fn drop(&mut self) {
        let (forward_depth, sampling_buffer) = self.backend_buffers(self.0.device());
        self.0.foward_depth = forward_depth;
        self.0.sampling_buffer = sampling_buffer;
    }
}

impl Scene {
    #[inline(always)]
    fn camera_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn lights_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn scene_bgl_entry() -> PreBindGroupLayoutEntry {
        PreBindGroupLayoutEntry {
            visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
            ty: BindingType::Buffer {
                ty: BufferBindingType::Uniform,
                has_dynamic_offset: false,
                min_binding_size: None,
            },
            count: None,
        }
    }

    #[inline(always)]
    fn init_scene_bind_group_layout(device: &Device) -> BindGroupLayout {
        bind_group_util::create_bind_group_layout(
            device,
            &[
                Self::camera_bgl_entry(),
                Self::lights_bgl_entry(),
                Self::scene_bgl_entry(),
            ],
        )
    }

    /// constructor
    // About `scene_desc`, entity is better than reference for the performance.
    // This is reference because only for as wgpu is.
    #[inline(always)]
    pub fn new(device_handler: DeviceHandler, scene_desc: &SceneDescriptor) -> Scene {
        let device = device_handler.device();
        let (foward_depth, sampling_buffer) = scene_desc.backend_buffers(device);
        let bind_group_layout = Self::init_scene_bind_group_layout(device);
        Scene {
            objects: Default::default(),
            bind_group_layout,
            foward_depth,
            sampling_buffer,
            clock: instant::Instant::now(),
            scene_desc: scene_desc.clone(),
            device_handler,
        }
    }

    /// Construct scene from default GPU device.
    /// # Arguments
    /// - `size`: (width, height)
    pub async fn from_default_device(scene_desc: &SceneDescriptor) -> Scene {
        Scene::new(DeviceHandler::default_device().await, scene_desc)
    }

    /// Creates compatible texture for render attachment.
    ///
    /// # Remarks
    /// The usage of texture is `TextureUsages::RENDER_ATTACHMENT | TetureUsages::COPY_SRC`.
    #[inline(always)]
    pub fn compatible_texture(&self) -> Texture {
        let config = self.scene_desc.render_texture;
        self.device().create_texture(&TextureDescriptor {
            label: None,
            size: Extent3d {
                width: config.canvas_size.0,
                height: config.canvas_size.1,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: TextureDimension::D2,
            format: config.format,
            usage: TextureUsages::RENDER_ATTACHMENT | TextureUsages::COPY_SRC,
        })
    }

    /// Returns the reference of its own `DeviceHandler`.
    #[inline(always)]
    pub const fn device_handler(&self) -> &DeviceHandler { &self.device_handler }

    /// Returns the reference of the device.
    #[inline(always)]
    pub const fn device(&self) -> &Arc<Device> { &self.device_handler.device }

    /// Returns the reference of the queue.
    #[inline(always)]
    pub const fn queue(&self) -> &Arc<Queue> { &self.device_handler.queue }

    /// Returns the elapsed time since the scene was created.
    #[inline(always)]
    pub fn elapsed(&self) -> std::time::Duration { self.clock.elapsed() }

    /// Returns the reference of the descriptor.
    #[inline(always)]
    pub const fn descriptor(&self) -> &SceneDescriptor { &self.scene_desc }

    /// Returns the mutable reference of the descriptor.
    ///
    /// # Remarks
    ///
    /// When the return value is dropped, the depth buffer and sampling buffer are automatically updated.
    /// Use `studio_config_mut` if you only want to update the colors of the camera, lights, and background.
    #[inline(always)]
    pub fn descriptor_mut(&mut self) -> SceneDescriptorMut<'_> { SceneDescriptorMut(self) }

    /// Returns the reference of the studio configuration.
    #[inline(always)]
    pub const fn studio_config(&self) -> &StudioConfig { &self.scene_desc.studio }

    /// Returns the mutable reference of the studio configuration.
    #[inline(always)]
    pub fn studio_config_mut(&mut self) -> &mut StudioConfig { &mut self.scene_desc.studio }

    /// Returns the bind group layout in the scene.
    #[inline(always)]
    pub const fn bind_group_layout(&self) -> &BindGroupLayout { &self.bind_group_layout }

    /// Creates a `UNIFORM` buffer of the camera.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 0) uniform Camera {
    ///     mat4 camera_matrix;     // the camera matrix
    ///     mat4 camera_projection; // the projection into the normalized view volume
    /// };
    /// ```
    #[inline(always)]
    pub fn camera_buffer(&self) -> BufferHandler { self.scene_desc.camera_buffer(self.device()) }

    /// Creates a `STORAGE` buffer of all lights.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// struct Light {
    ///     vec4 position;      // the position of light, position.w == 1.0
    ///     vec4 color;         // the color of light, color.w == 1.0
    ///     uvec4 light_type;   // Point => uvec4(0, 0, 0, 0), Uniform => uvec4(1, 0, 0, 0)
    /// };
    ///
    /// layout(set = 0, binding = 1) buffer Lights {
    ///     Light lights[]; // the number of lights must be gotten from another place
    /// };
    /// ```
    #[inline(always)]
    pub fn lights_buffer(&self) -> BufferHandler { self.scene_desc.lights_buffer(self.device()) }

    /// Creates a `UNIFORM` buffer of the scene status.
    ///
    /// The bind group provides [`Scene`] holds this uniform buffer.
    ///
    /// # Shader Example
    /// ```glsl
    /// layout(set = 0, binding = 2) uniform Scene {
    ///     vec4 bk_color;  // color of back ground
    ///     float time;     // elapsed time since the scene was created.
    ///     uint nlights;   // the number of lights
    /// };
    /// ```
    #[inline(always)]
    pub fn scene_status_buffer(&self) -> BufferHandler {
        let bk = self.scene_desc.studio.background;
        let size = self.scene_desc.render_texture.canvas_size;
        let scene_info = SceneInfo {
            background_color: [bk.r as f32, bk.g as f32, bk.b as f32, bk.a as f32],
            resolution: [size.0, size.1],
            time: self.elapsed().as_secs_f32(),
            num_of_lights: self.scene_desc.studio.lights.len() as u32,
        };
        BufferHandler::from_slice(&[scene_info], self.device(), BufferUsages::UNIFORM)
    }

Returns the reference of the buffer.

Returns the size of the buffer.

Creates a binding resource from buffer slice.

Examples found in repository?
src/scene.rs (line 497)
492
493
494
495
496
497
498
499
500
501
502
    pub fn scene_bind_group(&self) -> BindGroup {
        bind_group_util::create_bind_group(
            self.device(),
            &self.bind_group_layout,
            vec![
                self.camera_buffer().binding_resource(),
                self.lights_buffer().binding_resource(),
                self.scene_status_buffer().binding_resource(),
            ],
        )
    }

Copy the values of buffer to dest.

Panic

Panic occurs if the size of dest is smaller than the one of self.

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.