-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrenderer.h
More file actions
1747 lines (1593 loc) · 68.5 KB
/
renderer.h
File metadata and controls
1747 lines (1593 loc) · 68.5 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
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#pragma once
#include <iostream>
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include "webgpu/webgpu.h"
#include "sdl2webgpu.h"
#include "SDL.h"
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include "glm/glm.hpp"
#include "glm/gtx/euler_angles.hpp"
#include "glm/gtx/quaternion.hpp"
#include "glm/gtx/string_cast.hpp"
#include "glm/ext.hpp"
#define TINYGLTF_IMPLEMENTATION
#define TINYGLTF_USE_RAPIDJSON
#define TINYGLTF_NO_INCLUDE_RAPIDJSON
#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "tiny_gltf.h"
#if __EMSCRIPTEN__
#include <emscripten.h>
#endif
#define HOLDER(T) using WGPU##T##Holder = std::unique_ptr<WGPU##T##Impl, decltype(&wgpu##T##Release)>
HOLDER(Instance);
HOLDER(Adapter);
HOLDER(Device);
HOLDER(Queue);
#if defined(__EMSCRIPTEN__)
HOLDER(SwapChain);
#endif
HOLDER(Surface);
HOLDER(TextureView);
HOLDER(CommandEncoder);
HOLDER(RenderPassEncoder);
HOLDER(CommandBuffer);
HOLDER(RenderPipeline);
HOLDER(ShaderModule);
HOLDER(BindGroupLayout);
HOLDER(PipelineLayout);
HOLDER(BindGroup);
HOLDER(Sampler);
void bufferDeleter(WGPUBuffer buffer) {
wgpuBufferDestroy(buffer);
wgpuBufferRelease(buffer);
}
using WGPUBufferHolder = std::unique_ptr<WGPUBufferImpl, decltype(&bufferDeleter)>;
void textureDeleter(WGPUTexture texture) {
std::cout << "Attempting to free texture: " << texture << std::endl;
wgpuTextureDestroy(texture);
std::cout << "Destroyed texture: " << texture << std::endl;
wgpuTextureRelease(texture);
std::cout << "Released texture: " << texture << std::endl;
}
using WGPUTextureHolder = std::unique_ptr<WGPUTextureImpl, decltype(&textureDeleter)>;
using SDL_WindowHolder = std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)>;
template<typename T>
void voidDeleter(T*) {}
template<typename T, typename Deleter>
void delete_ptr(std::unique_ptr<T, Deleter>& ptr) {
ptr.get_deleter()(ptr.release());
}
#if defined(__EMSCRIPTEN__)
constexpr const char* base_path = "";
#else
constexpr const char* base_path = "webgpu_resources/";
#endif
std::string get_file_contents(const char *filename) {
std::FILE *fp = fopen((std::string(base_path) + filename).c_str(), "rb");
if (!fp) {
std::cout << "Could not open file: " << filename << std::endl;
std::perror("Error: ");
throw(errno);
}
std::string contents;
std::fseek(fp, 0, SEEK_END);
contents.resize(std::ftell(fp));
std::rewind(fp);
std::fread(&contents[0], 1, contents.size(), fp);
std::fclose(fp);
return(contents);
}
struct Uniforms {
glm::mat4x4 projection;
glm::mat4x4 view;
};
static_assert(sizeof(glm::mat4x4) == (sizeof(float) * 4 * 4));
constexpr size_t TRANSFORM_SIZE = sizeof(glm::mat4x4);
struct PrimitiveUniforms {
glm::mat4x4 transform;
glm::vec4 base_color;
uint32_t has_texture; // actually just a bool
std::array<float, 3> _padding;
};
struct ModelUniforms {
glm::mat4x4 transform;
};
constexpr WGPUTextureFormat DEPTH_TEXTURE_FORMAT = WGPUTextureFormat_Depth24Plus;
struct Rect {
uint32_t width;
uint32_t height;
};
constexpr Rect SCREEN_SIZE = {640, 480};
constexpr uint32_t MAX_TEXTURE_SIZE = 4096;
constexpr uint32_t COPY_BUFFER_ALIGNMENT = 4;
struct RenderConfig {
glm::ivec2 size = { 640, 360 };
glm::u8vec3 clear_color = { 255, 255, 255 };
float zoom = 1.f;
RenderConfig();
};
void deviceLostCallback(WGPUDeviceLostReason reason, char const* message, void* /* pUserData */) {
std::cerr << "Device lost: " << reason;
if (message) std::cerr << " (" << message << ")";
std::cerr << std::endl;
}
WGPUAdapter requestAdapter(WGPUInstance instance, WGPURequestAdapterOptions const * options) {
struct UserData {
WGPUAdapter adapter = nullptr;
bool requestEnded = false;
};
UserData userData;
auto onAdapterRequestEnded = [](WGPURequestAdapterStatus status, WGPUAdapter adapter, char const * message, void * pUserData) {
UserData& userData = *reinterpret_cast<UserData*>(pUserData);
if (status == WGPURequestAdapterStatus_Success) {
userData.adapter = adapter;
} else {
std::cerr << "Could not get WebGPU adapter: " << message << std::endl;
}
userData.requestEnded = true;
};
wgpuInstanceRequestAdapter(
instance,
options,
onAdapterRequestEnded,
(void*)&userData
);
while (!userData.requestEnded) {
#ifdef __EMSCRIPTEN__
emscripten_sleep(100);
#endif
}
return userData.adapter;
}
WGPUDevice requestDevice(WGPUAdapter adapter, WGPUDeviceDescriptor const * descriptor) {
struct UserData {
WGPUDevice device = nullptr;
bool requestEnded = false;
};
UserData userData;
auto onDeviceRequestEnded = [](WGPURequestDeviceStatus status, WGPUDevice device, char const * message, void * pUserData) {
UserData& userData = *static_cast<UserData*>(pUserData);
if (status == WGPURequestDeviceStatus_Success) {
userData.device = device;
} else {
std::cerr << "Could not get WebGPU device: " << message << std::endl;
}
userData.requestEnded = true;
};
wgpuAdapterRequestDevice(adapter, descriptor, onDeviceRequestEnded, (void*)&userData);
while (!userData.requestEnded) {
#ifdef __EMSCRIPTEN__
emscripten_sleep(100);
#endif
}
return userData.device;
}
WGPUInstanceHolder getInstance() {
WGPUInstanceDescriptor desc = {nullptr};
#if defined(__EMSCRIPTEN__)
WGPUInstance instance = wgpuCreateInstance(nullptr);
#else
WGPUInstance instance = wgpuCreateInstance(&desc);
#endif
if (!instance) {
std::cerr << "Could not initialize WebGPU!" << std::endl;
exit(1);
}
std::cout << "WGPU instance: " << instance << std::endl;
return WGPUInstanceHolder(instance, wgpuInstanceRelease);
}
SDL_Window* initSDL(const char* window_title, const RenderConfig& config) {
SDL_SetMainReady();
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "Could not initialize SDL! Error: " << SDL_GetError() << std::endl;
exit(1);
}
SDL_Window *window = SDL_CreateWindow(
window_title,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
config.size.x,
config.size.y,
SDL_WINDOW_RESIZABLE);
if (!window) {
std::cerr << "Could not create window! Error: " << SDL_GetError() << std::endl;
exit(1);
}
return window;
}
std::vector<WGPUFeatureName> getAdapterFeatures(WGPUAdapter adapter) {
std::vector<WGPUFeatureName> features;
size_t featureCount = wgpuAdapterEnumerateFeatures(adapter, nullptr);
features.resize(featureCount);
wgpuAdapterEnumerateFeatures(adapter, features.data());
return features;
}
WGPUAdapterHolder getAdapter(WGPUInstance instance, WGPUSurface surface) {
std::cout << "Requesting adapter..." << std::endl;
WGPURequestAdapterOptions adapterOpts = {
.nextInChain = nullptr,
.compatibleSurface = surface,
.powerPreference = WGPUPowerPreference_Undefined,
.forceFallbackAdapter = false,
};
WGPUAdapter adapter = requestAdapter(instance, &adapterOpts);
if (!adapter) {
std::cerr << "Could not get WebGPU adapter!" << std::endl;
exit(1);
}
std::cout << "Received adapter: " << adapter << std::endl;
std::vector<WGPUFeatureName> features = getAdapterFeatures(adapter);
std::cout << "Adapter features:" << std::endl;
for (WGPUFeatureName f : features) {
std::cout << " - " << f << std::endl;
}
return WGPUAdapterHolder(adapter, wgpuAdapterRelease);
}
WGPUDeviceHolder getDevice(WGPUAdapter adapter, const WGPULimits& adapterLimits) {
std::cout << "Requesting device..." << std::endl;
WGPURequiredLimits requiredLimits = {
.nextInChain = nullptr,
.limits = {
.maxTextureDimension1D = MAX_TEXTURE_SIZE,
.maxTextureDimension2D = MAX_TEXTURE_SIZE,
.maxTextureArrayLayers = 1,
.maxBindGroups = 3,
.maxBindingsPerBindGroup = 3,
.maxSampledTexturesPerShaderStage = 1,
.maxSamplersPerShaderStage = 1,
.maxStorageTexturesPerShaderStage = 1,
.maxUniformBuffersPerShaderStage = 1,
.maxUniformBufferBindingSize = 1 << 12,
.minUniformBufferOffsetAlignment = adapterLimits.minUniformBufferOffsetAlignment,
.minStorageBufferOffsetAlignment = adapterLimits.minStorageBufferOffsetAlignment,
.maxVertexBuffers = 4,
.maxBufferSize = 1 << 21,
.maxVertexAttributes = 7,
.maxVertexBufferArrayStride = TRANSFORM_SIZE,
.maxInterStageShaderComponents = 5,
}
};
WGPUDeviceDescriptor deviceDesc = {
.nextInChain = nullptr,
.label = "My Device",
.requiredLimits = &requiredLimits,
.defaultQueue = {
.nextInChain = nullptr,
.label = "The default queue",
},
.deviceLostCallback = &deviceLostCallback,
};
WGPUDevice device = requestDevice(adapter, &deviceDesc);
auto onDeviceError = [](WGPUErrorType type, char const* message, void* /* pUserData */) {
std::cerr << "Uncaptured device error: type " << type;
if (message) std::cerr << " (" << message << ")";
std::cerr << std::endl;
};
wgpuDeviceSetUncapturedErrorCallback(device, onDeviceError, nullptr /* pUserData */);
if (!device) {
std::cerr << "Could not get WebGPU device!" << std::endl;
exit(1);
}
std::cout << "Received device: " << device << std::endl;
return WGPUDeviceHolder(device, wgpuDeviceRelease);
}
WGPUQueueHolder getQueue(WGPUDevice device) {
std::cout << "Requesting queue..." << std::endl;
WGPUQueue queue = wgpuDeviceGetQueue(device);
auto onQueueWorkDone = [](WGPUQueueWorkDoneStatus status, void* /* pUserData */) {
std::cout << "Queued work finished with status: " << status << std::endl;
};
wgpuQueueOnSubmittedWorkDone(queue, onQueueWorkDone, nullptr /* pUserData */);
if (!queue) {
std::cerr << "Could not get WebGPU queue!" << std::endl;
exit(1);
}
std::cout << "Received queue: " << queue << std::endl;
return WGPUQueueHolder(queue, wgpuQueueRelease);
}
#if defined(__EMSCRIPTEN__)
WGPUSwapChainHolder getSwapChain(WGPUSurface surface, WGPUDevice device, WGPUTextureFormat swapChainFormat, Rect screen_size) {
std::cout << "Creating swapchain device..." << std::endl;
WGPUSwapChainDescriptor swapChainDesc = {
.nextInChain = nullptr,
.label = "Swap chain",
.usage = WGPUTextureUsage_RenderAttachment,
.format = swapChainFormat,
.width = screen_size.width,
.height = screen_size.height,
.presentMode = WGPUPresentMode_Fifo,
};
WGPUSwapChain swapChain = wgpuDeviceCreateSwapChain(device, surface, &swapChainDesc);
if (!swapChain) {
std::cerr << "Could not create WebGPU swap chain!" << std::endl;
exit(1);
}
std::cout << "Received swapchain: " << swapChain << std::endl;
return WGPUSwapChainHolder(swapChain, wgpuSwapChainRelease);
}
WGPUTextureViewHolder getNextTexture(WGPUSwapChain swapChain) {
WGPUTextureView nextTexture = wgpuSwapChainGetCurrentTextureView(swapChain);
if (!nextTexture) {
std::cerr << "Cannot acquire next swap chain texture" << std::endl;
exit(1);
}
return WGPUTextureViewHolder(nextTexture, wgpuTextureViewRelease);
}
#endif
WGPUShaderModuleHolder createShaderModule(WGPUDevice device) {
std::string shader = get_file_contents("resources/shader.wgsl");
std::size_t pos = shader.find("DO_COLOR_CORRECTION");
if (pos != std::string::npos) {
#if defined(WEBGPU_BACKEND_WGPU)
shader.replace(pos, 19, "true ");
#elif defined(WEBGPU_BACKEND_DAWN) or defined(__EMSCRIPTEN__)
shader.replace(pos, 19, "false ");
#endif
}
char* shader_text = new char[shader.size() + 1];
std::copy(shader.begin(), shader.end(), shader_text);
shader_text[shader.size()] = '\0';
WGPUShaderModuleWGSLDescriptor shaderCodeDesc = {
.chain = {
.next = nullptr,
.sType = WGPUSType_ShaderModuleWGSLDescriptor,
},
.code = shader_text,
};
WGPUShaderModuleDescriptor shaderDesc = {
.nextInChain = &shaderCodeDesc.chain,
.label = "Shader module",
#ifdef WEBGPU_BACKEND_WGPU
.hintCount = 0,
.hints = nullptr,
#endif
};
WGPUShaderModule shaderModule = wgpuDeviceCreateShaderModule(device, &shaderDesc);
if (!shaderModule) {
std::cerr << "Could not create shader module!" << std::endl;
exit(1);
}
std::cout << "Created shader module: " << shaderModule << std::endl;
return WGPUShaderModuleHolder(shaderModule, wgpuShaderModuleRelease);
}
WGPUBindGroupLayoutHolder createBindGroupLayout(WGPUDevice device) {
WGPUBindGroupLayoutEntry bindGroupLayoutEntry = {
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
.minBindingSize = sizeof(Uniforms),
},
.sampler = {},
.texture = {},
};
WGPUBindGroupLayoutDescriptor bindGroupLayoutDesc = {
.nextInChain = nullptr,
.label = "Bind group layout",
.entryCount = 1,
.entries = &bindGroupLayoutEntry,
};
WGPUBindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout(device, &bindGroupLayoutDesc);
if (!bindGroupLayout) {
std::cerr << "Could not create bind group layout!" << std::endl;
exit(1);
}
std::cout << "Created bind group layout: " << bindGroupLayout << std::endl;
return WGPUBindGroupLayoutHolder(bindGroupLayout, wgpuBindGroupLayoutRelease);
}
WGPUBindGroupHolder createBindGroup(WGPUDevice device, WGPUBindGroupDescriptor layout) {
WGPUBindGroup bindGroup = wgpuDeviceCreateBindGroup(device, &layout);
if (!bindGroup) {
std::cerr << "Could not create bind group!" << std::endl;
exit(1);
}
std::cout << "Created bind group: " << bindGroup << std::endl;
return WGPUBindGroupHolder(bindGroup, wgpuBindGroupRelease);
}
WGPUBindGroupHolder createUniformsBindGroup(WGPUDevice device, WGPUBindGroupLayout layout, WGPUBuffer buffer) {
WGPUBindGroupEntry bindGroupEntry = {
.binding = 0,
.buffer = buffer,
.offset = 0,
.size = sizeof(Uniforms),
};
WGPUBindGroupDescriptor bindGroupDesc = {
.nextInChain = nullptr,
.label = "Uniform bind group",
.layout = layout,
.entryCount = 1,
.entries = &bindGroupEntry,
};
return createBindGroup(device, bindGroupDesc);
}
WGPUBindGroupLayoutHolder createModelBindGroupLayout(WGPUDevice device) {
std::array bindGroupLayoutEntry = {
WGPUBindGroupLayoutEntry{
.binding = 0,
.visibility = WGPUShaderStage_Vertex,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
.minBindingSize = sizeof(ModelUniforms),
},
.sampler = {},
.texture = {},
},
};
WGPUBindGroupLayoutDescriptor bindGroupLayoutDesc = {
.nextInChain = nullptr,
.label = "Model bind group layout",
.entryCount = static_cast<uint32_t>(bindGroupLayoutEntry.size()),
.entries = bindGroupLayoutEntry.data(),
};
WGPUBindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout(device, &bindGroupLayoutDesc);
if (!bindGroupLayout) {
std::cerr << "Could not create model bind group layout!" << std::endl;
exit(1);
}
std::cout << "Created model bind group layout: " << bindGroupLayout << std::endl;
return WGPUBindGroupLayoutHolder(bindGroupLayout, wgpuBindGroupLayoutRelease);
}
WGPUBindGroupLayoutHolder createPrimitiveBindGroupLayout(WGPUDevice device) {
std::array bindGroupLayoutEntry = {
WGPUBindGroupLayoutEntry{
.binding = 0,
.visibility = WGPUShaderStage_Vertex | WGPUShaderStage_Fragment,
.buffer = {
.type = WGPUBufferBindingType_Uniform,
.hasDynamicOffset = false,
.minBindingSize = sizeof(PrimitiveUniforms),
},
.sampler = {},
.texture = {},
},
WGPUBindGroupLayoutEntry{
.binding = 1,
.visibility = WGPUShaderStage_Fragment,
.buffer = {},
.sampler = {},
.texture = {
.sampleType = WGPUTextureSampleType_Float,
.viewDimension = WGPUTextureViewDimension_2D,
.multisampled = false,
},
},
WGPUBindGroupLayoutEntry{
.binding = 2,
.visibility = WGPUShaderStage_Fragment,
.buffer = {},
.sampler = {
.type = WGPUSamplerBindingType_Filtering,
},
.texture = {},
},
};
WGPUBindGroupLayoutDescriptor bindGroupLayoutDesc = {
.nextInChain = nullptr,
.label = "Primitive bind group layout",
.entryCount = static_cast<uint32_t>(bindGroupLayoutEntry.size()),
.entries = bindGroupLayoutEntry.data(),
};
WGPUBindGroupLayout bindGroupLayout = wgpuDeviceCreateBindGroupLayout(device, &bindGroupLayoutDesc);
if (!bindGroupLayout) {
std::cerr << "Could not create primitive bind group layout!" << std::endl;
exit(1);
}
std::cout << "Created primitive bind group layout: " << bindGroupLayout << std::endl;
return WGPUBindGroupLayoutHolder(bindGroupLayout, wgpuBindGroupLayoutRelease);
}
template<unsigned int N>
WGPUPipelineLayoutHolder createPipelineLayout(WGPUDevice device, std::array<WGPUBindGroupLayout, N> bindGroupLayouts) {
WGPUPipelineLayoutDescriptor pipelineLayoutDesc = {
.nextInChain = nullptr,
.label = "Pipeline layout",
.bindGroupLayoutCount = bindGroupLayouts.size(),
.bindGroupLayouts = bindGroupLayouts.data(),
};
WGPUPipelineLayout pipelineLayout = wgpuDeviceCreatePipelineLayout(device, &pipelineLayoutDesc);
if (!pipelineLayout) {
std::cerr << "Could not create pipeline layout!" << std::endl;
exit(1);
}
std::cout << "Created pipeline layout: " << pipelineLayout << std::endl;
return WGPUPipelineLayoutHolder(pipelineLayout, wgpuPipelineLayoutRelease);
}
WGPURenderPipelineHolder createRenderPipeline(WGPUDevice device, WGPUPipelineLayout layout, WGPUShaderModule shaders, WGPUTextureFormat swapChainFormat) {
WGPUBlendState blendState = {
.color = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_SrcAlpha,
.dstFactor = WGPUBlendFactor_OneMinusSrcAlpha,
},
.alpha = {
.operation = WGPUBlendOperation_Add,
.srcFactor = WGPUBlendFactor_Zero,
.dstFactor = WGPUBlendFactor_One,
}
};
WGPUColorTargetState colorTargetState = {
.nextInChain = nullptr,
.format = swapChainFormat,
.blend = &blendState,
.writeMask = WGPUColorWriteMask_All,
};
WGPUVertexAttribute positionAttrib = {
.format = WGPUVertexFormat_Float32x3,
.offset = 0,
.shaderLocation = 0,
};
WGPUVertexBufferLayout vertexPositionBufferLayout = {
.arrayStride = 12,
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &positionAttrib,
};
WGPUVertexAttribute normalAttrib = {
.format = WGPUVertexFormat_Float32x3,
.offset = 0,
.shaderLocation = 1,
};
WGPUVertexBufferLayout vertexNormalBufferLayout = {
.arrayStride = 12,
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &normalAttrib,
};
WGPUVertexAttribute texcoordAttrib = {
.format = WGPUVertexFormat_Float32x2,
.offset = 0,
.shaderLocation = 2,
};
WGPUVertexBufferLayout vertexTexcoordBufferLayout = {
.arrayStride = 8,
.stepMode = WGPUVertexStepMode_Vertex,
.attributeCount = 1,
.attributes = &texcoordAttrib,
};
std::array instanceTransformAttribs = {
WGPUVertexAttribute{
.format = WGPUVertexFormat_Float32x4,
.offset = 0,
.shaderLocation = 3,
},
WGPUVertexAttribute{
.format = WGPUVertexFormat_Float32x4,
.offset = sizeof(float) * 4,
.shaderLocation = 4,
},
WGPUVertexAttribute{
.format = WGPUVertexFormat_Float32x4,
.offset = sizeof(float) * 8,
.shaderLocation = 5,
},
WGPUVertexAttribute{
.format = WGPUVertexFormat_Float32x4,
.offset = sizeof(float) * 12,
.shaderLocation = 6,
},
};
WGPUVertexBufferLayout instanceTransformBufferLayout = {
.arrayStride = TRANSFORM_SIZE,
.stepMode = WGPUVertexStepMode_Instance,
.attributeCount = static_cast<uint32_t>(instanceTransformAttribs.size()),
.attributes = instanceTransformAttribs.data(),
};
std::array vertexBufferLayouts = {
vertexPositionBufferLayout,
vertexNormalBufferLayout,
vertexTexcoordBufferLayout,
instanceTransformBufferLayout,
};
WGPUFragmentState fragment = {
.nextInChain = nullptr,
.module = shaders,
.entryPoint = "fragment_main",
.constantCount = 0,
.constants = nullptr,
.targetCount = 1,
.targets = &colorTargetState,
};
WGPUDepthStencilState depthStencilState = {
.nextInChain = nullptr,
.format = DEPTH_TEXTURE_FORMAT,
.depthWriteEnabled = true,
.depthCompare = WGPUCompareFunction_Less,
.stencilFront = {
.compare = WGPUCompareFunction_Always,
.failOp = WGPUStencilOperation_Keep,
.depthFailOp = WGPUStencilOperation_Keep,
.passOp = WGPUStencilOperation_Keep,
},
.stencilBack = {
.compare = WGPUCompareFunction_Always,
.failOp = WGPUStencilOperation_Keep,
.depthFailOp = WGPUStencilOperation_Keep,
.passOp = WGPUStencilOperation_Keep,
},
.stencilReadMask = 0,
.stencilWriteMask = 0,
.depthBias = 0,
.depthBiasSlopeScale = 0.,
.depthBiasClamp = 0.,
};
WGPURenderPipelineDescriptor pipelineDesc = {
.nextInChain = nullptr,
.label = "Render pipeline",
.layout = layout,
.vertex = {
.nextInChain = nullptr,
.module = shaders,
.entryPoint = "vertex_main",
.constantCount = 0,
.constants = nullptr,
.bufferCount = static_cast<uint32_t>(vertexBufferLayouts.size()),
.buffers = vertexBufferLayouts.data(),
},
.primitive = {
.nextInChain = nullptr,
.topology = WGPUPrimitiveTopology_TriangleList,
.stripIndexFormat = WGPUIndexFormat_Undefined,
.frontFace = WGPUFrontFace_CCW,
.cullMode = WGPUCullMode_None,
},
.depthStencil = &depthStencilState,
.multisample = {
.nextInChain = nullptr,
.count = 1,
.mask = static_cast<uint32_t>(-1),
.alphaToCoverageEnabled = false,
},
.fragment = &fragment,
};
WGPURenderPipeline pipeline = wgpuDeviceCreateRenderPipeline(device, &pipelineDesc);
if (!pipeline) {
std::cerr << "Could not create render pipeline!" << std::endl;
exit(1);
}
std::cout << "Created render pipeline: " << pipeline << std::endl;
return WGPURenderPipelineHolder(pipeline, wgpuRenderPipelineRelease);
}
WGPUTextureViewHolder createDepthTextureView(WGPUTexture texture) {
WGPUTextureViewDescriptor depthTextureViewDescriptor = {
.nextInChain = nullptr,
.label = "Depth texture view",
.format = DEPTH_TEXTURE_FORMAT,
.dimension = WGPUTextureViewDimension_2D,
.baseMipLevel = 0,
.mipLevelCount = 1,
.baseArrayLayer = 0,
.arrayLayerCount = 1,
.aspect = WGPUTextureAspect_DepthOnly,
};
WGPUTextureView depthTextureView = wgpuTextureCreateView(texture, &depthTextureViewDescriptor);
if (!depthTextureView) {
std::cerr << "Could not create depth texture view!" << std::endl;
exit(1);
}
std::cout << "Created depth texture view: " << depthTextureView << std::endl;
return WGPUTextureViewHolder(depthTextureView, wgpuTextureViewRelease);
}
WGPUBufferHolder createBuffer(WGPUDevice device, WGPUBufferDescriptor bufferDesc) {
std::string label = bufferDesc.label ? bufferDesc.label : "";
WGPUBuffer buffer = wgpuDeviceCreateBuffer(device, &bufferDesc);
if (!buffer) {
std::cerr << "Could not create buffer!" << std::endl;
exit(1);
}
std::cout << "Created buffer: " << buffer;
if (label != "") {
std::cout << " (" << label << ")";
}
std::cout << std::endl;
return WGPUBufferHolder(buffer, bufferDeleter);
}
WGPUTextureHolder createTexture(WGPUDevice device, WGPUTextureDescriptor textureDesc) {
std::string label = textureDesc.label ? textureDesc.label : "";
WGPUTexture texture = wgpuDeviceCreateTexture(device, &textureDesc);
if (!texture) {
std::cerr << "Could not create texture!" << std::endl;
exit(1);
}
std::cout << "Created texture: " << texture;
if (label != "") {
std::cout << " (" << label << ")";
}
std::cout << std::endl;
return WGPUTextureHolder(texture, textureDeleter);
}
WGPUSamplerHolder createSampler(WGPUDevice device, WGPUSamplerDescriptor samplerDesc) {
WGPUSampler sampler = wgpuDeviceCreateSampler(device, &samplerDesc);
if (!sampler) {
std::cerr << "Could not create sampler!" << std::endl;
exit(1);
}
std::cout << "Created sampler: " << sampler << std::endl;
return WGPUSamplerHolder(sampler, wgpuSamplerRelease);
}
class ModelHandle {
size_t index;
friend class Renderer;
ModelHandle(size_t index) : index(index) {}
public:
ModelHandle() : index(std::numeric_limits<size_t>::max()) {}
bool operator==(const ModelHandle& other) const {
return index == other.index;
}
};
struct Transform {
glm::vec3 translation;
glm::vec3 rotation;
glm::vec3 scale;
glm::mat4x4 toMatrix() const {
glm::mat4x4 model_scale = glm::scale(glm::mat4x4(1.f), scale);
glm::mat4x4 model_translation = glm::translate(glm::mat4x4(1.f), translation);
glm::mat4x4 model_rotation = glm::yawPitchRoll(-rotation.x, rotation.z, rotation.y);
return model_translation * model_rotation * model_scale;
}
Transform() : translation(0.f), rotation(0.f, 0.f, 0.f), scale(1.f) {}
Transform(glm::vec3 translation, glm::vec3 rotation, glm::vec3 scale) : translation(translation), rotation(rotation), scale(scale) {}
};
template<typename T>
class Table {
struct Item {
T data;
size_t generation;
};
std::vector<Item> items;
std::unordered_set<size_t> free;
public:
class Index {
size_t index;
size_t generation;
friend class Table;
Index(size_t index, size_t generation) : index(index), generation(generation) {}
public:
size_t get_index() {
return index;
}
bool operator==(const Index& other) const {
return index == other.index && generation == other.generation;
}
};
Table() {}
Index add(T data) {
size_t index;
if (free.empty()) {
index = items.size();
items.push_back({std::move(data), 0});
} else {
auto it = free.begin();
index = *it;
free.erase(it);
items[index] = {std::move(data), items[index].generation + 1};
}
return Index(index, items[index].generation);
}
void remove(Index index) {
if (index.generation != items[index.index].generation) {
return;
}
free.insert(index.index);
items[index.index].generation++;
}
T& operator[](Index index) {
if (index.generation != items[index.index].generation) {
throw std::runtime_error("Invalid index");
}
return items[index.index].data;
}
const T& operator[](Index index) const {
if (index.generation != items[index.index].generation) {
throw std::runtime_error("Invalid index");
}
return items[index.index].data;
}
bool valid(size_t index) const {
return index < items.size() && free.find(index) == free.end();
}
T& rawget(size_t index) {
return items[index].data;
}
const T& rawget(size_t index) const {
return items[index].data;
}
size_t size() const {
return items.size() - free.size();
}
size_t capacity() const {
return items.capacity();
}
};
constexpr size_t UNCHANGED = std::numeric_limits<size_t>::max();
struct DynamicTransformBuffer {
WGPUDevice device;
WGPUQueue queue;
WGPUBufferDescriptor descriptor;
WGPUBufferHolder buffer = WGPUBufferHolder(nullptr, voidDeleter);
Table<Transform> data;
bool changed = false;
size_t current_instance_count = 0;
public:
using Index = Table<Transform>::Index;
DynamicTransformBuffer(WGPUDevice device, WGPUQueue queue, WGPUBufferDescriptor descriptor) : device(device), queue(queue), descriptor(descriptor) {
this->descriptor.size = 0;
}
const Transform& operator[](Index index) const {
return data[index];
}
Transform& operator[](Index index) {
changed = true;
return data[index];
}
Index add(const Transform& value) {
changed = true;
return data.add(value);
}
void remove(Index index) {
changed = true;
data.remove(index);
}
WGPUBuffer getBuffer(std::vector<glm::mat4x4>& ancilla) {
if (!changed) {
return buffer.get();
}
if (descriptor.size < data.size() * sizeof(glm::mat4x4)) {
std::cout << "Resizing buffer \"" << descriptor.label << "\" to " << data.size() * sizeof(glm::mat4x4) << " bytes" << std::endl;
descriptor.size = data.capacity() * sizeof(glm::mat4x4);
buffer = createBuffer(device, descriptor);
}
ancilla.clear();
for (size_t i = 0; i <= data.capacity(); i++) {
if (data.valid(i)) {
ancilla.push_back(data.rawget(i).toMatrix());
}
}
wgpuQueueWriteBuffer(
queue,
buffer.get(),
0,
ancilla.data(),
ancilla.size() * sizeof(glm::mat4x4));
changed = false;
current_instance_count = data.size();
return buffer.get();
}
size_t count() const {
return current_instance_count;
}
size_t size() const {
return current_instance_count * sizeof(glm::mat4x4);
}
};
struct GameConfig;
const char* get_window_title(GameConfig* config);
class Renderer {
struct ModelPrimitive {
WGPUBufferHolder position_buffer;
WGPUBufferHolder normal_buffer;
WGPUBufferHolder index_buffer;
WGPUBufferHolder texcoord_buffer;
WGPUBufferHolder uniform_buffer;
WGPUTextureHolder texture;
WGPUTextureViewHolder texture_view;
WGPUSamplerHolder sampler;
WGPUBindGroupHolder bind_group;
};
struct ModelType {
std::vector<ModelPrimitive> primitives;
DynamicTransformBuffer transforms;
WGPUBufferHolder model_uniform_buffer;
WGPUBindGroupHolder model_bind_group;
};
std::vector<glm::mat4x4> transform_matrix_buffer;
std::unordered_map<std::string, ModelHandle> model_types;
std::vector<ModelType> models;
std::shared_ptr<GameConfig> game_config;
RenderConfig render_config;
Transform camera_transform;
WGPUBufferHolder uniform_buffer = {nullptr, voidDeleter};
WGPUBindGroupHolder bind_group = {nullptr, voidDeleter};
WGPUInstanceHolder instance = {nullptr, voidDeleter};
SDL_WindowHolder window = {nullptr, voidDeleter};
WGPUSurfaceHolder surface = {nullptr, voidDeleter};
WGPUAdapterHolder adapter = {nullptr, voidDeleter};
WGPULimits adapter_limits;
WGPUDeviceHolder device = {nullptr, voidDeleter};
WGPULimits device_limits;
WGPUQueueHolder queue = {nullptr, voidDeleter};
WGPUShaderModuleHolder shader_module = {nullptr, voidDeleter};