-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathtriangle.rs
461 lines (421 loc) · 18 KB
/
triangle.rs
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
459
460
461
#![warn(unused_qualifications)]
use std::default::Default;
use std::error::Error;
use std::io::Cursor;
use std::mem;
use std::mem::{align_of, size_of, size_of_val}; // TODO: Remove when bumping MSRV to 1.80
use ash::util::*;
use ash::vk;
use ash_examples::*;
#[derive(Clone, Debug, Copy)]
struct Vertex {
pos: [f32; 4],
color: [f32; 4],
}
fn main() -> Result<(), Box<dyn Error>> {
unsafe {
let base = ExampleBase::new(1920, 1080)?;
let renderpass_attachments = [
vk::AttachmentDescription {
format: base.surface_format.format,
samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR,
store_op: vk::AttachmentStoreOp::STORE,
final_layout: vk::ImageLayout::PRESENT_SRC_KHR,
..Default::default()
},
vk::AttachmentDescription {
format: vk::Format::D16_UNORM,
samples: vk::SampleCountFlags::TYPE_1,
load_op: vk::AttachmentLoadOp::CLEAR,
initial_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
final_layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
..Default::default()
},
];
let color_attachment_refs = [vk::AttachmentReference {
attachment: 0,
layout: vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL,
}];
let depth_attachment_ref = vk::AttachmentReference {
attachment: 1,
layout: vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
};
let dependencies = [vk::SubpassDependency {
src_subpass: vk::SUBPASS_EXTERNAL,
src_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
dst_access_mask: vk::AccessFlags::COLOR_ATTACHMENT_READ
| vk::AccessFlags::COLOR_ATTACHMENT_WRITE,
dst_stage_mask: vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
..Default::default()
}];
let subpass = vk::SubpassDescription::default()
.color_attachments(&color_attachment_refs)
.depth_stencil_attachment(&depth_attachment_ref)
.pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS);
let renderpass_create_info = vk::RenderPassCreateInfo::default()
.attachments(&renderpass_attachments)
.subpasses(std::slice::from_ref(&subpass))
.dependencies(&dependencies);
let renderpass = base
.device
.create_render_pass(&renderpass_create_info, None)
.unwrap();
let framebuffers: Vec<vk::Framebuffer> = base
.present_image_views
.iter()
.map(|&present_image_view| {
let framebuffer_attachments = [present_image_view, base.depth_image_view];
let frame_buffer_create_info = vk::FramebufferCreateInfo::default()
.render_pass(renderpass)
.attachments(&framebuffer_attachments)
.width(base.surface_resolution.width)
.height(base.surface_resolution.height)
.layers(1);
base.device
.create_framebuffer(&frame_buffer_create_info, None)
.unwrap()
})
.collect();
let index_buffer_data = [0u32, 1, 2];
let index_buffer_info = vk::BufferCreateInfo::default()
.size(size_of_val(&index_buffer_data) as u64)
.usage(vk::BufferUsageFlags::INDEX_BUFFER)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
let index_buffer = base.device.create_buffer(&index_buffer_info, None).unwrap();
let index_buffer_memory_req = base.device.get_buffer_memory_requirements(index_buffer);
let index_buffer_memory_index = find_memorytype_index(
&index_buffer_memory_req,
&base.device_memory_properties,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
)
.expect("Unable to find suitable memorytype for the index buffer.");
let index_allocate_info = vk::MemoryAllocateInfo {
allocation_size: index_buffer_memory_req.size,
memory_type_index: index_buffer_memory_index,
..Default::default()
};
let index_buffer_memory = base
.device
.allocate_memory(&index_allocate_info, None)
.unwrap();
let index_ptr = base
.device
.map_memory(
index_buffer_memory,
0,
index_buffer_memory_req.size,
vk::MemoryMapFlags::empty(),
)
.unwrap();
let mut index_slice = Align::new(
index_ptr,
align_of::<u32>() as u64,
index_buffer_memory_req.size,
);
index_slice.copy_from_slice(&index_buffer_data);
base.device.unmap_memory(index_buffer_memory);
base.device
.bind_buffer_memory(index_buffer, index_buffer_memory, 0)
.unwrap();
let vertex_input_buffer_info = vk::BufferCreateInfo {
size: 3 * size_of::<Vertex>() as u64,
usage: vk::BufferUsageFlags::VERTEX_BUFFER,
sharing_mode: vk::SharingMode::EXCLUSIVE,
..Default::default()
};
let vertex_input_buffer = base
.device
.create_buffer(&vertex_input_buffer_info, None)
.unwrap();
let vertex_input_buffer_memory_req = base
.device
.get_buffer_memory_requirements(vertex_input_buffer);
let vertex_input_buffer_memory_index = find_memorytype_index(
&vertex_input_buffer_memory_req,
&base.device_memory_properties,
vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT,
)
.expect("Unable to find suitable memorytype for the vertex buffer.");
let vertex_buffer_allocate_info = vk::MemoryAllocateInfo {
allocation_size: vertex_input_buffer_memory_req.size,
memory_type_index: vertex_input_buffer_memory_index,
..Default::default()
};
let vertex_input_buffer_memory = base
.device
.allocate_memory(&vertex_buffer_allocate_info, None)
.unwrap();
let vertices = [
Vertex {
pos: [-1.0, 1.0, 0.0, 1.0],
color: [0.0, 1.0, 0.0, 1.0],
},
Vertex {
pos: [1.0, 1.0, 0.0, 1.0],
color: [0.0, 0.0, 1.0, 1.0],
},
Vertex {
pos: [0.0, -1.0, 0.0, 1.0],
color: [1.0, 0.0, 0.0, 1.0],
},
];
let vert_ptr = base
.device
.map_memory(
vertex_input_buffer_memory,
0,
vertex_input_buffer_memory_req.size,
vk::MemoryMapFlags::empty(),
)
.unwrap();
let mut vert_align = Align::new(
vert_ptr,
align_of::<Vertex>() as u64,
vertex_input_buffer_memory_req.size,
);
vert_align.copy_from_slice(&vertices);
base.device.unmap_memory(vertex_input_buffer_memory);
base.device
.bind_buffer_memory(vertex_input_buffer, vertex_input_buffer_memory, 0)
.unwrap();
let mut vertex_spv_file =
Cursor::new(&include_bytes!("../../shader/triangle/vert.spv")[..]);
let mut frag_spv_file = Cursor::new(&include_bytes!("../../shader/triangle/frag.spv")[..]);
let vertex_code =
read_spv(&mut vertex_spv_file).expect("Failed to read vertex shader spv file");
let vertex_shader_info = vk::ShaderModuleCreateInfo::default().code(&vertex_code);
let frag_code =
read_spv(&mut frag_spv_file).expect("Failed to read fragment shader spv file");
let frag_shader_info = vk::ShaderModuleCreateInfo::default().code(&frag_code);
let vertex_shader_module = base
.device
.create_shader_module(&vertex_shader_info, None)
.expect("Vertex shader module error");
let fragment_shader_module = base
.device
.create_shader_module(&frag_shader_info, None)
.expect("Fragment shader module error");
let layout_create_info = vk::PipelineLayoutCreateInfo::default();
let pipeline_layout = base
.device
.create_pipeline_layout(&layout_create_info, None)
.unwrap();
let shader_entry_name = c"main";
let shader_stage_create_infos = [
vk::PipelineShaderStageCreateInfo {
module: vertex_shader_module,
p_name: shader_entry_name.as_ptr(),
stage: vk::ShaderStageFlags::VERTEX,
..Default::default()
},
vk::PipelineShaderStageCreateInfo {
s_type: vk::StructureType::PIPELINE_SHADER_STAGE_CREATE_INFO,
module: fragment_shader_module,
p_name: shader_entry_name.as_ptr(),
stage: vk::ShaderStageFlags::FRAGMENT,
..Default::default()
},
];
let vertex_input_binding_descriptions = [vk::VertexInputBindingDescription {
binding: 0,
stride: size_of::<Vertex>() as u32,
input_rate: vk::VertexInputRate::VERTEX,
}];
let vertex_input_attribute_descriptions = [
vk::VertexInputAttributeDescription {
location: 0,
binding: 0,
format: vk::Format::R32G32B32A32_SFLOAT,
offset: offset_of!(Vertex, pos) as u32,
},
vk::VertexInputAttributeDescription {
location: 1,
binding: 0,
format: vk::Format::R32G32B32A32_SFLOAT,
offset: offset_of!(Vertex, color) as u32,
},
];
let vertex_input_state_info = vk::PipelineVertexInputStateCreateInfo::default()
.vertex_attribute_descriptions(&vertex_input_attribute_descriptions)
.vertex_binding_descriptions(&vertex_input_binding_descriptions);
let vertex_input_assembly_state_info = vk::PipelineInputAssemblyStateCreateInfo {
topology: vk::PrimitiveTopology::TRIANGLE_LIST,
..Default::default()
};
let viewports = [vk::Viewport {
x: 0.0,
y: 0.0,
width: base.surface_resolution.width as f32,
height: base.surface_resolution.height as f32,
min_depth: 0.0,
max_depth: 1.0,
}];
let scissors = [base.surface_resolution.into()];
let viewport_state_info = vk::PipelineViewportStateCreateInfo::default()
.scissors(&scissors)
.viewports(&viewports);
let rasterization_info = vk::PipelineRasterizationStateCreateInfo {
front_face: vk::FrontFace::COUNTER_CLOCKWISE,
line_width: 1.0,
polygon_mode: vk::PolygonMode::FILL,
..Default::default()
};
let multisample_state_info = vk::PipelineMultisampleStateCreateInfo {
rasterization_samples: vk::SampleCountFlags::TYPE_1,
..Default::default()
};
let noop_stencil_state = vk::StencilOpState {
fail_op: vk::StencilOp::KEEP,
pass_op: vk::StencilOp::KEEP,
depth_fail_op: vk::StencilOp::KEEP,
compare_op: vk::CompareOp::ALWAYS,
..Default::default()
};
let depth_state_info = vk::PipelineDepthStencilStateCreateInfo {
depth_test_enable: 1,
depth_write_enable: 1,
depth_compare_op: vk::CompareOp::LESS_OR_EQUAL,
front: noop_stencil_state,
back: noop_stencil_state,
max_depth_bounds: 1.0,
..Default::default()
};
let color_blend_attachment_states = [vk::PipelineColorBlendAttachmentState {
blend_enable: 0,
src_color_blend_factor: vk::BlendFactor::SRC_COLOR,
dst_color_blend_factor: vk::BlendFactor::ONE_MINUS_DST_COLOR,
color_blend_op: vk::BlendOp::ADD,
src_alpha_blend_factor: vk::BlendFactor::ZERO,
dst_alpha_blend_factor: vk::BlendFactor::ZERO,
alpha_blend_op: vk::BlendOp::ADD,
color_write_mask: vk::ColorComponentFlags::RGBA,
}];
let color_blend_state = vk::PipelineColorBlendStateCreateInfo::default()
.logic_op(vk::LogicOp::CLEAR)
.attachments(&color_blend_attachment_states);
let dynamic_state = [vk::DynamicState::VIEWPORT, vk::DynamicState::SCISSOR];
let dynamic_state_info =
vk::PipelineDynamicStateCreateInfo::default().dynamic_states(&dynamic_state);
let graphic_pipeline_info = vk::GraphicsPipelineCreateInfo::default()
.stages(&shader_stage_create_infos)
.vertex_input_state(&vertex_input_state_info)
.input_assembly_state(&vertex_input_assembly_state_info)
.viewport_state(&viewport_state_info)
.rasterization_state(&rasterization_info)
.multisample_state(&multisample_state_info)
.depth_stencil_state(&depth_state_info)
.color_blend_state(&color_blend_state)
.dynamic_state(&dynamic_state_info)
.layout(pipeline_layout)
.render_pass(renderpass);
let graphics_pipelines = base
.device
.create_graphics_pipelines(vk::PipelineCache::null(), &[graphic_pipeline_info], None)
.expect("Unable to create graphics pipeline");
let graphic_pipeline = graphics_pipelines[0];
let _ = base.render_loop(|| {
let (present_index, _) = base
.swapchain_loader
.acquire_next_image(
base.swapchain,
u64::MAX,
base.present_complete_semaphore,
vk::Fence::null(),
)
.unwrap();
let clear_values = [
vk::ClearValue {
color: vk::ClearColorValue {
float32: [0.0, 0.0, 0.0, 0.0],
},
},
vk::ClearValue {
depth_stencil: vk::ClearDepthStencilValue {
depth: 1.0,
stencil: 0,
},
},
];
let render_pass_begin_info = vk::RenderPassBeginInfo::default()
.render_pass(renderpass)
.framebuffer(framebuffers[present_index as usize])
.render_area(base.surface_resolution.into())
.clear_values(&clear_values);
record_submit_commandbuffer(
&base.device,
base.draw_command_buffer,
base.draw_commands_reuse_fence,
base.present_queue,
&[vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT],
&[base.present_complete_semaphore],
&[base.rendering_complete_semaphore],
|device, draw_command_buffer| {
device.cmd_begin_render_pass(
draw_command_buffer,
&render_pass_begin_info,
vk::SubpassContents::INLINE,
);
device.cmd_bind_pipeline(
draw_command_buffer,
vk::PipelineBindPoint::GRAPHICS,
graphic_pipeline,
);
device.cmd_set_viewport(draw_command_buffer, 0, &viewports);
device.cmd_set_scissor(draw_command_buffer, 0, &scissors);
device.cmd_bind_vertex_buffers(
draw_command_buffer,
0,
&[vertex_input_buffer],
&[0],
);
device.cmd_bind_index_buffer(
draw_command_buffer,
index_buffer,
0,
vk::IndexType::UINT32,
);
device.cmd_draw_indexed(
draw_command_buffer,
index_buffer_data.len() as u32,
1,
0,
0,
1,
);
// Or draw without the index buffer
// device.cmd_draw(draw_command_buffer, 3, 1, 0, 0);
device.cmd_end_render_pass(draw_command_buffer);
},
);
let wait_semaphors = [base.rendering_complete_semaphore];
let swapchains = [base.swapchain];
let image_indices = [present_index];
let present_info = vk::PresentInfoKHR::default()
.wait_semaphores(&wait_semaphors) // &base.rendering_complete_semaphore)
.swapchains(&swapchains)
.image_indices(&image_indices);
base.swapchain_loader
.queue_present(base.present_queue, &present_info)
.unwrap();
});
base.device.device_wait_idle().unwrap();
for pipeline in graphics_pipelines {
base.device.destroy_pipeline(pipeline, None);
}
base.device.destroy_pipeline_layout(pipeline_layout, None);
base.device
.destroy_shader_module(vertex_shader_module, None);
base.device
.destroy_shader_module(fragment_shader_module, None);
base.device.free_memory(index_buffer_memory, None);
base.device.destroy_buffer(index_buffer, None);
base.device.free_memory(vertex_input_buffer_memory, None);
base.device.destroy_buffer(vertex_input_buffer, None);
for framebuffer in framebuffers {
base.device.destroy_framebuffer(framebuffer, None);
}
base.device.destroy_render_pass(renderpass, None);
}
Ok(())
}