astrelis-render 0.2.4

Astrelis Core Rendering Module
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
//! Indirect draw buffer support for GPU-driven rendering.
//!
//! This module provides type-safe wrappers for indirect draw commands and buffers.
//! Indirect drawing allows the GPU to control draw parameters, enabling techniques
//! like GPU culling and dynamic batching.
//!
//! # Feature Requirements
//!
//! - `INDIRECT_FIRST_INSTANCE`: Required for using `first_instance` in indirect commands.
//! - `multi_draw_indirect()`: Available on all desktop GPUs (requires `DownlevelFlags::INDIRECT_EXECUTION`).
//! - `MULTI_DRAW_INDIRECT_COUNT`: Required for GPU-driven draw count variant.

use std::marker::PhantomData;

use bytemuck::{Pod, Zeroable};

use crate::context::GraphicsContext;
use crate::features::GpuFeatures;

/// Indirect draw command for non-indexed geometry.
///
/// This matches the layout expected by `wgpu::RenderPass::draw_indirect`.
///
/// # Fields
///
/// * `vertex_count` - Number of vertices to draw
/// * `instance_count` - Number of instances to draw
/// * `first_vertex` - Index of the first vertex to draw
/// * `first_instance` - Instance ID of the first instance (requires INDIRECT_FIRST_INSTANCE)
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct DrawIndirect {
    pub vertex_count: u32,
    pub instance_count: u32,
    pub first_vertex: u32,
    pub first_instance: u32,
}

// SAFETY: DrawIndirect is a repr(C) struct of u32s with no padding
unsafe impl Pod for DrawIndirect {}
unsafe impl Zeroable for DrawIndirect {}

impl DrawIndirect {
    /// Create a new indirect draw command.
    pub const fn new(
        vertex_count: u32,
        instance_count: u32,
        first_vertex: u32,
        first_instance: u32,
    ) -> Self {
        Self {
            vertex_count,
            instance_count,
            first_vertex,
            first_instance,
        }
    }

    /// Create a simple draw command for a single instance.
    pub const fn single(vertex_count: u32) -> Self {
        Self::new(vertex_count, 1, 0, 0)
    }

    /// Create a draw command for multiple instances.
    pub const fn instanced(vertex_count: u32, instance_count: u32) -> Self {
        Self::new(vertex_count, instance_count, 0, 0)
    }

    /// Size of the command in bytes.
    pub const fn size() -> u64 {
        std::mem::size_of::<Self>() as u64
    }
}

/// Indirect draw command for indexed geometry.
///
/// This matches the layout expected by `wgpu::RenderPass::draw_indexed_indirect`.
///
/// # Fields
///
/// * `index_count` - Number of indices to draw
/// * `instance_count` - Number of instances to draw
/// * `first_index` - Index of the first index to draw
/// * `base_vertex` - Value added to each index before indexing into the vertex buffer
/// * `first_instance` - Instance ID of the first instance (requires INDIRECT_FIRST_INSTANCE)
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct DrawIndexedIndirect {
    pub index_count: u32,
    pub instance_count: u32,
    pub first_index: u32,
    pub base_vertex: i32,
    pub first_instance: u32,
}

// SAFETY: DrawIndexedIndirect is a repr(C) struct with no padding
unsafe impl Pod for DrawIndexedIndirect {}
unsafe impl Zeroable for DrawIndexedIndirect {}

impl DrawIndexedIndirect {
    /// Create a new indexed indirect draw command.
    pub const fn new(
        index_count: u32,
        instance_count: u32,
        first_index: u32,
        base_vertex: i32,
        first_instance: u32,
    ) -> Self {
        Self {
            index_count,
            instance_count,
            first_index,
            base_vertex,
            first_instance,
        }
    }

    /// Create a simple indexed draw command for a single instance.
    pub const fn single(index_count: u32) -> Self {
        Self::new(index_count, 1, 0, 0, 0)
    }

    /// Create an indexed draw command for multiple instances.
    pub const fn instanced(index_count: u32, instance_count: u32) -> Self {
        Self::new(index_count, instance_count, 0, 0, 0)
    }

    /// Size of the command in bytes.
    pub const fn size() -> u64 {
        std::mem::size_of::<Self>() as u64
    }
}

/// Marker trait for indirect draw command types.
pub trait IndirectCommand: Pod + Zeroable + Default {
    /// Size of a single command in bytes.
    const SIZE: u64;
}

impl IndirectCommand for DrawIndirect {
    const SIZE: u64 = std::mem::size_of::<Self>() as u64;
}

impl IndirectCommand for DrawIndexedIndirect {
    const SIZE: u64 = std::mem::size_of::<Self>() as u64;
}

