-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsource.cpp
1512 lines (1371 loc) · 55.6 KB
/
source.cpp
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 _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1
#define SDL_MAIN_HANDLED
#include <algorithm>
#include <functional>
#include <filesystem>
#include <iostream>
#include <optional>
#include <queue>
#include <stdlib.h>
#include <chrono>
#include <thread>
#include <sstream>
#include "rapidjson/filereadstream.h"
#include "source.h"
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#else
#endif
void open_url(const char* url) {
#if defined(__EMSCRIPTEN__)
emscripten_run_script(std::string("window.open(\"" + std::string(url) + "\")").c_str());
#elif defined(_WIN32)
std::string command = "start ";
command += url;
std::system(command.c_str());
#elif defined(__APPLE__)
std::string command = "open ";
command += url;
std::system(command.c_str());
#else
std::string command = "xdg-open ";
command += url;
std::system(command.c_str());
#endif
}
std::string translate_path(const char* path) {
return std::string(base_path) + path;
}
const char* get_window_title(GameConfig* config) {
return config->window_name.c_str();
}
void mainloop(void* arg) {
World* world = static_cast<World*>(arg);
world->run_turn(); // SDL_Quit is only recieved as application is about to shutdown
}
int main(int argc, char** argv) {
lua_State* lua_state = luaL_newstate();
luaL_openlibs(lua_state);
if (!file_exists(translate_path("resources/"))) {
std::cout << "error: resources/ missing" << std::endl;
return 0;
}
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "Could not initialize SDL! Error: " << SDL_GetError() << std::endl;
exit(1);
}
std::shared_ptr<GameConfig> game_config = std::make_shared<GameConfig>();
World world = { game_config, lua_state };
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg((em_arg_callback_func)mainloop, &world, -1, 1);
#else
while (!world.run_turn()) {}
#endif
SDL_Quit();
}
bool file_exists(std::string_view path) {
return std::filesystem::exists(path);
}
void BitVec::clear() {
for (auto& v : data) {
v = 0;
}
}
void BitVec::fill() {
for (auto& v : data) {
v = numeric_max<size_t>();
}
}
void BitVec::set_len(size_t new_size, size_t new_val) {
size_t new_len = (new_size / word_size) + 1;
data.resize(new_len, new_val);
}
bool BitVec::get(size_t index) const {
size_t word_index = index / word_size;
if (word_index >= data.size()) {
return false;
}
size_t mask = static_cast<size_t>(1) << (index % word_size);
return data[word_index] & mask;
}
void BitVec::set(size_t index, bool new_val) {
size_t word_index = index / word_size;
if (word_index >= data.size()) {
return;
}
size_t mask = static_cast<size_t>(1) << (index % word_size);
if (new_val) {
data[word_index] |= mask;
} else {
data[word_index] &= ~mask;
}
}
GameConfig::GameConfig() {
if (!file_exists(translate_path("resources/game.config"))) {
std::cout << "error: resources/game.config missing";
exit(0);
}
rapidjson::Document doc = ReadJsonFile(translate_path("resources/game.config"));
std::optional<const char*> initial_scene = get_value<const char*>(doc, "initial_scene");
if (!initial_scene.has_value()) {
std::cout << "error: initial_scene unspecified";
exit(0);
}
this->initial_scene = initial_scene.value();
window_name = get_string(doc, "game_title").value_or("");
font = get_string(doc, "font");
}
std::size_t Ivec2Hasher::operator()(const glm::ivec2& vec) const noexcept {
uint32_t ux = static_cast<uint32_t>(vec.x);
uint32_t uy = static_cast<uint32_t>(vec.y);
uint64_t result = static_cast<uint64_t>(ux);
result <<= 32;
result |= static_cast<uint64_t>(uy);
return std::hash<uint64_t>{}(result);
}
void Actor::insert_sorted(std::vector<ComponentIndex>& v, ComponentIndex e) {
for (auto it = v.begin(); it != v.end(); it++) {
if (components[*it].key < components[e].key) {
continue;
}
v.insert(it, e);
return;
}
v.push_back(e);
}
void Actor::remove_sorted(std::vector<ComponentIndex>& v, ComponentIndex e) {
auto it = std::find(v.begin(), v.end(), e);
if (it != v.end()) {
v.erase(it);
}
}
Component& Actor::add_component(Component new_component) {
ComponentIndex index = 0;
if (!free_list.empty()) {
index = free_list.back();
free_list.pop_back();
components[index] = std::move(new_component);
} else {
components.push_back(std::move(new_component));
index = static_cast<ComponentIndex>(components.size() - 1);
}
Component& component = components[index];
keys[component.key] = index;
insert_sorted(types[component.type], index);
if (!component.lua_component["OnUpdate"].isNil()) {
insert_sorted(have_update, index);
}
if (!component.lua_component["OnLateUpdate"].isNil()) {
insert_sorted(have_late_update, index);
}
if (!component.lua_component["OnCollisionEnter"].isNil()) {
insert_sorted(have_on_collision_enter, index);
}
if (!component.lua_component["OnCollisionExit"].isNil()) {
insert_sorted(have_on_collision_exit, index);
}
if (!component.lua_component["OnTriggerEnter"].isNil()) {
insert_sorted(have_on_trigger_enter, index);
}
if (!component.lua_component["OnTriggerExit"].isNil()) {
insert_sorted(have_on_trigger_exit, index);
}
needs_destroy += static_cast<uint32_t>(!component.lua_component["OnDestroy"].isNil());
return component;
}
void Actor::remove_component(std::string key, bool force) {
ComponentIndex index = keys.at(key);
auto& component = components[index];
if (!force && needs_destroy != 0 && !component.lua_component["OnDestroy"].isNil()) {
insert_sorted(to_destroy, index);
return;
}
keys.erase(key);
std::vector<ComponentIndex>& type_list = types.at(component.type);
type_list.erase(std::find(type_list.begin(), type_list.end(), index));
if (type_list.empty()) {
types.erase(component.type);
}
remove_sorted(have_update, index);
remove_sorted(have_late_update, index);
remove_sorted(have_on_collision_enter, index);
remove_sorted(have_on_collision_exit, index);
remove_sorted(have_on_trigger_enter, index);
remove_sorted(have_on_trigger_exit, index);
component.lua_component = luabridge::LuaRef(component.lua_component.state());
component.key = "Erased Key";
component.type = "Erased Type";
free_list.push_back(index);
}
void Actor::clear() {
to_destroy.clear();
if (needs_destroy != 0) {
for (size_t i = 0; i < components.size(); i++) {
auto& component = components[i];
if (!component.lua_component.isNil()) {
remove_component(component.key);
}
}
call_destroy();
}
name = "Uninit";
components.clear();
keys.clear();
types.clear();
have_update.clear();
have_late_update.clear();
have_on_collision_enter.clear();
have_on_collision_exit.clear();
have_on_trigger_enter.clear();
have_on_trigger_exit.clear();
free_list.clear();
id = numeric_max<ActorId>();
}
void Actor::call_destroy() {
for (ComponentIndex i : to_destroy) {
luabridge::LuaRef component = components[i].lua_component;
sandbox_call(component["OnDestroy"], name, component);
remove_component(components[i].key, true);
needs_destroy -= 1;
}
to_destroy.clear();
}
static rapidjson::Document ReadJsonFile(const std::string &path)
{
FILE* file_pointer = nullptr;
rapidjson::Document out_document;
#ifdef _WIN32
fopen_s(&file_pointer, path.c_str(), "rb");
#else
file_pointer = fopen(path.c_str(), "rb");
#endif
char buffer[65536];
rapidjson::FileReadStream stream(file_pointer, buffer, sizeof(buffer));
out_document.ParseStream(stream);
std::fclose(file_pointer);
if (out_document.HasParseError()) {
std::cout << "error parsing json at [" << path << "]" << std::endl;
exit(0);
}
return out_document;
}
template<typename T>
std::optional<T> get_value(const rapidjson::Value& val, const char* key) {
if (val.HasMember(key) && val[key].Is<T>()) {
return val[key].Get<T>();
}
return {};
}
template<typename T>
void swap_remove(std::vector<T>& v, size_t index) {
if (v.size() == 0) {
return;
}
if (index == v.size() - 1) {
v.pop_back();
return;
}
std::swap(v[index], v.back());
v.pop_back();
}
static uint64_t ivec2_to_u64(glm::ivec2 v) {
uint32_t ux = static_cast<uint32_t>(v.x);
uint32_t uy = static_cast<uint32_t>(v.y);
uint64_t result = static_cast<uint64_t>(ux) << 32 | static_cast<uint32_t>(uy);
return result;
}
template<class ...Params>
void sandbox_call(luabridge::LuaRef function, std::string_view actor_name, Params... params) {
try {
function(params...);
}
catch (luabridge::LuaException e) {
std::string error = e.what();
std::replace(error.begin(), error.end(), '\\', '/');
std::cout << "\033[31m" << actor_name << " : " << error << "\033[0m" << std::endl;
}
}
std::optional<float> get_number(const rapidjson::Value& val, const char* key) {
if (val.HasMember(key) && (val[key].IsNumber())) {
return val[key].Get<float>();
}
return {};
}
std::optional<std::string> get_string(const rapidjson::Value& val, const char* key) {
if (val.HasMember(key) && val[key].Is<const char*>()) {
return val[key].Get<const char*>();
}
return {};
}
luabridge::LuaRef get_value(lua_State* lua_state, const rapidjson::Value& val, const char* key) {
if (!val.HasMember(key) || val[key].IsNull()) {
return luabridge::LuaRef(lua_state);
}
return get_value(lua_state, val[key]);
}
luabridge::LuaRef get_value(lua_State* lua_state, const rapidjson::Value& val) {
if (val.IsArray()) {
luabridge::LuaRef ref = luabridge::newTable(lua_state);
for (auto it = val.Begin(); it != val.End(); it++) {
ref.append(get_value(lua_state, *it));
}
return ref;
}
if (val.IsBool()) {
return luabridge::LuaRef(lua_state, val.Get<bool>());
}
if (val.IsInt()) {
return luabridge::LuaRef(lua_state, val.Get<int32_t>());
}
if (val.IsNumber()) {
return luabridge::LuaRef(lua_state, val.Get<float>());
}
if (val.IsObject()) {
luabridge::LuaRef ref = luabridge::newTable(lua_state);
for (auto it = val.MemberBegin(); it != val.MemberEnd(); it++) {
ref[it->name.GetString()] = get_value(lua_state, it->value);
}
return ref;
}
if (val.IsString()) {
return luabridge::LuaRef(lua_state, val.GetString());
}
return luabridge::LuaRef(lua_state);
}
void set_metatable(const luabridge::LuaRef& base, const luabridge::LuaRef& meta) {
lua_State* lua_state = base.state();
base.push(lua_state);
meta.push(lua_state);
lua_setmetatable(lua_state, -2);
lua_pop(lua_state, 1);
}
RenderConfig::RenderConfig() {
if (!file_exists(translate_path("resources/rendering.config"))) {
return;
}
rapidjson::Document config = ReadJsonFile(translate_path("resources/rendering.config"));
size.x = get_value<int>(config, "x_resolution").value_or(size.x);
size.y = get_value<int>(config, "y_resolution").value_or(size.y);
clear_color.r = static_cast<uint8_t>(get_value<int>(config, "clear_color_r").value_or(255));
clear_color.g = static_cast<uint8_t>(get_value<int>(config, "clear_color_g").value_or(255));
clear_color.b = static_cast<uint8_t>(get_value<int>(config, "clear_color_b").value_or(255));
zoom = get_number(config, "zoom_factor").value_or(1.f);
}
luabridge::LuaRef TemplateManager::make_template_component(std::string type) {
if (type == "Model") {
return { lua_state, Model(lua_state) };
}
if (components.count(type) == 0) {
load_component(type);
}
luabridge::LuaRef component = luabridge::newTable(lua_state);
set_metatable(component, components.find(type)->second);
return component;
}
void TemplateManager::load_component(std::string type) {
if (type == "Rigidbody") {
components.insert({ type, luabridge::LuaRef(lua_state) });
return;
}
const std::string filetype = translate_path("resources/component_types/") + type + ".lua";
if (!file_exists(filetype)) {
std::cout << "error: failed to locate component " << type;
exit(0);
}
if (luaL_dofile(lua_state, filetype.c_str()) != LUA_OK) {
std::cout << "problem with lua file " << type;
exit(0);
}
luabridge::LuaRef meta = luabridge::getGlobal(lua_state, type.c_str());
meta["__index"] = meta;
meta["enabled"] = true;
components.insert({ type, meta });
}
void TemplateManager::load_template(std::string name) {
if (templates.find(name) != templates.end()) {
return;
}
const std::string filename = translate_path("resources/actor_templates/") + name + ".template";
if (!file_exists(filename)) {
std::cout << "error: template " << name << " is missing";
exit(0);
}
rapidjson::Document doc = ReadJsonFile(filename);
Actor templ;
templ.name = get_value<const char*>(doc, "name").value_or("");
if (!doc.HasMember("components")) {
templates.insert({ name, templ });
return;
}
const auto& components = doc["components"];
std::vector<std::string> keys;
for (auto it = components.MemberBegin(); it != components.MemberEnd(); it++) {
keys.push_back(it->name.GetString());
}
std::sort(keys.begin(), keys.end());
for (auto& key : keys) {
const auto& component = components[key.c_str()];
std::string type = component["type"].GetString();
luabridge::LuaRef lua_component = make_template_component(type);
templ.keys.insert({ key, static_cast<ComponentIndex>(templ.components.size()) });
Component new_component = { lua_component, std::move(key), std::move(type) };
for (auto it = component.MemberBegin(); it != component.MemberEnd(); it++) {
if (it->name == "type") {
continue;
}
new_component.lua_component[it->name.GetString()] = get_value(lua_state, it->value);
}
new_component.lua_component["__index"] = new_component.lua_component;
templ.components.push_back(new_component);
}
templates.insert({ name, templ });
return;
}
void Model::on_start(lua_State* lua_state) {
on_update(lua_state); // Just run update early
}
void Model::on_update(lua_State* lua_state) {
if (mesh_dirty) {
if (instance.has_value()) {
on_destroy(lua_state);
}
Renderer* renderer = luabridge::getGlobal(lua_state, "_Renderer").cast<Renderer*>();
ModelHandle model = renderer->loadModel(translate_path("resources/meshes/") + mesh);
instance = {renderer->spawnInstance(model, transform)};
transform_dirty = false;
mesh_dirty = false;
} else if (transform_dirty) {
Renderer* renderer = luabridge::getGlobal(lua_state, "_Renderer").cast<Renderer*>();
renderer->getModelInstance(instance.value()) = transform;
transform_dirty = false;
}
}
void Model::on_destroy(lua_State* lua_state) {
if (!instance.has_value()) {
return;
}
Renderer* renderer = luabridge::getGlobal(lua_state, "_Renderer").cast<Renderer*>();
renderer->destroyInstance(instance.value());
instance = {};
}
TemplateManager::TemplateManager(std::shared_ptr<Renderer> renderer, lua_State* lua_state) : lua_state(lua_state), renderer(renderer) {
templates.insert({ "", {} });
}
Actor TemplateManager::create_actor(const rapidjson::Value& actor_json) {
std::string template_name = get_value<const char*>(actor_json, "template").value_or("");
load_template(template_name);
std::optional<const char*> name = get_value<const char*>(actor_json, "name");
const Actor& templ = templates.find(template_name)->second;
if (!actor_json.HasMember("components")) {
Actor actor = create_template_actor(std::move(template_name));
actor.name = name.value_or(templ.name.c_str());
return actor;
}
Actor actor;
actor.name = name.value_or(templ.name.c_str());
const auto& components = actor_json["components"];
std::vector<std::string> keys;
for (auto it = components.MemberBegin(); it != components.MemberEnd(); it++) {
keys.push_back(it->name.GetString());
}
for (const auto& component : templ.components) {
if (!components.HasMember(component.key.c_str())) {
keys.push_back(component.key);
}
}
std::sort(keys.begin(), keys.end());
for (auto& key : keys) {
luabridge::LuaRef new_component = luabridge::newTable(lua_state);
auto it = templ.keys.find(key);
std::string type;
if (it != templ.keys.end()) {
type = templ.components[it->second].type;
if (type == "Model") {
new_component = Model(templ.components[it->second].lua_component.cast<Model>());
} else {
set_metatable(new_component, templ.components[it->second].lua_component);
}
}
else {
type = components[key.c_str()]["type"].GetString();
if (type == "Model") {
new_component = Model(lua_state);
} else {
load_component(type);
set_metatable(new_component, this->components.find(type)->second);
}
}
if (components.HasMember(key.c_str())) {
const auto& component = components[key.c_str()];
for (auto it = component.MemberBegin(); it != component.MemberEnd(); it++) {
if (std::string_view{ it->name.GetString() } != "type") {
new_component[it->name.GetString()] = get_value(lua_state, it->value);
}
}
}
new_component["key"] = key;
actor.add_component({ new_component, std::move(key), std::move(type) });
}
return actor;
}
Actor TemplateManager::create_template_actor(std::string template_name) {
load_template(template_name);
const Actor& templ = templates.find(template_name)->second;
Actor actor;
actor.name = templ.name.c_str();
for (ComponentIndex i = 0; i < templ.components.size(); i++) {
const auto& component = templ.components[i];
std::string key = component.key;
std::string type = component.type;
if (type == "Model") {
actor.add_component({ { lua_state, Model(component.lua_component.cast<Model>()) }, std::move(key), std::move(type) });
} else {
luabridge::LuaRef new_component = luabridge::newTable(lua_state);
set_metatable(new_component, component.lua_component);
new_component["key"] = key;
actor.add_component({ new_component, std::move(key), std::move(type) });
}
}
return actor;
}
luabridge::LuaRef TemplateManager::create_component(std::string type, std::string key) {
if (type == "Model") {
Model new_component = { lua_state };
new_component.key = key;
return { lua_state, new_component };
} else {
luabridge::LuaRef new_component = luabridge::newTable(lua_state);
load_component(type);
set_metatable(new_component, components.find(type)->second);
new_component["key"] = key;
return new_component;
}
}
AudioManager::AudioManager() {
if (Mix_OpenAudio(48000, AUDIO_S16SYS, 1, 2048)) {
std::cout << "Failed to open audio";
exit(0);
}
Mix_AllocateChannels(50);
}
Mix_Chunk* AudioManager::load_sound(const std::string& file_name) {
if (audio.count(file_name) != 0) {
return audio[file_name];
}
std::string file_path_wav = translate_path("resources/audio/") + file_name + ".wav";
std::string file_path_ogg = translate_path("resources/audio/") + file_name + ".ogg";
Mix_Chunk* chunk = Mix_LoadWAV(file_path_wav.c_str());
if (chunk == nullptr) {
chunk = Mix_LoadWAV(file_path_ogg.c_str());
}
if (chunk == nullptr) {
std::cout << "error: failed to play audio clip " << file_name;
exit(0);
}
audio[file_name] = chunk;
return chunk;
}
int AudioManager::play_sound(Mix_Chunk* audio, int channel, bool loops) const {
return Mix_PlayChannel(channel, audio, -static_cast<int>(loops));
}
void AudioManager::stop_sound(int channel) const {
Mix_HaltChannel(channel);
}
void AudioManager::set_volume(int channel, int volume) const {
Mix_Volume(channel, volume);
}
luabridge::LuaRef AddComponentQueue::push(std::string type, ActorIndex index, ActorId id) {
std::stringstream key;
key << 'r' << global_count;
global_count += 1;
luabridge::LuaRef component_ref = templates.create_component(type, key.str());
Component component = {component_ref, key.str(), std::move(type)};
queue.push_back(Descriptor{ component, index, id });
return component_ref;
}
const std::string& World::LuaActor::get_name() const {
return actor.name;
}
ActorId World::LuaActor::get_id() const {
return actor.id;
}
luabridge::LuaRef World::LuaActor::get_component_by_key(const char* key, lua_State* lua_state) const {
auto it = actor.keys.find(key);
if (it == actor.keys.end()) {
return luabridge::LuaRef(lua_state);
}
return actor.components[it->second].lua_component;
}
luabridge::LuaRef World::LuaActor::get_component_by_type(const char* type, lua_State* lua_state) const {
auto it = actor.types.find(type);
if (it == actor.types.end()) {
return luabridge::LuaRef(lua_state);
}
return actor.components[it->second[0]].lua_component;
}
luabridge::LuaRef World::LuaActor::get_components_by_type(const char* type, lua_State* lua_state) const {
auto it = actor.types.find(type);
luabridge::LuaRef components = luabridge::newTable(lua_state);
if (it == actor.types.end()) {
return components;
}
const auto& actor_components = it->second;
for (uint32_t i = 0; i < actor_components.size(); i++) {
components[i + 1] = actor.components[actor_components[i]].lua_component;
}
return components;
}
luabridge::LuaRef World::LuaActor::add_component(const char* type, lua_State* lua_state) {
return actors.component_queue.push(type, index, actor.id);
}
void World::LuaActor::remove_component(luabridge::LuaRef component_ref) {
actor.remove_component(component_ref["key"]);
}
void World::LuaActor::call_component_method(luabridge::LuaRef component, std::string_view name) {
if (component.isNil()) {
return;
}
const luabridge::LuaRef& ref = component[name.data()];
if (ref.isNil() || !component["enabled"].cast<bool>()) {
return;
}
sandbox_call(ref, actor.name, component);
}
void InputManager::new_frame() {
just_pressed_keys.reset();
just_released_keys.reset();
just_pressed_mouse = 0;
just_released_mouse = 0;
scroll_delta = 0;
}
void InputManager::handle_key_event(SDL_KeyboardEvent& e) {
if (e.type == SDL_KEYDOWN) {
currently_down_keys[e.keysym.scancode] = true;
just_pressed_keys[e.keysym.scancode] = true;
just_released_keys[e.keysym.scancode] = false;
}
else if (e.type == SDL_KEYUP) {
currently_down_keys[e.keysym.scancode] = false;
just_pressed_keys[e.keysym.scancode] = false;
just_released_keys[e.keysym.scancode] = true;
}
}
void InputManager::handle_mouse_event(SDL_MouseButtonEvent& e) {
if (e.type == SDL_MOUSEBUTTONDOWN) {
mouse_state |= SDL_BUTTON(e.button);
just_pressed_mouse |= SDL_BUTTON(e.button);
}
else if (e.type == SDL_MOUSEBUTTONUP) {
mouse_state &= ~SDL_BUTTON(e.button);
just_released_mouse |= SDL_BUTTON(e.button);
}
}
void InputManager::handle_mouse_wheel_event(SDL_MouseWheelEvent& e) {
scroll_delta = e.preciseY;
}
void InputManager::handle_mouse_motion_event(SDL_MouseMotionEvent& e) {
mouse_pos.x = static_cast<float>(e.x);
mouse_pos.y = static_cast<float>(e.y);
}
glm::vec2 InputManager::get_mouse_pos() const {
return mouse_pos;
}
float InputManager::get_scroll_delta() const {
return scroll_delta;
}
bool InputManager::key_is_pressed(SDL_Scancode scancode) const {
return currently_down_keys[scancode];
}
bool InputManager::key_just_pressed(SDL_Scancode scancode) const {
return just_pressed_keys[scancode];
}
bool InputManager::key_just_released(SDL_Scancode scancode) const {
return just_released_keys[scancode];
}
bool InputManager::mouse_is_pressed(uint8_t button) const {
return mouse_state & SDL_BUTTON(button);
}
bool InputManager::mouse_just_pressed(uint8_t button) const {
return just_pressed_mouse & SDL_BUTTON(button);
}
bool InputManager::mouse_just_released(uint8_t button) const {
return just_released_mouse & SDL_BUTTON(button);
}
void EventBus::publish(std::string event_type, luabridge::LuaRef message) {
for (auto& handler : subs[event_type]) {
handler.function(handler.component, message);
}
}
void EventBus::schedule_subscribe(std::string event_type, luabridge::LuaRef component, luabridge::LuaRef function) {
subscribe_queue.push_back({ event_type, { component, function } });
}
void EventBus::schedule_unsubscribe(std::string event_type, luabridge::LuaRef component, luabridge::LuaRef function) {
unsubscribe_queue.push_back({ event_type, { component, function } });
}
void EventBus::apply_scheduled() {
for (auto& handler : subscribe_queue) {
subs[handler.first].push_back(handler.second);
}
for (auto& handler : unsubscribe_queue) {
auto& set = subs[handler.first];
auto it = std::find(set.begin(), set.end(), handler.second);
if (it != set.end()) {
set.erase(it);
}
}
subscribe_queue.clear();
unsubscribe_queue.clear();
}
void World::ActorCollection::apply_queue() {
std::vector<AddComponentQueue::Descriptor> to_add;
component_queue.queue.swap(to_add);
for (auto& descriptor : to_add) {
auto& lua_actor = *actors[descriptor.actor].actor;
if (lua_actor.actor.id != descriptor.id) {
continue;
}
Component& inserted = lua_actor.actor.add_component(std::move(descriptor.component));
inserted.lua_component["actor"] = &lua_actor;
lua_actor.call_component_method(inserted.lua_component, "OnStart");
}
}
luabridge::LuaRef World::ActorCollection::find(const char* name, lua_State* lua_state) {
auto it = names.find(name);
if (it == names.end()) {
return luabridge::LuaRef(lua_state);
}
return { lua_state, *actors[it->second[0]].actor };
}
luabridge::LuaRef World::ActorCollection::find_all(const char* name, lua_State* lua_state) {
auto it = names.find(name);
luabridge::LuaRef table = luabridge::newTable(lua_state);
if (it == names.end()) {
return table;
}
const auto& actor_indices = it->second;
for (uint32_t i = 0; i < actor_indices.size(); i++) {
ActorId id = actor_indices[i];
table[i + 1] = *actors[id].actor;
}
return table;
}
void World::ActorCollection::call_actor_start(ActorIndex from) {
ActorIndex next = head;
if (from != numeric_max<ActorIndex>()) {
next = from;
}
while (next != numeric_max<ActorIndex>()) {
LuaActor& lua_actor = *actors[next].actor;
curr_actor = next;
size_t size = lua_actor.actor.components.size();
for (size_t i = 0; i < size; i++) {
if (curr_actor_destroyed) {
curr_actor_destroyed = false;
break;
}
luabridge::LuaRef component = lua_actor.actor.components[i].lua_component;
lua_actor.call_component_method(component, "OnStart");
}
next = actors[curr_actor].next;
}
curr_actor = numeric_max<ActorIndex>();
}
void World::ActorCollection::call_new_actor_start() {
new_actors.clear();
std::vector<ActorIndex> actors_to_start;
new_actor_list.swap(actors_to_start);
for (ActorIndex index : actors_to_start) {
if (actors[index].actor.get() == nullptr) {
break;
}
LuaActor& lua_actor = *actors[index].actor;
size_t size = lua_actor.actor.components.size();
for (size_t i = 0; i < size; i++) {
luabridge::LuaRef component = lua_actor.actor.components[i].lua_component;
lua_actor.call_component_method(component, "OnStart");
}
}
}
void World::ActorCollection::call_actor_update() {
std::vector<ComponentIndex> to_run;
ActorIndex next = head;
while (next != numeric_max<ActorIndex>()) {
if (new_actors.count(next) != 0) {
next = actors[next].next;
continue;
}
auto& lua_actor = *actors[next].actor;
curr_actor = next;
to_run = lua_actor.actor.have_update;
auto& components = lua_actor.actor.components;
for (ComponentIndex i : to_run) {
if (curr_actor_destroyed) {
curr_actor_destroyed = false;
break;
}
lua_actor.call_component_method(components[i].lua_component, "OnUpdate");
}
next = actors[curr_actor].next;
}
curr_actor = numeric_max<ActorIndex>();
}
void World::ActorCollection::call_actor_late_update() {
std::vector<ComponentIndex> to_run;
ActorIndex next = head;
while (next != numeric_max<ActorIndex>()) {
if (new_actors.count(next) != 0) {
next = actors[next].next;
continue;
}
LuaActor& lua_actor = *actors[next].actor;
curr_actor = next;
to_run = lua_actor.actor.have_late_update;
for (ComponentIndex i : to_run) {
if (curr_actor_destroyed) {
curr_actor_destroyed = false;
break;
}
lua_actor.call_component_method(lua_actor.actor.components[i].lua_component, "OnLateUpdate");
}
next = actors[curr_actor].next;
}
curr_actor = numeric_max<ActorIndex>();
}
void World::ActorCollection::call_actor_destroy() {
std::vector<ComponentIndex> to_run;
ActorIndex next = head;
while (next != numeric_max<ActorIndex>()) {
if (new_actors.count(next) != 0) {
next = actors[next].next;
continue;
}
LuaActor& lua_actor = *actors[next].actor;
curr_actor = next;
lua_actor.actor.call_destroy();
next = actors[curr_actor].next;
}
curr_actor = numeric_max<ActorIndex>();
for (ActorIndex index : to_destroy) {
actors[index].actor->actor.clear();
freed_list.push_back(index);
}
to_destroy.clear();
}
luabridge::LuaRef World::ActorCollection::instantiate(const char* template_name, lua_State* lua_state) {
ActorIndex index = add_actor(component_queue.templates.create_template_actor(template_name));
return { lua_state, *actors[index].actor };
}
void World::ActorCollection::dont_destroy_on_load(ActorIndex index) {
destroy_on_load.set(index, false);
}
ActorIndex World::ActorCollection::add_actor(Actor actor) {
ActorIndex new_index = raw_add_actor(actor);
new_actors.insert(new_index);
new_actor_list.push_back(new_index);
return new_index;
}
ActorIndex World::ActorCollection::raw_add_actor(Actor actor) {
constexpr ActorIndex max_index = numeric_max<ActorIndex>();
ActorIndex new_index;
actor.id = next_id;
next_id += 1;
auto& name = names[actor.name];
if (freed_list.empty() || freed_list.back() == curr_actor) {
new_index = static_cast<ActorIndex>(actors.size());
actors.push_back({ std::make_unique<LuaActor>(LuaActor{std::move(actor), new_index, *this}), max_index, tail });
destroy_on_load.set_len(actors.size(), 0);
} else {
new_index = freed_list.back();