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
|
#include "game.hpp"
#include "camera.hpp"
#include "components.hpp"
#include "dynamic-array.hpp"
#include "entities.hpp"
#include "game-settings.hpp"
#include "helpers.hpp"
#include "imgui.h"
#include "math-helpers.hpp"
#include "physics.hpp"
#include "player-input.hpp"
#include "plugins.hpp"
#include "vendor/glm_include.hpp"
#include "window.hpp"
#include <BulletCollision/CollisionShapes/btConvexHullShape.h>
#include <BulletCollision/NarrowPhaseCollision/btRaycastCallback.h>
#include <GLFW/glfw3.h>
#include <cstring>
#include <iomanip>
#include <ostream>
#include <thread>
const long readLineLength = 128;
char readLine[readLineLength];
const char *levelName = "demo-level";
const char *PKE_FILE_BEGIN = ":PKFB:";
const char *PKE_FILE_END = ":PKFE:";
const char *PKE_FILE_VERSION = ":0:";
const char *PKE_FILE_OBJ_END = "";
const char *PKE_FILE_OBJ_ENTITY_TYPE = "EntityType:";
const char *PKE_FILE_OBJ_INSTANCE = "Instance:";
const char *PKE_FILE_ENTITY_TYPE_MODELS_DIR = "ModelsDir: ";
const char *PKE_FILE_ENTITY_TYPE_MODEL_FILE = "ModelFile: ";
const char *PKE_FILE_ENTITY_TYPE_ENTITY_TYPE_CODE = "EntityTypeCode: ";
const char *PKE_FILE_ENTITY_TYPE_ENTITY_HANDLE = "EntityHandle: ";
const char *PKE_FILE_ENTITY_TYPE_STARTING_INSTANCE_COUNT = "StartingInstanceCount: ";
const char *PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_VERTEX = "Importer_GLTF::AccessorIndexVertex: ";
const char *PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_NORMAL = "Importer_GLTF::AccessorIndexNormal: ";
const char *PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_UV = "Importer_GLTF::AccessorIndexUV: ";
const char *PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_INDEX = "Importer_GLTF::AccessorIndexIndex: ";
const char *PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_MASS = "BT::StartingMass: ";
const char *PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_LAYER = "BT::StartingCollisionLayer: ";
const char *PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_MASK = "BT::StartingCollisionMask: ";
const char *PKE_FILE_INSTANCE_ENTITY_HANDLE = "EntityHandle: ";
const char *PKE_FILE_INSTANCE_ENTITY_TYPE_CODE = "EntityTypeCode: ";
const char *PKE_FILE_INSTANCE_POS_POS = "InstPos::Pos: ";
const char *PKE_FILE_INSTANCE_POS_ROT = "InstPos::Rot: ";
const char *PKE_FILE_INSTANCE_POS_SCALE = "InstPos::Scale: ";
const char *PKE_FILE_INSTANCE_PHYSICS_MASS = "InstPos::Mass: ";
const char *PKE_FILE_INSTANCE_PHYSICS_COLLISION_LAYER = "InstPos::CollisionLayer: ";
const char *PKE_FILE_INSTANCE_PHYSICS_COLLISION_MASK = "InstPos::CollisionMask: ";
void SerializeEntityType(std::ofstream &stream, const EntityType &et) {
char handleStr[19] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
snprintf(handleStr, 19, "0x%016lX",static_cast<EntityHandle_T>(et.entityHandle));
EntityType e{};
if (et.modelsDir != e.modelsDir)
stream << PKE_FILE_ENTITY_TYPE_MODELS_DIR << et.modelsDir << std::endl;
if (et.modelFile != e.modelFile)
stream << PKE_FILE_ENTITY_TYPE_MODEL_FILE << et.modelFile << std::endl;
if (et.entityTypeCode != e.entityTypeCode)
stream << PKE_FILE_ENTITY_TYPE_ENTITY_TYPE_CODE << et.entityTypeCode << std::endl;
if (et.entityHandle != e.entityHandle)
stream << PKE_FILE_ENTITY_TYPE_ENTITY_HANDLE << handleStr << std::endl;
if (et.startingInstanceCount != e.startingInstanceCount)
stream << PKE_FILE_ENTITY_TYPE_STARTING_INSTANCE_COUNT << et.startingInstanceCount << std::endl;
if (et.Importer_GLTF.AccessorIndexVertex != e.Importer_GLTF.AccessorIndexVertex)
stream << PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_VERTEX << et.Importer_GLTF.AccessorIndexVertex << std::endl;
if (et.Importer_GLTF.AccessorIndexNormal != e.Importer_GLTF.AccessorIndexNormal)
stream << PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_NORMAL << et.Importer_GLTF.AccessorIndexNormal << std::endl;
if (et.Importer_GLTF.AccessorIndexUV != e.Importer_GLTF.AccessorIndexUV)
stream << PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_UV << et.Importer_GLTF.AccessorIndexUV << std::endl;
if (et.Importer_GLTF.AccessorIndexIndex != e.Importer_GLTF.AccessorIndexIndex)
stream << PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_INDEX << et.Importer_GLTF.AccessorIndexIndex << std::endl;
if (et.bt.startingMass != e.bt.startingMass)
stream << PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_MASS << et.bt.startingMass << std::endl;
if (et.bt.startingCollisionLayer != e.bt.startingCollisionLayer)
stream << PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_LAYER << static_cast<PhysicsCollision_T>(et.bt.startingCollisionLayer) << std::endl;
if (et.bt.startingCollisionMask != e.bt.startingCollisionMask)
stream << PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_MASK << static_cast<PhysicsCollision_T>(et.bt.startingCollisionMask) << std::endl;
}
void SerializeInstance(std::ofstream &stream, const CompInstance &comp) {
char handleStr[19] = { '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0' };
snprintf(handleStr, 19, "0x%016lX",static_cast<EntityHandle_T>(comp.entHandle));
EntityType *et = nullptr;
for (long i = 0; i < GlobalEntityTypes.Count(); ++i) {
if (GlobalEntityTypes[i].grBindsHandle == comp.grBindsHandle) {
et = &GlobalEntityTypes[i];
break;
}
}
assert(et != nullptr);
CompInstance c{};
InstPos baseInst{};
baseInst.posRot = btTransform{};
baseInst.posRot.setIdentity();
baseInst.scale = btVector3(1, 1, 1);
baseInst.mass = 1;
if (comp.entHandle != c.entHandle)
stream << PKE_FILE_INSTANCE_ENTITY_HANDLE << handleStr << std::endl;
stream << PKE_FILE_INSTANCE_ENTITY_TYPE_CODE << et->entityTypeCode << std::endl;
btTransform trans;
comp.bt.motionState->getWorldTransform(trans);
btVector3 scale = comp.bt.rigidBody->getCollisionShape()->getLocalScaling();
btScalar mass = comp.bt.rigidBody->getMass();
PhysicsCollision collisionLayer{static_cast<PhysicsCollision_T>(comp.bt.rigidBody->getBroadphaseProxy()->m_collisionFilterGroup)};
PhysicsCollision collisionMask{static_cast<PhysicsCollision_T>(comp.bt.rigidBody->getBroadphaseProxy()->m_collisionFilterMask)};
if (trans != baseInst.posRot) {
btVector3 pos = trans.getOrigin();
btQuaternion rot = trans.getRotation();
stream << PKE_FILE_INSTANCE_POS_POS << "["
<< std::setw(10) << pos[0] << ","
<< std::setw(10) << pos[1] << ","
<< std::setw(10) << pos[2] << "]" << std::endl
<< PKE_FILE_INSTANCE_POS_ROT << "["
<< std::setw(10) << rot[0] << ","
<< std::setw(10) << rot[1] << ","
<< std::setw(10) << rot[2] << ","
<< std::setw(10) << rot[3] << "]" << std::endl;
}
if (scale != baseInst.scale)
stream << PKE_FILE_INSTANCE_POS_SCALE << "["
<< std::setw(10) << scale[0] << ","
<< std::setw(10) << scale[1] << ","
<< std::setw(10) << scale[2] << "]" << std::endl;
if (mass != baseInst.mass) {
stream << PKE_FILE_INSTANCE_PHYSICS_MASS << mass << std::endl;
}
if (collisionLayer != c.physicsLayer) {
stream << PKE_FILE_INSTANCE_PHYSICS_COLLISION_LAYER << static_cast<PhysicsCollision_T>(collisionLayer) << std::endl;
}
if (collisionMask != c.physicsMask) {
stream << PKE_FILE_INSTANCE_PHYSICS_COLLISION_MASK << static_cast<PhysicsCollision_T>(collisionMask) << std::endl;
}
}
void ParseEntityType(std::ifstream &stream) {
EntityType et{};
while (stream.getline(readLine, readLineLength)) {
if (strcmp(PKE_FILE_OBJ_END, readLine) == 0) {
int64_t existingEntityTypeIndex = EntityType_FindByTypeCode(et.entityTypeCode);
if (existingEntityTypeIndex != -1) {
continue;
}
et.entityHandle = ECS_CreateEntity();
EntityType_Load(et);
GlobalEntityTypes.Push(et);
return;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_MODELS_DIR)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_MODELS_DIR);
uint64_t len = strlen(readLine + prefixLen) + 1;
char *val = Pke_New<char>(len);
memset(reinterpret_cast<void *>(val), '\0', len);
memcpy(val, readLine + prefixLen, len);
et.modelsDir = val;
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_MODEL_FILE)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_MODEL_FILE);
uint64_t len = strlen(readLine + prefixLen) + 1;
char *val = Pke_New<char>(len);
memset(reinterpret_cast<void *>(val), '\0', len);
memcpy(val, readLine + prefixLen, len);
et.modelFile = val;
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_ENTITY_TYPE_CODE)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_ENTITY_TYPE_CODE);
uint64_t len = strlen(readLine + prefixLen) + 1;
char *val = Pke_New<char>(len);
memset(reinterpret_cast<void *>(val), '\0', len);
memcpy(val, readLine + prefixLen, len);
et.entityTypeCode = val;
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_ENTITY_HANDLE)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_ENTITY_HANDLE);
EntityHandle_T handle_t;
STR2NUM_ERROR result = str2num(handle_t, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
et.entityHandle = EntityHandle{handle_t};
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_STARTING_INSTANCE_COUNT)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_STARTING_INSTANCE_COUNT);
STR2NUM_ERROR result = str2num(et.startingInstanceCount, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_VERTEX)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_VERTEX);
STR2NUM_ERROR result = str2num(et.Importer_GLTF.AccessorIndexVertex, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_NORMAL)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_NORMAL);
STR2NUM_ERROR result = str2num(et.Importer_GLTF.AccessorIndexNormal, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_UV)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_UV);
STR2NUM_ERROR result = str2num(et.Importer_GLTF.AccessorIndexUV, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_INDEX)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_IMPORTER_GLTF_ACCESSOR_INDEX_INDEX);
STR2NUM_ERROR result = str2num(et.Importer_GLTF.AccessorIndexIndex, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_MASS)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_MASS);
STR2NUM_ERROR result = str2num(et.bt.startingMass, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_LAYER)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_LAYER);
PhysicsCollision_T val = static_cast<PhysicsCollision_T>(et.bt.startingCollisionLayer);
STR2NUM_ERROR result = str2num(val, readLine + prefixLen);
et.bt.startingCollisionLayer = PhysicsCollision{val};
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_MASK)) {
uint64_t prefixLen = strlen(PKE_FILE_ENTITY_TYPE_PHYSICS_STARTING_COLLISION_MASK);
PhysicsCollision_T val = static_cast<PhysicsCollision_T>(et.bt.startingCollisionMask);
STR2NUM_ERROR result = str2num(val, readLine + prefixLen);
et.bt.startingCollisionMask = PhysicsCollision{val};
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
}
}
void ParseInstance(std::ifstream &stream) {
CompInstance comp{};
InstPos instPos{};
instPos.posRot = btTransform{};
instPos.posRot.setIdentity();
instPos.scale = btVector3(1, 1, 1);
instPos.mass = 1.f;
char entTypeCode[21];
memset(reinterpret_cast<void *>(entTypeCode), '\0', 21);
while (stream.getline(readLine, readLineLength)) {
if (strstr(PKE_FILE_OBJ_END, readLine)) {
if (entTypeCode[0] == '\0') {
printf("[Game::ParseInstance] Failed to create instance from save file. No EntTypeCode present.\n");
break;
}
int64_t existingEntityTypeIndex = EntityType_FindByTypeCode(entTypeCode);
if (existingEntityTypeIndex == -1) {
printf("[Game::ParseInstance] Failed to create instance from save file. Unknown EntityTypeCode: \"%s\"", entTypeCode);
break;
}
const auto &et = GlobalEntityTypes[existingEntityTypeIndex];
auto entityHandle = ECS_CreateEntity();
auto &compInst = ECS_CreateInstance(entityHandle, et.entityHandle);
compInst.physicsLayer = comp.physicsLayer;
compInst.physicsMask = comp.physicsMask;
btVector3 localInertia(0, 0, 0);
et.bt.shape->calculateLocalInertia(instPos.mass, localInertia);
compInst.bt.motionState = Pke_New<btDefaultMotionState>(MemBkt_Bullet);
new (compInst.bt.motionState) btDefaultMotionState(instPos.posRot);
compInst.bt.rigidBody = Pke_New<btRigidBody>(MemBkt_Bullet);
new (compInst.bt.rigidBody) btRigidBody(instPos.mass, compInst.bt.motionState, et.bt.shape, localInertia);
compInst.bt.rigidBody->setLinearVelocity(btVector3(0,0,0));
compInst.bt.rigidBody->setAngularVelocity(btVector3(0,0,0));
compInst.bt.rigidBody->getCollisionShape()->setLocalScaling(instPos.scale);
BtDynamicsWorld->addRigidBody(compInst.bt.rigidBody);
auto *broadphaseProxy = compInst.bt.rigidBody->getBroadphaseProxy();
broadphaseProxy->m_collisionFilterGroup = static_cast<PhysicsCollision_T>(comp.physicsLayer);
broadphaseProxy->m_collisionFilterMask = static_cast<PhysicsCollision_T>(comp.physicsMask);
compInst.bt.rigidBody->setUserPointer(reinterpret_cast<void *>(compInst.entHandle));
break;
}
if (strstr(readLine, PKE_FILE_INSTANCE_ENTITY_HANDLE)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_ENTITY_HANDLE);
EntityHandle_T handle_t;
STR2NUM_ERROR result = str2num(handle_t, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
comp.entHandle = EntityHandle{handle_t};
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_ENTITY_TYPE_CODE)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_ENTITY_TYPE_CODE);
uint64_t len = strlen(readLine + prefixLen);
memcpy(entTypeCode, readLine + prefixLen, len);
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_POS_POS)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_POS_POS);
char *startingChar = strchr(readLine + prefixLen, '[') + 1;
assert(startingChar != nullptr);
char *pEnd = nullptr;
long index = 0;
btVector3 pos;
do {
assert(index < 3);
STR2NUM_ERROR result = str2num(pos[index], startingChar, pEnd);
assert(result == STR2NUM_ERROR::SUCCESS);
startingChar = pEnd + 1;
++index;
} while (*pEnd != ']');
instPos.posRot.setOrigin(pos);
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_POS_ROT)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_POS_ROT);
char *startingChar = strchr(readLine + prefixLen, '[') + 1;
assert(startingChar != nullptr);
char *pEnd = nullptr;
long index = 0;
btQuaternion rot;
do {
assert(index < 4);
STR2NUM_ERROR result = str2num(rot[index], startingChar, pEnd);
assert(result == STR2NUM_ERROR::SUCCESS);
startingChar = pEnd + 1;
++index;
} while (*pEnd != ']');
instPos.posRot.setRotation(rot);
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_POS_SCALE)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_POS_SCALE);
char *startingChar = strchr(readLine + prefixLen, '[') + 1;
assert(startingChar != nullptr);
char *pEnd = nullptr;
long index = 0;
do {
assert(index < 3);
STR2NUM_ERROR result = str2num(instPos.scale[index], startingChar, pEnd);
assert(result == STR2NUM_ERROR::SUCCESS);
startingChar = pEnd + 1;
++index;
} while (*pEnd != ']');
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_PHYSICS_MASS)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_PHYSICS_MASS);
STR2NUM_ERROR result = str2num(instPos.mass, readLine + prefixLen);
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_PHYSICS_COLLISION_LAYER)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_PHYSICS_COLLISION_LAYER);
PhysicsCollision_T val = static_cast<PhysicsCollision_T>(comp.physicsLayer);
STR2NUM_ERROR result = str2num(val, readLine + prefixLen);
comp.physicsLayer = PhysicsCollision{val};
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
if (strstr(readLine, PKE_FILE_INSTANCE_PHYSICS_COLLISION_MASK)) {
uint64_t prefixLen = strlen(PKE_FILE_INSTANCE_PHYSICS_COLLISION_MASK);
PhysicsCollision_T val = static_cast<PhysicsCollision_T>(comp.physicsMask);
STR2NUM_ERROR result = str2num(val, readLine + prefixLen);
comp.physicsMask = PhysicsCollision{val};
assert(result == STR2NUM_ERROR::SUCCESS);
continue;
}
}
}
void Game_SaveSceneFile(const char *sceneFilePath) {
std::ofstream f(sceneFilePath);
assert(f.is_open());
f << PKE_FILE_BEGIN << std::endl;
f << PKE_FILE_VERSION << std::endl;
f << "" << std::endl;
for (long i = 0; i < GlobalEntityTypes.Count(); ++i) {
f << PKE_FILE_OBJ_ENTITY_TYPE << std::endl;
const auto &et = GlobalEntityTypes[i];
const CompGrBinds *grBinds = ECS_GetGrBinds(et.entityHandle);
// TODO ignore if no instances
if (grBinds == nullptr) {
continue;
}
SerializeEntityType(f, et);
f << PKE_FILE_OBJ_END << std::endl;
}
int64_t instanceBucketCount = ECS_GetInstances_BucketCount();
for (long b = 0; b < instanceBucketCount; ++b) {
uint64_t count;
auto *instances = ECS_GetInstances(b, count);
for (long i = 0; i < count; ++i) {
const auto &instance = instances[i];
if (instance.entHandle == EntityHandle_MAX)
continue;
f << PKE_FILE_OBJ_INSTANCE << std::endl;
SerializeInstance(f, instance);
f << PKE_FILE_OBJ_END << std::endl;
}
}
f << PKE_FILE_END << std::endl;
f.flush();
f.close();
}
void Game_LoadSceneFile(const char *sceneFilePath) {
std::ifstream f(sceneFilePath);
assert(f.is_open());
memset(readLine, '\0', readLineLength);
while (f.getline(readLine, readLineLength)) {
// EntityTypes
if (strcmp(PKE_FILE_OBJ_ENTITY_TYPE, readLine) == 0) {
ParseEntityType(f);
continue;
}
if (strcmp(PKE_FILE_OBJ_INSTANCE, readLine) == 0) {
ParseInstance(f);
continue;
}
}
f.close();
}
const uint64_t consoleBufferCount = 30;
const uint64_t consoleLineLength = 128;
char consoleBuffer[consoleBufferCount][consoleLineLength];
long consoleBufferIndex = 0;
void Game_RecordImGui() {
static bool scrollToBottom = true;
if (!ImGui::Begin("Console", &pkeSettings.editorSettings.isShowingConsole)) {
ImGui::End();
return;
}
ImVec2 region = ImGui::GetContentRegionAvail();
region.y -= 27;
if (ImGui::BeginListBox("##ConsoleHistory", region)) {
for (long i = consoleBufferIndex + 1; i < consoleBufferCount; ++i) {
ImGui::Text("%s", consoleBuffer[i]);
}
for (long i = 0; i < consoleBufferIndex; ++i) {
ImGui::Text("%s", consoleBuffer[i]);
}
if (scrollToBottom) ImGui::SetScrollHereY(1);
scrollToBottom = false;
ImGui::EndListBox();
}
ImGui::Separator();
if (ImGui::InputText("##ConsoleInput", consoleBuffer[consoleBufferIndex], consoleLineLength, ImGuiInputTextFlags_EnterReturnsTrue)) {
// TODO parse and execute.
scrollToBottom = true;
consoleBufferIndex = (consoleBufferIndex + 1) % consoleBufferCount;
memset(consoleBuffer[consoleBufferIndex], '\0', consoleLineLength);
}
auto focusedFlags = (ImGuiFocusedFlags_ChildWindows);
if (ImGui::IsWindowFocused(focusedFlags) && !ImGui::IsAnyItemFocused() && !ImGui::IsAnyItemHovered() && !ImGui::IsMouseClicked(ImGuiMouseButton_Left) && !ImGui::IsMouseClicked(ImGuiMouseButton_Left, true)) {
ImGui::SetKeyboardFocusHere(-1);
}
ImGui::End();
}
void Game_Tick(double delta) {
Pke_ResetBucket(pkeSettings.mem.bkt);
/*
* ECS_Tick() gets called first because it updates the public
* `EntitiesToBeRemoved` for all other ticks to use.
*/
ECS_Tick_Early(delta);
ECS_Tick(delta);
PkeInput_Tick(delta);
// TODO invoke external ticks here
if (pkePlugin.OnTick) {
pkePlugin.OnTick(delta);
}
EntityType_Tick_Late(delta);
ECS_Tick_Late(delta);
}
void Game_Main(PKEWindowProperties windowProps) {
fprintf(stdout, "Game_Main Entering\n");
try {
AM_Init();
Physics_Init();
Game_Init();
ECS_Init();
CreateWindow(windowProps);
PkeInput_Init();
EntityType_Init();
if (pkePlugin.OnInit) {
pkePlugin.OnInit();
}
GameTimePoint lastTimePoint = pkeSettings.steadyClock.now();
double deltaTillNextRender = pkeSettings.deltaPerFrame;
GameTimePoint lastLogTimePoint = pkeSettings.steadyClock.now();
int64_t tickCount = 0;
int64_t renderCount = 0;
int64_t nsAhead = 0.0;
while (pkeSettings.isGameRunning) {
glfwPollEvents();
int64_t nsAheadHolder = 0.0;
if (nsAhead > 0) {
nsAheadHolder = nsAhead;
std::this_thread::sleep_for(GameTimeDuration(nsAhead));
nsAhead = 0;
}
if (vidMode.refreshRate != pkeSettings.targetFPS) {
pkeSettings.targetFPS = vidMode.refreshRate;
pkeSettings.deltaPerFrame = 1 / double(pkeSettings.targetFPS);
}
GameTimePoint currentTimePoint = pkeSettings.steadyClock.now();
double deltaThisTick = ((currentTimePoint - lastTimePoint).count() - nsAheadHolder) / NANO_DENOM_DOUBLE;
deltaThisTick = std::min(deltaThisTick, pkeSettings.minimumDeltaPerFrame);
lastTimePoint = currentTimePoint;
deltaTillNextRender -= deltaThisTick;
bool shouldRender = pkeSettings.graphicsSettings.isFramerateUnlocked
|| pkeSettings.graphicsSettings.isWaitingForVsync
|| deltaTillNextRender <= 0.0;
if (shouldRender == false && (deltaTillNextRender > 0.0 && deltaTillNextRender - (deltaThisTick * 2.0) <= 0.0)) {
/*
* We are ahead of the render schedule
* && the current tick's speed would put us behind schedule next tick.
* Simulate the extra time we are ahead and prepare to sleep the difference
* before the next tick.
*/
nsAhead = std::floor(deltaTillNextRender * NANO_DENOM_DOUBLE);
deltaThisTick += deltaTillNextRender;
shouldRender = true;
}
tickCount += 1;
Game_Tick(deltaThisTick);
if (shouldRender) {
Render();
renderCount += 1;
double msBehind = deltaTillNextRender * -1000;
int64_t behindCount = 0;
while (deltaTillNextRender < pkeSettings.deltaPerFrame) {
behindCount += 1;
deltaTillNextRender += pkeSettings.deltaPerFrame;
}
if (behindCount > 2) {
fprintf(stderr, "[PKE::main] late render - simulated ahead: %fms - delta behind: %fms - missed frames:%ld\n", nsAheadHolder / (NANO_DENOM_DOUBLE / 1000), msBehind, behindCount - 1);
fflush(stderr);
}
}
if ((currentTimePoint - lastLogTimePoint).count() > std::chrono::nanoseconds::period::den) {
lastLogTimePoint = currentTimePoint;
fprintf(stdout, "TPS: ~%ld - actual:%ld - presents:%ld\n", int64_t(1 / deltaThisTick), tickCount, renderCount);
fflush(stdout);
tickCount = 0;
renderCount = 0;
}
pkeSettings.isGameRunning = !glfwWindowShouldClose(window);
}
vkDeviceWaitIdle(vkDevice);
} catch (const std::exception &exc) {
fprintf(stderr, "Game_Main EXCEPTION: %s\n", exc.what());
} catch (const char *err) {
fprintf(stderr, "Game_Main UNHANDLED EXCEPTION: %s\n", err);
} catch (...) {
fprintf(stderr, "Game_Main UNHANDLED EXCEPTION\n");
}
fprintf(stdout, "Game_Main SHUTDOWN INITIATED\n");
#ifndef NDEBUG
Pke_DebugPrint();
#endif
if (pkePlugin.OnTeardown) {
pkePlugin.OnTeardown();
}
Game_Teardown();
Event_Teardown();
EntityType_Teardown();
PkeInput_Teardown();
Physics_Teardown();
ECS_Teardown();
AM_DebugPrint();
AM_Teardown();
DestroyWindow();
Pke_DebugPrint();
fprintf(stdout, "Game_Main Exiting\n");
}
void Game_Init() {
pkeSettings.mem.bkt = Pke_BeginTransientBucket(1UL << 26);
for (long i = 0; i < consoleBufferCount; ++i) {
memset(consoleBuffer[i], '\0', consoleLineLength);
}
}
void Game_Teardown() { }
|