forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
792 lines (741 loc) · 27.1 KB
/
main.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
/* Entry point and main loop for Cataclysm
*/
#include <array>
#include <clocale>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <exception>
#include <functional>
#include <iostream>
#include <locale>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#if defined(_WIN32)
# include "platform_win.h"
#else
# include <csignal>
#endif
#include "color.h"
#include "crash.h"
#include "cursesdef.h"
#include "debug.h"
#include "filesystem.h"
#include "game.h"
#include "game_ui.h"
#include "init.h"
#include "input.h"
#include "language.h"
#include "loading_ui.h"
#include "runtime_handlers.h"
#include "string_formatter.h"
#include "main_menu.h"
#include "mapsharing.h"
#include "options.h"
#include "output.h"
#include "path_info.h"
#include "rng.h"
#include "type_id.h"
#include "ui_manager.h"
class ui_adaptor;
#if defined(TILES)
# define SDL_MAIN_HANDLED
# include "sdl_wrappers.h"
# if defined(_MSC_VER) && defined(USE_VCPKG)
# include <SDL2/SDL_version.h>
# else
# include <SDL_version.h>
# endif
#endif
#if defined(__ANDROID__)
#include <SDL_filesystem.h>
#include <SDL_keyboard.h>
#include <SDL_system.h>
#include <android/log.h>
#include <unistd.h>
// Taken from: https://codelab.wordpress.com/2014/11/03/how-to-use-standard-output-streams-for-logging-in-android-apps/
// Force Android standard output to adb logcat output
static int pfd[2];
static pthread_t thr;
static const char *tag = "cdda";
static void *thread_func( void * )
{
ssize_t rdsz;
char buf[128];
for( ;; ) {
if( ( ( rdsz = read( pfd[0], buf, sizeof buf - 1 ) ) > 0 ) ) {
if( buf[rdsz - 1] == '\n' ) {
--rdsz;
}
buf[rdsz] = 0; /* add null-terminator */
__android_log_write( ANDROID_LOG_DEBUG, tag, buf );
}
}
return 0;
}
int start_logger( const char *app_name )
{
tag = app_name;
/* make stdout line-buffered and stderr unbuffered */
setvbuf( stdout, 0, _IOLBF, 0 );
setvbuf( stderr, 0, _IONBF, 0 );
/* create the pipe and redirect stdout and stderr */
pipe( pfd );
dup2( pfd[1], 1 );
dup2( pfd[1], 2 );
/* spawn the logging thread */
if( pthread_create( &thr, 0, thread_func, 0 ) == -1 ) {
return -1;
}
pthread_detach( thr );
return 0;
}
#endif //__ANDROID__
#if !defined(_WIN32)
#if defined(TILES)
[[ noreturn ]]
static void signal_handler( int )
{
exit_handler( 0 );
}
#else
static void signal_handler( int signal )
{
if( signal == SIGINT ) {
const int old_timeout = inp_mngr.get_timeout();
inp_mngr.reset_timeout();
bool confirmed = query_yn( _( "Really Quit? All unsaved changes will be lost." ) );
inp_mngr.set_timeout( old_timeout );
ui_manager::redraw_invalidated();
catacurses::doupdate();
if( !confirmed ) {
return;
}
}
exit_handler( 0 );
}
#endif //defined(TILES)
#endif //!defined(_WIN32)
/**
* Report fatal error in a user-friendly way
* (stderr or a message box, depending on build.)
*/
static void report_fatal_error( const std::string &msg )
{
#if defined(TILES)
if( test_mode ) {
#endif
std::cerr << "Cataclysm BN: Fatal error" << std::endl << msg << std::endl;
#if defined(TILES)
} else {
SDL_ShowSimpleMessageBox(
SDL_MESSAGEBOX_ERROR,
"Cataclysm BN: Fatal error",
msg.c_str(),
nullptr
);
}
#endif
}
namespace
{
struct arg_handler {
//! Handler function to be invoked when this argument is encountered. The handler will be
//! called with the number of parameters after the flag was encountered, along with the array
//! of following parameters. It must return an integer indicating how many parameters were
//! consumed by the call or -1 to indicate that a required argument was missing.
using handler_method = std::function<int ( int, const char ** )>;
const char *flag; //!< The commandline parameter to handle (e.g., "--seed").
const char *param_documentation; //!< Human readable description of this arguments parameter.
const char *documentation; //!< Human readable documentation for this argument.
const char *help_group; //!< Section of the help message in which to include this argument.
handler_method handler; //!< The callback to be invoked when this argument is encountered.
};
void printHelpMessage( const arg_handler *first_pass_arguments, size_t num_first_pass_arguments,
const arg_handler *second_pass_arguments, size_t num_second_pass_arguments );
} // namespace
#if defined(USE_WINMAIN)
int APIENTRY WinMain( HINSTANCE /* hInstance */, HINSTANCE /* hPrevInstance */,
LPSTR /* lpCmdLine */, int /* nCmdShow */ )
{
int argc = __argc;
char **argv = __argv;
#elif defined(__ANDROID__)
extern "C" int SDL_main( int argc, char **argv ) {
#else
int main( int argc, char *argv[] )
{
#endif
init_crash_handlers();
int seed = time( nullptr );
bool verifyexit = false;
bool check_mods = false;
std::string dump;
dump_mode dmode = dump_mode::TSV;
std::vector<std::string> opts;
std::string world; /** if set try to load first save in this world on startup */
#if defined(__ANDROID__)
// Start the standard output logging redirector
start_logger( "cdda" );
// On Android first launch, we copy all data files from the APK into the app's writeable folder so std::io stuff works.
// Use the external storage so it's publicly modifiable data (so users can mess with installed data, save games etc.)
std::string external_storage_path( SDL_AndroidGetExternalStoragePath() );
if( external_storage_path.back() != '/' ) {
external_storage_path += '/';
}
PATH_INFO::init_base_path( external_storage_path );
#else
// Set default file paths
#if defined(PREFIX)
#define Q(STR) #STR
#define QUOTE(STR) Q(STR)
PATH_INFO::init_base_path( std::string( QUOTE( PREFIX ) ) );
#else
PATH_INFO::init_base_path( "" );
#endif
#endif
#if defined(__ANDROID__)
PATH_INFO::init_user_dir( external_storage_path );
#else
# if defined(USE_HOME_DIR) || defined(USE_XDG_DIR)
PATH_INFO::init_user_dir( "" );
# else
PATH_INFO::init_user_dir( "./" );
# endif
#endif
PATH_INFO::set_standard_filenames();
MAP_SHARING::setDefaults();
{
const char *section_default = nullptr;
const char *section_map_sharing = "Map sharing";
const char *section_user_directory = "User directories";
const std::array<arg_handler, 13> first_pass_arguments = {{
{
"--seed", "<string of letters and or numbers>",
"Sets the random number generator's seed value",
section_default,
[&seed]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
const unsigned char *hash_input = reinterpret_cast<const unsigned char *>( params[0] );
seed = djb2_hash( hash_input );
return 1;
}
},
{
"--jsonverify", nullptr,
"Checks the CDDA json files",
section_default,
[&verifyexit]( int, const char ** ) -> int {
verifyexit = true;
return 0;
}
},
{
"--check-mods", "[mods…]",
"Checks the json files belonging to CDDA mods",
section_default,
[&check_mods, &opts]( int n, const char *params[] ) -> int {
check_mods = true;
test_mode = true;
for( int i = 0; i < n; ++i )
{
opts.emplace_back( params[ i ] );
}
return 0;
}
},
{
"--dump-stats", "<what> [mode = TSV] [opts…]",
"Dumps item stats",
section_default,
[&dump, &dmode, &opts]( int n, const char *params[] ) -> int {
if( n < 1 )
{
return -1;
}
test_mode = true;
dump = params[ 0 ];
for( int i = 2; i < n; ++i )
{
opts.emplace_back( params[ i ] );
}
if( n >= 2 )
{
if( !strcmp( params[ 1 ], "TSV" ) ) {
dmode = dump_mode::TSV;
return 0;
} else if( !strcmp( params[ 1 ], "HTML" ) ) {
dmode = dump_mode::HTML;
return 0;
} else {
return -1;
}
}
return 0;
}
},
{
"--world", "<name>",
"Load world",
section_default,
[&world]( int n, const char *params[] ) -> int {
if( n < 1 )
{
return -1;
}
world = params[0];
return 1;
}
},
{
"--basepath", "<path>",
"Base path for all game data subdirectories",
section_default,
[]( int num_args, const char **params )
{
if( num_args < 1 ) {
return -1;
}
PATH_INFO::init_base_path( params[0] );
PATH_INFO::set_standard_filenames();
return 1;
}
},
{
"--shared", nullptr,
"Activates the map-sharing mode",
section_map_sharing,
[]( int, const char ** ) -> int {
MAP_SHARING::setSharing( true );
MAP_SHARING::setCompetitive( true );
MAP_SHARING::setWorldmenu( false );
return 0;
}
},
{
"--username", "<name>",
"Instructs map-sharing code to use this name for your character.",
section_map_sharing,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
MAP_SHARING::setUsername( params[0] );
return 1;
}
},
{
"--addadmin", "<username>",
"Instructs map-sharing code to use this name for your character and give you "
"access to the cheat functions.",
section_map_sharing,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
MAP_SHARING::addAdmin( params[0] );
return 1;
}
},
{
"--adddebugger", "<username>",
"Informs map-sharing code that you're running inside a debugger",
section_map_sharing,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
MAP_SHARING::addDebugger( params[0] );
return 1;
}
},
{
"--competitive", nullptr,
"Instructs map-sharing code to disable access to the in-game cheat functions",
section_map_sharing,
[]( int, const char ** ) -> int {
MAP_SHARING::setCompetitive( true );
return 0;
}
},
{
"--userdir", "<path>",
// NOLINTNEXTLINE(cata-text-style): the dot is not a period
"Base path for user-overrides to files from the ./data directory and named below",
section_user_directory,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::init_user_dir( params[0] );
PATH_INFO::set_standard_filenames();
return 1;
}
},
{
"--dont-debugmsg", nullptr,
"If set, no debug messages will be printed",
section_default,
[]( int, const char ** ) -> int {
dont_debugmsg = true;
return 0;
}
}
}
};
// The following arguments are dependent on one or more of the previous flags and are run
// in a second pass.
const std::array<arg_handler, 8> second_pass_arguments = {{
{
"--worldmenu", nullptr,
"Enables the world menu in the map-sharing code",
section_map_sharing,
[]( int, const char ** ) -> int {
MAP_SHARING::setWorldmenu( true );
return true;
}
},
{
"--datadir", "<directory name>",
"Sub directory from which game data is loaded",
nullptr,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_datadir( params[0] );
return 1;
}
},
{
"--savedir", "<directory name>",
"Subdirectory for game saves",
section_user_directory,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_savedir( params[0] );
return 1;
}
},
{
"--configdir", "<directory name>",
"Subdirectory for game configuration",
section_user_directory,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_config_dir( params[0] );
return 1;
}
},
{
"--memorialdir", "<directory name>",
"Subdirectory for memorials",
section_user_directory,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_memorialdir( params[0] );
return 1;
}
},
{
"--optionfile", "<filename>",
"Name of the options file within the configdir",
section_user_directory,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_options( params[0] );
return 1;
}
},
{
"--autopickupfile", "<filename>",
"Name of the autopickup options file within the configdir",
nullptr,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_autopickup( params[0] );
return 1;
}
},
{
"--motdfile", "<filename>",
"Name of the message of the day file within the motd directory",
nullptr,
[]( int num_args, const char **params ) -> int {
if( num_args < 1 )
{
return -1;
}
PATH_INFO::set_motd( params[0] );
return 1;
}
},
}
};
// Process CLI arguments.
const size_t num_first_pass_arguments =
sizeof( first_pass_arguments ) / sizeof( first_pass_arguments[0] );
const size_t num_second_pass_arguments =
sizeof( second_pass_arguments ) / sizeof( second_pass_arguments[0] );
int saved_argc = --argc; // skip program name
const char **saved_argv = const_cast<const char **>( ++argv );
while( argc ) {
if( !strcmp( argv[0], "--help" ) ) {
printHelpMessage( first_pass_arguments.data(), num_first_pass_arguments,
second_pass_arguments.data(), num_second_pass_arguments );
return 0;
} else {
bool arg_handled = false;
for( size_t i = 0; i < num_first_pass_arguments; ++i ) {
auto &arg_handler = first_pass_arguments[i];
if( !strcmp( argv[0], arg_handler.flag ) ) {
argc--;
argv++;
int args_consumed = arg_handler.handler( argc, const_cast<const char **>( argv ) );
if( args_consumed < 0 ) {
cata_printf( "Failed parsing parameter '%s'\n", *( argv - 1 ) );
exit( 1 );
}
argc -= args_consumed;
argv += args_consumed;
arg_handled = true;
break;
}
}
// Skip other options.
if( !arg_handled ) {
--argc;
++argv;
}
}
}
while( saved_argc ) {
bool arg_handled = false;
for( size_t i = 0; i < num_second_pass_arguments; ++i ) {
auto &arg_handler = second_pass_arguments[i];
if( !strcmp( saved_argv[0], arg_handler.flag ) ) {
--saved_argc;
++saved_argv;
int args_consumed = arg_handler.handler( saved_argc, saved_argv );
if( args_consumed < 0 ) {
cata_printf( "Failed parsing parameter '%s'\n", *( argv - 1 ) );
exit( 1 );
}
saved_argc -= args_consumed;
saved_argv += args_consumed;
arg_handled = true;
break;
}
}
// Ignore unknown options.
if( !arg_handled ) {
--saved_argc;
++saved_argv;
}
}
}
if( !dir_exist( PATH_INFO::datadir() ) ) {
std::string msg = string_format(
"Can't find directory \"%s\"\n"
"Please ensure the current working directory is correct.\n"
"Perhaps you meant to start \"cataclysm-launcher\"?\n",
PATH_INFO::datadir().c_str()
);
report_fatal_error( msg );
exit( 1 );
}
const auto check_dir_good = []( const std::string & dir ) {
if( !assure_dir_exist( dir ) ) {
std::string msg = string_format(
"Can't open or create \"%s\"\n"
"Please ensure you have write permission.\n",
dir.c_str()
);
report_fatal_error( msg );
exit( 1 );
}
if( !can_write_to_dir( dir ) ) {
std::string msg = string_format(
"Can't write to \"%s\"\n"
"Please ensure you have write permission and free storage space.\n",
dir.c_str()
);
report_fatal_error( msg );
exit( 1 );
}
};
check_dir_good( PATH_INFO::user_dir() );
check_dir_good( PATH_INFO::config_dir() );
check_dir_good( PATH_INFO::savedir() );
setupDebug( DebugOutput::file );
if( !init_language_system() ) {
exit_handler( -999 );
}
#if defined(TILES)
SDL_version compiled;
SDL_VERSION( &compiled );
DebugLog( DL::Info, DC::Main ) << "SDL version used during compile is "
<< static_cast<int>( compiled.major ) << "."
<< static_cast<int>( compiled.minor ) << "."
<< static_cast<int>( compiled.patch );
SDL_version linked;
SDL_GetVersion( &linked );
DebugLog( DL::Info, DC::Main ) << "SDL version used during linking and in runtime is "
<< static_cast<int>( linked.major ) << "."
<< static_cast<int>( linked.minor ) << "."
<< static_cast<int>( linked.patch );
#endif
#if !defined(TILES)
get_options().init();
get_options().load();
set_language(); // Have to set locale before initializing ncurses
#endif
// in test mode don't initialize curses to avoid escape sequences being inserted into output stream
if( !test_mode ) {
try {
// set minimum FULL_SCREEN sizes
FULL_SCREEN_WIDTH = 80;
FULL_SCREEN_HEIGHT = 24;
catacurses::init_interface();
} catch( const std::exception &err ) {
// can't use any curses function as it has not been initialized
std::cerr << "Error while initializing the interface: " << err.what() << std::endl;
DebugLog( DL::Error, DC::Main ) << "Error while initializing the interface: " << err.what();
return 1;
}
}
#if defined(TILES)
if( test_mode ) {
get_options().init();
get_options().load();
}
set_language();
#endif
rng_set_engine_seed( seed );
g = std::make_unique<game>();
// First load and initialize everything that does not
// depend on the mods.
try {
g->load_static_data();
if( verifyexit ) {
exit_handler( 0 );
}
if( !dump.empty() ) {
init_colors();
exit( g->dump_stats( dump, dmode, opts ) ? 0 : 1 );
}
if( check_mods ) {
init_colors();
loading_ui ui( false );
const std::vector<mod_id> mods( opts.begin(), opts.end() );
if( init::check_mods_for_errors( ui, mods ) ) {
exit( 0 );
} else {
exit( 1 );
}
}
} catch( const std::exception &err ) {
debugmsg( "%s", err.what() );
exit_handler( -999 );
}
// Now we do the actual game.
game_ui::init_ui();
catacurses::curs_set( 0 ); // Invisible cursor here, because MAPBUFFER.load() is crash-prone
#if !defined(_WIN32)
struct sigaction sigIntHandler;
sigIntHandler.sa_handler = signal_handler;
sigemptyset( &sigIntHandler.sa_mask );
sigIntHandler.sa_flags = 0;
sigaction( SIGINT, &sigIntHandler, nullptr );
#endif
prompt_select_lang_on_startup();
replay_buffered_debugmsg_prompts();
while( true ) {
if( !world.empty() ) {
if( !g->load( world ) ) {
break;
}
world.clear(); // ensure quit returns to opening screen
} else {
main_menu menu;
if( !menu.opening_screen() ) {
break;
}
}
shared_ptr_fast<ui_adaptor> ui = g->create_or_get_main_ui_adaptor();
while( !g->do_turn() );
}
exit_handler( -999 );
return 0;
}
namespace
{
void printHelpMessage( const arg_handler *first_pass_arguments,
size_t num_first_pass_arguments,
const arg_handler *second_pass_arguments,
size_t num_second_pass_arguments )
{
// Group all arguments by help_group.
std::multimap<std::string, const arg_handler *> help_map;
for( size_t i = 0; i < num_first_pass_arguments; ++i ) {
std::string help_group;
if( first_pass_arguments[i].help_group ) {
help_group = first_pass_arguments[i].help_group;
}
help_map.insert( std::make_pair( help_group, &first_pass_arguments[i] ) );
}
for( size_t i = 0; i < num_second_pass_arguments; ++i ) {
std::string help_group;
if( second_pass_arguments[i].help_group ) {
help_group = second_pass_arguments[i].help_group;
}
help_map.insert( std::make_pair( help_group, &second_pass_arguments[i] ) );
}
cata_printf( "Command line parameters:\n" );
std::string current_help_group;
auto it = help_map.begin();
auto it_end = help_map.end();
for( ; it != it_end; ++it ) {
if( it->first != current_help_group ) {
current_help_group = it->first;
cata_printf( "\n%s\n", current_help_group.c_str() );
}
const arg_handler *handler = it->second;
cata_printf( "%s", handler->flag );
if( handler->param_documentation ) {
cata_printf( " %s", handler->param_documentation );
}
cata_printf( "\n" );
if( handler->documentation ) {
cata_printf( " %s\n", handler->documentation );
}
}
}
} // namespace