aboutsummaryrefslogtreecommitdiff
path: root/examples/render-quad/src/draw_pass.rs
blob: 9b32fcbdcd6f451c616f8b2424120f9a199605d6 (plain)
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
//! Minimal code for drawing any level, based on traits from stockton-levels

use anyhow::{Context, Result};
use hal::{
    buffer::SubRange,
    command::{ClearColor, ClearValue, RenderAttachmentInfo, SubpassContents},
    format::Format,
    image::Layout,
    pass::Attachment,
    pso::{
        BlendDesc, BlendOp, BlendState, ColorBlendDesc, ColorMask, DepthStencilDesc, Face, Factor,
        FrontFace, InputAssemblerDesc, LogicOp, PolygonMode, Primitive, Rasterizer, State,
        VertexInputRate,
    },
};
use legion::{Entity, IntoQuery};
use std::{
    array::IntoIter,
    iter::{empty, once},
};
use stockton_skeleton::{
    buffers::draw::DrawBuffers,
    builders::{
        AttachmentSpec, CompletePipeline, PipelineSpecBuilder, RenderpassSpec, ShaderDesc,
        ShaderKind, VertexBufferSpec, VertexPrimitiveAssemblerSpec,
    },
    draw_passes::util::TargetSpecificResources,
    mem::{DataPool, StagingPool},
    queue_negotiator::QueueFamilyNegotiator,
    types::*,
    DrawPass, IntoDrawPass, PassPosition, RenderingContext, Session,
};

use crate::ExampleState;

/// The vertices that go to the shader (XY + RGB)
#[derive(Debug, Clone, Copy)]
#[repr(C)]
struct Vertex(pub Vector2, pub Vector3);

/// An example draw pass
pub struct ExampleDrawPass<'a> {
    /// Index and vertex buffer pair
    draw_buffers: DrawBuffers<'a, Vertex, DataPool, StagingPool>,

    /// Resources that depend on the surface. This is seperate so that we can deal with surface changes more easily.
    surface_resources: SurfaceDependentResources,

    /// Entity we get our state from
    state_ent: Entity,
}

/// Config for our draw pass. This is turned into our drawpass using [`IntoDrawPass`]
pub struct ExampleDrawPassConfig {
    pub state_ent: Entity,
}

impl<'a, P: PassPosition> DrawPass<P> for ExampleDrawPass<'a> {
    /// Called every frame to queue actual drawing.
    fn queue_draw(
        &mut self,
        session: &Session,
        img_view: &ImageViewT,
        cmd_buffer: &mut CommandBufferT,
    ) -> anyhow::Result<()> {
        // Commit any changes to our vertex buffers
        // We queue this first so that it's executed before any draw commands
        self.draw_buffers
            .vertex_buffer
            .record_commit_cmds(cmd_buffer)?;
        self.draw_buffers
            .index_buffer
            .record_commit_cmds(cmd_buffer)?;

        // Get framebuffer
        let fb = self.surface_resources.framebuffers.get_next();

        // Get state
        let (state,) = <(&ExampleState,)>::query().get(&session.world, self.state_ent)?;

        // Begin render pass & bind everything needed
        unsafe {
            cmd_buffer.begin_render_pass(
                &self.surface_resources.pipeline.renderpass,
                fb,
                self.surface_resources.pipeline.render_area,
                vec![RenderAttachmentInfo {
                    image_view: img_view,
                    clear_value: ClearValue {
                        color: ClearColor {
                            float32: [0.0, 0.0, 0.0, 1.0],
                        },
                    },
                }]
                .into_iter(),
                SubpassContents::Inline,
            );
            cmd_buffer.bind_graphics_pipeline(&self.surface_resources.pipeline.pipeline);

            // Bind buffers
            cmd_buffer.bind_vertex_buffers(
                0,
                once((
                    self.draw_buffers.vertex_buffer.get_buffer(),
                    SubRange {
                        offset: 0,
                        size: None,
                    },
                )),
            );
            cmd_buffer.bind_index_buffer(
                self.draw_buffers.index_buffer.get_buffer(),
                SubRange {
                    offset: 0,
                    size: None,
                },
                hal::IndexType::U16,
            );
        }

        // Draw an example
        self.draw_buffers.index_buffer[0] = (0, 1, 2);
        self.draw_buffers.vertex_buffer[0] = Vertex(Vector2::new(0.5, 0.5), state.color());
        self.draw_buffers.vertex_buffer[1] = Vertex(Vector2::new(0.0, -0.5), state.color());
        self.draw_buffers.vertex_buffer[2] = Vertex(Vector2::new(-0.5, 0.5), state.color());

        unsafe {
            cmd_buffer.draw_indexed(0..3, 0, 0..1);
        }

        // Remember to clean up afterwards!
        unsafe {
            cmd_buffer.end_render_pass();
        }

        Ok(())
    }

    /// Destroy all our vulkan objects
    fn deactivate(self, context: &mut RenderingContext) -> Result<()> {
        self.draw_buffers.deactivate(context);
        self.surface_resources.deactivate(context)?;

        Ok(())
    }

    /// Deal with a surface change
    fn handle_surface_change(
        mut self,
        _session: &Session,
        context: &mut RenderingContext,
    ) -> Result<Self> {
        // We need to make sure there's never an invalid value for self.surface_resources,
        // and that we deactivate everything in case of an error (since we'll be dropped in that case).
        let new_resources = match SurfaceDependentResources::new::<P>(context) {
            Ok(x) => x,
            Err(e) => {
                <Self as DrawPass<P>>::deactivate(self, context)?;

                return Err(e);
            }
        };

        let old_resources = self.surface_resources;
        self.surface_resources = new_resources;

        match old_resources.deactivate(context) {
            Ok(_) => Ok(self),
            Err(e) => {
                <Self as DrawPass<P>>::deactivate(self, context)?;
                Err(e)
            }
        }
    }
}

