Repository navigation
Expand file tree
/
Copy pathmain.v
More file actions
213 lines (206 loc) · 8.13 KB
/
Copy pathmain.v
File metadata and controls
213 lines (206 loc) · 8.13 KB
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
// A finite clear-and-present example that recreates its swapchain after resize.
module main
import antono2.glfw
import antono2.vulkan as vk
import antono2.vulkan.ergonomic as vke
import examples.presentation.windowing
import os
import time
const resize_timeout = 5 * time.second
fn main() {
run() or {
eprintln(err)
exit(1)
}
}
fn run() ! {
if !glfw.initialize() { return error('GLFW initialization failed') }
defer { glfw.terminate() }
glfw.window_hint(glfw.client_api, glfw.no_api)
// A small 16:9 window, enlarged below to exercise swapchain recreation.
initial_width := 640
initial_height := 360
window := windowing.create_windowed(initial_width, initial_height, 'Vulkan presentation')!
defer { glfw.destroy_window(window) }
mut count := u32(0)
names := glfw.get_required_instance_extensions(&count)
mut extensions := []string{}
for i in 0 .. int(count) {
extensions << unsafe { cstring_to_vstring(names[i]) }
}
mut instance := vke.new_instance_with_options(vke.InstanceOptions{ extensions: extensions })!
defer { instance.destroy() }
mut surface := vk.SurfaceKHR(unsafe { nil })
vke.require_success(glfw.create_window_surface(instance.handle, window, unsafe { nil },
&surface), 'glfwCreateWindowSurface')!
defer { vk.destroy_surface_khr(instance.handle, surface, unsafe { nil }) }
devices := instance.physical_devices()!
if devices.len == 0 { return error('no Vulkan device') }
physical := devices[0]
family := physical.find_present_queue_family(u32(vk.QueueFlagBits.graphics), surface)!
mut device := physical.new_device_with_options(vke.DeviceOptions{
queue_family: family
extensions: [
'VK_KHR_swapchain',
]
})!
defer { device.destroy() }
render_generation(physical, device, surface, window)!
if '--startup-only' in os.args[1..] {
// The startup fixture's minimal manager handles mapping only.
return
}
resized_width := 800
resized_height := 450
resize_window(window, resized_width, resized_height)!
render_generation(physical, device, surface, window)!
println('Presented two swapchain generations, including resize.')
}
fn resize_window(window &glfw.Window, width int, height int) ! {
mut previous_width := i32(0)
mut previous_height := i32(0)
glfw.get_framebuffer_size(window, &previous_width, &previous_height)
glfw.set_window_size(window, width, height)
timer := time.new_stopwatch()
for {
mut current_width := i32(0)
mut current_height := i32(0)
glfw.get_framebuffer_size(window, ¤t_width, ¤t_height)
if current_width > 0 && current_height > 0
&& (current_width != previous_width || current_height != previous_height) {
return
}
remaining := resize_timeout - timer.elapsed()
if remaining <= 0 {
return error('Framebuffer did not resize after requesting ${width}x${height}')
}
// X11 window managers can apply the resize asynchronously.
glfw.wait_events_timeout(f64(remaining) / f64(time.second))
}
}
fn render_generation(physical vke.PhysicalDevice, device &vke.OwnedDevice, surface vk.SurfaceKHR, window &glfw.Window) ! {
frames_per_generation := 6 // Keep the example finite while reusing synchronization objects.
frame_timeout_ns := u64(10_000_000_000) // Ten seconds for submitted GPU work.
acquire_timeout_ns := u64(1_000_000_000) // One second to obtain a presentation image.
support := physical.surface_support(surface)!
required_usage := u32(vk.ImageUsageFlagBits.transfer_dst) | u32(vk.ImageUsageFlagBits.color_attachment)
if support.capabilities.supportedUsageFlags & required_usage != required_usage {
return error('this clear example requires transfer-destination and color-attachment swapchain images')
}
format := vke.select_surface_format(support.formats, [
vk.SurfaceFormatKHR{ format: .b8g8r8a8_srgb, colorSpace: .srgb_nonlinear },
])!
mut width := i32(0)
mut height := i32(0)
glfw.get_framebuffer_size(window, &width, &height)
if width <= 0 || height <= 0 {
return error('window is minimized; resume when extent is nonzero')
}
extent := vke.select_surface_extent(support.capabilities, vk.Extent2D{
width: u32(width)
height: u32(height)
})
// Request one image above the surface minimum, clamped to its supported limit.
extra_swapchain_images := u32(1)
info := vk.SwapchainCreateInfoKHR{
surface: surface
minImageCount: vke.select_surface_image_count(support.capabilities,
extra_swapchain_images)
imageFormat: format.format
imageColorSpace: format.colorSpace
imageExtent: extent
imageArrayLayers: 1 // A single 2D presentation layer, not a stereo array.
imageUsage: required_usage
imageSharingMode: .exclusive
preTransform: support.capabilities.currentTransform
compositeAlpha: vke.select_composite_alpha(support.capabilities.supportedCompositeAlpha, [
.opaque,
])!
presentMode: .fifo // Portable, display-synchronized presentation.
clipped: vk._true
}
mut swapchain := device.new_swapchain(&info)!
defer { swapchain.destroy() }
mut pool := device.new_command_pool(u32(vk.CommandPoolCreateFlagBits.reset_command_buffer))!
defer { pool.destroy() }
mut command := pool.allocate_primary(1)![0]
mut ready := device.new_semaphore()!
defer { ready.destroy() }
mut done := []&vke.OwnedSemaphore{}
defer {
for mut semaphore in done {
semaphore.destroy()
}
}
for _ in swapchain.images {
done << device.new_semaphore()!
}
// Start signaled so the first frame does not wait for a nonexistent submission.
mut fence := device.new_fence(true)!
defer { fence.destroy() }
// Also complete submitted work before cleanup on an error path.
defer { device.wait_idle() or {} }
for _ in 0 .. frames_per_generation {
glfw.poll_events()
vke.require_success(fence.wait(frame_timeout_ns)!, 'wait frame')!
acquired := swapchain.acquire(acquire_timeout_ns, ready.handle, unsafe { nil })!
index := acquired.image_index or {
if acquired.status == .error_out_of_date_khr { return }
return error('image acquisition did not complete: ${acquired.status}')
}
command.reset(0)!
command.begin(u32(vk.CommandBufferUsageFlagBits.one_time_submit))!
// Clear the only mip level and array layer of this swapchain image.
range := vk.ImageSubresourceRange{
aspectMask: u32(vk.ImageAspectFlagBits.color)
levelCount: 1
layerCount: 1
}
// Undefined discards old pixels: each frame replaces the entire image.
before := vk.ImageMemoryBarrier{
oldLayout: .undefined
newLayout: .transfer_dst_optimal
dstAccessMask: u32(vk.AccessFlagBits.transfer_write)
srcQueueFamilyIndex: vk.queue_family_ignored
dstQueueFamilyIndex: vk.queue_family_ignored
image: swapchain.images[index]
subresourceRange: range
}
// No memory/buffer barriers; the final count of 1 refers to this image barrier.
vk.cmd_pipeline_barrier(command.handle, u32(vk.PipelineStageFlagBits.top_of_pipe),
u32(vk.PipelineStageFlagBits.transfer), 0, 0, unsafe { nil }, 0, unsafe { nil }, 1,
&before)
// Opaque dark blue, expressed as linear RGBA components in [0, 1].
color := vk.ClearColorValue{
float32: [f32(0.05), 0.15, 0.35, 1.0]!
}
vk.cmd_clear_color_image(command.handle, swapchain.images[index], .transfer_dst_optimal,
&color, 1, &range)
after := vk.ImageMemoryBarrier{
oldLayout: .transfer_dst_optimal
newLayout: .present_src_khr
srcAccessMask: u32(vk.AccessFlagBits.transfer_write)
srcQueueFamilyIndex: vk.queue_family_ignored
dstQueueFamilyIndex: vk.queue_family_ignored
image: swapchain.images[index]
subresourceRange: range
}
// No memory/buffer barriers; the final count of 1 refers to this image barrier.
vk.cmd_pipeline_barrier(command.handle, u32(vk.PipelineStageFlagBits.transfer),
u32(vk.PipelineStageFlagBits.bottom_of_pipe), 0, 0, unsafe { nil }, 0, unsafe { nil },
1, &after)
command.end()!
fence.reset()!
device.queue.submit([command], vke.SubmitOptions{
wait_semaphores: [ready.handle]
wait_stage_masks: [
u32(vk.PipelineStageFlagBits.transfer),
]
signal_semaphores: [done[index].handle]
fence: fence.handle
})!
status := device.queue.present(swapchain, index, [done[index].handle])!
if status == .error_out_of_date_khr { return }
}
device.wait_idle()!
}