Files
@ r2302:369e3d3adaa8
Branch filter:
Location: cpp/openttd-patchpack/source/openttd.c
r2302:369e3d3adaa8
30.4 KiB
text/x-c
(svn r2826) Remove another write-only variable, thanks glx
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 | /* $Id$ */
#include "stdafx.h"
#include "string.h"
#include "table/strings.h"
#include "debug.h"
#include "driver.h"
#include "saveload.h"
#include "strings.h"
#include "map.h"
#include "tile.h"
#define VARDEF
#include "openttd.h"
#include "functions.h"
#include "mixer.h"
#include "spritecache.h"
#include "gfx.h"
#include "gui.h"
#include "station.h"
#include "vehicle.h"
#include "viewport.h"
#include "window.h"
#include "player.h"
#include "command.h"
#include "town.h"
#include "industry.h"
#include "news.h"
#include "engine.h"
#include "sound.h"
#include "economy.h"
#include "fileio.h"
#include "hal.h"
#include "airport.h"
#include "console.h"
#include "screenshot.h"
#include "network.h"
#include "signs.h"
#include "depot.h"
#include "waypoint.h"
#include <stdarg.h>
#ifdef GPMI
#include <gpmi.h>
#include <gpmi/packages/paths.h>
#endif /* GPMI */
void GenerateWorld(int mode, uint size_x, uint size_y);
void CallLandscapeTick(void);
void IncreaseDate(void);
void RunOtherPlayersLoop(void);
void DoPaletteAnimations(void);
void MusicLoop(void);
void ResetMusic(void);
void InitializeStations(void);
void DeleteAllPlayerStations(void);
extern void SetDifficultyLevel(int mode, GameOptions *gm_opt);
extern void DoStartupNewPlayer(bool is_ai);
extern void ShowOSErrorBox(const char *buf);
bool LoadSavegame(const char *filename);
bool _dbg_screen_rect;
/* TODO: usrerror() for errors which are not of an internal nature but
* caused by the user, i.e. missing files or fatal configuration errors.
* Post-0.4.0 since Celestar doesn't want this in SVN before. --pasky */
void CDECL error(const char *s, ...) {
va_list va;
char buf[512];
va_start(va, s);
vsprintf(buf, s, va);
va_end(va);
ShowOSErrorBox(buf);
if (_video_driver)
_video_driver->stop();
assert(0);
exit(1);
}
void CDECL ShowInfoF(const char *str, ...)
{
va_list va;
char buf[1024];
va_start(va, str);
vsprintf(buf, str, va);
va_end(va);
ShowInfo(buf);
}
void *ReadFileToMem(const char *filename, size_t *lenp, size_t maxsize)
{
FILE *in;
byte *mem;
size_t len;
in = fopen(filename, "rb");
if (in == NULL)
return NULL;
fseek(in, 0, SEEK_END);
len = ftell(in);
fseek(in, 0, SEEK_SET);
if (len > maxsize || (mem = malloc(len + 1)) == NULL) {
fclose(in);
return NULL;
}
mem[len] = 0;
if (fread(mem, len, 1, in) != 1) {
fclose(in);
free(mem);
return NULL;
}
fclose(in);
*lenp = len;
return mem;
}
static void showhelp(void)
{
char buf[4096], *p;
p = strecpy(buf,
"Command line options:\n"
" -v drv = Set video driver (see below)\n"
" -s drv = Set sound driver (see below)\n"
" -m drv = Set music driver (see below)\n"
" -r res = Set resolution (for instance 800x600)\n"
" -h = Display this help text\n"
" -t date = Set starting date\n"
" -d [[fac=]lvl[,...]]= Debug mode\n"
" -l lng = Select Language\n"
" -e = Start Editor\n"
" -g [savegame] = Start new/save game immediately\n"
" -G seed = Set random seed\n"
" -n [ip#player:port] = Start networkgame\n"
" -D = Start dedicated server\n"
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
" -f = Fork into the background (dedicated only)\n"
#endif
" -i = Force to use the DOS palette (use this if you see a lot of pink)\n"
" -p #player = Player as #player (deprecated) (network only)\n"
" -c config_file = Use 'config_file' instead of 'openttd.cfg'\n",
lastof(buf)
);
GetDriverList(p);
ShowInfo(buf);
}
typedef struct {
char *opt;
int numleft;
char **argv;
const char *options;
char *cont;
} MyGetOptData;
static void MyGetOptInit(MyGetOptData *md, int argc, char **argv, const char *options)
{
md->cont = NULL;
md->numleft = argc;
md->argv = argv;
md->options = options;
}
static int MyGetOpt(MyGetOptData *md)
{
char *s,*r,*t;
if ((s=md->cont) != NULL)
goto md_continue_here;
while(true) {
if (--md->numleft < 0)
return -1;
s = *md->argv++;
if (*s == '-') {
md_continue_here:;
s++;
if (*s != 0) {
// Found argument, try to locate it in options.
if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
// ERROR!
return -2;
}
if (r[1] == ':') {
// Item wants an argument. Check if the argument follows, or if it comes as a separate arg.
if (!*(t = s + 1)) {
// It comes as a separate arg. Check if out of args?
if (--md->numleft < 0 || *(t = *md->argv) == '-') {
// Check if item is optional?
if (r[2] != ':')
return -2;
md->numleft++;
t = NULL;
} else {
md->argv++;
}
}
md->opt = t;
md->cont = NULL;
return *s;
}
md->opt = NULL;
md->cont = s;
return *s;
}
} else {
// This is currently not supported.
return -2;
}
}
}
static void ParseResolution(int res[2], char *s)
{
char *t = strchr(s, 'x');
if (t == NULL) {
ShowInfoF("Invalid resolution '%s'", s);
return;
}
res[0] = clamp(strtoul(s, NULL, 0), 64, MAX_SCREEN_WIDTH);
res[1] = clamp(strtoul(t + 1, NULL, 0), 64, MAX_SCREEN_HEIGHT);
}
static void InitializeDynamicVariables(void)
{
/* Dynamic stuff needs to be initialized somewhere... */
_station_sort = NULL;
_vehicle_sort = NULL;
_town_sort = NULL;
_industry_sort = NULL;
}
static void UnInitializeDynamicVariables(void)
{
/* Dynamic stuff needs to be free'd somewhere... */
CleanPool(&_town_pool);
CleanPool(&_industry_pool);
CleanPool(&_station_pool);
CleanPool(&_vehicle_pool);
CleanPool(&_sign_pool);
CleanPool(&_order_pool);
free(_station_sort);
free(_vehicle_sort);
free(_town_sort);
free(_industry_sort);
}
static void UnInitializeGame(void)
{
UnInitWindowSystem();
UnInitNewgrEngines();
free(_config_file);
}
static void LoadIntroGame(void)
{
char filename[256];
_game_mode = GM_MENU;
CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
_opt_ptr = &_opt_newgame;
GfxLoadSprites();
LoadStringWidthTable();
// Setup main window
ResetWindowSystem();
SetupColorsAndInitialWindow();
// Generate a world.
sprintf(filename, "%sopntitle.dat", _path.data_dir);
if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
#if defined SECOND_DATA_DIR
sprintf(filename, "%sopntitle.dat", _path.second_data_dir);
if (SaveOrLoad(filename, SL_LOAD) != SL_OK)
#endif
GenerateWorld(1, 64, 64); // if failed loading, make empty world.
}
_pause = 0;
_local_player = 0;
MarkWholeScreenDirty();
// Play main theme
if (_music_driver->is_song_playing()) ResetMusic();
}
#if defined(UNIX) && !defined(__MORPHOS__)
extern void DedicatedFork(void);
#endif
extern void CheckExternalFiles(void);
int ttd_main(int argc, char* argv[])
{
MyGetOptData mgo;
int i;
bool network = false;
char *network_conn = NULL;
char *language = NULL;
const char *optformat;
char musicdriver[16], sounddriver[16], videodriver[16];
int resolution[2] = {0,0};
uint startdate = -1;
bool dedicated;
musicdriver[0] = sounddriver[0] = videodriver[0] = 0;
_game_mode = GM_MENU;
_switch_mode = SM_MENU;
_switch_mode_errorstr = INVALID_STRING_ID;
_dedicated_forks = false;
dedicated = false;
_config_file = NULL;
// The last param of the following function means this:
// a letter means: it accepts that param (e.g.: -h)
// a ':' behind it means: it need a param (e.g.: -m<driver>)
// a '::' behind it means: it can optional have a param (e.g.: -d<debug>)
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
optformat = "m:s:v:hDfn::l:eit:d::r:g::G:p:c:";
#else
optformat = "m:s:v:hDn::l:eit:d::r:g::G:p:c:"; // no fork option
#endif
MyGetOptInit(&mgo, argc-1, argv+1, optformat);
while ((i = MyGetOpt(&mgo)) != -1) {
switch(i) {
case 'm': ttd_strlcpy(musicdriver, mgo.opt, sizeof(musicdriver)); break;
case 's': ttd_strlcpy(sounddriver, mgo.opt, sizeof(sounddriver)); break;
case 'v': ttd_strlcpy(videodriver, mgo.opt, sizeof(videodriver)); break;
case 'D': {
sprintf(musicdriver,"null");
sprintf(sounddriver,"null");
sprintf(videodriver,"dedicated");
dedicated = true;
} break;
case 'f': {
_dedicated_forks = true;
}; break;
case 'n': {
network = true;
if (mgo.opt)
// Optional, you can give an IP
network_conn = mgo.opt;
else
network_conn = NULL;
} break;
case 'r': ParseResolution(resolution, mgo.opt); break;
case 'l': {
language = mgo.opt;
} break;
case 't': {
startdate = atoi(mgo.opt);
} break;
case 'd': {
#if defined(WIN32)
CreateConsole();
#endif
if (mgo.opt)
SetDebugString(mgo.opt);
} break;
case 'e': _switch_mode = SM_EDITOR; break;
case 'i': _use_dos_palette = true; break;
case 'g':
if (mgo.opt) {
strcpy(_file_to_saveload.name, mgo.opt);
_switch_mode = SM_LOAD;
} else
_switch_mode = SM_NEWGAME;
break;
case 'G':
_random_seeds[0][0] = atoi(mgo.opt);
break;
case 'p': {
int i = atoi(mgo.opt);
// Play as an other player in network games
if (IS_INT_INSIDE(i, 1, MAX_PLAYERS)) _network_playas = i;
break;
}
case 'c':
_config_file = strdup(mgo.opt);
break;
case -2:
case 'h':
showhelp();
return 0;
}
}
DeterminePaths();
CheckExternalFiles();
#ifdef GPMI
/* Set the debug proc */
gpmi_debug_proc = &gpmi_debug_openttd;
/* Initialize GPMI */
gpmi_init();
/* Add our paths so we can find our own packages */
gpmi_path_append(&gpmi_path_modules, "gpmi/modules");
gpmi_path_append(&gpmi_path_packages, "gpmi/packages");
#endif /* GPMI */
#if defined(UNIX) && !defined(__MORPHOS__)
// We must fork here, or we'll end up without some resources we need (like sockets)
if (_dedicated_forks)
DedicatedFork();
#endif
LoadFromConfig();
CheckConfig();
LoadFromHighScore();
// override config?
if (musicdriver[0]) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
if (sounddriver[0]) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
if (videodriver[0]) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
if (resolution[0]) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
if (startdate != (uint)-1) _patches.starting_date = startdate;
if (_dedicated_forks && !dedicated)
_dedicated_forks = false;
// enumerate language files
InitializeLanguagePacks();
// initialize screenshot formats
InitializeScreenshotFormats();
// initialize airport state machines
InitializeAirports();
/* initialize all variables that are allocated dynamically */
InitializeDynamicVariables();
// Sample catalogue
DEBUG(misc, 1) ("Loading sound effects...");
MxInitialize(11025);
SoundInitialize("sample.cat");
// This must be done early, since functions use the InvalidateWindow* calls
InitWindowSystem();
GfxLoadSprites();
LoadStringWidthTable();
DEBUG(misc, 1) ("Loading drivers...");
LoadDriver(SOUND_DRIVER, _ini_sounddriver);
LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
_savegame_sort_order = 1; // default sorting of savegames is by date, newest first
#ifdef ENABLE_NETWORK
// initialize network-core
NetworkStartUp();
#endif /* ENABLE_NETWORK */
_opt_ptr = &_opt_newgame;
/* XXX - ugly hack, if diff_level is 9, it means we got no setting from the config file */
if (_opt_newgame.diff_level == 9)
SetDifficultyLevel(0, &_opt_newgame);
// initialize the ingame console
IConsoleInit();
InitializeGUI();
IConsoleCmdExec("exec scripts/autoexec.scr 0");
GenerateWorld(1, 64, 64); // Make the viewport initialization happy
#ifdef ENABLE_NETWORK
if ((network) && (_network_available)) {
if (network_conn != NULL) {
const char *port = NULL;
const char *player = NULL;
uint16 rport;
rport = NETWORK_DEFAULT_PORT;
ParseConnectionString(&player, &port, network_conn);
if (player != NULL) _network_playas = atoi(player);
if (port != NULL) rport = atoi(port);
LoadIntroGame();
_switch_mode = SM_NONE;
NetworkClientConnectGame(network_conn, rport);
}
}
#endif /* ENABLE_NETWORK */
_video_driver->main_loop();
WaitTillSaved();
IConsoleFree();
#ifdef ENABLE_NETWORK
if (_network_available) {
// Shut down the network and close any open connections
NetworkDisconnect();
NetworkUDPClose();
NetworkShutDown();
}
#endif /* ENABLE_NETWORK */
_video_driver->stop();
_music_driver->stop();
_sound_driver->stop();
SaveToConfig();
SaveToHighScore();
// uninitialize airport state machines
UnInitializeAirports();
/* uninitialize variables that are allocated dynamic */
UnInitializeDynamicVariables();
/* Close all and any open filehandles */
FioCloseAll();
UnInitializeGame();
return 0;
}
static void ShowScreenshotResult(bool b)
{
if (b) {
SetDParamStr(0, _screenshot_name);
ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
} else {
ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
}
}
static void MakeNewGame(void)
{
_game_mode = GM_NORMAL;
// Copy in game options
_opt_ptr = &_opt;
memcpy(_opt_ptr, &_opt_newgame, sizeof(GameOptions));
GfxLoadSprites();
// Reinitialize windows
ResetWindowSystem();
LoadStringWidthTable();
SetupColorsAndInitialWindow();
// Randomize world
GenerateWorld(0, 1<<_patches.map_x, 1<<_patches.map_y);
// In a dedicated server, the server does not play
if (_network_dedicated) {
_local_player = OWNER_SPECTATOR;
} else {
// Create a single player
DoStartupNewPlayer(false);
_local_player = 0;
_current_player = _local_player;
DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_REPLACE_VEHICLE);
}
MarkWholeScreenDirty();
}
static void MakeNewEditorWorld(void)
{
_game_mode = GM_EDITOR;
// Copy in game options
_opt_ptr = &_opt;
memcpy(_opt_ptr, &_opt_newgame, sizeof(GameOptions));
GfxLoadSprites();
// Re-init the windowing system
ResetWindowSystem();
// Create toolbars
SetupColorsAndInitialWindow();
// Startup the game system
GenerateWorld(1, 1<<_patches.map_x, 1<<_patches.map_y);
_local_player = OWNER_NONE;
MarkWholeScreenDirty();
}
void StartupPlayers(void);
void StartupDisasters(void);
/**
* Start Scenario starts a new game based on a scenario.
* Eg 'New Game' --> select a preset scenario
* This starts a scenario based on your current difficulty settings
*/
static void StartScenario(void)
{
_game_mode = GM_NORMAL;
// invalid type
if (_file_to_saveload.mode == SL_INVALID) {
printf("Savegame is obsolete or invalid format: %s\n", _file_to_saveload.name);
ShowErrorMessage(_error_message, STR_4009_GAME_LOAD_FAILED, 0, 0);
_game_mode = GM_MENU;
return;
}
GfxLoadSprites();
// Reinitialize windows
ResetWindowSystem();
LoadStringWidthTable();
SetupColorsAndInitialWindow();
// Load game
if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
LoadIntroGame();
ShowErrorMessage(_error_message, STR_4009_GAME_LOAD_FAILED, 0, 0);
}
_opt_ptr = &_opt;
memcpy(&_opt_ptr->diff, &_opt_newgame.diff, sizeof(GameDifficulty));
_opt.diff_level = _opt_newgame.diff_level;
// Inititalize data
StartupPlayers();
StartupEngines();
StartupDisasters();
_local_player = 0;
_current_player = _local_player;
DoCommandP(0, (_patches.autorenew << 15 ) | (_patches.autorenew_months << 16) | 4, _patches.autorenew_money, NULL, CMD_REPLACE_VEHICLE);
MarkWholeScreenDirty();
}
bool SafeSaveOrLoad(const char *filename, int mode, int newgm)
{
byte ogm = _game_mode;
int r;
_game_mode = newgm;
r = SaveOrLoad(filename, mode);
if (r == SL_REINIT) {
if (ogm == GM_MENU)
LoadIntroGame();
else if (ogm == GM_EDITOR)
MakeNewEditorWorld();
else
MakeNewGame();
return false;
} else if (r != SL_OK) {
_game_mode = ogm;
return false;
} else
return true;
}
void SwitchMode(int new_mode)
{
#ifdef ENABLE_NETWORK
// If we are saving something, the network stays in his current state
if (new_mode != SM_SAVE) {
// If the network is active, make it not-active
if (_networking) {
if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
NetworkReboot();
NetworkUDPClose();
} else {
NetworkDisconnect();
NetworkUDPClose();
}
}
// If we are a server, we restart the server
if (_is_network_server) {
// But not if we are going to the menu
if (new_mode != SM_MENU) {
NetworkServerStart();
} else {
// This client no longer wants to be a network-server
_is_network_server = false;
}
}
}
#endif /* ENABLE_NETWORK */
switch (new_mode) {
case SM_EDITOR: /* Switch to scenario editor */
MakeNewEditorWorld();
break;
case SM_NEWGAME: /* New Game --> 'Random game' */
#ifdef ENABLE_NETWORK
if (_network_server)
snprintf(_network_game_info.map_name, NETWORK_NAME_LENGTH, "Random Map");
#endif /* ENABLE_NETWORK */
MakeNewGame();
break;
case SM_START_SCENARIO: /* New Game --> Choose one of the preset scenarios */
#ifdef ENABLE_NETWORK
if (_network_server)
snprintf(_network_game_info.map_name, NETWORK_NAME_LENGTH, "%s (Loaded scenario)", _file_to_saveload.title);
#endif /* ENABLE_NETWORK */
StartScenario();
break;
case SM_LOAD: { /* Load game, Play Scenario */
_opt_ptr = &_opt;
_error_message = INVALID_STRING_ID;
if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL)) {
LoadIntroGame();
ShowErrorMessage(_error_message, STR_4009_GAME_LOAD_FAILED, 0, 0);
} else {
_local_player = 0;
DoCommandP(0, 0, 0, NULL, CMD_PAUSE); // decrease pause counter (was increased from opening load dialog)
#ifdef ENABLE_NETWORK
if (_network_server)
snprintf(_network_game_info.map_name, NETWORK_NAME_LENGTH, "%s (Loaded game)", _file_to_saveload.title);
#endif /* ENABLE_NETWORK */
}
break;
}
case SM_LOAD_SCENARIO: { /* Load scenario from scenario editor */
int i;
if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR)) {
_opt_ptr = &_opt;
_local_player = OWNER_NONE;
_generating_world = true;
// delete all players.
for (i = 0; i != MAX_PLAYERS; i++) {
ChangeOwnershipOfPlayerItems(i, 0xff);
_players[i].is_active = false;
}
_generating_world = false;
// delete all stations owned by a player
DeleteAllPlayerStations();
} else
ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
break;
}
case SM_MENU: /* Switch to game intro menu */
LoadIntroGame();
break;
case SM_SAVE: /* Save game */
if (SaveOrLoad(_file_to_saveload.name, SL_SAVE) != SL_OK)
ShowErrorMessage(INVALID_STRING_ID, STR_4007_GAME_SAVE_FAILED, 0, 0);
else
DeleteWindowById(WC_SAVELOAD, 0);
break;
case SM_GENRANDLAND: /* Generate random land within scenario editor */
GenerateWorld(2, 1<<_patches.map_x, 1<<_patches.map_y);
// XXX: set date
_local_player = OWNER_NONE;
MarkWholeScreenDirty();
break;
}
if (_switch_mode_errorstr != INVALID_STRING_ID)
ShowErrorMessage(INVALID_STRING_ID,_switch_mode_errorstr,0,0);
}
// State controlling game loop.
// The state must not be changed from anywhere
// but here.
// That check is enforced in DoCommand.
void StateGameLoop(void)
{
// dont execute the state loop during pause
if (_pause) return;
// _frame_counter is increased somewhere else when in network-mode
// Sidenote: _frame_counter is ONLY used for _savedump in non-MP-games
// Should that not be deleted? If so, the next 2 lines can also be deleted
if (!_networking)
_frame_counter++;
if (_savedump_path[0] && (uint)_frame_counter >= _savedump_first && (uint)(_frame_counter -_savedump_first) % _savedump_freq == 0 ) {
char buf[100];
sprintf(buf, "%s%.5d.sav", _savedump_path, _frame_counter);
SaveOrLoad(buf, SL_SAVE);
if ((uint)_frame_counter >= _savedump_last) exit(1);
}
if (_game_mode == GM_EDITOR) {
RunTileLoop();
CallVehicleTicks();
CallLandscapeTick();
CallWindowTickEvent();
NewsLoop();
} else {
// All these actions has to be done from OWNER_NONE
// for multiplayer compatibility
uint p = _current_player;
_current_player = OWNER_NONE;
AnimateAnimatedTiles();
IncreaseDate();
RunTileLoop();
CallVehicleTicks();
CallLandscapeTick();
// To bad the AI does not work in multiplayer, because states are not saved
// perfectly
if (!_networking)
RunOtherPlayersLoop();
CallWindowTickEvent();
NewsLoop();
_current_player = p;
}
}
static void DoAutosave(void)
{
char buf[200];
if (_patches.keep_all_autosave && _local_player != OWNER_SPECTATOR) {
const Player *p = GetPlayer(_local_player);
char *s;
sprintf(buf, "%s%s", _path.autosave_dir, PATHSEP);
SetDParam(0, p->name_1);
SetDParam(1, p->name_2);
SetDParam(2, _date);
s = (char*)GetString(buf + strlen(_path.autosave_dir) + strlen(PATHSEP), STR_4004);
strcpy(s, ".sav");
} else { /* Save a maximum of 15 autosaves */
int n = _autosave_ctr;
_autosave_ctr = (_autosave_ctr + 1) & 15;
sprintf(buf, "%s%sautosave%d.sav", _path.autosave_dir, PATHSEP, n);
}
DEBUG(misc, 2) ("Autosaving to %s", buf);
if (SaveOrLoad(buf, SL_SAVE) != SL_OK)
ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
}
static void ScrollMainViewport(int x, int y)
{
if (_game_mode != GM_MENU) {
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
assert(w);
WP(w,vp_d).scrollpos_x += x << w->viewport->zoom;
WP(w,vp_d).scrollpos_y += y << w->viewport->zoom;
}
}
static const int8 scrollamt[16][2] = {
{ 0, 0},
{-2, 0}, // 1:left
{ 0,-2}, // 2:up
{-2,-1}, // 3:left + up
{ 2, 0}, // 4:right
{ 0, 0}, // 5:left + right
{ 2,-1}, // 6:right + up
{ 0,-2}, // 7:left + right + up = up
{ 0 ,2}, // 8:down
{-2 ,1}, // 9:down+left
{ 0, 0}, // 10:impossible
{-2, 0}, // 11:left + up + down = left
{ 2, 1}, // 12:down+right
{ 0, 2}, // 13:left + right + down = down
{ 0,-2}, // 14:left + right + up = up
{ 0, 0}, // 15:impossible
};
static void HandleKeyScrolling(void)
{
if (_dirkeys && !_no_scroll) {
int factor = _shift_pressed ? 50 : 10;
ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
}
}
void GameLoop(void)
{
int m;
// autosave game?
if (_do_autosave) {
_do_autosave = false;
DoAutosave();
RedrawAutosave();
}
// handle scrolling of the main window
if (_dirkeys) HandleKeyScrolling();
// make a screenshot?
if ((m=_make_screenshot) != 0) {
_make_screenshot = 0;
switch(m) {
case 1: // make small screenshot
UndrawMouseCursor();
ShowScreenshotResult(MakeScreenshot());
break;
case 2: // make large screenshot
ShowScreenshotResult(MakeWorldScreenshot(-(int)MapMaxX() * 32, 0, MapMaxX() * 64, MapSizeY() * 32, 0));
break;
}
}
// switch game mode?
if ((m=_switch_mode) != SM_NONE) {
_switch_mode = SM_NONE;
SwitchMode(m);
}
IncreaseSpriteLRU();
InteractiveRandom();
if (_scroller_click_timeout > 3)
_scroller_click_timeout -= 3;
else
_scroller_click_timeout = 0;
_caret_timer += 3;
_timer_counter+=8;
CursorTick();
#ifdef ENABLE_NETWORK
// Check for UDP stuff
NetworkUDPGameLoop();
if (_networking) {
// Multiplayer
NetworkGameLoop();
} else {
if (_network_reconnect > 0 && --_network_reconnect == 0) {
// This means that we want to reconnect to the last host
// We do this here, because it means that the network is really closed
NetworkClientConnectGame(_network_last_host, _network_last_port);
}
// Singleplayer
StateGameLoop();
}
#else
StateGameLoop();
#endif /* ENABLE_NETWORK */
if (!_pause && _display_opt&DO_FULL_ANIMATION)
DoPaletteAnimations();
if (!_pause || _cheats.build_in_pause.value)
MoveAllTextEffects();
InputLoop();
MusicLoop();
}
void BeforeSaveGame(void)
{
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
if (w != NULL) {
_saved_scrollpos_x = WP(w,vp_d).scrollpos_x;
_saved_scrollpos_y = WP(w,vp_d).scrollpos_y;
_saved_scrollpos_zoom = w->viewport->zoom;
}
}
static void ConvertTownOwner(void)
{
TileIndex tile;
for (tile = 0; tile != MapSize(); tile++) {
if (IsTileType(tile, MP_STREET)) {
if (IsLevelCrossing(tile) && _m[tile].m3 & 0x80)
_m[tile].m3 = OWNER_TOWN;
if (_m[tile].owner & 0x80) SetTileOwner(tile, OWNER_TOWN);
} else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
if (_m[tile].owner & 0x80) SetTileOwner(tile, OWNER_TOWN);
}
}
}
// before savegame version 4, the name of the company determined if it existed
static void CheckIsPlayerActive(void)
{
Player *p;
FOR_ALL_PLAYERS(p) {
if (p->name_1 != 0) {
p->is_active = true;
}
}
}
// since savegame version 4.1, exclusive transport rights are stored at towns
static void UpdateExclusiveRights(void)
{
Town *t;
FOR_ALL_TOWNS(t) if (t->xy != 0) {
t->exclusivity=(byte)-1;
}
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
could be implemented this way:
1.) Go through all stations
Build an array town_blocked[ town_id ][ player_id ]
that stores if at least one station in that town is blocked for a player
2.) Go through that array, if you find a town that is not blocked for
one player, but for all others, then give him exclusivity.
*/
}
const byte convert_currency[] = {
0, 1, 12, 8, 3,
10, 14, 19, 4, 5,
9, 11, 13, 6, 17,
16, 22, 21, 7, 15,
18, 2, 20, };
// since savegame version 4.2 the currencies are arranged differently
static void UpdateCurrencies(void)
{
_opt.currency = convert_currency[_opt.currency];
}
/* Up to revision 1413 the invisible tiles at the southern border have not been
* MP_VOID, even though they should have. This is fixed by this function
*/
static void UpdateVoidTiles(void)
{
uint i;
for (i = 0; i < MapMaxY(); ++i)
SetTileType(i * MapSizeX() + MapMaxX(), MP_VOID);
for (i = 0; i < MapSizeX(); ++i)
SetTileType(MapSizeX() * MapMaxY() + i, MP_VOID);
}
// since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255)
static void UpdateSignOwner(void)
{
SignStruct *ss;
FOR_ALL_SIGNS(ss) {
ss->owner = OWNER_NONE; // no owner
}
}
extern void UpdateOldAircraft( void );
extern void UpdateOilRig( void );
bool AfterLoadGame(uint version)
{
Window *w;
ViewPort *vp;
Player *p;
// in version 2.1 of the savegame, town owner was unified.
if (version <= 0x200) {
ConvertTownOwner();
}
// from version 4.1 of the savegame, exclusive rights are stored at towns
if (version <= 0x400) {
UpdateExclusiveRights();
}
// from version 4.2 of the savegame, currencies are in a different order
if (version <= 0x401) {
UpdateCurrencies();
}
// from version 6.0 of the savegame, signs have an "owner"
if (version <= 0x600) {
UpdateSignOwner();
}
/* In old version there seems to be a problem that water is owned by
OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
(0x402) version, so I just check when versions are older, and then
walk through the whole map.. */
if (version <= 0x402) {
TileIndex tile = TileXY(0, 0);
uint w = MapSizeX();
uint h = MapSizeY();
BEGIN_TILE_LOOP(tile_cur, w, h, tile)
if (IsTileType(tile_cur, MP_WATER) && GetTileOwner(tile_cur) >= MAX_PLAYERS)
SetTileOwner(tile_cur, OWNER_WATER);
END_TILE_LOOP(tile_cur, w, h, tile)
}
// convert road side to my format.
if (_opt.road_side) _opt.road_side = 1;
// Load the sprites
GfxLoadSprites();
// Update current year
SetDate(_date);
// reinit the landscape variables (landscape might have changed)
InitializeLandscapeVariables(true);
// Update all vehicles
AfterLoadVehicles();
// Update all waypoints
if (version < 0x0C00)
FixOldWaypoints();
UpdateAllWaypointSigns();
// in version 2.2 of the savegame, we have new airports
if (version <= 0x201) {
UpdateOldAircraft();
}
UpdateAllStationVirtCoord();
// Setup town coords
AfterLoadTown();
UpdateAllSignVirtCoords();
// make sure there is a town in the game
if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1))
{
_error_message = STR_NO_TOWN_IN_SCENARIO;
return false;
}
// Initialize windows
ResetWindowSystem();
SetupColorsAndInitialWindow();
w = FindWindowById(WC_MAIN_WINDOW, 0);
WP(w,vp_d).scrollpos_x = _saved_scrollpos_x;
WP(w,vp_d).scrollpos_y = _saved_scrollpos_y;
vp = w->viewport;
vp->zoom = _saved_scrollpos_zoom;
vp->virtual_width = vp->width << vp->zoom;
vp->virtual_height = vp->height << vp->zoom;
// in version 4.0 of the savegame, is_active was introduced to determine
// if a player does exist, rather then checking name_1
if (version <= 0x400) {
CheckIsPlayerActive();
}
// the void tiles on the southern border used to belong to a wrong class.
if (version <= 0x402)
UpdateVoidTiles();
// If Load Scenario / New (Scenario) Game is used,
// a player does not exist yet. So create one here.
// 1 exeption: network-games. Those can have 0 players
// But this exeption is not true for network_servers!
if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
DoStartupNewPlayer(false);
DoZoomInOutWindow(ZOOM_NONE, w); // update button status
MarkWholeScreenDirty();
//In 5.1, Oilrigs have been moved (again)
if (version <= 0x500) {
UpdateOilRig();
}
if (version <= 0x600) {
BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
if (IsTileType(tile, MP_HOUSE)) {
_m[tile].m4 = _m[tile].m2;
//XXX magic
SetTileType(tile, MP_VOID);
_m[tile].m2 = ClosestTownFromTile(tile,(uint)-1)->index;
SetTileType(tile, MP_HOUSE);
} else if (IsTileType(tile, MP_STREET)) {
//XXX magic
_m[tile].m4 |= (_m[tile].m2 << 4);
if (IsTileOwner(tile, OWNER_TOWN)) {
SetTileType(tile, MP_VOID);
_m[tile].m2 = ClosestTownFromTile(tile,(uint)-1)->index;
SetTileType(tile, MP_STREET);
} else {
_m[tile].m2 = 0;
}
}
} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
}
if (version < 0x900) {
Town *t;
FOR_ALL_TOWNS(t) {
UpdateTownMaxPass(t);
}
}
if (version < 0xF00) {
BEGIN_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0) {
if (IsTileType(tile, MP_RAILWAY) && HasSignals(tile) && HASBIT(_m[tile].m4, 2)) {
CLRBIT(_m[tile].m4, 2);
SETBIT(_m[tile].m4, 3);
}
} END_TILE_LOOP(tile, MapSizeX(), MapSizeY(), 0);
}
if (version < 0x1000) {
int i;
FOR_ALL_PLAYERS(p) {
for (i = 0; i < 256; i++) {
p->engine_replacement[i] = INVALID_ENGINE;
}
p->engine_renew = false;
p->engine_renew_months = -6;
p->engine_renew_money = 100000;
}
// Set the human controlled player to the patch settings
p = GetPlayer(_local_player);
p->engine_renew = _patches.autorenew;
p->engine_renew_months = _patches.autorenew_months;
p->engine_renew_money = _patches.autorenew_money;
}
FOR_ALL_PLAYERS(p) {
p->avail_railtypes = GetPlayerRailtypes(p->index);
}
return true;
}
|