impl<'a, P: PassPosition> IntoDrawPass<ExampleDrawPass<'a>, P> for ExampleDrawPassConfig {
    /// Create our example draw pass
    fn init(
        self,
        _session: &mut Session,
        context: &mut RenderingContext,
    ) -> Result<ExampleDrawPass<'a>> {
        let surface_resources = SurfaceDependentResources::new::<P>(context)?;
        let draw_buffers =
            match DrawBuffers::from_context(context).context("Error creating draw buffers") {
                Ok(x) => x,
                Err(e) => {
                    surface_resources.deactivate(context)?;
                    return Err(e);
                }
            };

        Ok(ExampleDrawPass {
            draw_buffers,
            surface_resources,
            state_ent: self.state_ent,
        })
    }

    fn find_aux_queues(
        _adapter: &Adapter,
        _queue_negotiator: &mut QueueFamilyNegotiator,
    ) -> Result<()> {
        // We don't need any queues, but we'd need code to find their families here if we did.
        Ok(())
    }
}

/// Used to store resources which depend on the surface, for convenience in handle_surface_change
struct SurfaceDependentResources {
    pub pipeline: CompletePipeline,
    pub framebuffers: TargetSpecificResources<FramebufferT>,
}

impl SurfaceDependentResources {
    pub fn new<P: PassPosition>(context: &mut RenderingContext) -> Result<Self> {
        let (pipeline, framebuffers) = {
            // Our graphics pipeline
            // Vulkan has a lot of config, so this is basically always going to be a big builder block
            let pipeline_spec = PipelineSpecBuilder::default()
                .rasterizer(Rasterizer {
                    polygon_mode: PolygonMode::Fill,
                    cull_face: Face::NONE,
                    front_face: FrontFace::CounterClockwise,
                    depth_clamping: false,
                    depth_bias: None,
                    conservative: true,
                    line_width: State::Static(1.0),
                })
                .depth_stencil(DepthStencilDesc {
                    depth: None,
                    depth_bounds: false,
                    stencil: None,
                })
                .blender(BlendDesc {
                    logic_op: Some(LogicOp::Copy),
                    targets: vec![ColorBlendDesc {
                        mask: ColorMask::ALL,
                        blend: Some(BlendState {
                            color: BlendOp::Add {
                                src: Factor::SrcAlpha,
                                dst: Factor::OneMinusSrcAlpha,
                            },
                            alpha: BlendOp::Add {
                                src: Factor::SrcAlpha,
                                dst: Factor::OneMinusSrcAlpha,
                            },
                        }),
                    }],
                })
                .primitive_assembler(VertexPrimitiveAssemblerSpec::with_buffers(
                    InputAssemblerDesc::new(Primitive::TriangleList),
                    vec![VertexBufferSpec {
                        attributes: vec![Format::Rg32Sfloat, Format::Rgb32Sfloat],
                        rate: VertexInputRate::Vertex,
                    }],
                ))
                .shader_vertex(ShaderDesc {
                    source: include_str!("./data/shader.vert").to_string(),
                    entry: "main".to_string(),
                    kind: ShaderKind::Vertex,
                })
                .shader_fragment(ShaderDesc {
                    source: include_str!("./data/shader.frag").to_string(),
                    entry: "main".to_string(),
                    kind: ShaderKind::Fragment,
                })
                .renderpass(RenderpassSpec {
                    colors: vec![AttachmentSpec {
                        attachment: Attachment {
                            format: Some(context.properties().color_format),
                            samples: 1,
                            // Here we use PassPosition to get the proper operations
                            // Since, for example, the last pass needs to finish in present mode.
                            ops: P::attachment_ops(),
                            stencil_ops: P::attachment_ops(),
                            layouts: P::layout_as_range(),
                        },
                        // This is the layout we want to deal with in our `queue_draw` function.
                        // It's almost certainly `Layout::ColorAttachmentOptimal`
                        used_layout: Layout::ColorAttachmentOptimal,
                    }],
                    depth: None,
                    inputs: vec![],
                    resolves: vec![],
                    preserves: vec![],
                })
                .build()
                .context("Error building pipeline")?;

            // Lock our device to actually build it
            // Try to lock the device for as little time as possible
            let mut device = context.lock_device()?;

            let pipeline = pipeline_spec
                .build(&mut device, context.properties().extent, empty())
                .context("Error building pipeline")?;

            // Our framebuffers just have the swapchain framebuffer attachment
            // TargetSpecificResources makes sure we use a different one each frame.
            let fat = context.properties().swapchain_framebuffer_attachment();
            let framebuffers = TargetSpecificResources::new(
                || unsafe {
                    Ok(device.create_framebuffer(
                        &pipeline.renderpass,
                        IntoIter::new([fat.clone()]),
                        context.properties().extent,
                    )?)
                },
                context.properties().image_count as usize,
            )?;

            (pipeline, framebuffers)
        };

        Ok(Self {
            pipeline,
            framebuffers,
        })
    }

    pub fn deactivate(self, context: &mut RenderingContext) -> Result<()> {
        unsafe {
            let mut device = context.lock_device()?;
            for fb in self.framebuffers.dissolve() {
                device.destroy_framebuffer(fb);
            }

            self.pipeline.deactivate(&mut device);
        }

        Ok(())
    }
}