Repository navigation
Expand file tree
/
Copy pathtexture_test.c
More file actions
1037 lines (859 loc) · 37.4 KB
/
Copy pathtexture_test.c
File metadata and controls
1037 lines (859 loc) · 37.4 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
#include "pal2/pal_graphics.h"
#include "pal2/pal_system.h"
#include "pal2/pal_video.h"
#include "tests.h"
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define MAX_FRAMES_IN_FLIGHT 2
#define TEXTURE_WIDTH 128
#define TEXTURE_HEIGHT 128
#define CHECKER_SIZE 16
static void createCheckerboardTexture(
uint32_t* texture,
uint32_t width,
uint32_t height,
uint32_t checkerSize)
{
uint8_t* pixels = (uint8_t*)texture;
for (int32_t y = 0; y < height; ++y) {
for (int32_t x = 0; x < width; ++x) {
int32_t i = (y * width + x) * 4;
int checker = ((x / checkerSize) ^ (y / checkerSize)) & 1;
if (checker) {
pixels[i + 0] = 255; // Red bit
pixels[i + 1] = 0; // Green bit
pixels[i + 2] = 0; // Blue bit
pixels[i + 3] = 255; // Alpha bit
} else {
pixels[i + 0] = 0; // Red bit
pixels[i + 1] = 255; // Green bit
pixels[i + 2] = 0; // Blue bit
pixels[i + 3] = 255; // Alpha bit
}
}
}
}
static void PAL_CALL onGraphicsDebug(
void* userData,
PalDebugMessageSeverity severity,
PalDebugMessageType type,
const char* msg)
{
palLog(nullptr, msg);
}
PalBool textureTest()
{
PalResult result;
PalWindow* window = nullptr;
PalEventDriver* eventDriver = nullptr;
PalAdapter* adapter = nullptr;
PalDevice* device = nullptr;
PalSurface* surface = nullptr;
PalQueue* queue = nullptr;
PalSwapchain* swapchain = nullptr;
PalCommandPool* cmdPool = nullptr;
PalImageView** imageViews = nullptr;
PalCommandBuffer* cmdBuffers[MAX_FRAMES_IN_FLIGHT];
PalSemaphore* imageAvailableSemaphores[MAX_FRAMES_IN_FLIGHT];
PalFence* inFlightFences[MAX_FRAMES_IN_FLIGHT];
PalSemaphore** renderFinishedSemaphores; // count of swapchain images
PalFence** inFlightImages; // count of swapchain images
PalPipelineLayout* pipelineLayout = nullptr;
PalPipeline* pipeline = nullptr;
PalShader* shaders[2];
PalBuffer* vertexBuffer = nullptr;
PalBuffer* stagingBuffer = nullptr;
PalDescriptorSetLayout* descriptorSetLayout = nullptr;
PalDescriptorPool* descriptorPool = nullptr;
PalDescriptorSet* descriptorSet = nullptr;
PalEventDriverCreateInfo eventDriverCreateInfo = {0};
result = palCreateEventDriver(&eventDriverCreateInfo, &eventDriver);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create event driver");
return PAL_FALSE;
}
palSetEventDispatchMode(eventDriver, PAL_EVENT_TYPE_WINDOW_CLOSE, PAL_DISPATCH_MODE_POLL);
palSetEventDispatchMode(eventDriver, PAL_EVENT_TYPE_KEYDOWN, PAL_DISPATCH_MODE_POLL);
result = palInitVideo(nullptr, eventDriver, nullptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to initialize video");
return PAL_FALSE;
}
PalWindowCreateInfo windowCreateInfo = {0};
windowCreateInfo.height = WINDOW_HEIGHT;
windowCreateInfo.width = WINDOW_WIDTH;
windowCreateInfo.show = PAL_TRUE;
windowCreateInfo.title = "Texture Window";
PalVideoFeatures videoFeatures = palGetVideoFeatures();
if (!(videoFeatures & PAL_VIDEO_FEATURE_DECORATED_WINDOW)) {
windowCreateInfo.style |= PAL_WINDOW_STYLE_BORDERLESS;
}
result = palCreateWindow(&windowCreateInfo, &window);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create window");
return PAL_FALSE;
}
// get window handle. You can use any window from any library
// so long as you can get the window handle and display (if on X11, wayland)
// If pal video system will not be used, there is no need to initialize it
PalWindowHandleInfo winHandle = {0};
palGetWindowHandleInfo(window, &winHandle);
// using pal_system.h will be easy to know the underlying windowing API or use typedefs.
// We will use the pal_system module.
PalPlatformInfo platformInfo = {0};
palGetPlatformInfo(&platformInfo);
PalWindowInstanceType windowInstanceType = PAL_WINDOW_INSTANCE_TYPE_XCB;
if (platformInfo.apiType == PAL_PLATFORM_API_TYPE_WAYLAND) {
windowInstanceType = PAL_WINDOW_INSTANCE_TYPE_WAYLAND;
} else if (platformInfo.apiType == PAL_PLATFORM_API_TYPE_X11) {
windowInstanceType = PAL_WINDOW_INSTANCE_TYPE_X11;
} else if (platformInfo.apiType == PAL_PLATFORM_API_TYPE_WIN32) {
windowInstanceType = PAL_WINDOW_INSTANCE_TYPE_WIN32;
}
PalGraphicsDebugger debugger = {0};
debugger.callback = onGraphicsDebug;
debugger.userData = nullptr;
result = palInitGraphics(nullptr, nullptr, 0, nullptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to initialize graphics");
return PAL_FALSE;
}
// enumerate all available adapters
uint32_t adapterCount = 0;
result = palEnumerateAdapters(&adapterCount, nullptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to get adapters");
return PAL_FALSE;
}
if (adapterCount == 0) {
palLog(nullptr, "No adapters found");
return PAL_FALSE;
}
palLog(nullptr, "Adapter count: %d", adapterCount);
PalAdapter** adapters = nullptr;
adapters = palAllocate(nullptr, sizeof(PalAdapter*) * adapterCount, 0);
if (!adapters) {
palLog(nullptr, "Failed to allocate memory");
return PAL_FALSE;
}
result = palEnumerateAdapters(&adapterCount, adapters);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to get adapters");
return PAL_FALSE;
}
PalAdapterCapabilities caps = {0};
PalAdapterInfo adapterInfo = {0};
for (int32_t i = 0; i < adapterCount; i++) {
adapter = adapters[i];
palGetAdapterCapabilities(adapter, &caps);
if (caps.maxGraphicsQueues == 0) {
adapter = nullptr;
continue;
}
// We want an adapter that supports spirv 1.0 or dxil 6.0
palGetAdapterInfo(adapter, &adapterInfo);
// we prefer spirv first if an adapter supports multiple shader formats
uint32_t target = 0;
if (adapterInfo.shaderFormats & PAL_SHADER_FORMAT_SPIRV) {
target = palGetHighestSupportedShaderTarget(adapter, PAL_SHADER_FORMAT_SPIRV);
if (target >= PAL_MAKE_SHADER_TARGET(1, 0)) {
break;
}
}
if (adapterInfo.shaderFormats & PAL_SHADER_FORMAT_DXIL) {
target = palGetHighestSupportedShaderTarget(adapter, PAL_SHADER_FORMAT_DXIL);
if (target >= PAL_MAKE_SHADER_TARGET(6, 0)) {
break;
}
}
adapter = nullptr;
continue;
}
palFree(nullptr, adapters);
if (!adapter) {
palLog(nullptr, "Failed to find a required adapter");
return PAL_FALSE;
}
// create a device
PalAdapterFeatures adapterFeatures = palGetAdapterFeatures(adapter);
PalAdapterFeatures features = PAL_ADAPTER_FEATURE_SWAPCHAIN;
if (adapterFeatures & PAL_ADAPTER_FEATURE_FENCE_RESET) {
features |= PAL_ADAPTER_FEATURE_FENCE_RESET;
}
result = palCreateDevice(adapter, features, &device);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create device");
return PAL_FALSE;
}
// create surface
result = palCreateSurface(
device,
winHandle.nativeWindow,
winHandle.nativeInstance,
windowInstanceType,
&surface);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create surface");
return PAL_FALSE;
}
// create a graphics command queue and check if its supports presenting to the surface
PalBool foundQueue = PAL_FALSE;
for (int i = 0; i < caps.maxGraphicsQueues; i++) {
result = palCreateQueue(device, PAL_QUEUE_TYPE_GRAPHICS, &queue);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create queue");
return PAL_FALSE;
}
if (!palCanQueuePresent(queue, surface)) {
palDestroyQueue(queue);
queue = nullptr;
} else {
// found a queue
foundQueue = PAL_TRUE;
break;
}
}
if (!foundQueue) {
palLog(nullptr, "Failed to find a queue that can present to the surface");
return PAL_FALSE;
}
// create a swapchain with the graphics queue
PalSurfaceCapabilities surfaceCaps = {0};
palGetSurfaceCapabilities(device, surface, &surfaceCaps);
PalSwapchainCreateInfo swapchainCreateInfo = {0};
swapchainCreateInfo.clipped = PAL_TRUE;
swapchainCreateInfo.compositeAlpha = PAL_COMPOSITE_ALPHA_OPAQUE;
swapchainCreateInfo.height = WINDOW_HEIGHT;
swapchainCreateInfo.width = WINDOW_WIDTH;
swapchainCreateInfo.imageArrayLayerCount = 1;
swapchainCreateInfo.presentMode = PAL_PRESENT_MODE_FIFO;
swapchainCreateInfo.format = PAL_SURFACE_FORMAT_BGRA8_UNORM_SRGB_NONLINEAR;
// rare but possible on andriod
if (WINDOW_WIDTH > surfaceCaps.maxImageWidth) {
swapchainCreateInfo.width = surfaceCaps.maxImageWidth / 2;
}
if (WINDOW_HEIGHT > surfaceCaps.maxImageHeight) {
swapchainCreateInfo.height = surfaceCaps.maxImageHeight / 2;
}
// check if the minimal image count is not good for you
// and increase it but not pass the max count
swapchainCreateInfo.imageCount = surfaceCaps.minImageCount;
if (swapchainCreateInfo.imageCount == 1) {
swapchainCreateInfo.imageCount++;
if (surfaceCaps.maxImageCount < 2) {
palLog(nullptr, "Surface does not support double buffers");
return PAL_FALSE;
}
}
result = palCreateSwapchain(device, queue, surface, &swapchainCreateInfo, &swapchain);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create swapchain");
return PAL_FALSE;
}
// get all swapchain images and create image views for them
uint32_t imageCount = swapchainCreateInfo.imageCount;
imageViews = palAllocate(nullptr, sizeof(PalImageView*) * imageCount, 0);
inFlightImages = palAllocate(nullptr, sizeof(PalFence*) * imageCount, 0);
renderFinishedSemaphores = palAllocate(nullptr, sizeof(PalSemaphore*) * imageCount, 0);
if (!imageViews || !inFlightImages || !renderFinishedSemaphores) {
palLog(nullptr, "Failed to allocate memory");
return PAL_FALSE;
}
PalImageInfo imageInfo;
palGetImageInfo(palGetSwapchainImage(swapchain, 0), &imageInfo);
PalImageViewCreateInfo imageViewCreateInfo = {0};
imageViewCreateInfo.type = PAL_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.subresourceRange.layerArrayCount = 1;
imageViewCreateInfo.subresourceRange.mipLevelCount = 1;
imageViewCreateInfo.subresourceRange.startArrayLayer = 0;
imageViewCreateInfo.subresourceRange.startMipLevel = 0;
imageViewCreateInfo.format = imageInfo.format;
for (int i = 0; i < imageCount; i++) {
// get swapchain image
// this is fast since the images are cache by PAL
PalImage* image = palGetSwapchainImage(swapchain, i);
if (!image) {
palLog(nullptr, "Failed to get swapchain image");
}
result = palCreateImageView(device, image, &imageViewCreateInfo, &imageViews[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create image view");
return PAL_FALSE;
}
// create render finished semaphores
result = palCreateSemaphore(device, PAL_FALSE, &renderFinishedSemaphores[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create semaphore");
return PAL_FALSE;
}
inFlightImages[i] = nullptr;
}
result = palCreateCommandPool(device, queue, &cmdPool);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create command pool");
return PAL_FALSE;
}
// create synchronization objects and command buffers
for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
result = palCreateSemaphore(device, PAL_FALSE, &imageAvailableSemaphores[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create semaphore");
return PAL_FALSE;
}
result = palCreateFence(device, PAL_TRUE, &inFlightFences[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create fence");
return PAL_FALSE;
}
result = palAllocateCommandBuffer(
device,
cmdPool,
PAL_COMMAND_BUFFER_TYPE_PRIMARY,
&cmdBuffers[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to allocate command buffer");
return PAL_FALSE;
}
}
// create vertex and staging buffer
// clang-format off
float vertices[] = {
-0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, 0.0f, 1.0f};
// clang-format on
PalBufferCreateInfo bufferCreateInfo = {0};
bufferCreateInfo.size = sizeof(vertices);
bufferCreateInfo.usages = PAL_BUFFER_USAGE_VERTEX;
bufferCreateInfo.usages |= PAL_BUFFER_USAGE_TRANSFER_DST; // will recieve
bufferCreateInfo.memoryUsage = PAL_BUFFER_MEMORY_USAGE_AUTO_GPU_ONLY;
result = palCreateBuffer(device, &bufferCreateInfo, &vertexBuffer);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create buffer");
return PAL_FALSE;
}
bufferCreateInfo.usages = PAL_BUFFER_USAGE_TRANSFER_SRC; // will send
bufferCreateInfo.memoryUsage = PAL_BUFFER_MEMORY_USAGE_AUTO_CPU_UPLOAD;
result = palCreateBuffer(device, &bufferCreateInfo, &stagingBuffer);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create buffer");
return PAL_FALSE;
}
// map the staging buffer and upload the vertices
void* ptr = nullptr;
result = palMapBuffer(stagingBuffer, 0, sizeof(vertices), &ptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to map buffer");
return PAL_FALSE;
}
memcpy(ptr, vertices, sizeof(vertices));
palUnmapBuffer(stagingBuffer);
PalFence* fence = nullptr;
result = palCreateFence(device, PAL_FALSE, &fence);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create fence");
return PAL_FALSE;
}
// we dont want to load the texture from disk so we will create a
// checkerboard texture and use that rather
uint32_t texture[TEXTURE_WIDTH * TEXTURE_HEIGHT];
memset(texture, 0, TEXTURE_WIDTH * TEXTURE_HEIGHT);
createCheckerboardTexture(texture, TEXTURE_WIDTH, TEXTURE_HEIGHT, CHECKER_SIZE);
// create image for the texture
PalImage* checkerboard = nullptr;
PalImageCreateInfo imageCreateInfo = {0};
imageCreateInfo.arrayLayerCount = 1;
imageCreateInfo.depth = 1;
imageCreateInfo.format = PAL_FORMAT_R8G8B8A8_UNORM;
imageCreateInfo.mipLevelCount = 1; // simple
imageCreateInfo.sampleCount = PAL_SAMPLE_COUNT_1; // simple
imageCreateInfo.type = PAL_IMAGE_TYPE_2D;
imageCreateInfo.usages = PAL_IMAGE_USAGE_TRANSFER_DST | PAL_IMAGE_USAGE_SAMPLED;
imageCreateInfo.width = TEXTURE_WIDTH;
imageCreateInfo.height = TEXTURE_HEIGHT;
imageCreateInfo.memoryUsage = PAL_IMAGE_MEMORY_USAGE_AUTO_GPU_ONLY;
result = palCreateImage(device, &imageCreateInfo, &checkerboard);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create image");
return PAL_FALSE;
}
// create staging buffer to transfer the data to the image
PalBufferImageCopyInfo bufferImageCopyInfo = {0};
bufferImageCopyInfo.ImageArrayLayerCount = 1;
bufferImageCopyInfo.imageWidth = TEXTURE_WIDTH;
bufferImageCopyInfo.imageHeight = TEXTURE_HEIGHT;
bufferImageCopyInfo.imageDepth = 1; // 2D image
PalImageStagingRequirements stagingReq = {0};
palComputeImageStagingRequirements(
device,
imageCreateInfo.format,
&bufferImageCopyInfo,
&stagingReq);
// update our copy with the required buffer row length and buffer image height
bufferImageCopyInfo.bufferRowLength = stagingReq.bufferRowLength;
bufferImageCopyInfo.bufferImageHeight = stagingReq.bufferImageHeight;
// create staging buffer to transfer the data to the image
PalBuffer* imageStagingBuffer = nullptr;
PalBufferCreateInfo imageStagingBufferCreateInfo = {0};
imageStagingBufferCreateInfo.size = stagingReq.bufferSize;
imageStagingBufferCreateInfo.usages = PAL_BUFFER_USAGE_TRANSFER_SRC;
imageStagingBufferCreateInfo.memoryUsage = PAL_BUFFER_MEMORY_USAGE_AUTO_CPU_UPLOAD;
result = palCreateBuffer(device, &imageStagingBufferCreateInfo, &imageStagingBuffer);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create buffer");
return PAL_FALSE;
}
// copy data
void* data = nullptr;
result = palMapBuffer(imageStagingBuffer, 0, imageStagingBufferCreateInfo.size, &data);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to map buffer");
return PAL_FALSE;
}
palWriteImageStaging(device, imageCreateInfo.format, &bufferImageCopyInfo, texture, data);
palUnmapBuffer(imageStagingBuffer);
// use the first command buffer to upload the copy
// and reset it when done
// set a fence and check at the last line before the main loop
// to see if we have to wait for the copy to be executed
result = palCmdBegin(cmdBuffers[0], nullptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to begin command buffer");
return PAL_FALSE;
}
PalBufferCopyInfo copyInfo = {0};
copyInfo.size = sizeof(vertices);
palCmdCopyBuffer(cmdBuffers[0], vertexBuffer, stagingBuffer, ©Info);
PalBarrierInfo barrierInfo = {0};
barrierInfo.oldState = PAL_USAGE_STATE_TRANSFER_WRITE;
barrierInfo.srcStages = PAL_PIPELINE_STAGE_TRANSFER;
barrierInfo.newState = PAL_USAGE_STATE_TRANSFER_READ;
barrierInfo.dstStages = PAL_PIPELINE_STAGE_TRANSFER;
palCmdBufferBarrier(cmdBuffers[0], vertexBuffer, &barrierInfo);
// copy image staging buffer to the checkerboard image
// first the image must be in the correct layout
barrierInfo.oldState = PAL_USAGE_STATE_UNDEFINED;
barrierInfo.srcStages = PAL_PIPELINE_STAGE_NONE;
barrierInfo.newState = PAL_USAGE_STATE_TRANSFER_WRITE;
barrierInfo.dstStages = PAL_PIPELINE_STAGE_TRANSFER;
// set a barrier on the image to transition it into transfer dst state
PalImageSubresourceRange checkerboardRange = {0};
checkerboardRange.startMipLevel = 0;
checkerboardRange.startArrayLayer = 0;
checkerboardRange.mipLevelCount = 1;
checkerboardRange.layerArrayCount = 1;
palCmdImageBarrier(cmdBuffers[0], checkerboard, &checkerboardRange, &barrierInfo);
palCmdCopyBufferToImage(cmdBuffers[0], checkerboard, imageStagingBuffer, &bufferImageCopyInfo);
// transition the image to shader read state
barrierInfo.oldState = PAL_USAGE_STATE_TRANSFER_WRITE;
barrierInfo.srcStages = PAL_PIPELINE_STAGE_TRANSFER;
barrierInfo.newState = PAL_USAGE_STATE_SHADER_READ;
barrierInfo.dstStages = PAL_PIPELINE_STAGE_FRAGMENT_SHADER;
palCmdImageBarrier(cmdBuffers[0], checkerboard, &checkerboardRange, &barrierInfo);
result = palCmdEnd(cmdBuffers[0]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to end command buffer");
return PAL_FALSE;
}
PalCommandBufferSubmitInfo submitInfo = {0};
submitInfo.cmdBuffer = cmdBuffers[0];
submitInfo.fence = fence;
result = palSubmitCommandBuffer(queue, &submitInfo);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to submit command buffer");
return PAL_FALSE;
}
// now we have the checkerboard texture data in the image
// we need an image view and a sampler
PalImageView* checkerboardImageView = nullptr;
PalImageViewCreateInfo checkerboardImageViewCreateInfo = {0};
checkerboardImageViewCreateInfo.type = PAL_IMAGE_VIEW_TYPE_2D;
checkerboardImageViewCreateInfo.subresourceRange = checkerboardRange;
checkerboardImageViewCreateInfo.format = PAL_FORMAT_R8G8B8A8_UNORM;
result = palCreateImageView(
device,
checkerboard,
&checkerboardImageViewCreateInfo,
&checkerboardImageView);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create image view");
return PAL_FALSE;
}
PalSampler* sampler = nullptr;
PalSamplerCreateInfo samplerCreateInfo = {0};
samplerCreateInfo.addressModeU = PAL_SAMPLER_ADDRESS_MODE_REPEAT;
samplerCreateInfo.addressModeV = PAL_SAMPLER_ADDRESS_MODE_REPEAT;
samplerCreateInfo.addressModeW = PAL_SAMPLER_ADDRESS_MODE_REPEAT;
samplerCreateInfo.borderColor = PAL_BORDER_COLOR_INT_OPAQUE_BLACK;
samplerCreateInfo.compareOp = PAL_COMPARE_OP_NEVER; // will not be used if its not enabled
samplerCreateInfo.enableAnisotropy = PAL_FALSE;
samplerCreateInfo.enableCompare = PAL_FALSE;
samplerCreateInfo.magFilterMode = PAL_FILTER_MODE_LINEAR;
samplerCreateInfo.minFilterMode = PAL_FILTER_MODE_LINEAR;
samplerCreateInfo.maxAnisotropy = 1.0f;
result = palCreateSampler(device, &samplerCreateInfo, &sampler);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create sampler");
return PAL_FALSE;
}
// create shaders
uint32_t bytecodeSize = 0;
void* bytecode = nullptr;
const char* sources[2];
PalShaderEntryInfo entries[2];
PalViewport viewport = {0};
viewport.width = (float)WINDOW_WIDTH;
viewport.maxDepth = 1.0f;
PalShaderCreateInfo shaderCreateInfo = {0};
if (adapterInfo.shaderFormats & PAL_SHADER_FORMAT_SPIRV) {
sources[0] = "graphics/shaders/bin/spirv/texture_vert.spv";
sources[1] = "graphics/shaders/bin/spirv/texture_frag.spv";
viewport.height = -(float)WINDOW_HEIGHT;
viewport.y = (float)WINDOW_HEIGHT;
} else if (adapterInfo.shaderFormats & PAL_SHADER_FORMAT_DXIL) {
sources[0] = "graphics/shaders/bin/dxil/texture_vert.dxil";
sources[1] = "graphics/shaders/bin/dxil/texture_frag.dxil";
viewport.height = (float)WINDOW_HEIGHT;
}
entries[0].stage = PAL_SHADER_STAGE_VERTEX;
entries[0].entryName = "main";
entries[0].patchControlPoints = 0;
entries[1].stage = PAL_SHADER_STAGE_FRAGMENT;
entries[1].entryName = "main";
entries[1].patchControlPoints = 0;
for (int i = 0; i < 2; i++) {
// read file
if (!readFile(sources[i], nullptr, &bytecodeSize)) {
palLog(nullptr, "Failed to read shader file");
return PAL_FALSE;
}
bytecode = palAllocate(nullptr, bytecodeSize, 0);
if (!bytecode) {
palLog(nullptr, "Failed to allocate memory");
return PAL_FALSE;
}
readFile(sources[i], bytecode, &bytecodeSize);
shaderCreateInfo.code = bytecode;
shaderCreateInfo.codeSize = bytecodeSize;
shaderCreateInfo.entries = &entries[i];
shaderCreateInfo.entryCount = 1;
result = palCreateShader(device, &shaderCreateInfo, &shaders[i]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create shader");
return PAL_FALSE;
}
palFree(nullptr, bytecode);
}
// create descriptor set layout
PalDescriptorSetLayoutBinding descriptorBindings[2];
descriptorBindings[0].descriptorCount = 1; // not an array
descriptorBindings[0].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
descriptorBindings[1].descriptorCount = 1; // not an array
descriptorBindings[1].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLER;
PalDescriptorSetLayoutCreateInfo descriptorSetLayoutcreateInfo = {0};
descriptorSetLayoutcreateInfo.bindingCount = 2;
descriptorSetLayoutcreateInfo.bindings = descriptorBindings;
result =
palCreateDescriptorSetLayout(device, &descriptorSetLayoutcreateInfo, &descriptorSetLayout);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create descriptor set layout");
return PAL_FALSE;
}
// create descriptor pool
PalDescriptorPoolBindingSize storageBufferBindingsizes[2];
storageBufferBindingsizes[0].bindingCount = 1;
storageBufferBindingsizes[0].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
storageBufferBindingsizes[1].bindingCount = 1;
storageBufferBindingsizes[1].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLER;
PalDescriptorPoolCreateInfo descriptorPoolCreateInfo = {0};
descriptorPoolCreateInfo.maxDescriptorSets = 1; // only one set
descriptorPoolCreateInfo.bindingSizeCount = 2;
descriptorPoolCreateInfo.bindingSizes = storageBufferBindingsizes;
result = palCreateDescriptorPool(device, &descriptorPoolCreateInfo, &descriptorPool);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create descriptor pool");
return PAL_FALSE;
}
// allocate a single descriptor set from the descriptor pool
// using the layout we created above
result = palAllocateDescriptorSet(device, descriptorPool, descriptorSetLayout, &descriptorSet);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to allocate descriptor set");
return PAL_FALSE;
}
// write the inital data to the descriptor set since its created empty
PalDescriptorImageViewInfo descriptorImageInfo = {0};
descriptorImageInfo.imageView = checkerboardImageView;
PalDescriptorSamplerInfo descriptorSamplerInfo = {0};
descriptorSamplerInfo.sampler = sampler;
PalDescriptorSetWriteInfo writeInfos[2];
writeInfos[0].layoutBindingIndex = 0;
writeInfos[0].imageViewInfos = &descriptorImageInfo;
writeInfos[0].descriptorSet = descriptorSet;
writeInfos[0].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLED_IMAGE;
writeInfos[0].descriptorCount = 1;
writeInfos[0].arrayElement = 0;
writeInfos[0].bufferInfos = nullptr;
writeInfos[0].samplerInfos = nullptr;
writeInfos[0].tlasInfos = nullptr;
writeInfos[1].layoutBindingIndex = 1;
writeInfos[1].samplerInfos = &descriptorSamplerInfo;
writeInfos[1].descriptorSet = descriptorSet;
writeInfos[1].descriptorType = PAL_DESCRIPTOR_TYPE_SAMPLER;
writeInfos[1].descriptorCount = 1;
writeInfos[1].arrayElement = 0;
writeInfos[1].imageViewInfos = nullptr;
writeInfos[1].tlasInfos = nullptr;
writeInfos[1].bufferInfos = nullptr;
result = palUpdateDescriptorSet(device, 2, writeInfos);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to update descriptor set");
return PAL_FALSE;
}
// create pipeline layout
PalPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {0};
pipelineLayoutCreateInfo.descriptorSetLayoutCount = 1;
pipelineLayoutCreateInfo.descriptorSetLayouts = &descriptorSetLayout;
result = palCreatePipelineLayout(device, &pipelineLayoutCreateInfo, &pipelineLayout);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create pipeline layout");
return PAL_FALSE;
}
PalRenderingLayoutInfo renderingLayoutInfo = {0};
renderingLayoutInfo.colorAttachentCount = 1;
renderingLayoutInfo.colorAttachmentsFormat = &imageInfo.format;
renderingLayoutInfo.sampleCount = PAL_SAMPLE_COUNT_1;
renderingLayoutInfo.viewCount = 1;
// create graphics pipeline
PalGraphicsPipelineCreateInfo pipelineCreateInfo = {0};
PalVertexLayout vertexLayout = {0};
PalVertexAttribute vertexAttributes[2];
// position
vertexAttributes[0].semanticID = PAL_VERTEX_SEMANTIC_ID_POSITION;
vertexAttributes[0].type = PAL_VERTEX_TYPE_FLOAT2;
// texture coordinates
vertexAttributes[1].semanticID = PAL_VERTEX_SEMANTIC_ID_TEXCOORD;
vertexAttributes[1].type = PAL_VERTEX_TYPE_FLOAT2;
vertexLayout.attributeCount = 2;
vertexLayout.attributes = vertexAttributes;
vertexLayout.binding = 0; // first vertex buffer binding slot
vertexLayout.type = PAL_VERTEX_LAYOUT_TYPE_PER_VERTEX;
pipelineCreateInfo.vertexLayoutCount = 1;
pipelineCreateInfo.vertexLayouts = &vertexLayout;
// color blend attachment
PalColorBlendAttachment blendAttachment = {0};
blendAttachment.colorWriteMask |= PAL_COLOR_MASK_RED;
blendAttachment.colorWriteMask |= PAL_COLOR_MASK_GREEN;
blendAttachment.colorWriteMask |= PAL_COLOR_MASK_BLUE;
blendAttachment.colorWriteMask |= PAL_COLOR_MASK_ALPHA;
pipelineCreateInfo.colorBlendAttachments = &blendAttachment;
pipelineCreateInfo.colorBlendAttachmentCount = 1;
// shaders
pipelineCreateInfo.shaderCount = 2;
pipelineCreateInfo.shaders = shaders;
pipelineCreateInfo.topology = PAL_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
pipelineCreateInfo.pipelineLayout = pipelineLayout;
pipelineCreateInfo.renderingLayout = &renderingLayoutInfo;
result = palCreateGraphicsPipeline(device, &pipelineCreateInfo, &pipeline);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to create pipeline");
return PAL_FALSE;
}
for (int i = 0; i < 2; i++) {
palDestroyShader(shaders[i]);
}
// wait for the vertices copy to be done
result = palWaitFence(fence, PAL_INFINITE);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait fence");
return PAL_FALSE;
}
// the vertices have been copied
palDestroyFence(fence);
palDestroyBuffer(stagingBuffer);
palDestroyBuffer(imageStagingBuffer);
// main loop
uint32_t currentFrame = 0;
PalBool running = PAL_TRUE;
PalRect2D scissor = {0};
scissor.height = WINDOW_HEIGHT;
scissor.width = WINDOW_WIDTH;
while (running) {
// update the video system to push video events
palUpdateVideo();
PalEvent event;
while (palPollEvent(eventDriver, &event)) {
switch (event.type) {
case PAL_EVENT_TYPE_WINDOW_CLOSE: {
running = PAL_FALSE;
break;
}
case PAL_EVENT_TYPE_KEYDOWN: {
PalKeycode keycode = 0;
palUnpackUint32(event.data, &keycode, nullptr);
if (keycode == PAL_KEYCODE_ESCAPE) {
running = PAL_FALSE;
}
break;
}
}
}
result = palWaitFence(inFlightFences[currentFrame], PAL_INFINITE);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait fence");
return PAL_FALSE;
}
// get next swapchain image
PalSwapchainNextImageInfo nextImageInfo = {0};
nextImageInfo.fence = nullptr;
nextImageInfo.signalSemaphore = imageAvailableSemaphores[currentFrame];
nextImageInfo.timeout = PAL_INFINITE;
uint32_t imageIndex = 0;
result = palGetNextSwapchainImage(swapchain, &nextImageInfo, &imageIndex);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to get next swapchain image");
return PAL_FALSE;
}
if (inFlightImages[imageIndex] != nullptr) {
result = palWaitFence(inFlightImages[imageIndex], PAL_INFINITE);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait fence");
return PAL_FALSE;
}
}
inFlightImages[imageIndex] = inFlightFences[currentFrame];
if (adapterFeatures & PAL_ADAPTER_FEATURE_FENCE_RESET) {
result = palResetFence(inFlightFences[currentFrame]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait fence");
return PAL_FALSE;
}
} else {
// recreate since we dont support fence resetting
palDestroyFence(inFlightFences[currentFrame]);
result = palCreateFence(device, PAL_FALSE, &inFlightFences[currentFrame]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait fence");
return PAL_FALSE;
}
}
// reset the command buffer
result = palResetCommandBuffer(cmdBuffers[currentFrame]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to reset command buffer");
return PAL_FALSE;
}
result = palCmdBegin(cmdBuffers[currentFrame], nullptr);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to begin command buffer");
return PAL_FALSE;
}
// change the state of the image view to make it renderable
barrierInfo.oldState = PAL_USAGE_STATE_UNDEFINED;
barrierInfo.srcStages = PAL_PIPELINE_STAGE_NONE;
barrierInfo.newState = PAL_USAGE_STATE_COLOR_ATTACHMENT_WRITE;
barrierInfo.dstStages = PAL_PIPELINE_STAGE_COLOR_ATTACHMENT;
PalImageSubresourceRange imageRange = {0};
imageRange.layerArrayCount = 1;
imageRange.mipLevelCount = 1;
imageRange.startArrayLayer = 0;
imageRange.startMipLevel = 0;
PalImage* image = palGetSwapchainImage(swapchain, imageIndex);
palCmdImageBarrier(cmdBuffers[currentFrame], image, &imageRange, &barrierInfo);
PalClearValue clearValue;
clearValue.color[0] = 0.2f;
clearValue.color[1] = 0.2f;
clearValue.color[2] = 0.2f;
clearValue.color[3] = 1.0f;
PalAttachmentDesc colorAttachment = {0};
colorAttachment.loadOp = PAL_LOAD_OP_CLEAR;
colorAttachment.storeOp = PAL_STORE_OP_STORE;
colorAttachment.clearValue = clearValue;
colorAttachment.imageView = imageViews[imageIndex];
PalRenderingInfo renderingInfo = {0};
renderingInfo.viewCount = 1;
renderingInfo.colorAttachentCount = 1;
renderingInfo.colorAttachments = &colorAttachment;
renderingInfo.arrayLayerCount = 1;
renderingInfo.viewCount = 1;
renderingInfo.renderArea.width = WINDOW_WIDTH;
renderingInfo.renderArea.height = WINDOW_HEIGHT;
palCmdBeginRendering(cmdBuffers[currentFrame], &renderingInfo);
palCmdBindPipeline(cmdBuffers[currentFrame], pipeline);
palCmdBindDescriptorSet(cmdBuffers[currentFrame], 0, descriptorSet);
palCmdSetViewport(cmdBuffers[currentFrame], 1, &viewport);
palCmdSetScissors(cmdBuffers[currentFrame], 1, &scissor);
uint64_t offset[] = {0};
palCmdBindVertexBuffers(cmdBuffers[currentFrame], 0, 1, &vertexBuffer, offset);
palCmdDraw(cmdBuffers[currentFrame], 6, 1, 0, 0);
palCmdEndRendering(cmdBuffers[currentFrame]);
// change the state of the image view to make it presentable
barrierInfo.oldState = PAL_USAGE_STATE_COLOR_ATTACHMENT_WRITE;
barrierInfo.srcStages = PAL_PIPELINE_STAGE_COLOR_ATTACHMENT;
barrierInfo.newState = PAL_USAGE_STATE_PRESENT;
barrierInfo.dstStages = PAL_PIPELINE_STAGE_NONE;
palCmdImageBarrier(cmdBuffers[currentFrame], image, &imageRange, &barrierInfo);
result = palCmdEnd(cmdBuffers[currentFrame]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to end command buffer");
return PAL_FALSE;
}
// submit command buffer
PalCommandBufferSubmitInfo submitInfo = {0};
submitInfo.cmdBuffer = cmdBuffers[currentFrame];
submitInfo.fence = inFlightFences[currentFrame];
submitInfo.waitSemaphore = imageAvailableSemaphores[currentFrame];
submitInfo.signalSemaphore = renderFinishedSemaphores[imageIndex];
submitInfo.waitStages = PAL_PIPELINE_STAGE_COLOR_ATTACHMENT;
result = palSubmitCommandBuffer(queue, &submitInfo);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to submit command buffer");
return PAL_FALSE;
}
// present
result = palPresentSwapchain(swapchain, imageIndex, renderFinishedSemaphores[imageIndex]);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to present swapchain");
return PAL_FALSE;
}
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
result = palWaitQueue(queue);
if (result != PAL_RESULT_SUCCESS) {
logResult(result, "Failed to wait queue");
return PAL_FALSE;
}
palDestroyPipeline(pipeline);