Repository navigation
Expand file tree
/
Copy pathMain.cpp
More file actions
992 lines (813 loc) · 33.5 KB
/
Copy pathMain.cpp
File metadata and controls
992 lines (813 loc) · 33.5 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
/*
This file is part of "Avanor, the Land of Mystery" roguelike game
Copyright (C) 2000-2006 Vadim Gaidukevich
Copyright (C) 2025,2026 Joachim de Groot
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <sstream>
#include <typeinfo>
#include <unistd.h>
#ifdef __APPLE__
#include <climits>
#include <cstring>
#include <mach-o/dyld.h>
#endif
#include <argparse/argparse.hpp>
#include <cereal/archives/json.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/polymorphic.hpp>
#include <cereal/types/set.hpp>
#include "engine/simulation.h"
#include "engine/global.h"
#include "engine/xarchive.h"
#include "engine/xlua.h"
#include "game/game.h"
#include "helpers/hiscore.h"
#include "helpers/manual.h"
#include "item/xmoney.h"
// Throwaway proofs that the Cereal serialize()/CEREAL_REGISTER_TYPE chain
// added so far (XObject -> XMapObject -> XBaseObject -> XItem -> XMoney)
// actually round-trips real polymorphic/weak_ptr/custom-comparator-set
// object graphs, the riskiest unknowns named by the save/restore rewrite
// plan. Not part of the real save/restore path - remove once the rewrite
// is further along and has its own proper regression coverage.
namespace cereal_pilot {
// Cereal constructs shared_ptr<T> internally using its own plain-delete
// deleter, not XItem::Own()'s Invalidate()-aware one - unlike a normal
// Own()'d object, a cereal-loaded object has no safety net if its last
// shared_ptr reference drops before something calls Invalidate() on it
// explicitly. In the real restore path (Phase 4) every loaded object
// becomes really owned by a real container as part of the same graph
// deserialization, so it'll go through the same explicit
// Invalidate()-before-last-reference-drops discipline as everything else
// already does - but a throwaway orphaned local like these needs that
// same explicit call, or ~XObject()'s invariant trips.
static void RetireOrphan(const std::shared_ptr<XItem>& item)
{
if (item) {
item->Invalidate();
}
}
static bool TestPolymorphicItem()
{
auto original = XItem::Own(new XMoney(500));
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(original);
}
std::cout << oss.str() << std::endl;
std::shared_ptr<XItem> restored;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored);
}
const bool pass = restored
&& restored.get() != original.get()
&& dynamic_cast<XMoney*>(restored.get()) != nullptr
&& restored->kind == original->kind
&& restored->quantity == original->quantity
&& restored->value == original->value
&& restored->guid() == original->guid();
RetireOrphan(original);
RetireOrphan(restored);
return pass;
}
static bool TestItemList()
{
XItemList original_list;
original_list.insert(XItem::Own(new XMoney(100)));
original_list.insert(XItem::Own(new XMoney(250)));
// XItemList::insert() merges same-category items that Compare() calls
// equal into a single stack rather than adding a second entry - both
// XMoney(100) and XMoney(250) share ItemKind::MONEY and always compare
// equal, so this confirms they combine into one element with the summed
// quantity, not two.
const size_t original_size = original_list.size();
const int original_quantity = original_size == 1 ? (*original_list.begin())->quantity : -1;
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(original_list);
}
XItemList restored_list;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored_list);
}
bool pass = original_size == 1 && original_quantity == 350
&& restored_list.size() == original_size
&& (*restored_list.begin())->quantity == original_quantity;
// Heterogeneous lookup via the transparent comparator (find by raw
// XItem*, not shared_ptr<XItem>) is used throughout the codebase -
// confirm it still works against a restored set.
for (const auto& item : restored_list) {
pass = pass && restored_list.find(item.get()) != restored_list.end();
}
for (const auto& item : original_list) {
RetireOrphan(item);
}
for (const auto& item : restored_list) {
RetireOrphan(item);
}
return pass;
}
// Mimics the exact shape XBodyPart::owner will need in Phase 3: an object
// (Owner) holding, via a directly-owned subobject (Sub, analogous to
// XBodyPart living in XCreature::components), a weak_ptr pointing back at
// itself. Proves the underlying Cereal mechanism generically, without
// prematurely building out the real (much larger) XCreature.
struct SelfRefOwner;
struct SelfRefSub {
std::weak_ptr<SelfRefOwner> owner;
template<class Archive>
void serialize(Archive& ar)
{
ar(owner);
}
};
struct SelfRefOwner : public std::enable_shared_from_this<SelfRefOwner> {
int value{};
std::unique_ptr<SelfRefSub> sub;
template<class Archive>
void serialize(Archive& ar)
{
ar(value, sub);
}
};
static bool TestSelfReferentialWeakPtr()
{
auto owner = std::make_shared<SelfRefOwner>();
owner->value = 42;
owner->sub = std::make_unique<SelfRefSub>();
owner->sub->owner = owner;
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(owner);
}
std::shared_ptr<SelfRefOwner> restored;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored);
}
return restored
&& restored->value == owner->value
&& restored->sub
&& restored->sub->owner.lock() == restored;
}
// The real thing: spawns an actual game world (same init path as the
// established -test soak mode) and round-trips a real, fully-populated
// XCreature - not a synthetic stand-in. Exercises everything the
// XCreature/XBodyPart/magic-modifier/skills work depends on: polymorphic
// dispatch through the full creature hierarchy, xai's ai_owner fixup,
// XBodyPart's self-referential owner, and worn items staying resident in
// (and round-tripping identically with) contain.
static bool TestRealCreature()
{
static_cast<void>(Game.Create('T'));
std::shared_ptr<XCreature> original;
for (const auto& [key, loc] : Game.locations) {
if (original) {
break;
}
if (!loc || !loc->map) {
continue;
}
for (int i = 0; i < loc->map->CellCount() && !original; i++) {
if (auto& cr = loc->map->map[i].pMonster) {
original = cr;
}
}
}
if (!original) {
std::cout << "TestRealCreature: no creature found to test with" << std::endl;
return false;
}
// Through a reference rather than typeid(*original): dereferencing a
// shared_ptr is a function call, and clang rightly points out that
// typeid evaluates its operand when the type is polymorphic. It is
// meant to - the runtime type is the whole point - and saying so this
// way asks for it without the warning.
const XCreature& creature = *original;
std::cout << "TestRealCreature: runtime type is " << typeid(creature).name() << std::endl;
const auto original_guid = original->guid();
const auto original_contain_size = original->contain.size();
const auto original_components_size = original->components.size();
// A worn item (if any) must stay resident in contain by identity -
// note whether there is one, to check the same invariant Wear()
// enforces at runtime survives the round trip.
bool had_worn_item = false;
for (auto& bp : original->components) {
if (bp->Item()) {
had_worn_item = true;
break;
}
}
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(original);
}
std::shared_ptr<XCreature> restored;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored);
}
bool pass = restored
&& restored.get() != original.get()
&& restored->guid() == original_guid
&& restored->contain.size() == original_contain_size
&& restored->components.size() == original_components_size;
if (had_worn_item) {
bool found_worn_in_restored_contain = false;
for (auto& bp : restored->components) {
if (auto item = bp->Item()) {
found_worn_in_restored_contain = restored->contain.find(item) != restored->contain.end();
break;
}
}
pass = pass && found_worn_in_restored_contain;
}
std::cout
<< " guid " << original_guid << " -> " << (restored ? restored->guid() : 0)
<< ", contain " << original_contain_size << " -> " << (restored ? restored->contain.size() : 0)
<< ", components " << original_components_size << " -> " << (restored ? restored->components.size() : 0)
<< std::endl;
// `original` is a real, live creature still referenced elsewhere in
// the running game (the map tile, scheduler, etc.) - must NOT be
// invalidated here, unlike every other orphaned test object in this
// file. `restored` is a genuine orphan (this function is its only
// reference) and needs the usual explicit Invalidate(), same as
// TestPolymorphicItem()'s original/restored.
if (restored) {
restored->Invalidate();
}
return pass;
}
static bool TestRealLocation()
{
std::shared_ptr<XLocation> original = Game.Location("MAIN");
if (!original || !original->map) {
std::cout << "TestRealLocation: MAIN not built, nothing to test with" << std::endl;
return false;
}
const auto original_guid = original->guid();
const auto original_id = original->id;
const auto original_len = original->map->len;
const auto original_hgt = original->map->hgt;
const auto original_ways_count = original->ways_list.size();
std::set<XAnyPlace*> original_places;
int original_monster_count = 0;
int original_item_count = 0;
for (int i = 0; i < original->map->CellCount(); i++) {
if (original->map->map[i].pMonster) {
original_monster_count++;
}
original_item_count += static_cast<int>(original->map->map[i].item_list.size());
}
for (int y = 0; y < original_hgt; y++) {
for (int x = 0; x < original_len; x++) {
if (auto* p = original->map->GetPlace(x, y)) {
original_places.insert(p);
}
}
}
// A creature reachable from this location's map can carry a custom
// Lua event handler that, via NotifyLuaEventHandler(LuaEvent::SAVE/LuaEvent::LOAD)
// inside XCreature::serialize(), calls back into Location.StoreInt/
// RestoreInt - Lua bindings backed by XLocation::lua_int_buffer, a
// pointer NotifyLuaEventHandler/NotifyLuaEvent point at that object's
// own lua_ints member before firing. No special setup needed here:
// it's just another field in the normal archive stream below.
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(original);
}
std::shared_ptr<XLocation> restored;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored);
}
bool pass = restored
&& restored.get() != original.get()
&& restored->guid() == original_guid
&& restored->id == original_id
&& restored->map
&& restored->map->len == original_len
&& restored->map->hgt == original_hgt
&& restored->ways_list.size() == original_ways_count;
std::set<XAnyPlace*> restored_places;
int restored_monster_count = 0;
int restored_item_count = 0;
if (restored && restored->map) {
for (int i = 0; i < restored->map->CellCount(); i++) {
if (restored->map->map[i].pMonster) {
restored_monster_count++;
}
restored_item_count += static_cast<int>(restored->map->map[i].item_list.size());
}
for (int y = 0; y < restored->map->hgt; y++) {
for (int x = 0; x < restored->map->len; x++) {
if (auto* p = restored->map->GetPlace(x, y)) {
restored_places.insert(p);
// Setup() must have re-derived `location` (and, per
// cell, XMapTile::place) after load, exactly like the
// real constructors do - not persisted directly.
pass = pass && (p->location == restored.get());
}
}
}
}
pass = pass
&& (restored_places.size() == original_places.size())
&& (restored_monster_count == original_monster_count)
&& (restored_item_count == original_item_count);
std::cout
<< " guid " << original_guid << " -> " << (restored ? restored->guid() : 0)
<< ", places " << original_places.size() << " -> " << restored_places.size()
<< ", ways " << original_ways_count << " -> " << (restored ? restored->ways_list.size() : 0)
<< ", monsters " << original_monster_count << " -> " << restored_monster_count
<< ", items " << original_item_count << " -> " << restored_item_count
<< std::endl;
// `original` is Game.locations["MAIN"] itself, still live and
// referenced there - must NOT be invalidated. `restored` is a
// genuine orphan (this function is its only reference).
if (restored) {
restored->Invalidate();
}
return pass;
}
static bool TestRealScheduler()
{
// A fresh, isolated scheduler rather than Game.Scheduler itself -
// XScheduler::Get() has real side effects (it can advance time,
// reschedule entries whose timer hasn't yet expired) that would be
// unsafe to trigger against the live, shared one mid-test.
XScheduler local_sched;
local_sched.SetTime(12345);
// Add() takes ownership via XItem::Own() (see its own comment) for
// XItem-derived entries - matches how real code schedules things
// (e.g. Game.Scheduler.Add(new XCorpse(...))), not something this
// test needs to manage itself.
local_sched.Add(new XMoney(500));
std::ostringstream oss;
{
cereal::JSONOutputArchive archive(oss);
archive(local_sched);
}
XScheduler restored;
{
std::istringstream iss(oss.str());
cereal::JSONInputArchive archive(iss);
archive(restored);
}
bool pass = restored.GetTime() == local_sched.GetTime();
// ttm/ttmb round-trip via XObject::serialize() same as every other
// field - a freshly-constructed XMoney's ttm is 0, which Place()
// turns negative (expired) the moment it's re-placed one slot
// ahead, so a single Get() call is enough to retrieve it back.
auto entry = restored.Get();
pass = pass && entry && dynamic_cast<XMoney*>(entry.get()) != nullptr;
// See TestRealCreature() above for why this goes through a reference.
// The name() a type_info hands back outlives everything here, so
// holding the pointer is safe.
const char* entry_type = "none";
if (entry) {
const XObject& object = *entry;
entry_type = typeid(object).name();
}
std::cout
<< " scheduler time " << local_sched.GetTime() << " -> " << restored.GetTime()
<< ", entry " << entry_type
<< std::endl;
// Genuine orphan (Cereal's plain-delete deleter, no Invalidate()
// safety net) - Get() doesn't remove it from `restored`'s own
// internal data[], so invalidating it here is enough: restored's
// own destructor will find it already invalid and just drop the
// reference, not double-invalidate it.
if (entry) {
entry->Invalidate();
}
return pass;
}
} // namespace cereal_pilot
// Answers whether every round-trip came back intact, so that
// the caller can make that the process's exit status.
[[nodiscard]] static bool RunCerealPilotTest()
{
const bool item_pass = cereal_pilot::TestPolymorphicItem();
const bool list_pass = cereal_pilot::TestItemList();
const bool selfref_pass = cereal_pilot::TestSelfReferentialWeakPtr();
const bool creature_pass = cereal_pilot::TestRealCreature();
const bool location_pass = cereal_pilot::TestRealLocation();
const bool scheduler_pass = cereal_pilot::TestRealScheduler();
std::cout << "polymorphic item: " << (item_pass ? "PASS" : "FAIL") << std::endl;
std::cout << "XItemList round-trip: " << (list_pass ? "PASS" : "FAIL") << std::endl;
std::cout << "self-referential weak: " << (selfref_pass ? "PASS" : "FAIL") << std::endl;
std::cout << "real creature: " << (creature_pass ? "PASS" : "FAIL") << std::endl;
std::cout << "real location: " << (location_pass ? "PASS" : "FAIL") << std::endl;
std::cout << "scheduler round-trip: " << (scheduler_pass ? "PASS" : "FAIL") << std::endl;
const bool pass = item_pass && list_pass && selfref_pass && creature_pass
&& location_pass && scheduler_pass;
std::cout << "CEREAL PILOT: " << (pass ? "PASS" : "FAIL") << std::endl;
// TestRealCreature() calls Game.Create('T'), populating a whole real
// game world - unlike -test/-demo mode, this mode returns from main()
// right after this function without ever tearing that world down, so
// static/global destructors at process exit would otherwise run
// against a world nothing ever Invalidate()'d. -test/-demo mode
// always runs the scheduler for a while before their own equivalent
// teardown call - a completely fresh, never-ticked world segfaulted
// inside InvalidateAllObjects() (confirmed via gdb: a virtual call
// through a corrupted vtable pointer, i.e. a stale/dangling entry in
// the object registry), so mirror that by running a few ticks first.
for (int i = 0; i < 100; i++) {
const auto o = Game.Scheduler.Get();
// Nothing left to run: stop rather than follow a null.
if (!o) {
break;
}
o->Run();
}
XObject::InvalidateAllObjects();
return pass;
}
const char* logo_text[] = {
MSG_CYAN
" .oooooo oo oo .oooooo oo oo .oooo. ooooooo. ",
" dP' 88 88 88 dP' 88 88b 88 dP' `Yb 88 `Yb",
"d8 88 88 88 d8 88 88Yb 88 88 88 88 88",
"88 88 Y8 8Y 88 88 88 Yb 88 88 88 88 88",
"88ooooo88 Yb dY 88ooooo88 88 Yb 88 88 88 88oooodP ",
"88 88 Yb dY 88 88 88 Yb88 88 88 88 Yb ",
"88 88 YbdY 88 88 88 Y88 `8b d8' 88 Yb ",
"88 88 YY 88 88 88 88 `Y8bd8P 88 Yb",
MSG_WHITE,
" T h e L a n d o f M y s t e r y",
"",
MSG_GREEN
" version " GAME_VERSION_FULL "\n",
MSG_YELLOW,
" (c) 2000 - 2006 by Vadim Gaidukevich",
" (c) 2025 - 2026 by Joachim de Groot",
"",
MSG_YELLOW
" http://avanor.sourceforge.net",
"",
"",
};
void ShowLogo()
{
int logo_height = sizeof(logo_text) / sizeof(char*), logo_width = 0, i;
for (i = 0; i < logo_height; i++)
if (x_strlen(logo_text[i]) > logo_width) {
logo_width = x_strlen(logo_text[i]);
}
int shift_x = (size_x - logo_width) / 2;
int shift_y = (size_y - logo_height) / 2;
vClrScr();
for (i = 0; i < logo_height; i++) {
vGotoXY(shift_x, i + shift_y);
vPutS(logo_text[i]);
}
// The keys, built here rather than being the last line of logo_text,
// because [R] is only worth offering when there is something to
// restore - and that can change within a run, when an unusable saved
// game is deleted and this screen comes back.
std::string keys;
if (XArchive::HasSavedGame()) {
keys += MSG_LIGHTGRAY "[" MSG_WHITE "R" MSG_LIGHTGRAY
"] - Restore game ";
}
keys += MSG_LIGHTGRAY "[" MSG_WHITE "N" MSG_LIGHTGRAY "] - New game "
MSG_LIGHTGRAY "[" MSG_WHITE "?" MSG_LIGHTGRAY "] - read Manual "
MSG_LIGHTGRAY "[" MSG_WHITE "Esc" MSG_LIGHTGRAY "] - Exit";
// Centred on its own width rather than shifted to the logo's left edge.
vGotoXY((size_x - x_strlen(keys.c_str())) / 2, logo_height + shift_y);
vPutS(keys);
vRefresh();
}
XGame Game;
#ifdef __APPLE__
// Avanor draws on a terminal, and an application opened from Finder has
// none. What used to bridge that was a shell script beside the game in
// the bundle, with the script as the bundle's executable; the trouble is
// that this left the game a plain executable standing next to the thing
// macOS had approved rather than being it, and a plain executable can
// carry no notarisation ticket of its own - so it was assessed a second
// time, on its own, and that assessment can only be answered by asking
// Apple over the network. Approving Avanor and then opening it again
// with no network would fail.
//
// So the bundle's executable is the game, and the game is what hands
// itself to Terminal.
//
// LaunchServices sets __CFBundleIdentifier to the bundle it is starting,
// which is how this tells being opened from Finder from being run in a
// shell. Terminal sets the variable too - to its own identifier - so the
// copy it goes on to run does not bounce back here, and neither does
// `./avanor --version` in CI, which has no bundle and no terminal.
static void vRelaunchInTerminal()
{
// Must match CFBundleIdentifier in resources/Info.plist.
static const char* const BundleId = "com.avanor.avanor";
const char* const launched = getenv("__CFBundleIdentifier");
if (launched == nullptr || strcmp(launched, BundleId) != 0) {
return;
}
if (isatty(STDOUT_FILENO)) {
return;
}
char path[PATH_MAX];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) != 0) {
return;
}
execl("/usr/bin/open", "open", "-a", "Terminal", path,
static_cast<char*>(nullptr));
// Only reached if open could not be started at all. Carrying on would
// draw the game where nobody can see it, so say why instead.
std::cerr << "avanor: cannot open Terminal to play in" << std::endl;
exit(1);
}
#endif
namespace {
// Out of a world that would not load. The reason is said here rather than
// where it was found: XLua::Init() runs with the alternate screen up, and
// vFinit() takes that screen away along with everything written on it, so
// the one line worth reading would go with it.
int WorldFailed()
{
vFinit();
std::cerr << "world: " << XLua::LastError() << std::endl;
std::cerr << "avanor: the world could not be loaded - fix the script"
" above and start again" << std::endl;
return 1;
}
} // namespace
int main(int argc, char* argv[])
{
#ifdef __APPLE__
// Before the arguments are read: opened from Finder there are none
// worth reading, and this does not come back.
vRelaunchInTerminal();
#endif
argparse::ArgumentParser program("avanor", GAME_VERSION_FULL);
program.add_description("Avanor, the Land of Mystery - a roguelike.");
program.add_argument("-g", "--god")
.flag()
.help("play with a thousand extra hit points, and a say in whether you die");
program.add_argument("-s", "--seed")
.scan<'i', unsigned long>()
.metavar("N")
.help("build the world from this seed instead of the clock");
// One run does one of these, or none of them and plays the game.
auto& mode = program.add_mutually_exclusive_group();
mode.add_argument("--demo")
.flag()
.help("watch the world run itself, with no hero in it");
mode.add_argument("--test")
.flag()
.help("run the world without a hero, for finding bugs and benchmarking");
mode.add_argument("--test-save")
.flag()
.help("build a world, play a hundred turns, save it, and report");
mode.add_argument("--test-load")
.flag()
.help("restore what --test-save wrote, and report what came back");
mode.add_argument("--test-cereal")
.flag()
.help("round-trip the serialization of one location and report");
mode.add_argument("--simulate")
.metavar("NAME")
.help("play out one of world/simulations.lua's questions and report");
program.add_argument("--arg")
.metavar("N")
.scan<'i', int>()
.default_value(0)
.help("the number --simulate hands to the scenario");
// Before the screen is taken over by curses, so that --help and any
// complaint about the command line can still be read.
try {
program.parse_args(argc, argv);
} catch (const std::exception& err) {
std::cerr << err.what() << std::endl << program;
return 1;
}
// Before anything opens a file: the world, the manual and the score
// table are all named relative to where the game runs from.
vEnterDataDir();
vRandSeed(program.is_used("--seed") ? program.get<unsigned long>("--seed")
: static_cast<unsigned long>(time(nullptr)));
vInit();
vClrScr();
vHideCursor();
ShowLogo();
if (program.get<bool>("--test-cereal")) {
const bool ok = RunCerealPilotTest();
vFinit();
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
} else if (program.get<bool>("--test-save")) {
// End-to-end proof of the real XArchive::StoreGame()/RestoreGame()
// entry points, as two separate process invocations (this one,
// then -test-load in a fresh process) rather than one process
// doing both: RestoreGame() populates Game.locations[]/Scheduler
// directly, which is only safe against an empty, freshly-started
// world (exactly how production uses it, via XGame::Create('R')
// right at startup) - calling it against this process's own
// already-live Game.Create('T') world would silently orphan the
// live locations via plain shared_ptr reassignment, without ever
// Invalidate()ing them first.
if (!Game.Create('T')) {
return WorldFailed();
}
for (int i = 0; i < 100; i++) {
const auto o = Game.Scheduler.Get();
// Nothing left to run: stop rather than follow a null.
if (!o) {
break;
}
o->Run();
}
const bool ok = XArchive::StoreGame(XArchive::TEST_SLOT);
std::cout << "StoreGame: " << (ok ? "PASS" : "FAIL") << std::endl;
for (int i = 0; i < 100; i++) {
const auto o = Game.Scheduler.Get();
// Nothing left to run: stop rather than follow a null.
if (!o) {
break;
}
o->Run();
}
XObject::InvalidateAllObjects();
vFinit();
return ok ? 0 : 1;
} else if (program.get<bool>("--test-load")) {
if (!XLocation::Restoration()) {
return WorldFailed();
}
const XArchive::LoadResult loaded = XArchive::RestoreGame(XArchive::TEST_SLOT);
const bool ok = loaded.ok();
// Says which way it went wrong, so a failing run names the reason
// instead of leaving all four of them to be guessed at.
std::cout << "RestoreGame: " << (ok ? "PASS" : "FAIL");
if (!ok) {
std::cout << " (" << loaded.what() << ")";
}
std::cout << std::endl;
if (ok) {
int location_count = 0;
int monster_count = 0;
int item_count = 0;
for (auto& [key, loc] : Game.locations) {
if (!loc || !loc->map) {
continue;
}
location_count++;
for (int i = 0; i < loc->map->CellCount(); i++) {
if (loc->map->map[i].pMonster) {
monster_count++;
}
item_count += static_cast<int>(loc->map->map[i].item_list.size());
}
}
std::cout
<< " locations " << location_count
<< ", monsters " << monster_count
<< ", items " << item_count
<< ", hero " << (XCreature::main_creature ? "present" : "none")
<< std::endl;
// A floor above another level saves the name of what it
// stands on, not the pointers - those are made again after
// the load. Unlinked, every cell outside such a floor's own
// corner of the map answers nothing, and the first creature
// up there to look out of a window walks into it. Checked
// here rather than left to the turns below, which only find
// it if that creature happens to get a turn.
int unlinked = 0;
for (const auto& [key, loc] : Game.locations) {
if (!loc || loc->below.empty()) {
continue;
}
if (!loc->below_location || !loc->map || !loc->map->below) {
unlinked++;
std::cout << " " << key << " stands on '" << loc->below
<< "' but is not linked to it" << std::endl;
}
}
std::cout << "Floors above: " << (unlinked ? "FAIL" : "PASS") << std::endl;
// Long enough for the creatures of a restored world to take
// real turns in it: at 100 the first restore bug of this
// kind (an unlinked floor above) went unnoticed, and needed
// 20000 to show up on its own.
for (int i = 0; i < 20000; i++) {
const auto o = Game.Scheduler.Get();
// Nothing left to run: stop rather than follow a null.
if (!o) {
break;
}
o->Run();
}
}
XObject::InvalidateAllObjects();
vFinit();
return ok ? 0 : 1;
} else if (program.is_used("--simulate")) {
if (!Game.Create('T')) {
return WorldFailed();
}
const bool ran = RunSimulation(program.get<std::string>("--simulate"),
program.get<int>("--arg"));
// Out without tearing the world down again: a simulation is a
// measurement, and its answer has already been printed.
std::cout.flush();
std::cerr.flush();
_exit(ran ? 0 : 1);
} else if (program.get<bool>("--test")) {
if (!Game.Create('T')) {
return WorldFailed();
}
Game.RunWithoutHero();
} else if (program.get<bool>("--demo")) {
if (!Game.Create('D')) {
return WorldFailed();
}
Game.RunDemo();
} else {
Game.isGodMode = program.get<bool>("--god");
// The title screen is offered again after a saved game is refused
// without anything being built - the player has just been given
// the chance to delete it, and the menu they come back to no
// longer offers to restore what is no longer there.
while (true) {
char ch = 0;
while (true) {
// Read the key whole before narrowing it: the extended
// codes do not fit in a char, and KEY_RESIZE truncates to
// 'Z', which is the key that leaves the game.
const int key = vGetch();
if (key == KEY_RESIZE) {
ShowLogo();
continue;
}
ch = static_cast<char>(toupper(key));
if (ch == '?') {
XManual man;
man.Run();
ShowLogo();
continue;
}
if (ch == KEY_ESC || ch == 'Z') {
vFinit();
return 0;
}
// 'R' only while the menu is actually offering it: with no
// save on disk there is nothing for it to restore, and
// answering an unlisted key would say "there is not a
// saved game to load" to somebody who was never invited
// to ask.
if (ch == 'N' || (ch == 'R' && XArchive::HasSavedGame())) {
break;
}
}
Game.back_to_menu = false;
// False for a restore that produced nothing playable, which
// has already said so on screen, or for a world that would
// not load, which has not - the screen it would have said it
// on is about to be taken away.
if (Game.Create(ch)) {
Game.Run();
break;
}
if (!XLua::LastError().empty()) {
return WorldFailed();
}
if (!Game.back_to_menu) {
break;
}
ShowLogo();
}
}
vFinit();
return 0;
}