-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApplication.cpp
More file actions
932 lines (768 loc) · 33.7 KB
/
Application.cpp
File metadata and controls
932 lines (768 loc) · 33.7 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
#include "Application.h"
#include "webgpu/webgpu.hpp"
#include "FileManagement.h"
#include "webgpu-utils.h"
#include "stb_image.h"
// Standard library includes
#include <iostream>
#include <cassert>
#include <vector>
#include <array>
#include <filesystem>
// Other libraries
#include <GLFW/glfw3.h>
#include <glfw3webgpu.h>
#include <glm/ext.hpp>
using namespace wgpu;
// APPLICATION METHODS IMPLEMENT
bool Application::Initialize() {
// WINDOW ----------------------------------------------------------------------------------------------
glfwInit();
// hints
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
window = glfwCreateWindow(640, 480, "WebGPU", nullptr, nullptr);
// glfw window -> Application instance
// set user pointer to access application instance in callbacks
glfwSetWindowUserPointer(window, this);
// create lambda function for resize callback using pointer to App
// must be a NON-Capturing lambda to be converted to function pointer
auto resizeCallback = [](GLFWwindow* window, int width, int height) {
// get application instance
Application* appPtr = reinterpret_cast<Application*>(glfwGetWindowUserPointer(window));
if (appPtr) appPtr->reSizeScreen();
};
// finally set the callback!
glfwSetFramebufferSizeCallback(window, resizeCallback);
glfwSetCursorPosCallback(window, [](GLFWwindow* window, double xpos, double ypos) {
// get application instance
auto that = reinterpret_cast<Application*>(glfwGetWindowUserPointer(window));
if (that != nullptr) that->onDrag(xpos, ypos);
});
glfwSetMouseButtonCallback(window, [](GLFWwindow* window, int button, int action, int mods) {
// get application instance
auto that = reinterpret_cast<Application*>(glfwGetWindowUserPointer(window));
if (that != nullptr) that->onClick(button, action, mods);
});
glfwSetScrollCallback(window, [](GLFWwindow* window, double xoffset, double yoffset) {
// get application instance
auto that = reinterpret_cast<Application*>(glfwGetWindowUserPointer(window));
if (that != nullptr) that->onScroll(xoffset, yoffset);
});
// INSTANCE SETUP ----------------------------------------------------------------------------------------------
// create a descriptor
InstanceDescriptor desc = {};
// desc.nextInChain = nullptr;
#ifdef WEBGPU_BACKEND_DAWN
// Make sure the uncaptured error callback is called as soon as an error
// occurs rather than at the next call to "wgpuDeviceTick".
DawnTogglesDescriptor toggles;
toggles.chain.next = nullptr;
toggles.chain.sType = SType::DawnTogglesDescriptor;
toggles.disabledToggleCount = 0;
toggles.enabledToggleCount = 1;
const char* toggleName = "enable_immediate_error_handling";
toggles.enabledToggles = &toggleName;
desc.nextInChain = &toggles.chain;
#endif // WEBGPU_BACKEND_DAWN
// instance using this descriptor
Instance instance = createInstance(desc);
// We can check whether there is actually an instance created
if (!instance) {
std::cerr << "Could not initialize WebGPU!" << std::endl;
return 1;
}
std::cout << "WGPU instance: " << instance << std::endl;
// ADAPTER SETUP -----------------------------------------------------------------------------------------------
std::cout << "Requesting adapter..." << std::endl;
RequestAdapterOptions adapterOpts = {};
adapterOpts.nextInChain = nullptr;
// surface
surface = glfwGetWGPUSurface(instance, window);
adapterOpts.compatibleSurface = surface;
adapter = instance.requestAdapter(adapterOpts);
std::cout << "Got adapter: " << adapter << std::endl;
// after adapter obtained
instance.release();
// DEVICE ----------------------------------------------------------------------------------------------
std::cout << "Requesting device..." << std::endl;
// create default device descriptor!!!
DeviceDescriptor deviceDesc = {};
deviceDesc.nextInChain = nullptr;
deviceDesc.label = "My Device"; // anything works here, that's your call
deviceDesc.requiredFeatureCount = 0; // we do not require any specific feature
deviceDesc.requiredLimits = nullptr; // we do not require any specific limit
deviceDesc.defaultQueue.nextInChain = nullptr;
deviceDesc.defaultQueue.label = "The default queue";
// set reuired limits
RequiredLimits requiredLimits = GetRequiredLimits(adapter);
deviceDesc.requiredLimits = &requiredLimits;
// deviceDesc.deviceLostCallback = nullptr;
// A function that is invoked whenever the device stops being available -> Deprecated? TODO
deviceDesc.deviceLostCallback = [](WGPUDeviceLostReason reason, char const* message, void* /* pUserData */) {
std::cout << "Device lost: reason " << reason;
if (message) std::cout << " (" << message << ")";
std::cout << std::endl;
};
device = adapter.requestDevice(deviceDesc);
std::cout << "Got device: " << device << std::endl;
uncapturedErrorCallbackHandle = device.setUncapturedErrorCallback(
[](ErrorType type, char const* message) {
std::cout << "Uncaptured error callback: " << type;
if (message) std::cout << " (" << message << ")";
std::cout << std::endl;
}
);
//QUEUE OPERATIONS ----------------------------------------------------------------------------------------------
queue = device.getQueue();
// SURFACE CONFIGURATION -----------------------------------------
SurfaceConfiguration config = {};
config.nextInChain = nullptr;
// size of texture for now
config.width = 640;
config.height = 480;
// flag as to-be used for render output
config.usage = TextureUsage::RenderAttachment;
// use format of the surface (from adapter)
surfaceFormat = surface.getPreferredFormat(adapter);
config.format = surfaceFormat;
// no view formats
config.viewFormatCount = 0;
config.viewFormats = nullptr;
config.device = device;
// presentation: first in, first out
config.presentMode = PresentMode::Fifo;
// transparency
config.alphaMode = CompositeAlphaMode::Auto;
surface.configure(config);
// after getting device & surface config
//adapter.release();
depthTextureFormat = TextureFormat::Depth24Plus;
InitializePipeline();
InitializeBuffers();
InitializeDepthTexture();
Texture colorTexture = getObjTexture("../files/wahoo.bmp", device, &colorTextureView);
if (!colorTexture) {
std::cerr << "Could not load obj texture!" << std::endl;
}
Texture cubemapTexture = InitializeCubeMapTexture("../files/venice_sunset", & cubemapTextureView);
if (!cubemapTexture) {
std::cerr << "Could not load cubemap texture" << std::endl;
}
InitializeBindGroups(); // after buffers are created and passed
return true;
}
void Application::Terminate() {
// indexBuffer.release();
vertexBuffer.release();
uniformBuffer.release();
layout.release();
bindGroupLayout.release();
bindGroup.release();
pipeline.release();
depthTextureView.release();
depthTexture.destroy();
depthTexture.release();
colorTextureView.release();
adapter.release();
surface.unconfigure();
queue.release();
surface.release();
device.release();
glfwDestroyWindow(window);
glfwTerminate();
}
void Application::MainLoop() {
glfwPollEvents();
//update uniforms
float t = static_cast<float>(glfwGetTime());
queue.writeBuffer(uniformBuffer, offsetof(Uniforms, time), &t, sizeof(float)); // offset for mvp
// next target texture view
TextureView targetView = GetNextSurfaceTextureView();
if (!targetView) return;
// encoder for render pass
CommandEncoderDescriptor encoderDesc = {};
encoderDesc.nextInChain = nullptr;
encoderDesc.label = "render-pass encoder";
CommandEncoder encoder = device.createCommandEncoder(encoderDesc);
// render pass descriptor
RenderPassDescriptor renderPassDesc = {};
renderPassDesc.nextInChain = nullptr;
// color attachment (just 1 for now)
RenderPassColorAttachment renderPassColorAttachment = {};
renderPassColorAttachment.view = targetView; // draw to targetview
renderPassColorAttachment.resolveTarget = nullptr; // only for multi-sampling
renderPassColorAttachment.loadOp = LoadOp::Clear; // operation before render pass
renderPassColorAttachment.storeOp = StoreOp::Store; // operation after rendre pass
// renderPassColorAttachment.clearValue = Color{ 0.5, 0.5, 0.5, 1.0 };
#ifndef WEBGPU_BACKEND_WGPU
renderPassColorAttachment.depthSlice = WGPU_DEPTH_SLICE_UNDEFINED;
#endif // NOT WEBGPU_BACKEND_WGPU
renderPassDesc.colorAttachmentCount = 1;
renderPassDesc.colorAttachments = &renderPassColorAttachment;
// for depth buffer
RenderPassDepthStencilAttachment depthStencilAttachment;
depthStencilAttachment.view = depthTextureView; // created in InitializeDepthTexture()
depthStencilAttachment.depthClearValue = 1.0f;
depthStencilAttachment.depthLoadOp = LoadOp::Clear;
depthStencilAttachment.depthStoreOp = StoreOp::Store;
/*depthStencilAttachment.depthLoadOp = LoadOp::Undefined;
depthStencilAttachment.depthStoreOp = StoreOp::Undefined;*/
depthStencilAttachment.depthReadOnly = false;
// do not use stencil for now (but setup required)
/*depthStencilAttachment.stencilClearValue = 0;
depthStencilAttachment.stencilLoadOp = LoadOp::Clear;
depthStencilAttachment.stencilStoreOp = StoreOp::Store;
depthStencilAttachment.stencilReadOnly = true;*/
renderPassDesc.depthStencilAttachment = &depthStencilAttachment;
// TODO: necessary for DAWN maybe?
/*constexpr auto NaNf = std::numeric_limits<float>::quiet_NaN();
depthStencilAttachment.clearDepth = NaNf;*/
renderPassDesc.timestampWrites = nullptr;
// get access to commands for rendering (pass the descriptor)
RenderPassEncoder renderPass = encoder.beginRenderPass(renderPassDesc);
renderPass.setPipeline(pipeline);
renderPass.setVertexBuffer(0, vertexBuffer, 0, vertexBuffer.getSize());
// renderPass.setIndexBuffer(indexBuffer, IndexFormat::Uint16, 0, indexBuffer.getSize());
renderPass.setBindGroup(0, bindGroup, 0, nullptr);
// renderPass.drawIndexed(indexCount, 1, 0, 0, 0);
renderPass.draw(indexCount, 1, 0, 0);
renderPass.end();
renderPass.release();
// encode and submit render command
CommandBufferDescriptor cmdBufferDescriptor = {};
cmdBufferDescriptor.nextInChain = nullptr;
cmdBufferDescriptor.label = "Command buffer";
CommandBuffer command = encoder.finish(cmdBufferDescriptor);
encoder.release();
// std::cout << "Submitting render command..." << std::endl;
queue.submit(1, &command);
command.release();
// std::cout << "Command render submitted." << std::endl;
// release at end
targetView.release();
#ifndef __EMSCRIPTEN__
surface.present();
#endif
#if defined(WEBGPU_BACKEND_DAWN)
device.tick();
#elif defined(WEBGPU_BACKEND_WGPU)
wgpuDevicePoll(device, false, nullptr);
#endif
}
bool Application::IsRunning() {
return !glfwWindowShouldClose(window);
}
TextureView Application::GetNextSurfaceTextureView() {
// first get surface texture (more like a raw container)
SurfaceTexture surfaceTexture;
surface.getCurrentTexture(&surfaceTexture);
// check success
if (surfaceTexture.status != SurfaceGetCurrentTextureStatus::Success) {
return nullptr;
}
Texture texture = surfaceTexture.texture;
// second create view texture (config TODO)
TextureViewDescriptor viewDescriptor;
viewDescriptor.nextInChain = nullptr;
viewDescriptor.label = "Surface texture view";
viewDescriptor.format = texture.getFormat();
viewDescriptor.dimension = TextureViewDimension::_2D;
viewDescriptor.baseMipLevel = 0;
viewDescriptor.mipLevelCount = 1;
viewDescriptor.baseArrayLayer = 0;
viewDescriptor.arrayLayerCount = 1;
viewDescriptor.aspect = TextureAspect::All;
TextureView targetView = texture.createView(viewDescriptor);
// dont need surface texture once we get texture view
#ifndef WEBGPU_BACKEND_WGPU
// We no longer need the texture, only its view
// (NB: with wgpu-native, surface textures must not be manually released)
wgpuTextureRelease(surfaceTexture.texture);
#endif // WEBGPU_BACKEND_WGPU
return targetView;
}
void Application::InitializePipeline() {
RenderPipelineDescriptor pipelineDesc;
ShaderModule shaderModule = FileManagement::loadShaderModule("../files/shader0.wgsl", device);
if (!shaderModule) {
std::cerr << "Shader module creation failed!" << std::endl;
return;
}
if (surfaceFormat == TextureFormat::Undefined) {
std::cerr << "Surface format is undefined!" << std::endl;
return;
}
// 0. Vertex pipeline state
VertexState vertexState;
// vertexBufferLayout
VertexBufferLayout vertexBufferLayout;
vertexBufferLayout.arrayStride = sizeof(VertexAttr);
vertexBufferLayout.stepMode = VertexStepMode::Vertex;
// position attribute
VertexAttribute positionAttrib;
positionAttrib.shaderLocation = 0;
positionAttrib.format = VertexFormat::Float32x3;
positionAttrib.offset = 0;
//color attribute
VertexAttribute colorAttrib;
colorAttrib.shaderLocation = 1;
colorAttrib.format = VertexFormat::Float32x3;
colorAttrib.offset = offsetof(VertexAttr, color);
//normal attribute
VertexAttribute normalAttrib;
normalAttrib.shaderLocation = 2;
normalAttrib.format = VertexFormat::Float32x3; //vec3
normalAttrib.offset = offsetof(VertexAttr, normal);
// uv attribute
VertexAttribute uvAttrib;
uvAttrib.shaderLocation = 3;
uvAttrib.format = VertexFormat::Float32x2;
uvAttrib.offset = offsetof(VertexAttr, uv);
// pass position & color attr to vertexBufferLayout
std::vector<VertexAttribute> vertexAttributes(4);
vertexAttributes[0] = positionAttrib;
vertexAttributes[1] = colorAttrib;
vertexAttributes[2] = normalAttrib;
vertexAttributes[3] = uvAttrib;
vertexBufferLayout.attributeCount = vertexAttributes.size();
vertexBufferLayout.attributes = vertexAttributes.data();
//// pass vertexBufferLayout to pipelineDesc
vertexState.bufferCount = 1;
vertexState.buffers = &vertexBufferLayout;
// shader contains: shader module, entry point
vertexState.module = shaderModule;
vertexState.entryPoint = "vs_main";
vertexState.constantCount = 0;
vertexState.constants = nullptr;
pipelineDesc.vertex = vertexState;
// 1. Primitive pipeline state (primitive assembly and rasterization)
pipelineDesc.primitive.topology = PrimitiveTopology::TriangleList;
pipelineDesc.primitive.stripIndexFormat = IndexFormat::Undefined; // consider vertices sequentially
pipelineDesc.primitive.frontFace = FrontFace::CCW; // Front if vertices increment CCW
pipelineDesc.primitive.cullMode = WGPUCullMode_None; // no CULL yet: TODO
// 2. Fragment shader state
FragmentState fragmentState;
fragmentState.module = shaderModule;
fragmentState.entryPoint = "fs_main";
fragmentState.constantCount = 0;
fragmentState.constants = nullptr;
// configure blending stage
BlendState blendState;
// rgb = a_s * rgb_s + (1 - a_s) * rgb_d
blendState.color.srcFactor = BlendFactor::SrcAlpha;
blendState.color.dstFactor = BlendFactor::OneMinusSrcAlpha;
blendState.color.operation = BlendOperation::Add;
blendState.alpha.srcFactor = BlendFactor::Zero;
blendState.alpha.dstFactor = BlendFactor::One;
blendState.alpha.operation = BlendOperation::Add;
ColorTargetState colorTarget;
colorTarget.format = surfaceFormat;
colorTarget.blend = &blendState;
colorTarget.writeMask = ColorWriteMask::All;
fragmentState.targetCount = 1;
fragmentState.targets = &colorTarget;
pipelineDesc.fragment = &fragmentState;
// 3. Stencil/depth state
DepthStencilState depthStencilState = Default;
depthStencilState.depthCompare = CompareFunction::LessEqual;
depthStencilState.depthWriteEnabled = true;
depthStencilState.format = depthTextureFormat;
depthStencilState.stencilReadMask = 0;
depthStencilState.stencilWriteMask = 0;
pipelineDesc.depthStencil = &depthStencilState;
// Multi-sample
pipelineDesc.multisample.count = 1; // off for now
pipelineDesc.multisample.mask = ~0u;
pipelineDesc.multisample.alphaToCoverageEnabled = false;
// define pipeline layout (describe pipeline resources)
// Uniforms Binding Layout
std::vector<BindGroupLayoutEntry> bindingLayoutEntries(4, Default); // Default sets buffer, sampler, etc. to undefined
// 0. Uniforms
BindGroupLayoutEntry& bindingLayout = bindingLayoutEntries[0];
bindingLayout.binding = 0;// binding index, same as attrubute used in shader for uTime
bindingLayout.visibility = ShaderStage::Vertex | ShaderStage::Fragment;
bindingLayout.buffer.type = BufferBindingType::Uniform; // 1. undefined -> BUFFER
bindingLayout.buffer.minBindingSize = sizeof(Uniforms);
// 1. Texture Binding Layout
BindGroupLayoutEntry& textureBindingLayout = bindingLayoutEntries[1];
textureBindingLayout.binding = 1;
textureBindingLayout.visibility = ShaderStage::Fragment;
textureBindingLayout.texture.sampleType = TextureSampleType::Float;// 1. undefined -> TEXTURE
textureBindingLayout.texture.viewDimension = TextureViewDimension::_2D;
// 2. Sampler
BindGroupLayoutEntry& samplerBindingLayout = bindingLayoutEntries[2];
samplerBindingLayout.binding = 2;
samplerBindingLayout.visibility = ShaderStage::Fragment;
samplerBindingLayout.sampler.type = SamplerBindingType::Filtering;
// 3. Cube-map Texture Binding Layout
BindGroupLayoutEntry& cubemapBindingLayout = bindingLayoutEntries[3];
cubemapBindingLayout.binding = 3;
cubemapBindingLayout.visibility = ShaderStage::Fragment;
cubemapBindingLayout.texture.sampleType = TextureSampleType::Float;
cubemapBindingLayout.texture.viewDimension = TextureViewDimension::Cube;
// Binding group of binding layout
BindGroupLayoutDescriptor bindGroupLayoutDesc{};
bindGroupLayoutDesc.entryCount = (uint32_t)bindingLayoutEntries.size();
bindGroupLayoutDesc.entries = bindingLayoutEntries.data();
bindGroupLayout = device.createBindGroupLayout(bindGroupLayoutDesc);
// layout descriptor
PipelineLayoutDescriptor layoutDesc{};
layoutDesc.bindGroupLayoutCount = 1;
layoutDesc.bindGroupLayouts = (WGPUBindGroupLayout*)&bindGroupLayout;
layout = device.createPipelineLayout(layoutDesc);
// ask backend to figure out the layout itself by inspecting the shader
pipelineDesc.layout = layout;
pipeline = device.createRenderPipeline(pipelineDesc);
shaderModule.release();
}
RequiredLimits Application::GetRequiredLimits(Adapter adapter) const {
SupportedLimits supportedLimits;
adapter.getLimits(&supportedLimits);
RequiredLimits requiredLimits = Default;
requiredLimits.limits.maxVertexAttributes = 4; // pos col nor uv
requiredLimits.limits.maxVertexBuffers = 1;
// requiredLimits.limits.maxBufferSize = 150000 * sizeof(VertexAttr);
// requiredLimits.limits.maxVertexBufferArrayStride = 6 * sizeof(float);
// requiredLimits.limits.maxInterStageShaderComponents = 3; // 3f for color, doesn't count built-in components like position
requiredLimits.limits.minUniformBufferOffsetAlignment = supportedLimits.limits.minUniformBufferOffsetAlignment;
requiredLimits.limits.minStorageBufferOffsetAlignment = supportedLimits.limits.minStorageBufferOffsetAlignment;
// depth texture
requiredLimits.limits.maxTextureDimension1D = 480;
requiredLimits.limits.maxTextureDimension2D = 640;
requiredLimits.limits.maxTextureArrayLayers = 1;
// for uniforms
requiredLimits.limits.maxBindGroups = 1;
requiredLimits.limits.maxUniformBuffersPerShaderStage = 1;
requiredLimits.limits.maxUniformBufferBindingSize = sizeof(Uniforms);
// textures
requiredLimits.limits.maxSampledTexturesPerShaderStage = 1;
requiredLimits.limits.maxSamplersPerShaderStage = 1;
requiredLimits.limits.maxTextureDimension1D = 2048;
requiredLimits.limits.maxTextureDimension2D = 2048;
return requiredLimits;
}
void Application::InitializeSurface()
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
SurfaceConfiguration config = {};
config.nextInChain = nullptr;
// size of texture for now
config.width = width;
config.height = height;
// flag as to-be used for render output
config.usage = TextureUsage::RenderAttachment;
// use format of the surface (from adapter)
surfaceFormat = surface.getPreferredFormat(adapter);
config.format = surfaceFormat;
// no view formats
config.viewFormatCount = 0;
config.viewFormats = nullptr;
config.device = device;
// presentation: first in, first out
config.presentMode = PresentMode::Fifo;
// transparency
config.alphaMode = CompositeAlphaMode::Auto;
surface.configure(config);
}
void Application::InitializeBuffers() {
std::vector<VertexAttr> verticesList;
bool success = FileManagement::getObjGeometry("../files/sphere.obj", verticesList);
//bool success = FileManagement::getObjGeometry("../files/wahoo.obj", verticesList);
if (!success) {
std::cerr << "Could not load geometry!" << std::endl;
exit(1);
}
indexCount = static_cast<uint32_t>(verticesList.size());
// VERTEX BUFFER
BufferDescriptor bufferDesc;
bufferDesc.label = "Vertex Buffer";
bufferDesc.usage = BufferUsage::CopyDst | BufferUsage::Vertex;
bufferDesc.size = verticesList.size() * sizeof(VertexAttr);
bufferDesc.size = (bufferDesc.size + 3) & ~3; // align to 4 bytes
bufferDesc.mappedAtCreation = false;
vertexBuffer = device.createBuffer(bufferDesc);
queue.writeBuffer(vertexBuffer, 0, verticesList.data(), bufferDesc.size);
// UNIFORM BUFFER
BufferDescriptor uniformBufferDesc;
uniformBufferDesc.label = "Uniform Buffer";
uniformBufferDesc.usage = BufferUsage::CopyDst | BufferUsage::Uniform;
uniformBufferDesc.size = sizeof(Uniforms);
uniformBufferDesc.size = (uniformBufferDesc.size + 3) & ~3; // align to 4 bytes
uniformBufferDesc.mappedAtCreation = false;
uniformBuffer = device.createBuffer(uniformBufferDesc);
Uniforms uniforms;
uniforms.time = 1.0f;
viewCamera.getViewMatrix(uniforms.viewMatrix);
viewCamera.getProjMatrix(uniforms.projMatrix);
uniforms.modelMatrix = glm::rotate(glm::mat4(1.0f), glm::radians(45.0f), glm::vec3(0, 1, 0));
/*uniforms.modelMatrix =
glm::scale(
glm::rotate(glm::mat4(1.0f),
glm::radians(45.0f),
glm::vec3(0, 1, 0)),
glm::vec3(0.05f));*/
uniforms.modelInvTranspose = glm::inverseTranspose(uniforms.modelMatrix);
uniforms.cameraPos = viewCamera.getPosition();
queue.writeBuffer(uniformBuffer, 0, &uniforms, sizeof(Uniforms));
}
void Application::InitializeBindGroups() {
// UNIFORM
BindGroupEntry binding{};
binding.binding = 0;
binding.buffer = uniformBuffer;
binding.offset = 0;
binding.size = sizeof(Uniforms);
// OBJ COLOR TEXTURE
BindGroupEntry textureBinding{}; // TODO: other specidications?????
textureBinding.binding = 1;
textureBinding.textureView = colorTextureView;
// SAMPLER
BindGroupEntry samplerBinding{};
samplerBinding.binding = 2;
samplerBinding.sampler = sampler;
// CUBE-MAP TEXTURE
BindGroupEntry cubemapBinding{};
cubemapBinding.binding = 3;
cubemapBinding.textureView = cubemapTextureView;
std::vector<BindGroupEntry> bindingEntries(4);
bindingEntries[0] = binding;
bindingEntries[1] = textureBinding;
bindingEntries[2] = samplerBinding;
bindingEntries[3] = cubemapBinding;
BindGroupDescriptor bindGroupDesc{};
bindGroupDesc.layout = bindGroupLayout; // defined in layer pipeline
bindGroupDesc.entryCount = (uint32_t)bindingEntries.size();
bindGroupDesc.entries = bindingEntries.data();
bindGroup = device.createBindGroup(bindGroupDesc);
}
void Application::InitializeDepthTexture()
{
int width, height;
glfwGetFramebufferSize(window, &width, &height);
// depth texture
TextureDescriptor depthTextureDesc;
depthTextureDesc.dimension = TextureDimension::_2D;
depthTextureDesc.format = depthTextureFormat;
depthTextureDesc.mipLevelCount = 1;
depthTextureDesc.sampleCount = 1;
depthTextureDesc.size = { static_cast<uint32_t>(width), static_cast<uint32_t>(height), 1 };
depthTextureDesc.usage = TextureUsage::RenderAttachment;
depthTextureDesc.viewFormatCount = 1;
depthTextureDesc.viewFormats = (WGPUTextureFormat*)&depthTextureFormat;
depthTexture = device.createTexture(depthTextureDesc);
// texture view for accessibility
TextureViewDescriptor depthTextureViewDesc;
depthTextureViewDesc.aspect = TextureAspect::DepthOnly;
depthTextureViewDesc.baseArrayLayer = 0;
depthTextureViewDesc.arrayLayerCount = 1;
depthTextureViewDesc.baseMipLevel = 0;
depthTextureViewDesc.mipLevelCount = 1;
depthTextureViewDesc.dimension = TextureViewDimension::_2D;
depthTextureViewDesc.format = depthTextureFormat;
depthTextureView = depthTexture.createView(depthTextureViewDesc);
SamplerDescriptor samplerDesc;
samplerDesc.addressModeU = AddressMode::ClampToEdge;
samplerDesc.addressModeV = AddressMode::ClampToEdge;
samplerDesc.addressModeW = AddressMode::ClampToEdge;
samplerDesc.magFilter = FilterMode::Linear;
samplerDesc.minFilter = FilterMode::Linear;
samplerDesc.mipmapFilter = MipmapFilterMode::Linear;
samplerDesc.lodMinClamp = 0.0f;
samplerDesc.lodMaxClamp = 1.0f;
samplerDesc.compare = CompareFunction::Undefined;
samplerDesc.maxAnisotropy = 1;
sampler = device.createSampler(samplerDesc);
}
Texture Application::InitializeCubeMapTexture(const std::filesystem::path& basePath, TextureView* CMtextureView) {
// address to 6 images (TODO: hard-coded) + STBI Loading
const char* cubemapPaths[] = {
"posx.png",
"negx.png",
"posy.png",
"negy.png",
"posz.png",
"negz.png",
};
Extent3D cubemapSize = { 0, 0, 6 };
std::array<uint8_t*, 6> cubemapData;
for (uint32_t layer = 0; layer < 6; ++layer) {
auto fullPath = basePath / cubemapPaths[layer];
int width, height, channels;
cubemapData[layer] = stbi_load(fullPath.string().c_str(), &width, &height, &channels, 4); // 4 rgba
if (layer == 0) {
cubemapSize.width = (uint32_t)width;
cubemapSize.height = (uint32_t)height;
}
if (cubemapData[layer] == nullptr) {
for (uint32_t i = 0; i < layer; ++i) {
stbi_image_free(cubemapData[i]);
}
std::cerr << "Could not load cube texture " << cubemapPaths[layer] << std::endl;
return nullptr;
}
}
// create texture descriptor
unsigned int size = cubemapSize.width; // assume square
TextureDescriptor textureDesc;
textureDesc.dimension = TextureDimension::_2D; // case A: 2d texture * 6 layers STORAGE
textureDesc.format = WGPUTextureFormat_RGBA8Unorm;
textureDesc.mipLevelCount = 1;
textureDesc.sampleCount = 1;
textureDesc.size = { size, size, 6 };
textureDesc.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst; // shader binding & copy from CPU
textureDesc.viewFormatCount = 0; // no alternate formats for texture view
textureDesc.viewFormats = nullptr;
Texture cubeTexture = device.createTexture(textureDesc);
ImageCopyTexture destination;
destination.texture = cubeTexture;
destination.mipLevel = 0;
destination.origin = { 0, 0, 0 };
destination.aspect = TextureAspect::All;
TextureDataLayout source;
source.offset = 0;
source.bytesPerRow = 4 * size; // 4 bytes per pixel
source.rowsPerImage = size;
// send to GPU
Extent3D singleLayerSize = { size, size, 1 };
for (uint32_t layer = 0; layer < 6; ++layer) {
destination.origin = { 0, 0, layer };
queue.writeTexture(destination, cubemapData[layer], (size_t)(4 * size * size), source, singleLayerSize); // TODO singleLayerSize
stbi_image_free(cubemapData[layer]);
}
// create texture view
if (CMtextureView) { // check if pointer was provided
// texture view
TextureViewDescriptor textureViewDesc;
textureViewDesc.aspect = TextureAspect::All;
textureViewDesc.baseArrayLayer = 0;
textureViewDesc.arrayLayerCount = 6;
textureViewDesc.baseMipLevel = 0;
textureViewDesc.mipLevelCount = 1;
textureViewDesc.dimension = TextureViewDimension::Cube; // case B: CUBE is how the shader should INTERPRET texture
textureViewDesc.format = textureDesc.format;
*CMtextureView = cubeTexture.createView(textureViewDesc);
}
return cubeTexture;
}
Texture Application::getObjTexture(const std::filesystem::path& path, Device device, TextureView* textureView)
{
int width, height, channels;
unsigned char* data = stbi_load(path.string().c_str(), &width, &height, &channels, 4); // 4 rgba
if (nullptr == data) return nullptr;
// create texture descriptor
TextureDescriptor textureDesc;
textureDesc.dimension = TextureDimension::_2D;
textureDesc.format = WGPUTextureFormat_RGBA8Unorm; // unsigned, normalized 0-1
textureDesc.mipLevelCount = 1;
textureDesc.sampleCount = 1;
textureDesc.size = { (unsigned int)width, (unsigned int)height, 1 };
textureDesc.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst; // shader binding & copy from CPU
textureDesc.viewFormatCount = 0; // no alternate formats for texture view
textureDesc.viewFormats = nullptr;
Texture colorTexture = device.createTexture(textureDesc);
ImageCopyTexture destination;
destination.texture = colorTexture;
destination.mipLevel = 0;
destination.origin = { 0, 0, 0 };
destination.aspect = TextureAspect::All;
TextureDataLayout source;
source.offset = 0;
source.bytesPerRow = 4 * textureDesc.size.width;
source.rowsPerImage = textureDesc.size.height;
queue.writeTexture(destination, data, width * height * 4, source, textureDesc.size);
// TODO mipmapping
// LOADING MY OWN TEXTURE INSTEAD -------------------------------------------------------
//std::vector<uint8_t> pixels(4 * textureDesc.size.width * textureDesc.size.height);
//int cellSize = 32;
//for (uint32_t i = 0; i < textureDesc.size.width; ++i) {
// for (uint32_t j = 0; j < textureDesc.size.height; ++j) {
// uint8_t* p = &pixels[4 * (j * textureDesc.size.width + i)];
// float dx = i - textureDesc.size.width / 2.0f;
// float dy = j - textureDesc.size.height / 2.0f;
// int band = static_cast<int>(sqrtf(dx * dx + dy * dy) / 4) % 2; // ring size = 4px
// uint8_t v = band ? 255 : 0; // alternate black/white
// p[0] = v;
// p[1] = v;
// p[2] = v;
// p[3] = 255;
// }
//}
// queue.writeTexture(destination, pixels.data(), pixels.size(), source, textureDesc.size);
// ----------------------------------------------------------------------------------------------
// release
stbi_image_free(data);
if (textureView) {
// texture view
TextureViewDescriptor textureViewDesc;
textureViewDesc.aspect = TextureAspect::All;
textureViewDesc.baseArrayLayer = 0;
textureViewDesc.arrayLayerCount = 1;
textureViewDesc.baseMipLevel = 0;
textureViewDesc.mipLevelCount = 1;
textureViewDesc.dimension = TextureViewDimension::_2D;
textureViewDesc.format = textureDesc.format;
*textureView = colorTexture.createView(textureViewDesc);
}
return colorTexture;
}
void Application::reSizeScreen()
{
// terminate depth texture & surface
depthTextureView.release();
depthTexture.destroy();
depthTexture.release();
surface.unconfigure();
// surface.release(); DONT
InitializeDepthTexture();
InitializeSurface();
}
// Camera mouse interactions ------------------------------------------------
void Application::updateViewMatrix() {
// call camera's view matrix function
glm::mat4x4 viewMatrix;
viewCamera.getViewMatrix(viewMatrix);
// send to shader
queue.writeBuffer(
uniformBuffer,
offsetof(Uniforms, viewMatrix),
&viewMatrix,
sizeof(Uniforms::viewMatrix)
);
}
void Application::onClick(int button, int action, int) {
if (button == GLFW_MOUSE_BUTTON_LEFT) {
switch (action) {
case GLFW_PRESS:
// start dragging
viewCamera.dragState.dragging = true;
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
viewCamera.dragState.startMousePos = glm::vec2(-(float)xpos, (float)ypos); // TODO - ?
viewCamera.dragState.startCameraAngles = viewCamera.angles;
break;
case GLFW_RELEASE:
// stop dragging
viewCamera.dragState.dragging = false;
break;
}
}
}
void Application::onDrag(double xpos, double ypos) {
if (!viewCamera.dragState.dragging) return;
glm::vec2 currMousePos = glm::vec2(-(float)xpos, (float)ypos);
glm::vec2 offset = currMousePos - viewCamera.dragState.startMousePos;
viewCamera.angles = viewCamera.dragState.startCameraAngles + offset * 0.01f;
viewCamera.angles.y = glm::clamp(
viewCamera.angles.y,
-3.14159f / 2 + 1e-5f,
3.14159f / 2 - 1e-5f
);
updateViewMatrix();
}
void Application::onScroll(double xoffset, double yoffset) {
viewCamera.zoom += yoffset * 0.1f;
viewCamera.zoom = glm::clamp(viewCamera.zoom, -2.0f, 2.0f);
updateViewMatrix();
}