src/openttd.cpp
branchnoai
changeset 9505 9711235f5693
parent 9476 1d1ed96f32ad
child 9574 698395509d12
equal deleted inserted replaced
9504:de4993fa3d98 9505:9711235f5693
     1 /* $Id$ */
     1 /* $Id$ */
       
     2 
       
     3 /** @file openttd.cpp */
     2 
     4 
     3 #include "stdafx.h"
     5 #include "stdafx.h"
     4 #define VARDEF
     6 #define VARDEF
     5 #include "string.h"
     7 #include "string.h"
     6 #include "table/strings.h"
     8 #include "table/strings.h"
   225 		s = *md->argv++;
   227 		s = *md->argv++;
   226 		if (*s == '-') {
   228 		if (*s == '-') {
   227 md_continue_here:;
   229 md_continue_here:;
   228 			s++;
   230 			s++;
   229 			if (*s != 0) {
   231 			if (*s != 0) {
   230 				// Found argument, try to locate it in options.
   232 				/* Found argument, try to locate it in options. */
   231 				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
   233 				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
   232 					// ERROR!
   234 					/* ERROR! */
   233 					return -2;
   235 					return -2;
   234 				}
   236 				}
   235 				if (r[1] == ':') {
   237 				if (r[1] == ':') {
   236 					// Item wants an argument. Check if the argument follows, or if it comes as a separate arg.
   238 					/* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
   237 					if (!*(t = s + 1)) {
   239 					if (!*(t = s + 1)) {
   238 						// It comes as a separate arg. Check if out of args?
   240 						/* It comes as a separate arg. Check if out of args? */
   239 						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
   241 						if (--md->numleft < 0 || *(t = *md->argv) == '-') {
   240 							// Check if item is optional?
   242 							/* Check if item is optional? */
   241 							if (r[2] != ':')
   243 							if (r[2] != ':')
   242 								return -2;
   244 								return -2;
   243 							md->numleft++;
   245 							md->numleft++;
   244 							t = NULL;
   246 							t = NULL;
   245 						} else {
   247 						} else {
   253 				md->opt = NULL;
   255 				md->opt = NULL;
   254 				md->cont = s;
   256 				md->cont = s;
   255 				return *s;
   257 				return *s;
   256 			}
   258 			}
   257 		} else {
   259 		} else {
   258 			// This is currently not supported.
   260 			/* This is currently not supported. */
   259 			return -2;
   261 			return -2;
   260 		}
   262 		}
   261 	}
   263 	}
   262 }
   264 }
   263 
   265 
   310 	_game_mode = GM_MENU;
   312 	_game_mode = GM_MENU;
   311 	CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
   313 	CLRBITS(_display_opt, DO_TRANS_BUILDINGS); // don't make buildings transparent in intro
   312 	_opt_ptr = &_opt_newgame;
   314 	_opt_ptr = &_opt_newgame;
   313 	ResetGRFConfig(false);
   315 	ResetGRFConfig(false);
   314 
   316 
   315 	// Setup main window
   317 	/* Setup main window */
   316 	ResetWindowSystem();
   318 	ResetWindowSystem();
   317 	SetupColorsAndInitialWindow();
   319 	SetupColorsAndInitialWindow();
   318 
   320 
   319 	// Generate a world.
   321 	/* Generate a world. */
   320 	snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.data_dir);
   322 	snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.data_dir);
   321 #if defined SECOND_DATA_DIR
   323 #if defined SECOND_DATA_DIR
   322 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
   324 	if (SaveOrLoad(filename, SL_LOAD) != SL_OK) {
   323 		snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.second_data_dir);
   325 		snprintf(filename, lengthof(filename), "%sopntitle.dat",  _paths.second_data_dir);
   324 	}
   326 	}
   333 	/* Make sure you can't scroll in the menu */
   335 	/* Make sure you can't scroll in the menu */
   334 	_scrolling_viewport = 0;
   336 	_scrolling_viewport = 0;
   335 	_cursor.fix_at = false;
   337 	_cursor.fix_at = false;
   336 	MarkWholeScreenDirty();
   338 	MarkWholeScreenDirty();
   337 
   339 
   338 	// Play main theme
   340 	/* Play main theme */
   339 	if (_music_driver->is_song_playing()) ResetMusic();
   341 	if (_music_driver->is_song_playing()) ResetMusic();
   340 }
   342 }
   341 
   343 
   342 #if defined(UNIX) && !defined(__MORPHOS__)
   344 #if defined(UNIX) && !defined(__MORPHOS__)
   343 extern void DedicatedFork();
   345 extern void DedicatedFork();
   367 	_switch_mode = SM_MENU;
   369 	_switch_mode = SM_MENU;
   368 	_switch_mode_errorstr = INVALID_STRING_ID;
   370 	_switch_mode_errorstr = INVALID_STRING_ID;
   369 	_dedicated_forks = false;
   371 	_dedicated_forks = false;
   370 	_config_file = NULL;
   372 	_config_file = NULL;
   371 
   373 
   372 	// The last param of the following function means this:
   374 	/* The last param of the following function means this:
   373 	//   a letter means: it accepts that param (e.g.: -h)
   375 	 *   a letter means: it accepts that param (e.g.: -h)
   374 	//   a ':' behind it means: it need a param (e.g.: -m<driver>)
   376 	 *   a ':' behind it means: it need a param (e.g.: -m<driver>)
   375 	//   a '::' behind it means: it can optional have a param (e.g.: -d<debug>)
   377 	 *   a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
   376 	optformat = "m:s:v:a:hD::n::eit:d::r:g::G:c:xl:"
   378 	optformat = "m:s:v:a:hD::n::eit:d::r:g::G:c:xl:"
   377 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
   379 #if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
   378 		"f"
   380 		"f"
   379 #endif
   381 #endif
   380 	;
   382 	;
   444 
   446 
   445 	DeterminePaths(argv[0]);
   447 	DeterminePaths(argv[0]);
   446 	CheckExternalFiles();
   448 	CheckExternalFiles();
   447 
   449 
   448 #if defined(UNIX) && !defined(__MORPHOS__)
   450 #if defined(UNIX) && !defined(__MORPHOS__)
   449 	// We must fork here, or we'll end up without some resources we need (like sockets)
   451 	/* We must fork here, or we'll end up without some resources we need (like sockets) */
   450 	if (_dedicated_forks)
   452 	if (_dedicated_forks)
   451 		DedicatedFork();
   453 		DedicatedFork();
   452 #endif
   454 #endif
   453 
   455 
   454 	LoadFromConfig();
   456 	LoadFromConfig();
   455 	CheckConfig();
   457 	CheckConfig();
   456 	LoadFromHighScore();
   458 	LoadFromHighScore();
   457 
   459 
   458 	// override config?
   460 	/* override config? */
   459 	if (!StrEmpty(musicdriver)) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
   461 	if (!StrEmpty(musicdriver)) ttd_strlcpy(_ini_musicdriver, musicdriver, sizeof(_ini_musicdriver));
   460 	if (!StrEmpty(sounddriver)) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
   462 	if (!StrEmpty(sounddriver)) ttd_strlcpy(_ini_sounddriver, sounddriver, sizeof(_ini_sounddriver));
   461 	if (!StrEmpty(videodriver)) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
   463 	if (!StrEmpty(videodriver)) ttd_strlcpy(_ini_videodriver, videodriver, sizeof(_ini_videodriver));
   462 	if (!StrEmpty(ai)) AI_ForceAI(ai);
   464 	if (!StrEmpty(ai)) AI_ForceAI(ai);
   463 	if (resolution[0] != 0) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
   465 	if (resolution[0] != 0) { _cur_resolution[0] = resolution[0]; _cur_resolution[1] = resolution[1]; }
   468 	if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
   470 	if (dedicated_host) snprintf(_network_server_bind_ip_host, NETWORK_HOSTNAME_LENGTH, "%s", dedicated_host);
   469 	if (dedicated_port) _network_server_port = dedicated_port;
   471 	if (dedicated_port) _network_server_port = dedicated_port;
   470 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
   472 	if (_dedicated_forks && !dedicated) _dedicated_forks = false;
   471 #endif /* ENABLE_NETWORK */
   473 #endif /* ENABLE_NETWORK */
   472 
   474 
   473 	// enumerate language files
   475 	/* enumerate language files */
   474 	InitializeLanguagePacks();
   476 	InitializeLanguagePacks();
   475 
   477 
   476 	// initialize screenshot formats
   478 	/* initialize screenshot formats */
   477 	InitializeScreenshotFormats();
   479 	InitializeScreenshotFormats();
   478 
   480 
   479 	// initialize airport state machines
   481 	/* initialize airport state machines */
   480 	InitializeAirports();
   482 	InitializeAirports();
   481 
   483 
   482 	/* initialize all variables that are allocated dynamically */
   484 	/* initialize all variables that are allocated dynamically */
   483 	InitializeDynamicVariables();
   485 	InitializeDynamicVariables();
   484 
   486 
   485 	/* start the AI */
   487 	/* start the AI */
   486 	AI_Initialize();
   488 	AI_Initialize();
   487 
   489 
   488 	// Sample catalogue
   490 	/* Sample catalogue */
   489 	DEBUG(misc, 1, "Loading sound effects...");
   491 	DEBUG(misc, 1, "Loading sound effects...");
   490 	MxInitialize(11025);
   492 	MxInitialize(11025);
   491 	SoundInitialize("sample.cat");
   493 	SoundInitialize("sample.cat");
   492 
   494 
   493 	/* Initialize FreeType */
   495 	/* Initialize FreeType */
   494 	InitFreeType();
   496 	InitFreeType();
   495 
   497 
   496 	// This must be done early, since functions use the InvalidateWindow* calls
   498 	/* This must be done early, since functions use the InvalidateWindow* calls */
   497 	InitWindowSystem();
   499 	InitWindowSystem();
   498 
   500 
   499 	/* Initialize game palette */
   501 	/* Initialize game palette */
   500 	GfxInitPalettes();
   502 	GfxInitPalettes();
   501 
   503 
   503 	LoadDriver(SOUND_DRIVER, _ini_sounddriver);
   505 	LoadDriver(SOUND_DRIVER, _ini_sounddriver);
   504 	LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
   506 	LoadDriver(MUSIC_DRIVER, _ini_musicdriver);
   505 	LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
   507 	LoadDriver(VIDEO_DRIVER, _ini_videodriver); // load video last, to prevent an empty window while sound and music loads
   506 	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
   508 	_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
   507 
   509 
   508 	// restore saved music volume
   510 	/* restore saved music volume */
   509 	_music_driver->set_volume(msf.music_vol);
   511 	_music_driver->set_volume(msf.music_vol);
   510 
   512 
   511 	NetworkStartUp(); // initialize network-core
   513 	NetworkStartUp(); // initialize network-core
   512 
   514 
   513 #if defined(ENABLE_NETWORK)
   515 #if defined(ENABLE_NETWORK)
   537 	if (_switch_mode != SM_NONE) {
   539 	if (_switch_mode != SM_NONE) {
   538 		_opt = _opt_newgame;
   540 		_opt = _opt_newgame;
   539 		UpdatePatches();
   541 		UpdatePatches();
   540 	}
   542 	}
   541 
   543 
   542 	// initialize the ingame console
   544 	/* initialize the ingame console */
   543 	IConsoleInit();
   545 	IConsoleInit();
   544 	_cursor.in_window = true;
   546 	_cursor.in_window = true;
   545 	InitializeGUI();
   547 	InitializeGUI();
   546 	IConsoleCmdExec("exec scripts/autoexec.scr 0");
   548 	IConsoleCmdExec("exec scripts/autoexec.scr 0");
   547 
   549 
   721  */
   723  */
   722 static void StartScenario()
   724 static void StartScenario()
   723 {
   725 {
   724 	_game_mode = GM_NORMAL;
   726 	_game_mode = GM_NORMAL;
   725 
   727 
   726 	// invalid type
   728 	/* invalid type */
   727 	if (_file_to_saveload.mode == SL_INVALID) {
   729 	if (_file_to_saveload.mode == SL_INVALID) {
   728 		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
   730 		DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
   729 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   731 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   730 		_game_mode = GM_MENU;
   732 		_game_mode = GM_MENU;
   731 		return;
   733 		return;
   732 	}
   734 	}
   733 
   735 
   734 	// Reinitialize windows
   736 	/* Reinitialize windows */
   735 	ResetWindowSystem();
   737 	ResetWindowSystem();
   736 
   738 
   737 	SetupColorsAndInitialWindow();
   739 	SetupColorsAndInitialWindow();
   738 
   740 
   739 	ResetGRFConfig(true);
   741 	ResetGRFConfig(true);
   740 
   742 
   741 	// Load game
   743 	/* Load game */
   742 	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
   744 	if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode) != SL_OK) {
   743 		LoadIntroGame();
   745 		LoadIntroGame();
   744 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   746 		ShowErrorMessage(INVALID_STRING_ID, STR_4009_GAME_LOAD_FAILED, 0, 0);
   745 	}
   747 	}
   746 
   748 
   747 	_opt_ptr = &_opt;
   749 	_opt_ptr = &_opt;
   748 	_opt_ptr->diff = _opt_newgame.diff;
   750 	_opt_ptr->diff = _opt_newgame.diff;
   749 	_opt.diff_level = _opt_newgame.diff_level;
   751 	_opt.diff_level = _opt_newgame.diff_level;
   750 
   752 
   751 	// Inititalize data
   753 	/* Inititalize data */
   752 	StartupEconomy();
   754 	StartupEconomy();
   753 	StartupPlayers();
   755 	StartupPlayers();
   754 	StartupEngines();
   756 	StartupEngines();
   755 	StartupDisasters();
   757 	StartupDisasters();
   756 
   758 
   784 }
   786 }
   785 
   787 
   786 void SwitchMode(int new_mode)
   788 void SwitchMode(int new_mode)
   787 {
   789 {
   788 #ifdef ENABLE_NETWORK
   790 #ifdef ENABLE_NETWORK
   789 	// If we are saving something, the network stays in his current state
   791 	/* If we are saving something, the network stays in his current state */
   790 	if (new_mode != SM_SAVE) {
   792 	if (new_mode != SM_SAVE) {
   791 		// If the network is active, make it not-active
   793 		/* If the network is active, make it not-active */
   792 		if (_networking) {
   794 		if (_networking) {
   793 			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
   795 			if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
   794 				NetworkReboot();
   796 				NetworkReboot();
   795 				NetworkUDPCloseAll();
   797 				NetworkUDPCloseAll();
   796 			} else {
   798 			} else {
   797 				NetworkDisconnect();
   799 				NetworkDisconnect();
   798 				NetworkUDPCloseAll();
   800 				NetworkUDPCloseAll();
   799 			}
   801 			}
   800 		}
   802 		}
   801 
   803 
   802 		// If we are a server, we restart the server
   804 		/* If we are a server, we restart the server */
   803 		if (_is_network_server) {
   805 		if (_is_network_server) {
   804 			// But not if we are going to the menu
   806 			/* But not if we are going to the menu */
   805 			if (new_mode != SM_MENU) {
   807 			if (new_mode != SM_MENU) {
   806 				NetworkServerStart();
   808 				NetworkServerStart();
   807 			} else {
   809 			} else {
   808 				// This client no longer wants to be a network-server
   810 				/* This client no longer wants to be a network-server */
   809 				_is_network_server = false;
   811 				_is_network_server = false;
   810 			}
   812 			}
   811 		}
   813 		}
   812 	}
   814 	}
   813 #endif /* ENABLE_NETWORK */
   815 #endif /* ENABLE_NETWORK */
   897 		break;
   899 		break;
   898 
   900 
   899 	case SM_GENRANDLAND: /* Generate random land within scenario editor */
   901 	case SM_GENRANDLAND: /* Generate random land within scenario editor */
   900 		SetLocalPlayer(OWNER_NONE);
   902 		SetLocalPlayer(OWNER_NONE);
   901 		GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
   903 		GenerateWorld(GW_RANDOM, 1 << _patches.map_x, 1 << _patches.map_y);
   902 		// XXX: set date
   904 		/* XXX: set date */
   903 		MarkWholeScreenDirty();
   905 		MarkWholeScreenDirty();
   904 		break;
   906 		break;
   905 	}
   907 	}
   906 
   908 
   907 	if (_switch_mode_errorstr != INVALID_STRING_ID) {
   909 	if (_switch_mode_errorstr != INVALID_STRING_ID) {
   908 		ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
   910 		ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
   909 	}
   911 	}
   910 }
   912 }
   911 
   913 
   912 
   914 
   913 // State controlling game loop.
   915 /* State controlling game loop.
   914 // The state must not be changed from anywhere
   916  * The state must not be changed from anywhere
   915 // but here.
   917  * but here.
   916 // That check is enforced in DoCommand.
   918  * That check is enforced in DoCommand. */
   917 void StateGameLoop()
   919 void StateGameLoop()
   918 {
   920 {
   919 	// dont execute the state loop during pause
   921 	/* dont execute the state loop during pause */
   920 	if (_pause_game) return;
   922 	if (_pause_game) return;
   921 	if (IsGeneratingWorld()) return;
   923 	if (IsGeneratingWorld()) return;
   922 
   924 
   923 	if (_game_mode == GM_EDITOR) {
   925 	if (_game_mode == GM_EDITOR) {
   924 		RunTileLoop();
   926 		RunTileLoop();
   925 		CallVehicleTicks();
   927 		CallVehicleTicks();
   926 		CallLandscapeTick();
   928 		CallLandscapeTick();
   927 		CallWindowTickEvent();
   929 		CallWindowTickEvent();
   928 		NewsLoop();
   930 		NewsLoop();
   929 	} else {
   931 	} else {
   930 		// All these actions has to be done from OWNER_NONE
   932 		/* All these actions has to be done from OWNER_NONE
   931 		//  for multiplayer compatibility
   933 		 *  for multiplayer compatibility */
   932 		PlayerID p = _current_player;
   934 		PlayerID p = _current_player;
   933 		_current_player = OWNER_NONE;
   935 		_current_player = OWNER_NONE;
   934 
   936 
   935 		AnimateAnimatedTiles();
   937 		AnimateAnimatedTiles();
   936 		IncreaseDate();
   938 		IncreaseDate();
   965 		SetDParam(0, p->name_1);
   967 		SetDParam(0, p->name_1);
   966 		SetDParam(1, p->name_2);
   968 		SetDParam(1, p->name_2);
   967 		SetDParam(2, _date);
   969 		SetDParam(2, _date);
   968 		s = GetString(s, STR_4004, lastof(buf));
   970 		s = GetString(s, STR_4004, lastof(buf));
   969 		strecpy(s, ".sav", lastof(buf));
   971 		strecpy(s, ".sav", lastof(buf));
   970 	} else { /* generate a savegame name and number according to _patches.max_num_autosaves */
   972 	} else { // generate a savegame name and number according to _patches.max_num_autosaves
   971 		snprintf(buf, lengthof(buf), "%s%sautosave%d.sav", _paths.autosave_dir, PATHSEP, _autosave_ctr);
   973 		snprintf(buf, lengthof(buf), "%s%sautosave%d.sav", _paths.autosave_dir, PATHSEP, _autosave_ctr);
   972 
   974 
   973 		_autosave_ctr++;
   975 		_autosave_ctr++;
   974 		if (_autosave_ctr >= _patches.max_num_autosaves) {
   976 		if (_autosave_ctr >= _patches.max_num_autosaves) {
   975 			// we reached the limit for numbers of autosaves. We will start over
   977 			/* we reached the limit for numbers of autosaves. We will start over */
   976 			_autosave_ctr = 0;
   978 			_autosave_ctr = 0;
   977 		}
   979 		}
   978 	}
   980 	}
   979 
   981 
   980 	DEBUG(sl, 2, "Autosaving to '%s'", buf);
   982 	DEBUG(sl, 2, "Autosaving to '%s'", buf);
   993 	}
   995 	}
   994 }
   996 }
   995 
   997 
   996 static const int8 scrollamt[16][2] = {
   998 static const int8 scrollamt[16][2] = {
   997 	{ 0,  0},
   999 	{ 0,  0},
   998 	{-2,  0}, //  1 : left
  1000 	{-2,  0}, ///<  1 : left
   999 	{ 0, -2}, //  2 : up
  1001 	{ 0, -2}, ///<  2 : up
  1000 	{-2, -1}, //  3 : left + up
  1002 	{-2, -1}, ///<  3 : left + up
  1001 	{ 2,  0}, //  4 : right
  1003 	{ 2,  0}, ///<  4 : right
  1002 	{ 0,  0}, //  5 : left + right
  1004 	{ 0,  0}, ///<  5 : left + right
  1003 	{ 2, -1}, //  6 : right + up
  1005 	{ 2, -1}, ///<  6 : right + up
  1004 	{ 0, -2}, //  7 : left + right + up = up
  1006 	{ 0, -2}, ///<  7 : left + right + up = up
  1005 	{ 0  ,2}, //  8 : down
  1007 	{ 0  ,2}, ///<  8 : down
  1006 	{-2  ,1}, //  9 : down+left
  1008 	{-2  ,1}, ///<  9 : down+left
  1007 	{ 0,  0}, // 10 : impossible
  1009 	{ 0,  0}, ///< 10 : impossible
  1008 	{-2,  0}, // 11 : left + up + down = left
  1010 	{-2,  0}, ///< 11 : left + up + down = left
  1009 	{ 2,  1}, // 12 : down+right
  1011 	{ 2,  1}, ///< 12 : down+right
  1010 	{ 0,  2}, // 13 : left + right + down = down
  1012 	{ 0,  2}, ///< 13 : left + right + down = down
  1011 	{ 0, -2}, // 14 : left + right + up = up
  1013 	{ 0, -2}, ///< 14 : left + right + up = up
  1012 	{ 0,  0}, // 15 : impossible
  1014 	{ 0,  0}, ///< 15 : impossible
  1013 };
  1015 };
  1014 
  1016 
  1015 static void HandleKeyScrolling()
  1017 static void HandleKeyScrolling()
  1016 {
  1018 {
  1017 	if (_dirkeys && !_no_scroll) {
  1019 	if (_dirkeys && !_no_scroll) {
  1024 {
  1026 {
  1025 	ThreadMsg message;
  1027 	ThreadMsg message;
  1026 
  1028 
  1027 	if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
  1029 	if ((message = OTTD_PollThreadEvent()) != 0) ProcessSentMessage(message);
  1028 
  1030 
  1029 	// autosave game?
  1031 	/* autosave game? */
  1030 	if (_do_autosave) {
  1032 	if (_do_autosave) {
  1031 		_do_autosave = false;
  1033 		_do_autosave = false;
  1032 		DoAutosave();
  1034 		DoAutosave();
  1033 		RedrawAutosave();
  1035 		RedrawAutosave();
  1034 	}
  1036 	}
  1035 
  1037 
  1036 	// handle scrolling of the main window
  1038 	/* handle scrolling of the main window */
  1037 	HandleKeyScrolling();
  1039 	HandleKeyScrolling();
  1038 
  1040 
  1039 	// make a screenshot?
  1041 	/* make a screenshot? */
  1040 	if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
  1042 	if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
  1041 
  1043 
  1042 	// switch game mode?
  1044 	/* switch game mode? */
  1043 	if (_switch_mode != SM_NONE) {
  1045 	if (_switch_mode != SM_NONE) {
  1044 		SwitchMode(_switch_mode);
  1046 		SwitchMode(_switch_mode);
  1045 		_switch_mode = SM_NONE;
  1047 		_switch_mode = SM_NONE;
  1046 	}
  1048 	}
  1047 
  1049 
  1057 	_caret_timer += 3;
  1059 	_caret_timer += 3;
  1058 	_timer_counter += 8;
  1060 	_timer_counter += 8;
  1059 	CursorTick();
  1061 	CursorTick();
  1060 
  1062 
  1061 #ifdef ENABLE_NETWORK
  1063 #ifdef ENABLE_NETWORK
  1062 	// Check for UDP stuff
  1064 	/* Check for UDP stuff */
  1063 	if (_network_available) NetworkUDPGameLoop();
  1065 	if (_network_available) NetworkUDPGameLoop();
  1064 
  1066 
  1065 	if (_networking && !IsGeneratingWorld()) {
  1067 	if (_networking && !IsGeneratingWorld()) {
  1066 		// Multiplayer
  1068 		/* Multiplayer */
  1067 		NetworkGameLoop();
  1069 		NetworkGameLoop();
  1068 	} else {
  1070 	} else {
  1069 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
  1071 		if (_network_reconnect > 0 && --_network_reconnect == 0) {
  1070 			// This means that we want to reconnect to the last host
  1072 			/* This means that we want to reconnect to the last host
  1071 			// We do this here, because it means that the network is really closed
  1073 			 * We do this here, because it means that the network is really closed */
  1072 			NetworkClientConnectGame(_network_last_host, _network_last_port);
  1074 			NetworkClientConnectGame(_network_last_host, _network_last_port);
  1073 		}
  1075 		}
  1074 		// Singleplayer
  1076 		/* Singleplayer */
  1075 		StateGameLoop();
  1077 		StateGameLoop();
  1076 	}
  1078 	}
  1077 #else
  1079 #else
  1078 	StateGameLoop();
  1080 	StateGameLoop();
  1079 #endif /* ENABLE_NETWORK */
  1081 #endif /* ENABLE_NETWORK */
  1117 			default: break;
  1119 			default: break;
  1118 		}
  1120 		}
  1119 	}
  1121 	}
  1120 }
  1122 }
  1121 
  1123 
  1122 // before savegame version 4, the name of the company determined if it existed
  1124 /* before savegame version 4, the name of the company determined if it existed */
  1123 static void CheckIsPlayerActive()
  1125 static void CheckIsPlayerActive()
  1124 {
  1126 {
  1125 	Player *p;
  1127 	Player *p;
  1126 
  1128 
  1127 	FOR_ALL_PLAYERS(p) {
  1129 	FOR_ALL_PLAYERS(p) {
  1128 		if (p->name_1 != 0) p->is_active = true;
  1130 		if (p->name_1 != 0) p->is_active = true;
  1129 	}
  1131 	}
  1130 }
  1132 }
  1131 
  1133 
  1132 // since savegame version 4.1, exclusive transport rights are stored at towns
  1134 /* since savegame version 4.1, exclusive transport rights are stored at towns */
  1133 static void UpdateExclusiveRights()
  1135 static void UpdateExclusiveRights()
  1134 {
  1136 {
  1135 	Town *t;
  1137 	Town *t;
  1136 
  1138 
  1137 	FOR_ALL_TOWNS(t) {
  1139 	FOR_ALL_TOWNS(t) {
  1153 	10, 14, 19,  4,  5,
  1155 	10, 14, 19,  4,  5,
  1154 	 9, 11, 13,  6, 17,
  1156 	 9, 11, 13,  6, 17,
  1155 	16, 22, 21,  7, 15,
  1157 	16, 22, 21,  7, 15,
  1156 	18,  2, 20, };
  1158 	18,  2, 20, };
  1157 
  1159 
  1158 // since savegame version 4.2 the currencies are arranged differently
  1160 /* since savegame version 4.2 the currencies are arranged differently */
  1159 static void UpdateCurrencies()
  1161 static void UpdateCurrencies()
  1160 {
  1162 {
  1161 	_opt.currency = convert_currency[_opt.currency];
  1163 	_opt.currency = convert_currency[_opt.currency];
  1162 }
  1164 }
  1163 
  1165 
  1170 
  1172 
  1171 	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
  1173 	for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
  1172 	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
  1174 	for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
  1173 }
  1175 }
  1174 
  1176 
  1175 // since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255)
  1177 /* since savegame version 6.0 each sign has an "owner", signs without owner (from old games are set to 255) */
  1176 static void UpdateSignOwner()
  1178 static void UpdateSignOwner()
  1177 {
  1179 {
  1178 	Sign *si;
  1180 	Sign *si;
  1179 
  1181 
  1180 	FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
  1182 	FOR_ALL_SIGNS(si) si->owner = OWNER_NONE;
  1193 	TileIndex map_size = MapSize();
  1195 	TileIndex map_size = MapSize();
  1194 	Window *w;
  1196 	Window *w;
  1195 	ViewPort *vp;
  1197 	ViewPort *vp;
  1196 	Player *p;
  1198 	Player *p;
  1197 
  1199 
  1198 	// in version 2.1 of the savegame, town owner was unified.
  1200 	/* in version 2.1 of the savegame, town owner was unified. */
  1199 	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
  1201 	if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
  1200 
  1202 
  1201 	// from version 4.1 of the savegame, exclusive rights are stored at towns
  1203 	/* from version 4.1 of the savegame, exclusive rights are stored at towns */
  1202 	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
  1204 	if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
  1203 
  1205 
  1204 	// from version 4.2 of the savegame, currencies are in a different order
  1206 	/* from version 4.2 of the savegame, currencies are in a different order */
  1205 	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
  1207 	if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
  1206 
  1208 
  1207 	// from version 6.1 of the savegame, signs have an "owner"
  1209 	/* from version 6.1 of the savegame, signs have an "owner" */
  1208 	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
  1210 	if (CheckSavegameVersionOldStyle(6, 1)) UpdateSignOwner();
  1209 
  1211 
  1210 	/* In old version there seems to be a problem that water is owned by
  1212 	/* In old version there seems to be a problem that water is owned by
  1211 	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
  1213 	    OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
  1212 	    (4.3) version, so I just check when versions are older, and then
  1214 	    (4.3) version, so I just check when versions are older, and then
  1217 				SetTileOwner(t, OWNER_WATER);
  1219 				SetTileOwner(t, OWNER_WATER);
  1218 			}
  1220 			}
  1219 		}
  1221 		}
  1220 	}
  1222 	}
  1221 
  1223 
  1222 	// convert road side to my format.
  1224 	/* convert road side to my format. */
  1223 	if (_opt.road_side) _opt.road_side = 1;
  1225 	if (_opt.road_side) _opt.road_side = 1;
  1224 
  1226 
  1225 	/* Check if all NewGRFs are present, we are very strict in MP mode */
  1227 	/* Check if all NewGRFs are present, we are very strict in MP mode */
  1226 	GRFListCompatibility gcf_res = IsGoodGRFConfigList();
  1228 	GRFListCompatibility gcf_res = IsGoodGRFConfigList();
  1227 	if (_networking && gcf_res != GLC_ALL_GOOD) return false;
  1229 	if (_networking && gcf_res != GLC_ALL_GOOD) return false;
  1234 
  1236 
  1235 	/* Update current year
  1237 	/* Update current year
  1236 	 * must be done before loading sprites as some newgrfs check it */
  1238 	 * must be done before loading sprites as some newgrfs check it */
  1237 	SetDate(_date);
  1239 	SetDate(_date);
  1238 
  1240 
  1239 	// Load the sprites
  1241 	/* Load the sprites */
  1240 	GfxLoadSprites();
  1242 	GfxLoadSprites();
  1241 	LoadStringWidthTable();
  1243 	LoadStringWidthTable();
  1242 
  1244 
  1243 	/* Connect front and rear engines of multiheaded trains and converts
  1245 	/* Connect front and rear engines of multiheaded trains and converts
  1244 	 * subtype to the new format */
  1246 	 * subtype to the new format */
  1245 	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
  1247 	if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
  1246 
  1248 
  1247 	/* Connect front and rear engines of multiheaded trains */
  1249 	/* Connect front and rear engines of multiheaded trains */
  1248 	ConnectMultiheadedTrains();
  1250 	ConnectMultiheadedTrains();
  1249 
  1251 
  1250 	// reinit the landscape variables (landscape might have changed)
  1252 	/* reinit the landscape variables (landscape might have changed) */
  1251 	InitializeLandscapeVariables(true);
  1253 	InitializeLandscapeVariables(true);
  1252 
  1254 
  1253 	// Update all vehicles
  1255 	/* Update all vehicles */
  1254 	AfterLoadVehicles();
  1256 	AfterLoadVehicles();
  1255 
  1257 
  1256 	// Update all waypoints
  1258 	/* Update all waypoints */
  1257 	if (CheckSavegameVersion(12)) FixOldWaypoints();
  1259 	if (CheckSavegameVersion(12)) FixOldWaypoints();
  1258 
  1260 
  1259 	UpdateAllWaypointSigns();
  1261 	UpdateAllWaypointSigns();
  1260 
  1262 
  1261 	// in version 2.2 of the savegame, we have new airports
  1263 	/* in version 2.2 of the savegame, we have new airports */
  1262 	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
  1264 	if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
  1263 
  1265 
  1264 	UpdateAllStationVirtCoord();
  1266 	UpdateAllStationVirtCoord();
  1265 
  1267 
  1266 	// Setup town coords
  1268 	/* Setup town coords */
  1267 	AfterLoadTown();
  1269 	AfterLoadTown();
  1268 	UpdateAllSignVirtCoords();
  1270 	UpdateAllSignVirtCoords();
  1269 
  1271 
  1270 	// make sure there is a town in the game
  1272 	/* make sure there is a town in the game */
  1271 	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
  1273 	if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, (uint)-1)) {
  1272 		_error_message = STR_NO_TOWN_IN_SCENARIO;
  1274 		_error_message = STR_NO_TOWN_IN_SCENARIO;
  1273 		return false;
  1275 		return false;
  1274 	}
  1276 	}
  1275 
  1277 
  1276 	// Initialize windows
  1278 	/* Initialize windows */
  1277 	ResetWindowSystem();
  1279 	ResetWindowSystem();
  1278 	SetupColorsAndInitialWindow();
  1280 	SetupColorsAndInitialWindow();
  1279 
  1281 
  1280 	w = FindWindowById(WC_MAIN_WINDOW, 0);
  1282 	w = FindWindowById(WC_MAIN_WINDOW, 0);
  1281 
  1283 
  1285 	vp = w->viewport;
  1287 	vp = w->viewport;
  1286 	vp->zoom = _saved_scrollpos_zoom;
  1288 	vp->zoom = _saved_scrollpos_zoom;
  1287 	vp->virtual_width = vp->width << vp->zoom;
  1289 	vp->virtual_width = vp->width << vp->zoom;
  1288 	vp->virtual_height = vp->height << vp->zoom;
  1290 	vp->virtual_height = vp->height << vp->zoom;
  1289 
  1291 
  1290 	// in version 4.1 of the savegame, is_active was introduced to determine
  1292 	/* in version 4.1 of the savegame, is_active was introduced to determine
  1291 	// if a player does exist, rather then checking name_1
  1293 	 * if a player does exist, rather then checking name_1 */
  1292 	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
  1294 	if (CheckSavegameVersionOldStyle(4, 1)) CheckIsPlayerActive();
  1293 
  1295 
  1294 	// the void tiles on the southern border used to belong to a wrong class (pre 4.3).
  1296 	/* the void tiles on the southern border used to belong to a wrong class (pre 4.3). */
  1295 	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
  1297 	if (CheckSavegameVersionOldStyle(4, 3)) UpdateVoidTiles();
  1296 
  1298 
  1297 	// If Load Scenario / New (Scenario) Game is used,
  1299 	/* If Load Scenario / New (Scenario) Game is used,
  1298 	//  a player does not exist yet. So create one here.
  1300 	 *  a player does not exist yet. So create one here.
  1299 	// 1 exeption: network-games. Those can have 0 players
  1301 	 * 1 exeption: network-games. Those can have 0 players
  1300 	//   But this exeption is not true for network_servers!
  1302 	 *   But this exeption is not true for network_servers! */
  1301 	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
  1303 	if (!_players[0].is_active && (!_networking || (_networking && _network_server)))
  1302 		DoStartupNewPlayer(false);
  1304 		DoStartupNewPlayer(false);
  1303 
  1305 
  1304 	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
  1306 	DoZoomInOutWindow(ZOOM_NONE, w); // update button status
  1305 	MarkWholeScreenDirty();
  1307 	MarkWholeScreenDirty();
  1591 				if (statspec != NULL) {
  1593 				if (statspec != NULL) {
  1592 					wp->stat_id = _m[wp->xy].m4 + 1;
  1594 					wp->stat_id = _m[wp->xy].m4 + 1;
  1593 					wp->grfid = statspec->grfid;
  1595 					wp->grfid = statspec->grfid;
  1594 					wp->localidx = statspec->localidx;
  1596 					wp->localidx = statspec->localidx;
  1595 				} else {
  1597 				} else {
  1596 					// No custom graphics set, so set to default.
  1598 					/* No custom graphics set, so set to default. */
  1597 					wp->stat_id = 0;
  1599 					wp->stat_id = 0;
  1598 					wp->grfid = 0;
  1600 					wp->grfid = 0;
  1599 					wp->localidx = 0;
  1601 					wp->localidx = 0;
  1600 				}
  1602 				}
  1601 
  1603 
  1602 				// Move ground type bits from m2 to m4.
  1604 				/* Move ground type bits from m2 to m4. */
  1603 				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
  1605 				_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
  1604 				// Store waypoint index in the tile.
  1606 				/* Store waypoint index in the tile. */
  1605 				_m[wp->xy].m2 = wp->index;
  1607 				_m[wp->xy].m2 = wp->index;
  1606 			}
  1608 			}
  1607 		}
  1609 		}
  1608 	} else {
  1610 	} else {
  1609 		/* As of version 17, we recalculate the custom graphic ID of waypoints
  1611 		/* As of version 17, we recalculate the custom graphic ID of waypoints
  1616 	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
  1618 	if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
  1617 		for (TileIndex t = 0; t < map_size; t++) {
  1619 		for (TileIndex t = 0; t < map_size; t++) {
  1618 			switch (GetTileType(t)) {
  1620 			switch (GetTileType(t)) {
  1619 				case MP_RAILWAY:
  1621 				case MP_RAILWAY:
  1620 					if (HasSignals(t)) {
  1622 					if (HasSignals(t)) {
  1621 						// convert PBS signals to combo-signals
  1623 						/* convert PBS signals to combo-signals */
  1622 						if (HASBIT(_m[t].m2, 2)) SetSignalType(t, SIGTYPE_COMBO);
  1624 						if (HASBIT(_m[t].m2, 2)) SetSignalType(t, SIGTYPE_COMBO);
  1623 
  1625 
  1624 						// move the signal variant back
  1626 						/* move the signal variant back */
  1625 						SetSignalVariant(t, HASBIT(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
  1627 						SetSignalVariant(t, HASBIT(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
  1626 						CLRBIT(_m[t].m2, 3);
  1628 						CLRBIT(_m[t].m2, 3);
  1627 					}
  1629 					}
  1628 
  1630 
  1629 					// Clear PBS reservation on track
  1631 					/* Clear PBS reservation on track */
  1630 					if (!IsTileDepotType(t, TRANSPORT_RAIL)) {
  1632 					if (!IsTileDepotType(t, TRANSPORT_RAIL)) {
  1631 						SB(_m[t].m4, 4, 4, 0);
  1633 						SB(_m[t].m4, 4, 4, 0);
  1632 					} else {
  1634 					} else {
  1633 						CLRBIT(_m[t].m3, 6);
  1635 						CLRBIT(_m[t].m3, 6);
  1634 					}
  1636 					}
  1635 					break;
  1637 					break;
  1636 
  1638 
  1637 				case MP_STREET:
  1639 				case MP_STREET: /* Clear PBS reservation on crossing */
  1638 					// Clear PBS reservation on crossing
       
  1639 					if (IsLevelCrossing(t)) CLRBIT(_m[t].m5, 0);
  1640 					if (IsLevelCrossing(t)) CLRBIT(_m[t].m5, 0);
  1640 					break;
  1641 					break;
  1641 
  1642 
  1642 				case MP_STATION:
  1643 				case MP_STATION: /* Clear PBS reservation on station */
  1643 					// Clear PBS reservation on station
       
  1644 					CLRBIT(_m[t].m3, 6);
  1644 					CLRBIT(_m[t].m3, 6);
  1645 					break;
  1645 					break;
  1646 
  1646 
  1647 				default: break;
  1647 				default: break;
  1648 			}
  1648 			}