forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebgpu_basic_rendering.cpp
451 lines (379 loc) · 15.4 KB
/
webgpu_basic_rendering.cpp
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
// Copyright 2021 The Emscripten Authors. All rights reserved.
// Emscripten is available under two separate licenses, the MIT license and the
// University of Illinois/NCSA Open Source License. Both these licenses can be
// found in the LICENSE file.
// Based on https://github.com/kainino0x/webgpu-cross-platform-demo
#include <webgpu/webgpu_cpp.h>
#undef NDEBUG
#include <array>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/html5_webgpu.h>
static const wgpu::Instance instance = wgpuCreateInstance(nullptr);
static const char shaderCode[] = R"(
@vertex
fn main_v(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
var pos = array<vec2<f32>, 3>(
vec2<f32>(0.0, 0.5), vec2<f32>(-0.5, -0.5), vec2<f32>(0.5, -0.5));
return vec4<f32>(pos[idx], 0.0, 1.0);
}
@fragment
fn main_f() -> @location(0) vec4<f32> {
return vec4<f32>(0.0, 0.502, 1.0, 1.0); // 0x80/0xff ~= 0.502
}
)";
static wgpu::Adapter adapter;
static wgpu::Device device;
static wgpu::Queue queue;
static wgpu::Buffer readbackBuffer;
static wgpu::RenderPipeline pipeline;
static int testsCompleted = 0;
void GetAdapter(void (*callback)(wgpu::Adapter)) {
instance.RequestAdapter(nullptr, [](WGPURequestAdapterStatus status, WGPUAdapter cAdapter, const char* message, void* userdata) {
if (message) {
printf("RequestAdapter: %s\n", message);
}
assert(status == WGPURequestAdapterStatus_Success);
wgpu::Adapter adapter = wgpu::Adapter::Acquire(cAdapter);
reinterpret_cast<void (*)(wgpu::Adapter)>(userdata)(adapter);
}, reinterpret_cast<void*>(callback));
}
void GetDevice(void (*callback)(wgpu::Device)) {
adapter.RequestDevice(nullptr, [](WGPURequestDeviceStatus status, WGPUDevice cDevice, const char* message, void* userdata) {
if (message) {
printf("RequestDevice: %s\n", message);
}
assert(status == WGPURequestDeviceStatus_Success);
wgpu::Device device = wgpu::Device::Acquire(cDevice);
reinterpret_cast<void (*)(wgpu::Device)>(userdata)(device);
}, reinterpret_cast<void*>(callback));
}
void init() {
device.SetUncapturedErrorCallback(
[](WGPUErrorType errorType, const char* message, void*) {
printf("%d: %s\n", errorType, message);
}, nullptr);
queue = device.GetQueue();
wgpu::ShaderModule shaderModule{};
{
wgpu::ShaderModuleWGSLDescriptor wgslDesc{};
wgslDesc.code = shaderCode;
wgpu::ShaderModuleDescriptor descriptor{};
descriptor.nextInChain = &wgslDesc;
shaderModule = device.CreateShaderModule(&descriptor);
shaderModule.GetCompilationInfo([](WGPUCompilationInfoRequestStatus status, const WGPUCompilationInfo* info, void*) {
assert(status == WGPUCompilationInfoRequestStatus_Success);
assert(info->messageCount == 0);
std::printf("Shader compile succeeded\n");
}, nullptr);
}
{
wgpu::BindGroupLayoutDescriptor bglDesc{};
auto bgl = device.CreateBindGroupLayout(&bglDesc);
wgpu::BindGroupDescriptor desc{};
desc.layout = bgl;
desc.entryCount = 0;
desc.entries = nullptr;
device.CreateBindGroup(&desc);
}
{
wgpu::PipelineLayoutDescriptor pl{};
pl.bindGroupLayoutCount = 0;
pl.bindGroupLayouts = nullptr;
wgpu::ColorTargetState colorTargetState{};
colorTargetState.format = wgpu::TextureFormat::BGRA8Unorm;
wgpu::FragmentState fragmentState{};
fragmentState.module = shaderModule;
fragmentState.targetCount = 1;
fragmentState.targets = &colorTargetState;
wgpu::DepthStencilState depthStencilState{};
depthStencilState.format = wgpu::TextureFormat::Depth32Float;
depthStencilState.depthCompare = wgpu::CompareFunction::Always;
wgpu::RenderPipelineDescriptor descriptor{};
descriptor.layout = device.CreatePipelineLayout(&pl);
descriptor.vertex.module = shaderModule;
descriptor.fragment = &fragmentState;
descriptor.primitive.topology = wgpu::PrimitiveTopology::TriangleList;
descriptor.depthStencil = &depthStencilState;
pipeline = device.CreateRenderPipeline(&descriptor);
}
}
// The depth stencil attachment isn't really needed to draw the triangle
// and doesn't really affect the render result.
// But having one should give us a slightly better test coverage for the compile of the depth stencil descriptor.
void render(wgpu::TextureView view, wgpu::TextureView depthStencilView) {
wgpu::RenderPassColorAttachment attachment{};
attachment.view = view;
attachment.loadOp = wgpu::LoadOp::Clear;
attachment.storeOp = wgpu::StoreOp::Store;
attachment.clearValue = {0, 0, 0, 1};
wgpu::RenderPassDescriptor renderpass{};
renderpass.colorAttachmentCount = 1;
renderpass.colorAttachments = &attachment;
wgpu::RenderPassDepthStencilAttachment depthStencilAttachment = {};
depthStencilAttachment.view = depthStencilView;
depthStencilAttachment.depthClearValue = 0;
depthStencilAttachment.depthLoadOp = wgpu::LoadOp::Clear;
depthStencilAttachment.depthStoreOp = wgpu::StoreOp::Store;
renderpass.depthStencilAttachment = &depthStencilAttachment;
wgpu::CommandBuffer commands;
{
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
{
wgpu::RenderPassEncoder pass = encoder.BeginRenderPass(&renderpass);
pass.SetPipeline(pipeline);
pass.Draw(3);
pass.End();
}
commands = encoder.Finish();
}
queue.Submit(1, &commands);
}
void issueContentsCheck(const char* functionName,
wgpu::Buffer readbackBuffer, uint32_t expectData) {
struct UserData {
const char* functionName;
wgpu::Buffer readbackBuffer;
uint32_t expectData;
};
UserData* userdata = new UserData;
userdata->functionName = functionName;
userdata->readbackBuffer = readbackBuffer;
userdata->expectData = expectData;
readbackBuffer.MapAsync(
wgpu::MapMode::Read, 0, 4,
[](WGPUBufferMapAsyncStatus status, void* vp_userdata) {
assert(status == WGPUBufferMapAsyncStatus_Success);
std::unique_ptr<UserData> userdata(reinterpret_cast<UserData*>(vp_userdata));
const void* ptr = userdata->readbackBuffer.GetConstMappedRange();
printf("%s: readback -> %p%s\n", userdata->functionName,
ptr, ptr ? "" : " <------- FAILED");
assert(ptr != nullptr);
uint32_t readback = static_cast<const uint32_t*>(ptr)[0];
userdata->readbackBuffer.Unmap();
printf(" got %08x, expected %08x%s\n",
readback, userdata->expectData,
readback == userdata->expectData ? "" : " <------- FAILED");
testsCompleted++;
}, userdata);
}
void doCopyTestMappedAtCreation(bool useRange) {
static constexpr uint32_t kValue = 0x05060708;
size_t size = useRange ? 12 : 4;
wgpu::Buffer src;
{
wgpu::BufferDescriptor descriptor{};
descriptor.size = size;
descriptor.usage = wgpu::BufferUsage::CopySrc;
descriptor.mappedAtCreation = true;
src = device.CreateBuffer(&descriptor);
}
size_t offset = useRange ? 8 : 0;
uint32_t* ptr = static_cast<uint32_t*>(useRange ?
src.GetMappedRange(offset, 4) :
src.GetMappedRange());
printf("%s: getMappedRange -> %p%s\n", __FUNCTION__,
ptr, ptr ? "" : " <------- FAILED");
assert(ptr != nullptr);
*ptr = kValue;
src.Unmap();
wgpu::Buffer dst;
{
wgpu::BufferDescriptor descriptor{};
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
dst = device.CreateBuffer(&descriptor);
}
// Write some random data to the buffer, just to verify that
// wgpuQueueWriteBuffer works.
char data[4];
queue.WriteBuffer(dst, 0, data, sizeof(data));
wgpu::CommandBuffer commands;
{
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(src, offset, dst, 0, 4);
commands = encoder.Finish();
}
queue.Submit(1, &commands);
issueContentsCheck(__FUNCTION__, dst, kValue);
}
void doCopyTestMapAsync(bool useRange) {
static constexpr uint32_t kValue = 0x01020304;
size_t size = useRange ? 12 : 4;
wgpu::Buffer src;
{
wgpu::BufferDescriptor descriptor{};
descriptor.size = size;
descriptor.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::CopySrc;
src = device.CreateBuffer(&descriptor);
}
size_t offset = useRange ? 8 : 0;
struct UserData {
const char* functionName;
bool useRange;
size_t offset;
wgpu::Buffer src;
};
UserData* userdata = new UserData;
userdata->functionName = __FUNCTION__;
userdata->useRange = useRange;
userdata->offset = offset;
userdata->src = src;
src.MapAsync(wgpu::MapMode::Write, offset, 4,
[](WGPUBufferMapAsyncStatus status, void* vp_userdata) {
assert(status == WGPUBufferMapAsyncStatus_Success);
std::unique_ptr<UserData> userdata(reinterpret_cast<UserData*>(vp_userdata));
uint32_t* ptr = static_cast<uint32_t*>(userdata->useRange ?
userdata->src.GetMappedRange(userdata->offset, 4) :
userdata->src.GetMappedRange());
printf("%s: getMappedRange -> %p%s\n", userdata->functionName,
ptr, ptr ? "" : " <------- FAILED");
assert(ptr != nullptr);
*ptr = kValue;
userdata->src.Unmap();
wgpu::Buffer dst;
{
wgpu::BufferDescriptor descriptor{};
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
dst = device.CreateBuffer(&descriptor);
}
wgpu::CommandBuffer commands;
{
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(userdata->src, userdata->offset, dst, 0, 4);
commands = encoder.Finish();
}
queue.Submit(1, &commands);
issueContentsCheck(userdata->functionName, dst, kValue);
}, userdata);
}
void doRenderTest() {
wgpu::Texture readbackTexture;
{
wgpu::TextureDescriptor descriptor{};
descriptor.usage = wgpu::TextureUsage::RenderAttachment | wgpu::TextureUsage::CopySrc;
descriptor.size = {1, 1, 1};
descriptor.format = wgpu::TextureFormat::BGRA8Unorm;
// Test for viewFormats binding
std::array<wgpu::TextureFormat, 2> viewFormats =
{ wgpu::TextureFormat::BGRA8Unorm, wgpu::TextureFormat::BGRA8Unorm };
descriptor.viewFormatCount = viewFormats.size();
descriptor.viewFormats = viewFormats.data();
readbackTexture = device.CreateTexture(&descriptor);
}
wgpu::Texture depthTexture;
{
wgpu::TextureDescriptor descriptor{};
descriptor.usage = wgpu::TextureUsage::RenderAttachment;
descriptor.size = {1, 1, 1};
descriptor.format = wgpu::TextureFormat::Depth32Float;
depthTexture = device.CreateTexture(&descriptor);
}
render(readbackTexture.CreateView(), depthTexture.CreateView());
{
// A little texture.GetFormat test
assert(wgpu::TextureFormat::BGRA8Unorm == readbackTexture.GetFormat());
assert(wgpu::TextureFormat::Depth32Float == depthTexture.GetFormat());
}
{
wgpu::BufferDescriptor descriptor{};
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
readbackBuffer = device.CreateBuffer(&descriptor);
}
wgpu::CommandBuffer commands;
{
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
wgpu::ImageCopyTexture src{};
src.texture = readbackTexture;
src.origin = {0, 0, 0};
wgpu::ImageCopyBuffer dst{};
dst.buffer = readbackBuffer;
dst.layout.bytesPerRow = 256;
wgpu::Extent3D extent = {1, 1, 1};
encoder.CopyTextureToBuffer(&src, &dst, &extent);
commands = encoder.Finish();
}
queue.Submit(1, &commands);
// Check the color value encoded in the shader makes it out correctly.
static const uint32_t expectData = 0xff0080ff;
issueContentsCheck(__FUNCTION__, readbackBuffer, expectData);
}
wgpu::Surface surface;
wgpu::TextureView canvasDepthStencilView;
const uint32_t kWidth = 300;
const uint32_t kHeight = 150;
void frame() {
wgpu::SurfaceTexture surfaceTexture;
surface.GetCurrentTexture(&surfaceTexture);
wgpu::TextureView backbuffer = surfaceTexture.texture.CreateView();
render(backbuffer, canvasDepthStencilView);
// TODO: Read back from the canvas with drawImage() (or something) and
// check the result.
emscripten_cancel_main_loop();
// exit(0) (rather than emscripten_force_exit(0)) ensures there is no dangling keepalive.
exit(0);
}
void run() {
init();
doCopyTestMappedAtCreation(false);
doCopyTestMappedAtCreation(true);
doCopyTestMapAsync(false);
doCopyTestMapAsync(true);
doRenderTest();
{
wgpu::SurfaceDescriptorFromCanvasHTMLSelector canvasDesc{};
canvasDesc.selector = "#canvas";
wgpu::SurfaceDescriptor surfDesc{};
surfDesc.nextInChain = &canvasDesc;
surface = instance.CreateSurface(&surfDesc);
wgpu::SurfaceCapabilities capabilities;
surface.GetCapabilities(adapter, &capabilities);
wgpu::SurfaceConfiguration config{
.device = device,
.format = capabilities.formats[0],
.usage = wgpu::TextureUsage::RenderAttachment,
.alphaMode = wgpu::CompositeAlphaMode::Auto,
.width = kWidth,
.height = kHeight,
.presentMode = wgpu::PresentMode::Fifo};
surface.Configure(&config);
{
wgpu::TextureDescriptor descriptor{};
descriptor.usage = wgpu::TextureUsage::RenderAttachment;
descriptor.size = {kWidth, kHeight, 1};
descriptor.format = wgpu::TextureFormat::Depth32Float;
canvasDepthStencilView = device.CreateTexture(&descriptor).CreateView();
}
}
emscripten_set_main_loop(frame, 0, false);
}
int main() {
GetAdapter([](wgpu::Adapter a) {
adapter = a;
wgpu::AdapterInfo info;
adapter.GetInfo(&info);
printf("adapter vendor: %s\n", info.vendor);
printf("adapter architecture: %s\n", info.architecture);
printf("adapter device: %s\n", info.device);
printf("adapter description: %s\n", info.description);
GetDevice([](wgpu::Device dev) {
device = dev;
run();
});
});
// The test result will be reported when the main_loop completes.
// emscripten_exit_with_live_runtime isn't needed because the WebGPU
// callbacks should all automatically keep the runtime alive until
// emscripten_set_main_loop, and that should keep it alive until
// emscripten_cancel_main_loop.
//
// This code is returned when the runtime exits unless something else sets
// it, like exit(0).
return 99;
}