Repository navigation
Expand file tree
/
Copy path0_basic.cpp
More file actions
421 lines (335 loc) · 12 KB
/
Copy path0_basic.cpp
File metadata and controls
421 lines (335 loc) · 12 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
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
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <cassert>
#include <iostream>
#include <numeric>
#include <print>
#include <stdexcept>
#include <string>
#ifdef NOAPI_BACKEND_VULKAN
#include <volk.h>
#define GLFW_INCLUDE_VULKAN
#endif
#include <GLFW/glfw3.h>
#ifdef NOAPI_BACKEND_VULKAN
#include <vulkan/noapi.hpp>
#else
#include <webgpu/noapi.hpp>
#include "glfw3webgpu.h"
#endif
#ifdef __EMSCRIPTEN__
#include <emscripten/emscripten.h>
#endif
static const std::string slang_compute = R"slang(
import noapi;
import test_constants;
static const uint ELEMENT_COUNT = 5;
struct ComputeData : IGpuLoadable {
GpuPtr<float> upload;
GpuPtr<float> download;
static const uint gpuStride = 16;
static ComputeData gpuLoad(GpuAddress at) {
var from = GpuReader(at);
ComputeData out;
out.upload = from.next<GpuPtr<float> >();
out.download = from.next<GpuPtr<float> >();
return out;
}
}
[shader("compute")]
[numthreads(16, 1, 1)]
void computeMain(uint3 thread : SV_DispatchThreadID) {
if(thread.x >= ELEMENT_COUNT) return;
let data = *gpuComputeData<ComputeData>();
data.download[thread.x] = data.upload[thread.x] * gpuTestScaleFactor();
}
)slang";
static const std::string slang_triangle = R"slang(
import noapi;
struct Varyings {
float4 position : SV_Position;
float3 color : COLOR;
}
struct Vertex : IGpuLoadable {
float2 position;
float3 color;
static const uint gpuStride = 20;
static Vertex gpuLoad(GpuAddress at) {
var from = GpuReader(at);
Vertex out;
out.position = from.next<float2>();
out.color = from.next<float3>();
return out;
}
}
[shader("vertex")]
Varyings vertexMain(uint index : SV_VertexID) {
let vertices = *gpuVertexData<GpuPtr<Vertex> >();
let vertex = vertices[index];
Varyings output;
output.position = float4(vertex.position, 0.0, 1.0);
output.color = vertex.color;
return output;
}
[shader("fragment")]
float4 fragmentMain(Varyings varyings) : SV_Target {
return float4(varyings.color, 1.0);
}
)slang";
static const std::string slang_user_module = R"slang(
module test_constants;
public float gpuTestScaleFactor() { return 6.0; }
)slang";
#ifdef NOAPI_BACKEND_VULKAN
using GpuBackendDefault = GpuVulkanDefault;
static GpuBackendDefault setup_backend(GLFWwindow* window) {
auto vk = gpuSetupDefaultVulkanEXT([window](VkInstance instance) -> VkSurfaceKHR {
VkSurfaceKHR surface;
if(glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS)
throw std::runtime_error("Failed to setup Vulkan surface");
return surface;
});
if(!vk) throw std::runtime_error(vk.error());
return *vk;
}
static void shutdown_backend(GpuBackendDefault& vulkan) {
vkDestroyDevice(vulkan.device, nullptr);
vkDestroySurfaceKHR(vulkan.instance, vulkan.surface, nullptr);
if(vulkan.messenger) vkDestroyDebugUtilsMessengerEXT(vulkan.instance, vulkan.messenger, nullptr);
vkDestroyInstance(vulkan.instance, nullptr);
volkFinalize();
}
#else
using GpuBackendDefault = GpuWebGPUDefault;
static GpuBackendDefault setup_backend(GLFWwindow* window) {
auto wg = gpuSetupDefaultWebGPUEXT([window](WGPUInstance instance) -> WGPUSurface {
auto surface = glfwCreateWindowWGPUSurface(instance, window);
if(!surface) throw std::runtime_error("Failed to setup WebGPU surface");
return surface;
});
if(!wg) throw std::runtime_error(wg.error());
return *wg;
}
static void shutdown_backend(GpuBackendDefault& wgpu) {
wgpuSurfaceRelease(wgpu.surface);
wgpuDeviceRelease(wgpu.device);
wgpuAdapterRelease(wgpu.adapter);
wgpuInstanceRelease(wgpu.instance);
}
#endif
extern "C" uint16_t noapi_c_compat_packed_default_sampler(void);
typedef struct AppState {
GLFWwindow *window;
GpuBackendDefault backend;
GpuQueue* queue;
GpuSurface* surface;
GpuPipeline* pipeline;
gpu* triangle; // Root data struct: a pointer to the vertex array
gpu* indices;
uint32_t width;
uint32_t height;
} AppState;
struct Vertex {
float x, y;
float r, g, b;
};
static void resize_surface(AppState *state) {
auto desc = gpuSurfaceGetConfigurationEXT(state->surface);
desc.texture.dimensions = {state->width, state->height, 1};
gpuSurfaceReconfigureEXT(state->queue, state->surface, desc);
}
static void on_framebuffer_resize(GLFWwindow *window, int width, int height) {
AppState *state = (AppState *)glfwGetWindowUserPointer(window);
state->width = width;
state->height = height;
}
static void render_frame(AppState *state) {
// A minimized window has nothing to present, and a surface can't be configured for a zero extent
if (state->width == 0 || state->height == 0) return;
auto configured = gpuSurfaceGetConfigurationEXT(state->surface).texture.dimensions;
if (configured.x != state->width || configured.y != state->height)
resize_surface(state);
auto target = gpuSurfaceNextTextureEXT(state->queue, state->surface);
if (!target) { // Out of date, lost or timed out: reconfigure and try again next frame
resize_surface(state);
return;
}
GpuColorAttachment color {
.texture = target,
.loadOp = LOAD_OP_CLEAR,
.clearValue = {0.05f, 0.05f, 0.08f, 1.0f},
};
GpuRenderPassDesc pass {
.colorAttachments = {&color, 1},
};
auto cmd = gpuStartCommandRecording(state->queue);
gpuBeginRenderPass(cmd, pass);
gpuSetPipeline(cmd, state->pipeline);
gpuDrawIndexedInstanced(cmd, state->triangle, state->triangle, state->indices, 3, 1);
gpuEndRenderPass(cmd, pass);
auto submission = gpuSubmit(state->queue, {&cmd, 1});
gpuSurfacePresentEXT(state->queue, state->surface, submission);
}
#ifdef __EMSCRIPTEN__
static void emscripten_frame(void *arg) {
AppState *state = (AppState *)arg;
glfwPollEvents();
render_frame(state);
}
#endif
int real_main() {
assert(noapi_c_compat_packed_default_sampler() == GpuSamplerDesc{}.pack() && "C and C++ disagree about GpuSamplerDesc");
AppState state = {0};
const int initial_width = 800;
const int initial_height = 600;
if (!glfwInit()) {
std::println(std::cerr, "Glfw initialization failed\n");
return -1;
}
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
#ifdef NOAPI_BACKEND_VULKAN
state.window = glfwCreateWindow(initial_width, initial_height, "NoAPI Triangle (vulkan)", NULL, NULL);
#elifdef NOAPI_BACKEND_WEBGPU
state.window = glfwCreateWindow(initial_width, initial_height, "NoAPI Triangle (webgpu)", NULL, NULL);
#else
state.window = glfwCreateWindow(initial_width, initial_height, "NoAPI Triangle (unknown)", NULL, NULL);
#endif
assert(state.window && "Failed to create glfw window");
glfwSetWindowUserPointer(state.window, &state);
glfwSetFramebufferSizeCallback(state.window, on_framebuffer_resize);
gpuSetShaderDiagnosticCallbackEXT([](GpuStringView message, void*) {
std::println("[shader] {}", std::string_view(message.ptr, message.count));
}, nullptr);
gpuAddShaderModuleEXT("test_constants", GpuStringView{slang_user_module.data(), slang_user_module.size()});
state.backend = setup_backend(state.window);
state.queue = gpuCreateQueue(state.backend);
auto upload = gpuMalloc<float>(state.queue, 5, MEMORY_DEFAULT);
for(size_t i = 0; i < 5; ++i)
upload[i] = i;
auto download = gpuMalloc<float>(state.queue, 5, MEMORY_READBACK);
struct ShaderData {
gpu* upload;
gpu* download;
};
auto data = gpuMalloc<ShaderData>(state.queue);
data->upload = gpuHostToDevicePointer(state.queue, upload);
data->download = gpuHostToDevicePointer(state.queue, download);
auto data_gpu = gpuHostToDevicePointer(state.queue, data);
gpuSyncMemoryEXT(state.queue, data_gpu);
auto pipe = gpuCreateComputePipeline(state.queue, string_to_bytes(slang_compute));
auto counter = gpuMalloc<uint64_t>(state.queue, 1, MEMORY_READBACK);
*counter = 0;
auto counter_gpu = gpuHostToDevicePointer(state.queue, counter);
gpuSyncMemoryEXT(state.queue, counter_gpu);
const auto capabilities = gpuGetCapabilitiesEXT(state.queue);
constexpr uint64_t SIGNALLED = 7;
{
auto cmd = gpuStartCommandRecording(state.queue);
gpuSyncMemoryEXT(cmd, data->upload);
gpuSetPipeline(cmd, pipe);
gpuDispatch(cmd, data_gpu, {1, 1, 1});
gpuSignalAfter(cmd, STAGE_COMPUTE, counter_gpu, SIGNALLED, SIGNAL_ATOMIC_MAX);
gpuWaitBefore(cmd, STAGE_TRANSFER, counter_gpu, SIGNALLED, OP_GREATER_EQUAL);
gpuSyncMemoryEXT(cmd, data->download);
gpuSyncMemoryEXT(cmd, counter_gpu);
auto index = gpuSubmit(state.queue, {&cmd, 1});
gpuWaitSemaphore(state.queue, gpuGetSubmissionSemaphoreEXT(state.queue), index);
}
std::println("upload: {}, download: {}", upload[3], download[3]);
std::println("split barrier: signals={} splits={}, counter={} (expected {})",
capabilities.split_barrier_signals, capabilities.split_barriers,
*counter, capabilities.split_barrier_signals ? SIGNALLED : 0);
assert(*counter == (capabilities.split_barrier_signals ? SIGNALLED : 0)
&& "gpuSignalAfter didn't leave the counter where the queue's capabilities say it would");
gpuFreePipeline(state.queue, pipe);
{
int fb_width, fb_height;
glfwGetFramebufferSize(state.window, &fb_width, &fb_height);
state.width = (uint32_t)fb_width;
state.height = (uint32_t)fb_height;
}
state.surface = gpuCreateSurfaceEXT(state.queue, state.backend, GpuSurfaceDescriptor{
.texture = {
.dimensions = {state.width, state.height, 1},
.format = FORMAT_NONE, // Whatever the surface prefers, until the capabilities are known
.usage = USAGE_COLOR_ATTACHMENT,
},
.presentMode = PRESENT_MODE_BEST_AVAILABLE,
});
auto caps = gpuGetSurfaceCapabilitiesEXT(state.queue, state.surface);
std::print("surface formats (best first):");
for(auto format: caps.formatList())
std::print(" {}{}", (int)format, gpuFormatIsSrgbEXT(format) ? " (srgb)" : "");
std::print("\npresent modes (best first):");
for(auto mode: caps.presentModeList())
std::print(" {}", (int)mode);
std::println("\ntransparency: {}", caps.supportsTransparency);
GpuSurfaceDescriptor config;
for(auto format: caps.formatList())
if(!gpuFormatIsSrgbEXT(format)) {
config = gpuSurfaceGetConfigurationEXT(state.surface);
config.texture.format = format;
gpuSurfaceReconfigureEXT(state.queue, state.surface, config);
break;
}
std::println("surface: {}x{}, format {}, present mode {}", config.texture.dimensions.x, config.texture.dimensions.y, (int)config.texture.format, (int)config.presentMode);
auto vertices = gpuMalloc<Vertex>(state.queue, 3);
vertices[0] = {-0.5f, -0.5f, 0.0f, 0.0f, 1.0f};
vertices[1] = { 0.5f, -0.5f, 0.0f, 1.0f, 0.0f};
vertices[2] = { 0.0f, 0.5f, 1.0f, 0.0f, 0.0f};
auto indices = gpuMalloc<uint32_t>(state.queue, 3);
std::iota(indices, indices + 3, 0);
struct TriangleData {
gpu* vertices;
};
auto triangle = gpuMalloc<TriangleData>(state.queue);
triangle->vertices = gpuHostToDevicePointer(state.queue, vertices);
state.triangle = gpuHostToDevicePointer(state.queue, triangle);
state.indices = gpuHostToDevicePointer(state.queue, indices);
gpuSyncMemoryEXT(state.queue, triangle->vertices);
gpuSyncMemoryEXT(state.queue, state.indices);
gpuSyncMemoryEXT(state.queue, state.triangle);
GpuColorTarget target { .format = config.texture.format };
state.pipeline = gpuCreateGraphicsPipeline(state.queue, string_to_bytes(slang_triangle), string_to_bytes(slang_triangle), GpuRasterDesc{
.colorTargets = {&target, 1},
.blendstate = GpuBlendDesc{
.srcColorFactor = FACTOR_SRC_ALPHA,
.dstColorFactor = FACTOR_ONE_MINUS_SRC_ALPHA,
},
});
assert(state.pipeline && "Pipeline creation failed");
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg(emscripten_frame, &state, 0, true);
#else
while (!glfwWindowShouldClose(state.window)) {
glfwPollEvents();
render_frame(&state);
}
gpuWaitIdleEXT(state.queue);
gpuFreePipeline(state.queue, state.pipeline);
gpuFreeSurfaceEXT(state.queue, state.surface);
gpuFreeQueue(state.queue);
shutdown_backend(state.backend);
glfwDestroyWindow(state.window);
glfwTerminate();
#endif
return 0;
}
#ifdef _WIN32
#include <windows.h>
#endif
#ifdef _WIN32
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) {
AllocConsole();
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
freopen("CONIN$", "r", stdin);
return real_main();
}
#else
int main() {
return real_main();
}
#endif