/// A type-safe GPU buffer for indirect draw commands.
///
/// This wrapper ensures type safety and provides convenient methods for
/// writing and using indirect draw commands.
///
/// # Type Parameters
///
/// * `T` - The type of indirect command (either `DrawIndirect` or `DrawIndexedIndirect`)
///
/// # Example
///
/// ```ignore
/// use astrelis_render::{IndirectBuffer, DrawIndexedIndirect, Renderer};
///
/// // Create an indirect buffer for 100 indexed draw commands
/// let indirect_buffer = IndirectBuffer::<DrawIndexedIndirect>::new(
///     context,
///     Some("My Indirect Buffer"),
///     100,
/// );
///
/// // Write commands
/// let commands = vec![
///     DrawIndexedIndirect::single(36),  // Draw 36 indices
///     DrawIndexedIndirect::instanced(36, 10),  // Draw 36 indices, 10 instances
/// ];
/// indirect_buffer.write(&context.queue, &commands);
///
/// // In render pass
/// render_pass.draw_indexed_indirect(indirect_buffer.buffer(), 0);
/// ```
pub struct IndirectBuffer<T: IndirectCommand> {
    buffer: wgpu::Buffer,
    capacity: usize,
    _marker: PhantomData<T>,
}

impl<T: IndirectCommand> IndirectBuffer<T> {
    /// Create a new indirect buffer with the specified capacity.
    ///
    /// # Arguments
    ///
    /// * `context` - The graphics context
    /// * `label` - Optional debug label
    /// * `capacity` - Maximum number of commands the buffer can hold
    ///
    /// # Panics
    ///
    /// Panics if `INDIRECT_FIRST_INSTANCE` feature is not enabled on the context.
    pub fn new(context: &GraphicsContext, label: Option<&str>, capacity: usize) -> Self {
        // Check that required feature is available
        context.require_feature(GpuFeatures::INDIRECT_FIRST_INSTANCE);

        let buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
            label,
            size: T::SIZE * capacity as u64,
            usage: wgpu::BufferUsages::INDIRECT
                | wgpu::BufferUsages::COPY_DST
                | wgpu::BufferUsages::STORAGE,
            mapped_at_creation: false,
        });

        Self {
            buffer,
            capacity,
            _marker: PhantomData,
        }
    }

    /// Create a new indirect buffer initialized with commands.
    ///
    /// # Arguments
    ///
    /// * `context` - The graphics context
    /// * `label` - Optional debug label
    /// * `commands` - Initial commands to write to the buffer
    ///
    /// # Panics
    ///
    /// Panics if `INDIRECT_FIRST_INSTANCE` feature is not enabled on the context.
    pub fn new_init(context: &GraphicsContext, label: Option<&str>, commands: &[T]) -> Self {
        context.require_feature(GpuFeatures::INDIRECT_FIRST_INSTANCE);

        let buffer = context.device().create_buffer(&wgpu::BufferDescriptor {
            label,
            size: T::SIZE * commands.len() as u64,
            usage: wgpu::BufferUsages::INDIRECT
                | wgpu::BufferUsages::COPY_DST
                | wgpu::BufferUsages::STORAGE,
            mapped_at_creation: false,
        });

        context
            .queue()
            .write_buffer(&buffer, 0, bytemuck::cast_slice(commands));

        Self {
            buffer,
            capacity: commands.len(),
            _marker: PhantomData,
        }
    }

    /// Get the underlying wgpu buffer.
    pub fn buffer(&self) -> &wgpu::Buffer {
        &self.buffer
    }

    /// Get the capacity (maximum number of commands).
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Get the size of the buffer in bytes.
    pub fn size_bytes(&self) -> u64 {
        T::SIZE * self.capacity as u64
    }

    /// Get the byte offset of a command at the given index.
    pub fn offset_of(&self, index: usize) -> u64 {
        T::SIZE * index as u64
    }

    /// Write commands to the buffer starting at the given index.
    ///
    /// # Arguments
    ///
    /// * `queue` - The command queue to use for the write
    /// * `start_index` - Index of the first command to write
    /// * `commands` - Commands to write
    ///
    /// # Panics
    ///
    /// Panics if the write would exceed the buffer capacity.
    pub fn write_at(&self, queue: &wgpu::Queue, start_index: usize, commands: &[T]) {
        assert!(
            start_index + commands.len() <= self.capacity,
            "Indirect buffer write would exceed capacity: {} + {} > {}",
            start_index,
            commands.len(),
            self.capacity
        );

        let offset = T::SIZE * start_index as u64;
        queue.write_buffer(&self.buffer, offset, bytemuck::cast_slice(commands));
    }

    /// Write commands to the buffer starting at index 0.
    ///
    /// # Arguments
    ///
    /// * `queue` - The command queue to use for the write
    /// * `commands` - Commands to write
    ///
    /// # Panics
    ///
    /// Panics if the write would exceed the buffer capacity.
    pub fn write(&self, queue: &wgpu::Queue, commands: &[T]) {
        self.write_at(queue, 0, commands);
    }

    /// Clear the buffer by writing zeros.
    pub fn clear(&self, queue: &wgpu::Queue) {
        let zeros = vec![T::default(); self.capacity];
        queue.write_buffer(&self.buffer, 0, bytemuck::cast_slice(&zeros));
    }
}

