-
Notifications
You must be signed in to change notification settings - Fork 0
/
SturdyEngine.h
2266 lines (1987 loc) · 95.6 KB
/
SturdyEngine.h
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
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <algorithm>
#include <vector>
#include <cstring>
#include <string>
#include <cstdlib>
#include <cstdint>
#include <optional>
#include <set>
#include <chrono>
#include <memory> //does java like gc for us... todo: use this in games
#include <thread>
#include "cpuinfo/cpuinfo.h"
#include <glm/ext/matrix_clip_space.hpp>
#include <OpenXR/openxr.h> //TODO: actually use this
#include <glm/glm.hpp>
constexpr auto procInfoMode = 1;
/*
TODO list:
- OpenXR Vulkan Pipelines
- Dynamic Shader Support
- Shader Buffers
- Multi-window Support
- Camera API
- Default Shaders(2D/3D, RTX, Mesh Shader, VR)
- Basic effect shaders
- Render Pipeline Hotswap(Swap between 2d, 3d, and all supported pipelines in the update function
- APIs for gamepad, keyboard, and mouse support(GLFW Abstraction)
- Shader-accessible uniforms for depth buffer and screen-space + worldspace movement vectors per pixel
- get legal documents for engine
- add engine-wide support for compute shaders
- add engine-wide support for hdr10
- basic button api
- Code Generators for scenes to improve load times
- Focus listeners(window defocus and focus)
*/
using vec2 = glm::vec2;
using vec3 = glm::vec3;
namespace SFT {
namespace Scene {
namespace Camera {
class Camera2D {
public:
private:
vec2 pos;
glm::mat4x4 projectionMatrix;
};
class Camera3D {
public:
void setPosition(vec3 position) {
this->pos = position;
}
template<typename T>
void setPosition(T x, T y, T z) {
this->pos = vec3(x, y, z);
}
void setRotationDeg(vec3 rotation) {
this->rot = vec3(glm::radians(rotation.x), glm::radians(rotation.y), glm::radians(rotation.z));
}
void setRotationRad(vec3 rotation) {
this->rot = rotation;
}
template<typename T>
void setRotationDeg(T x, T y, T z) {
this->rot = vec3(glm::radians(x), glm::radians(y), glm::radians(z));
}
template<typename T>
void setRotationRad(T x, T y, T z) {
this->rot = vec3(x, y, z);
}
vec3 getRotationRad() {
return this->rot;
}
vec3 getRotationDeg() {
return vec3(glm::degrees(this->rot.x), glm::degrees(this->rot.y), glm::degrees(this->rot.z));
}
vec3 getPosition() {
return this->pos;
}
enum ProjectionMatrixes {
Perspective, Orthographic
};
//this overload is a very good way to break shit, using the other one is recommended, this is only here to allow for some very advanced tricks, and for inheritance
void setProjectionMatrix(glm::mat4x4 matrix) {
this->projectionMatrix = matrix;
}
private:
vec3 pos;
vec3 rot;
glm::mat4x4 projectionMatrix;
};
//NOTE: the perspective camera's far poroperty will be null if it is set to be infinite, for most 3D programs this is your go to camera type
class PerspectiveCamera3D : Camera3D {
public:
double fov, aspect, near, far;
void setProjectionParameters(double fov = 45.0, double aspect = 16.0 / 9.0, double near = 0.000000002, double far = 1000000.0) {
this->setProjectionMatrix(glm::perspective(glm::radians(fov), aspect, near, far));
setMainProperties(fov, aspect, near);
this->far = far;
}
//sets the perspective camera to only have a near clipping plane, and will not ever cull what is infront of it ever
void setProjectionParametersINF(double fov = 45.0, double aspect = 16.0 / 9.0, double near = 0.000000002) {
this->setProjectionMatrix(glm::infinitePerspective(glm::radians(fov), aspect, near));
setMainProperties(fov, aspect, near);
this->far = NULL;
}
private:
void setMainProperties(double fov, double aspect, double near) {
this->fov = fov;
this->aspect = aspect;
this->near = near;
}
};
//NOTE: near and far will be set to null in the case of an infinite ortho camera
class OrthographicCamera : Camera3D {
public:
double left, right, bottom, top, near, far;
void setProjectionParameters(double left, double right, double bottom, double top, double near, double far) {
this->setProjectionMatrix(glm::ortho(left, right, bottom, top, near, far));
this->setMainProperties(left, right, bottom, top, near, far);
}
void setProjectionParametersINF(double left, double right, double bottom, double top) {
this->setProjectionMatrix(glm::ortho(left, right, bottom, top));
this->setMainProperties(left, right, bottom, top);
}
private:
void setMainProperties(double left, double right, double bottom, double top, double near = NULL, double far = NULL) {
this->left = left;
this->right = right;
this->bottom = bottom;
this->top = top;
this->near = near;
this->far = far;
}
};
}
struct Vertex {
glm::vec2 pos;
glm::vec3 color;
static VkVertexInputBindingDescription getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
static std::array<VkVertexInputAttributeDescription, 2> getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 2> attributeDescriptions{};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
return attributeDescriptions;
}
};
class World2D {
private:
glm::mat3x3 transformationMatrix;
};
class World3D {
private:
glm::mat4x4 transformationMatrix;
};
struct Mesh {
public:
std::vector<Vertex> verticies;
std::vector<int> indicies;
};
class Scene {
public:
std::vector<Vertex> getVerts() {
return verts;
}
//I have hidden access to the raw scene description to make it possible to keep tabs on when the vertex buffer needs updating
void addVert(Vertex v) {
this->verts.push_back(v);
this->updateGPUBuffer = true;
}
void setVerts(std::vector<Vertex> v) {
this->verts = v;
this->updateGPUBuffer = true;
}
void removeUpdateFlag() {
this->updateGPUBuffer = false;
}
void setVertexBuffer(VkBuffer& buffer) {
this->vertexBuffer = buffer;
this->vertexBufferSet = true;
}
VkBuffer& getVertexBuffer() {
return this->vertexBuffer;
}
VkBuffer& getIndexBuffer() {
return this->indexBuffer;
}
void destroyVertexBuffer(VkDevice& device) {
if (this->vertexBufferSet == true) {
vkDestroyBuffer(device, this->indexBuffer, nullptr);
vkFreeMemory(device, this->indexBufferMemory, nullptr);
vkFreeMemory(device, this->vertexBufferMemory, nullptr);
vkDestroyBuffer(device, this->vertexBuffer, nullptr);
this->vertexBufferSet = false;
}
}
void setVertexBufferMemory(VkDeviceMemory& memory) {
this->vertexBufferMemory = memory;
this->vertexBufferSet = true;
}
void setDevice(VkDevice& device) {
this->device = device;
}
~Scene() {
destroyVertexBuffer(this->device);
}
void addMesh(Mesh& m) {
this->meshes.push_back(m); //you might want to make sure this object has lifetime, since the engine relies on it
}
void generateLists() {
this->verts.clear();
this->indicies.clear();
uint32_t totalVerts = 0;
uint32_t totalInd = 0;
for (auto i : meshes) {
totalVerts += i.verticies.size();
totalInd += i.indicies.size();
}
uint32_t totalDone[2] = { 0, 0 };
this->verts.resize(totalVerts);
this->indicies.resize(totalInd);
for (auto i : meshes) {
int indOffset = totalDone[1];
for (auto j : i.verticies) {
this->verts[totalDone[0]] = j;
totalDone[0] += 1;
}
for (auto j : i.indicies) {
uint32_t newInd = j + indOffset;
this->indicies[totalDone[1]] = newInd;
totalDone[1] += 1;
}
}
}
std::vector<uint32_t> getIndicies() {
return this->indicies;
}
void setIndexBuffer(VkBuffer& buffer) {
this->indexBuffer = buffer;
}
void setIndexBufferMemory(VkDeviceMemory& mem) {
this->indexBufferMemory = mem;
}
private:
std::vector<Mesh> meshes = { {
{
{{-0.5f, -0.5f}, {1.0f, 0.0f, 0.0f}},
{{0.5f, -0.5f}, {0.0f, 1.0f, 0.0f}},
{{0.5f, 0.5f}, {0.0f, 0.0f, 1.0f}},
{{-0.5f, 0.5f}, {1.0f, 1.0f, 1.0f}}
},
{
0, 1, 2, 2, 3, 0
}
} };
std::vector<Vertex> verts;
std::vector<uint32_t> indicies;
//todo: update this and make it so that we only need an update when changes are made here
bool updateGPUBuffer = false;
bool vertexBufferSet = false;
VkBuffer vertexBuffer;
VkDeviceMemory vertexBufferMemory;
VkBuffer indexBuffer;
VkDeviceMemory indexBufferMemory;
VkDevice device;
};
}
namespace Input {
namespace Keyboard {
enum Modifiers {
SHIFT, CTRL, ALT, CAPSLOCK, NUMLOCK, SUPER
};
};
namespace Mouse {
enum Modes {
NORMAL, HIDDEN, POINTERLOCKED
};
class Button {
public:
//this is just here ot allow you ot tell when a button event has been handled, useful for button apis
bool wasHandled;
vec2 position;
int button;
int lastAction;
bool pressed;
Button(int b = NULL, vec2 pos = vec2(0.0), bool handled = true, int lastAction = GLFW_RELEASE) {
this->wasHandled = handled;
this->button = b;
this->position = pos;
this->lastAction = lastAction;
this->pressed = false;
}
void setVars(vec2 pos, bool handled, int lastAction) {
this->position = pos;
this->wasHandled = handled;
this->lastAction = lastAction;
if (lastAction == GLFW_PRESS) {
this->pressed = true;
}
else {
this->pressed = false;
}
}
};
};
struct KeyboardInput {
bool modifiers[6];
bool keys[GLFW_KEY_LAST];
KeyboardInput() {
for (size_t i = 0; i < GLFW_KEY_LAST; ++i) {
this->keys[i] = false;
}
for (size_t i = 0; i < 6; ++i) {
this->modifiers[i] = false;
}
}
//wordy as hell, but works dynamically, cannot complain
void setMods(int mods) {
this->modifiers[Keyboard::Modifiers::SHIFT] = (mods & GLFW_MOD_SHIFT) != 0x0000;
this->modifiers[Keyboard::Modifiers::ALT] = (mods & GLFW_MOD_ALT) != 0x0000;
this->modifiers[Keyboard::Modifiers::CTRL] = (mods & GLFW_MOD_CONTROL) != 0x0000;
this->modifiers[Keyboard::Modifiers::SUPER] = (mods & GLFW_MOD_SUPER) != 0x0000;
this->modifiers[Keyboard::Modifiers::CAPSLOCK] = (mods & GLFW_MOD_CAPS_LOCK) != 0x0000;
this->modifiers[Keyboard::Modifiers::NUMLOCK] = (mods & GLFW_MOD_NUM_LOCK) != 0x0000;
}
};
using mouseButton = SFT::Input::Mouse::Button;
class MouseInput {
public:
MouseInput() {
for (size_t i = 0; i < GLFW_MOUSE_BUTTON_LAST; ++i) {
this->buttons[i] = Mouse::Button(i, vec2(0.0), true, GLFW_RELEASE);
}
this->mousePos = vec2(0.0);
}
mouseButton buttons[7];
vec2 mousePos;
};
namespace Gamepad {
};
};
const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;
const int MAX_FRAMES_IN_FLIGHT = 2;
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
namespace RequiredExtensions {
namespace DeviceExtensions {
const std::vector<const char*> Rasterized = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
const std::vector<const char*> Raytraced = {
VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME,
VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME,
VK_KHR_MAINTENANCE3_EXTENSION_NAME,
VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME,
VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME,
VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME,
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
};
namespace InstanceExtensions {
const std::vector<const char*> standard = {
};
}
};
#ifndef enableValidationLayers
const bool enableValidationLayers = false;
#endif
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pDebugMessenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
return func(instance, pCreateInfo, pAllocator, pDebugMessenger);
}
else {
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT debugMessenger, const VkAllocationCallbacks* pAllocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, debugMessenger, pAllocator);
}
}
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
struct SwapChainSupportDetails {
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
using string = std::string;
bool firstLoop = true;
enum class renderTypes {
Rasterized, Raytraced, MeshShaded, VRRasterized, VRMesh, VRRaytraced
};
class ColorDepthDescriptor {
public:
int r, g, b;
ColorDepthDescriptor(int r, int g, int b) {
this->r = r;
this->g = g;
this->b = b;
}
void logInfo() {
std::cout << "\t\t\tRGB: " << r << ", " << g << ", " << b << std::endl;
}
};
class VideoModeOrganizer {
public:
int width;
int height;
std::vector<ColorDepthDescriptor> colorDepths;
std::vector<int> framerates;
std::vector<VideoModeOrganizer> exclusions;
VideoModeOrganizer(int w = 0, int h = 0, std::vector<ColorDepthDescriptor> colorDepthList = {}, std::vector<int> framerates = {}, std::vector<VideoModeOrganizer> exclusions = {}) {
this->width = w;
this->height = h;
this->colorDepths = colorDepthList;
this->framerates = framerates;
this->exclusions = exclusions; // this is a list of incompatible formats, such as if such a framerate cannot be achieved, I have no idea if this will ever be used though
}
void addFramerateMode(int framerate) {
this->framerates.push_back(framerate);
}
void addColorDepthMode(ColorDepthDescriptor desc) {
this->colorDepths.push_back(desc);
}
void addExclusion(VideoModeOrganizer exclusion) {
this->exclusions.push_back(exclusion);
}
bool hasMode(ColorDepthDescriptor desc, int framerate) {
bool found = false;
for (auto i : colorDepths) {
for (auto j : framerates) {
if (i.r == desc.r && (i.g == desc.g && (i.b == desc.b && (j == framerate)))) {
found = true;
break;
}
}
if (found) break;
}
return found;
}
bool hasColorDepth(ColorDepthDescriptor desc) {
bool found = false;
for (auto i : colorDepths) {
if (i.r == desc.r && (i.g == desc.g && (i.b == desc.b))) {
found = true;
break;
}
}
return found;
}
bool hasFramerate(int framerate) {
bool found = false;
for (auto i : framerates) {
if (i == framerate) {
found = true;
break;
}
}
return found;
}
void logInfo(std::ostream outputLocation) {
outputLocation << "\tMode {" << std::endl;
outputLocation << "\t\tResolution: " << this->width << "X" << this->height << std::endl;
outputLocation << "\t\tColorDepths: {" << std::endl;
for (auto i : this->colorDepths) {
outputLocation << "\t\t\tRGB: " << i.r << ", " << i.g << ", " << i.b << std::endl;
}
outputLocation << "\t\t}" << std::endl;
outputLocation << "\t\tFramerates: {" << std::endl;
for (auto i : framerates) {
std::cout << "\t\t\t" << i << std::endl;
}
outputLocation << "\t\t}" << std::endl;
outputLocation << "\t}" << std::endl;
}
void logInfo() {
std::cout << "\tMode {" << std::endl;
std::cout << "\t\tResolution: " << this->width << "X" << this->height << std::endl;
std::cout << "\t\tColorDepths: {" << std::endl;
for (auto i : this->colorDepths) {
i.logInfo();
}
std::cout << "\t\t}" << std::endl;
std::cout << "\t\tFramerates: {" << std::endl;
for (auto i : framerates) {
std::cout << "\t\t\t" << i << std::endl;
}
std::cout << "\t\t}" << std::endl;
std::cout << "\t}" << std::endl;
}
};
class MonitorDescriptor {
public:
glm::vec4 bounds;
GLFWmonitor* obj;
const char* name;
std::vector<VideoModeOrganizer> vidOrganizers;
MonitorDescriptor(glm::vec4 bounds, GLFWmonitor* mon) {
this->bounds = bounds;
this->obj = mon;
const char* n = glfwGetMonitorName(mon);
getVideoModes(mon);
this->name = n;
}
VideoModeOrganizer getVideoModeOrganizer(int resolutionWidth, int resolutionHeight) {
VideoModeOrganizer toRet = NULL;
for (auto or : vidOrganizers) {
if (resolutionWidth == or.width && (resolutionHeight == or.height)) {
toRet = or ;
}
}
return toRet;
}
void setVideoModeOrganizer(VideoModeOrganizer organizer) {
for (int i = 0; i < vidOrganizers.size(); ++i) {
VideoModeOrganizer or = vidOrganizers[i];
if (organizer.width == or.width && (organizer.height == or.height)) {
vidOrganizers[i] = organizer;
}
}
}
void getVideoModes(GLFWmonitor* mon) {
int modeCount;
const GLFWvidmode* videoModes = glfwGetVideoModes(mon, &modeCount);
for (int i = 0; i < modeCount; ++i) {
GLFWvidmode mode = videoModes[i];
if (mode.width == 0 || (mode.height == 0 || (mode.redBits == 0 || (mode.greenBits == 0 || (mode.blueBits == 0 || (mode.refreshRate == 0)))))) continue;
bool found = false;
for (auto t : vidOrganizers) {
if (mode.width == t.width && (mode.height == t.height)) {
found = true;
break;
}
}
VideoModeOrganizer organizer = getVideoModeOrganizer(mode.width, mode.height);
if (!found) {
organizer = VideoModeOrganizer(mode.width, mode.height);
vidOrganizers.push_back(organizer);
}
ColorDepthDescriptor d = ColorDepthDescriptor(mode.redBits, mode.greenBits, mode.blueBits);
if (organizer.hasColorDepth(d) == false) {
organizer.addColorDepthMode(d);
}
if (organizer.hasFramerate(mode.refreshRate) == false) {
organizer.addFramerateMode(mode.refreshRate);
}
setVideoModeOrganizer(organizer);
}
}
void logInfo(std::ostream outputLocation) {
outputLocation << "Display Name: " << this->name << ", bounds: [" << bounds.x << ", " << bounds.y << ", " << bounds.z << ", " << bounds.w << "], Modes: {" << std::endl;
for (auto m : this->vidOrganizers) {
outputLocation << "\tMode {" << std::endl;
outputLocation << "\t\tResolution: " << m.width << "X" << m.height << std::endl;
outputLocation << "\t\tColorDepths: {" << std::endl;
for (auto i : m.colorDepths) {
outputLocation << "\t\t\tRGB: " << i.r << ", " << i.g << ", " << i.b << std::endl;
}
outputLocation << "\t\t}" << std::endl;
outputLocation << "\t\tFramerates: {" << std::endl;
for (auto i : m.framerates) {
outputLocation << "\t\t\t" << i << std::endl;
}
outputLocation << "\t\t}" << std::endl;
outputLocation << "\t}" << std::endl;
}
outputLocation << "}" << std::endl;
}
void logInfo() {
std::cout << "Display Name: " << this->name << ", bounds: [" << bounds.x << ", " << bounds.y << ", " << bounds.z << ", " << bounds.w << "], Modes: {" << std::endl;
for (auto m : this->vidOrganizers) {
m.logInfo();
}
std::cout << "}" << std::endl;
}
bool isPointInMonitor(glm::vec2 pos) {
int x2 = bounds.x + bounds.z;
int y2 = bounds.y + bounds.w;
if (pos.x >= bounds.x && (pos.y >= bounds.y && (pos.x <= x2 && (pos.y <= y2)))) {
return true;
}
return false;
}
MonitorDescriptor() {
this->bounds = glm::vec4(0);
this->obj = NULL;
}
};
class SturdyEngine {
public:
CPUInfo::CPU processor;
void run() {
bool rtCapable = false;
initWindow();
this->setup();
switch (renderer) {
case renderTypes::Rasterized:
initVulkanRasterized();
break;
case renderTypes::Raytraced:
renderer = renderTypes::Raytraced;
initVulkanRaytraced();
break;
}
mainLoop(); //Raytracing causes nullpointer exceptions with these two, TODO: either segment or error-proof
cleanup();
}
void draw() {
//call this function to actually draw a frame, this will be put on the developer to decide when this is called in update()
drawFrame();
}
void setRenderer(renderTypes type) {
this->renderer = type;
}
double getFrameRate() {
return this->frameRate;
}
double getFrameTime() {
return this->frameTime;
}
VkDevice getDevice() {
return this->device;
}
VkPhysicalDevice getGPU() {
return this->physicalDevice;
}
VkPhysicalDeviceProperties getGPUProperties(VkPhysicalDevice& dev) {
VkPhysicalDeviceProperties p;
vkGetPhysicalDeviceProperties(dev, &p);
return p;
}
VkPhysicalDeviceLimits getGPULimits(VkPhysicalDevice& dev) {
VkPhysicalDeviceProperties prop = getGPUProperties(dev);
VkPhysicalDeviceLimits limits = prop.limits;
return limits;
}
//returns true if the physical device supports raytracing
bool doesGPUSupportRT(VkPhysicalDevice& d) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(d, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(d, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(RequiredExtensions::DeviceExtensions::Raytraced.begin(), RequiredExtensions::DeviceExtensions::Raytraced.end());
for (const auto& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
//requests focus if your OS supports it, if used in setup it queues the request up for after the window is created
void requestFocus(GLFWwindow* window) {
if (windowExists) {
glfwRequestWindowAttention(window);
return;
}
if (window == this->window) {
this->windowShouldRequestFocus = true;
}
}
//requests focus if your OS supports it, if used in setup it queues the request up for after the window is created.
void requestFocus() {
if (windowExists) {
glfwRequestWindowAttention(window);
return;
}
this->windowShouldRequestFocus = true;
}
virtual void setup() {
//runs once per instance, use to load files and other setup tasks, the vulkan pipeline has yet to be initialized so you can decide which renderer and which extensions you want to use
}
virtual void update() {
//runs continuously until the window closes... be careful of logging if you're at high framerates, call draw() to make the frame update
}
virtual void clean() {
//runs on cleanup, and is the first thing to happen, so vulkan will be completely intact at the time of this call
}
//begin event handlers
int getSuggestedMaxThreadCount() {
return std::thread::hardware_concurrency();
}
//handles all key events raw
virtual void onKey(int key, int scancode, int action, int mods) {
}
//handles text input as expected of a good text box
virtual void onChar(char key) {
}
virtual void onMouseMove(vec2 pos) {
}
//calls back every time there is a change of state of a mouse button
virtual void onClick(Input::Mouse::Button button) {
}
virtual void onWindowResize(GLFWwindow* window, int width, int height) {
}
virtual void onScroll(int xDel, int yDel) {
}
GLFWwindow* getWindow() {
return window;
}
//call in setup, dynamic enable of extensions is not supported, what you have enabled to start is what you have to work with!
void addDeviceExtension(const char* ext) {
requiredDeviceExtensions.push_back(ext);
}
//call in setup, dynamic enable of extensions is not supported, what you have enabled to start is what you have to work with!
void addDeviceExtension(std::vector<const char*> exts) {
for (auto ext : exts) {
requiredDeviceExtensions.push_back(ext);
}
}
void addInstanceExtension(const char* ext) {
requiredInstanceExtensions.push_back(ext);
}
void addInstanceExtension(std::vector<const char*> exts) {
for (auto ext : exts) {
requiredInstanceExtensions.push_back(ext);
}
}
//use this in update or you might have a bad time,
void setCursorMode(std::optional<GLFWwindow*> window, int mode) {
if (windowExists) {
switch (mode) {
case Input::Mouse::POINTERLOCKED:
glfwSetInputMode(*window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
break;
case Input::Mouse::HIDDEN:
glfwSetInputMode(*window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
break;
case Input::Mouse::NORMAL:
glfwSetInputMode(*window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
break;
}
}
else {
//this is what happens during setup()
this->startingCursorMode = mode;
return;
}
}
void setWindowTitle(const char* title) {
this->windowTitle = title;
std::optional<GLFWwindow*> w = this->window;
if (!customWindowName) {
customWindowName = true;
}
if (w) {
glfwSetWindowTitle(*w, this->windowTitle);
}
}
//exists for the explicit purpose of figuring out whether or not the window is fullscreen, more like a double check internally but is useful for developers to test for fullscreen
bool isWindowFullscren() {
return (glfwGetWindowMonitor(this->getWindow()) != NULL);
}
//returns monitor id for a vec2, returns 0 if out of bounds
int getMonitorID(vec2 pos) {
int id = 0;
for (size_t i = 0; i < monitors.size(); ++i) {
vec2 pos2{ pos.x, pos.y };
MonitorDescriptor monitor = monitors[i];
if (monitor.isPointInMonitor(pos2)) {
id = i;
break;
}
}
return id;
}
MonitorDescriptor getMonitorByPoint(vec2 pos) {
int id = 0;
for (size_t i = 0; i < monitors.size(); ++i) {
if (pos.x == NULL || pos.y == NULL) {
break;
}
vec2 posi = vec2(pos.x, pos.y);
MonitorDescriptor monitor = monitors[i];
if (monitor.isPointInMonitor(posi)) {
id = i;
break;
}
}
return monitors[id];
}
void setFullscreen(bool tf, int monitor = NULL) {
if (fullscreen == tf || (isWindowFullscren() == tf)) {
return;
}
fullscreen = tf;
if (tf == true) {
int x, y;
glfwGetWindowPos(getWindow(), &x, &y);
int id = 0;
for (size_t i = 0; i < monitors.size(); ++i) {
vec2 pos = vec2(x, y);
MonitorDescriptor monitor = monitors[i];
if (monitor.isPointInMonitor(pos)) {
id = i;
break;
}
}
glfwSetWindowMonitor(this->getWindow(), monitors[id].obj, monitors[id].bounds.x, monitors[id].bounds.y, monitors[id].bounds.z, monitors[id].bounds.w, getMonitorMaxRefreshRate(monitors[id].obj));
}
else {
GLFWmonitor* mon = glfwGetWindowMonitor(window);
if (mon == NULL) {
return; // is just here in case someone decides to use glfw directly in-engine, this will prevent crashes
}
int x, y, width, height;
glfwGetMonitorWorkarea(mon, &x, &y, &width, &height);
glfwSetWindowMonitor(this->getWindow(), nullptr, x + ((double)width / 2.0 - (windowedSize.x / 2.0)), y + ((double)height / 2.0 - (windowedSize.y / 2.0)), windowedSize.x, windowedSize.y, GLFW_DONT_CARE);
}
}
vec2 getWindowedSize() {
return windowedSize;
}
int getMonitorMaxRefreshRate(GLFWmonitor* mon) {
const GLFWvidmode* currentMode = glfwGetVideoMode(mon);
return currentMode->refreshRate;
}
void setWindowPosition(vec2 pos) {
glfwSetWindowPos(this->getWindow(), pos.x, pos.y);
}
vec2 getWindowPosition() {
int x, y;
glfwGetWindowPos(this->getWindow(), &x, &y);
vec2 pos(x, y);
return pos;
}
void setWindowDecorated(bool enable) {
if (enable == true) {
glfwWindowHint(GLFW_DECORATED, GLFW_TRUE);
}
else {
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
}
}
int getCurrentWindowMonitorID() {
int x, y;
glfwGetWindowPos(getWindow(), &x, &y);
int id = 0;
for (size_t i = 0; i < monitors.size(); ++i) {
vec2 pos = vec2(x, y);
MonitorDescriptor monitor = monitors[i];
if (monitor.isPointInMonitor(pos)) {
id = i;
break;
}
}
return id;
}
bool checkHDR10Support() {
const GLFWvidmode* currentMode = glfwGetVideoMode(monitors[getCurrentWindowMonitorID()].obj);
if (currentMode->blueBits > 8 && currentMode->redBits > 8 && currentMode->greenBits > 8) {
return true;
}
return false;
}
void setHDR10Support(bool enable) {
if (enable == true && checkHDR10Support()) {
glfwWindowHint(GL_RED_BITS, 10);
glfwWindowHint(GL_GREEN_BITS, 10);
glfwWindowHint(GL_BLUE_BITS, 10);
glfwWindowHint(GL_ALPHA_BITS, 2);
}
else {
if (enable == true) {
std::cout << "SturdyEngine could not enable HDR, either your monitor is not setup for HDR, or it is not supported at all." << std::endl;
}
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
glfwWindowHint(GL_ALPHA_BITS, 2);
}
}
int getDeviceMemoryCapacityMB(VkPhysicalDevice device) {
VkPhysicalDeviceMemoryProperties memProps;
vkGetPhysicalDeviceMemoryProperties(device, &memProps);
auto heapsPointer = memProps.memoryHeaps;
auto heaps = std::vector<VkMemoryHeap>(heapsPointer, heapsPointer + memProps.memoryHeapCount);
double totalSize = heaps[0].size / 1000000.0;
return round(totalSize);
}
renderTypes renderer;
Input::KeyboardInput keyboard;
Input::MouseInput mouse;
Scene::Scene getScene() {
return this->scene;
}
//Anything below this point is heavy on API calls and is recommended for seasoned engine devs only, you have been warned, any and all modifications to this file do not void the license terms, as I do need to make money
private:
GLFWwindow* window;
vec2 windowedSize;
bool fullscreen;
std::vector<VkBuffer> buffers;
VkInstance instance;
VkDebugUtilsMessengerEXT debugMessenger;
VkSurfaceKHR surface;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSwapchainKHR swapChain;
std::vector<VkImage> swapChainImages;
VkFormat swapChainImageFormat;
VkExtent2D swapChainExtent;
std::vector<VkImageView> swapChainImageViews;
std::vector<VkFramebuffer> swapChainFramebuffers;
VkRenderPass renderPass;
VkPipelineLayout pipelineLayout;
VkPipeline graphicsPipeline;
VkCommandPool commandPool;
std::vector<VkCommandBuffer> commandBuffers;
int startingCursorMode = Input::Mouse::NORMAL;
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
double frameRate = 0;
bool framebufferResized = false;
std::vector<VkFence> imagesInFlight;
size_t currentFrame = 0;
double frame = 0;
std::chrono::steady_clock::time_point lastTimeLogged = std::chrono::high_resolution_clock::now();
double frameTime = 0;
const char* windowTitle = "SturdyEngine";
bool windowExists = false;
bool customWindowName = false;