/// Extension trait for render passes to use indirect buffers.
pub trait RenderPassIndirectExt<'a> {
    /// Draw non-indexed geometry using an indirect buffer.
    ///
    /// # Arguments
    ///
    /// * `indirect_buffer` - Buffer containing draw commands
    /// * `index` - Index of the command to execute
    fn draw_indirect_at(&mut self, indirect_buffer: &'a IndirectBuffer<DrawIndirect>, index: usize);

    /// Draw indexed geometry using an indirect buffer.
    ///
    /// # Arguments
    ///
    /// * `indirect_buffer` - Buffer containing draw commands
    /// * `index` - Index of the command to execute
    fn draw_indexed_indirect_at(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndexedIndirect>,
        index: usize,
    );
}

impl<'a> RenderPassIndirectExt<'a> for wgpu::RenderPass<'a> {
    fn draw_indirect_at(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndirect>,
        index: usize,
    ) {
        let offset = indirect_buffer.offset_of(index);
        self.draw_indirect(indirect_buffer.buffer(), offset);
    }

    fn draw_indexed_indirect_at(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndexedIndirect>,
        index: usize,
    ) {
        let offset = indirect_buffer.offset_of(index);
        self.draw_indexed_indirect(indirect_buffer.buffer(), offset);
    }
}

/// Extension trait for multi-draw indirect operations.
///
/// Requires `DownlevelFlags::INDIRECT_EXECUTION` (available on all desktop GPUs).
pub trait RenderPassMultiDrawIndirectExt<'a> {
    /// Draw non-indexed geometry multiple times using an indirect buffer.
    ///
    /// # Arguments
    ///
    /// * `indirect_buffer` - Buffer containing draw commands
    /// * `start_index` - Index of the first command to execute
    /// * `count` - Number of commands to execute
    ///
    /// # Panics
    ///
    /// Requires `DownlevelFlags::INDIRECT_EXECUTION`.
    fn multi_draw_indirect(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndirect>,
        start_index: usize,
        count: u32,
    );

    /// Draw indexed geometry multiple times using an indirect buffer.
    ///
    /// # Arguments
    ///
    /// * `indirect_buffer` - Buffer containing draw commands
    /// * `start_index` - Index of the first command to execute
    /// * `count` - Number of commands to execute
    ///
    /// # Panics
    ///
    /// Requires `DownlevelFlags::INDIRECT_EXECUTION`.
    fn multi_draw_indexed_indirect(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndexedIndirect>,
        start_index: usize,
        count: u32,
    );
}

impl<'a> RenderPassMultiDrawIndirectExt<'a> for wgpu::RenderPass<'a> {
    fn multi_draw_indirect(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndirect>,
        start_index: usize,
        count: u32,
    ) {
        let offset = indirect_buffer.offset_of(start_index);
        self.multi_draw_indirect(indirect_buffer.buffer(), offset, count);
    }

    fn multi_draw_indexed_indirect(
        &mut self,
        indirect_buffer: &'a IndirectBuffer<DrawIndexedIndirect>,
        start_index: usize,
        count: u32,
    ) {
        let offset = indirect_buffer.offset_of(start_index);
        self.multi_draw_indexed_indirect(indirect_buffer.buffer(), offset, count);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_draw_indirect_size() {
        // Verify the struct matches wgpu's expected layout
        assert_eq!(DrawIndirect::size(), 16); // 4 u32s = 16 bytes
        assert_eq!(DrawIndirect::SIZE, 16);
    }

    #[test]
    fn test_draw_indexed_indirect_size() {
        // Verify the struct matches wgpu's expected layout
        assert_eq!(DrawIndexedIndirect::size(), 20); // 4 u32s + 1 i32 = 20 bytes
        assert_eq!(DrawIndexedIndirect::SIZE, 20);
    }

    #[test]
    fn test_draw_indirect_single() {
        let cmd = DrawIndirect::single(36);
        assert_eq!(cmd.vertex_count, 36);
        assert_eq!(cmd.instance_count, 1);
        assert_eq!(cmd.first_vertex, 0);
        assert_eq!(cmd.first_instance, 0);
    }

    #[test]
    fn test_draw_indexed_indirect_instanced() {
        let cmd = DrawIndexedIndirect::instanced(36, 100);
        assert_eq!(cmd.index_count, 36);
        assert_eq!(cmd.instance_count, 100);
        assert_eq!(cmd.first_index, 0);
        assert_eq!(cmd.base_vertex, 0);
        assert_eq!(cmd.first_instance, 0);
    }
}