Changeset - r14733:d5287af271c9
[Not reviewed]
master
0 3 0
yexo - 14 years ago 2010-03-06 01:58:55
yexo@openttd.org
(svn r19331) -Fix: when deleting an airport the size from the AirportSpec was used instead of the stored airport size
-Fix (r19319): detecting if a plane was landed at an airport failed
-Fix: reset the airporttile mapping when restarting a game
3 files changed with 4 insertions and 7 deletions:
0 comments (0 inline, 0 general)
src/newgrf_airporttiles.h
Show inline comments
 
/* $Id$ */
 

	
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file newgrf_airporttiles.h NewGRF handling of airport tiles. */
 

	
 
#ifndef NEWGRF_AIRPORTTILES_H
 
#define NEWGRF_AIRPORTTILES_H
 

	
 
#include "airport.h"
 
#include "station_map.h"
 
#include "newgrf_commons.h"
 
#include "airport.h"
 

	
 
/** Animation triggers for airport tiles */
 
enum AirpAnimationTrigger {
 
	AAT_BUILT,               ///< Triggered when the airport it build (for all tiles at the same time)
 
	AAT_TILELOOP,            ///< Triggered in the periodic tile loop
 
	AAT_STATION_NEW_CARGO,   ///< Triggered when new cargo arrives at the station (for all tiles at the same time)
 
	AAT_STATION_CARGO_TAKEN, ///< Triggered when a cargo type is completely removed from the station (for all tiles at the same time)
 
	AAT_STATION_250_ticks,   ///< Triggered every 250 ticks (for all tiles at the same time)
 
};
 

	
 
/**
 
 * Defines the data structure of each indivudual tile of an airport.
 
 */
 
struct AirportTileSpec {
 
	uint16 animation_info;                ///< Information about the animation (is it looping, how many loops etc)
 
	uint8 animation_speed;                ///< The speed of the animation
 

	
 
	StringID name;                        ///< Tile Subname string, land information on this tile will give you "AirportName (TileSubname)"
 
	uint8 callback_flags;                 ///< Flags telling which grf callback is set
 
	uint8 animation_triggers;             ///< When to start the animation
 
	uint8 animation_special_flags;        ///< Extra flags to influence the animation
 
	bool enabled;                         ///< entity still available (by default true). newgrf can disable it, though
 
	GRFFileProps grf_prop;                ///< properties related the the grf file
 

	
 
	static const AirportTileSpec *Get(StationGfx gfx);
 

	
 
	static void ResetAirportTiles();
 

	
 
private:
 
	static AirportTileSpec tiles[NUM_AIRPORTTILES];
 

	
 
	friend void AirportTileOverrideManager::SetEntitySpec(const AirportTileSpec *airpts);
 
};
 

	
 
StationGfx GetTranslatedAirportTileID(StationGfx gfx);
 
void AnimateAirportTile(TileIndex tile);
 
void AirportTileAnimationTrigger(Station *st, TileIndex tile, AirpAnimationTrigger trigger, CargoID cargo_type = CT_INVALID);
 
void AirportAnimationTrigger(Station *st, AirpAnimationTrigger trigger, CargoID cargo_type = CT_INVALID);
 
bool DrawNewAirportTile(TileInfo *ti, Station *st, StationGfx gfx, const AirportTileSpec *airts);
 

	
 
#endif /* NEWGRF_AIRPORTTILES_H */
src/openttd.cpp
Show inline comments
 
@@ -124,384 +124,385 @@ void CDECL error(const char *s, ...)
 
	va_end(va);
 

	
 
	ShowOSErrorBox(buf, true);
 

	
 
	/* Set the error message for the crash log and then invoke it. */
 
	CrashLog::SetErrorMessage(buf);
 
	abort();
 
}
 

	
 
/**
 
 * Shows some information on the console/a popup box depending on the OS.
 
 * @param str the text to show.
 
 */
 
void CDECL ShowInfoF(const char *str, ...)
 
{
 
	va_list va;
 
	char buf[1024];
 
	va_start(va, str);
 
	vsnprintf(buf, lengthof(buf), str, va);
 
	va_end(va);
 
	ShowInfo(buf);
 
}
 

	
 
/**
 
 * Show the help message when someone passed a wrong parameter.
 
 */
 
static void ShowHelp()
 
{
 
	char buf[8192];
 
	char *p = buf;
 

	
 
	p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
 
	p = strecpy(p,
 
		"\n"
 
		"\n"
 
		"Command line options:\n"
 
		"  -v drv              = Set video driver (see below)\n"
 
		"  -s drv              = Set sound driver (see below) (param bufsize,hz)\n"
 
		"  -m drv              = Set music driver (see below)\n"
 
		"  -b drv              = Set the blitter to use (see below)\n"
 
		"  -r res              = Set resolution (for instance 800x600)\n"
 
		"  -h                  = Display this help text\n"
 
		"  -t year             = Set starting year\n"
 
		"  -d [[fac=]lvl[,...]]= Debug mode\n"
 
		"  -e                  = Start Editor\n"
 
		"  -g [savegame]       = Start new/save game immediately\n"
 
		"  -G seed             = Set random seed\n"
 
#if defined(ENABLE_NETWORK)
 
		"  -n [ip:port#company]= Start networkgame\n"
 
		"  -p password         = Password to join server\n"
 
		"  -P password         = Password to join company\n"
 
		"  -D [ip][:port]      = Start dedicated server\n"
 
		"  -l ip[:port]        = Redirect DEBUG()\n"
 
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
 
		"  -f                  = Fork into the background (dedicated only)\n"
 
#endif
 
#endif /* ENABLE_NETWORK */
 
		"  -i palette          = Force to use the DOS (0) or Windows (1) palette\n"
 
		"                          (defines default setting when adding newgrfs)\n"
 
		"                        Default value (2) lets OpenTTD use the palette\n"
 
		"                          specified in graphics set file (see below)\n"
 
		"  -I graphics_set     = Force the graphics set (see below)\n"
 
		"  -S sounds_set       = Force the sounds set (see below)\n"
 
		"  -M music_set        = Force the music set (see below)\n"
 
		"  -c config_file      = Use 'config_file' instead of 'openttd.cfg'\n"
 
		"  -x                  = Do not automatically save to config file on exit\n"
 
		"\n",
 
		lastof(buf)
 
	);
 

	
 
	/* List the graphics packs */
 
	p = BaseGraphics::GetSetsList(p, lastof(buf));
 

	
 
	/* List the sounds packs */
 
	p = BaseSounds::GetSetsList(p, lastof(buf));
 

	
 
	/* List the music packs */
 
	p = BaseMusic::GetSetsList(p, lastof(buf));
 

	
 
	/* List the drivers */
 
	p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
 

	
 
	/* List the blitters */
 
	p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
 

	
 
	/* We need to initialize the AI, so it finds the AIs */
 
	AI::Initialize();
 
	p = AI::GetConsoleList(p, lastof(buf));
 
	AI::Uninitialize(true);
 

	
 
	/* ShowInfo put output to stderr, but version information should go
 
	 * to stdout; this is the only exception */
 
#if !defined(WIN32) && !defined(WIN64)
 
	printf("%s\n", buf);
 
#else
 
	ShowInfo(buf);
 
#endif
 
}
 

	
 

	
 
struct MyGetOptData {
 
	char *opt;
 
	int numleft;
 
	char **argv;
 
	const char *options;
 
	char *cont;
 

	
 
	MyGetOptData(int argc, char **argv, const char *options)
 
	{
 
		opt = NULL;
 
		numleft = argc;
 
		this->argv = argv;
 
		this->options = options;
 
		cont = NULL;
 
	}
 
};
 

	
 
static int MyGetOpt(MyGetOptData *md)
 
{
 
	char *s = md->cont;
 
	if (s != NULL)
 
		goto md_continue_here;
 

	
 
	for (;;) {
 
		if (--md->numleft < 0) return -1;
 

	
 
		s = *md->argv++;
 
		if (*s == '-') {
 
md_continue_here:;
 
			s++;
 
			if (*s != 0) {
 
				const char *r;
 
				/* Found argument, try to locate it in options. */
 
				if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
 
					/* ERROR! */
 
					return -2;
 
				}
 
				if (r[1] == ':') {
 
					char *t;
 
					/* 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;
 
		}
 
	}
 
}
 

	
 
/**
 
 * Extract the resolution from the given string and store
 
 * it in the 'res' parameter.
 
 * @param res variable to store the resolution in.
 
 * @param s   the string to decompose.
 
 */
 
static void ParseResolution(Dimension *res, const char *s)
 
{
 
	const char *t = strchr(s, 'x');
 
	if (t == NULL) {
 
		ShowInfoF("Invalid resolution '%s'", s);
 
		return;
 
	}
 

	
 
	res->width  = max(strtoul(s, NULL, 0), 64UL);
 
	res->height = max(strtoul(t + 1, NULL, 0), 64UL);
 
}
 

	
 
static void InitializeDynamicVariables()
 
{
 
	/* Dynamic stuff needs to be initialized somewhere... */
 
	_engine_mngr.ResetToDefaultMapping();
 
	_house_mngr.ResetMapping();
 
	_industry_mngr.ResetMapping();
 
	_industile_mngr.ResetMapping();
 
	_airporttile_mngr.ResetMapping();
 
}
 

	
 

	
 
/** Unitializes drivers, frees allocated memory, cleans pools, ...
 
 * Generally, prepares the game for shutting down
 
 */
 
static void ShutdownGame()
 
{
 
	IConsoleFree();
 

	
 
	if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
 

	
 
	DriverFactoryBase::ShutdownDrivers();
 

	
 
	UnInitWindowSystem();
 

	
 
	/* stop the AI */
 
	AI::Uninitialize(false);
 

	
 
	/* Uninitialize airport state machines */
 
	UnInitializeAirports();
 

	
 
	/* Uninitialize variables that are allocated dynamically */
 
	GamelogReset();
 
	_town_pool.CleanPool();
 
	_industry_pool.CleanPool();
 
	_station_pool.CleanPool();
 
	_roadstop_pool.CleanPool();
 
	_vehicle_pool.CleanPool();
 
	_sign_pool.CleanPool();
 
	_order_pool.CleanPool();
 
	_group_pool.CleanPool();
 
	_cargopacket_pool.CleanPool();
 
	_engine_pool.CleanPool();
 
	_company_pool.CleanPool();
 

	
 
	free(_config_file);
 

	
 
	/* Close all and any open filehandles */
 
	FioCloseAll();
 
}
 

	
 
static void LoadIntroGame()
 
{
 
	_game_mode = GM_MENU;
 

	
 
	ResetGRFConfig(false);
 

	
 
	/* Setup main window */
 
	ResetWindowSystem();
 
	SetupColoursAndInitialWindow();
 

	
 
	/* Load the default opening screen savegame */
 
	if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
 
		GenerateWorld(GWM_EMPTY, 64, 64); // if failed loading, make empty world.
 
		WaitTillGeneratedWorld();
 
		SetLocalCompany(COMPANY_SPECTATOR);
 
	} else {
 
		SetLocalCompany(COMPANY_FIRST);
 
	}
 

	
 
	_pause_mode = PM_UNPAUSED;
 
	_cursor.fix_at = false;
 

	
 
	CheckForMissingGlyphsInLoadedLanguagePack();
 

	
 
	/* Play main theme */
 
	if (_music_driver->IsSongPlaying()) ResetMusic();
 
}
 

	
 
void MakeNewgameSettingsLive()
 
{
 
#ifdef ENABLE_AI
 
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
 
		if (_settings_game.ai_config[c] != NULL) {
 
			delete _settings_game.ai_config[c];
 
		}
 
	}
 
#endif /* ENABLE_AI */
 

	
 
	_settings_game = _settings_newgame;
 

	
 
#ifdef ENABLE_AI
 
	for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
 
		_settings_game.ai_config[c] = NULL;
 
		if (_settings_newgame.ai_config[c] != NULL) {
 
			_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
 
		}
 
	}
 
#endif /* ENABLE_AI */
 
}
 

	
 
byte _savegame_sort_order;
 
#if defined(UNIX) && !defined(__MORPHOS__)
 
extern void DedicatedFork();
 
#endif
 

	
 
int ttd_main(int argc, char *argv[])
 
{
 
	int i;
 
	const char *optformat;
 
	char *musicdriver = NULL;
 
	char *sounddriver = NULL;
 
	char *videodriver = NULL;
 
	char *blitter = NULL;
 
	char *graphics_set = NULL;
 
	char *sounds_set = NULL;
 
	char *music_set = NULL;
 
	Dimension resolution = {0, 0};
 
	Year startyear = INVALID_YEAR;
 
	uint generation_seed = GENERATE_NEW_SEED;
 
	bool save_config = true;
 
#if defined(ENABLE_NETWORK)
 
	bool dedicated = false;
 
	bool network   = false;
 
	char *network_conn = NULL;
 
	char *debuglog_conn = NULL;
 
	char *dedicated_host = NULL;
 
	uint16 dedicated_port = 0;
 
	char *join_server_password = NULL;
 
	char *join_company_password = NULL;
 
#endif /* ENABLE_NETWORK */
 

	
 
	_game_mode = GM_MENU;
 
	_switch_mode = SM_MENU;
 
	_switch_mode_errorstr = INVALID_STRING_ID;
 
	_dedicated_forks = 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>) */
 
	optformat = "m:s:v:b:hD::n::ei::I:S:M:t:d::r:g::G:c:xl:p:P:"
 
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
 
		"f"
 
#endif
 
	;
 

	
 
	MyGetOptData mgo(argc - 1, argv + 1, optformat);
 

	
 
	while ((i = MyGetOpt(&mgo)) != -1) {
 
		switch (i) {
 
		case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
 
		case 'S': free(sounds_set); sounds_set = strdup(mgo.opt); break;
 
		case 'M': free(music_set); music_set = strdup(mgo.opt); break;
 
		case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
 
		case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
 
		case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
 
		case 'b': free(blitter); blitter = strdup(mgo.opt); break;
 
#if defined(ENABLE_NETWORK)
 
		case 'D':
 
			free(musicdriver);
 
			free(sounddriver);
 
			free(videodriver);
 
			free(blitter);
 
			musicdriver = strdup("null");
 
			sounddriver = strdup("null");
 
			videodriver = strdup("dedicated");
 
			blitter = strdup("null");
 
			dedicated = true;
 
			SetDebugString("net=6");
 
			if (mgo.opt != NULL) {
 
				/* Use the existing method for parsing (openttd -n).
 
				 * However, we do ignore the #company part. */
 
				const char *temp = NULL;
 
				const char *port = NULL;
 
				ParseConnectionString(&temp, &port, mgo.opt);
 
				if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
 
				if (port != NULL) dedicated_port = atoi(port);
 
			}
 
			break;
 
		case 'f': _dedicated_forks = true; break;
 
		case 'n':
 
			network = true;
 
			network_conn = mgo.opt; // optional IP parameter, NULL if unset
 
			break;
 
		case 'l':
 
			debuglog_conn = mgo.opt;
 
			break;
 
		case 'p':
 
			join_server_password = mgo.opt;
 
			break;
 
		case 'P':
 
			join_company_password = mgo.opt;
 
			break;
 
#endif /* ENABLE_NETWORK */
 
		case 'r': ParseResolution(&resolution, mgo.opt); break;
 
		case 't': startyear = atoi(mgo.opt); break;
 
		case 'd': {
 
#if defined(WIN32)
 
				CreateConsole();
src/station_cmd.cpp
Show inline comments
 
@@ -2040,425 +2040,422 @@ void UpdateAirportsNoise()
 
{
 
	Town *t;
 
	const Station *st;
 

	
 
	FOR_ALL_TOWNS(t) t->noise_reached = 0;
 

	
 
	FOR_ALL_STATIONS(st) {
 
		if (st->airport.tile != INVALID_TILE) {
 
			const AirportSpec *as = st->GetAirportSpec();
 
			Town *nearest = AirportGetNearestTown(as, st->airport.tile);
 
			nearest->noise_reached += GetAirportNoiseLevelForTown(as, nearest->xy, st->airport.tile);
 
		}
 
	}
 
}
 

	
 
/** Place an Airport.
 
 * @param tile tile where airport will be built
 
 * @param flags operation to perform
 
 * @param p1 airport type, @see airport.h
 
 * @param p2 various bitstuffed elements
 
 * - p2 = (bit     0) - allow airports directly adjacent to other airports.
 
 * - p2 = (bit 16-31) - station ID to join (NEW_STATION if build new one)
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	bool airport_upgrade = true;
 
	StationID station_to_join = GB(p2, 16, 16);
 
	bool reuse = (station_to_join != NEW_STATION);
 
	if (!reuse) station_to_join = INVALID_STATION;
 
	bool distant_join = (station_to_join != INVALID_STATION);
 

	
 
	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
 

	
 
	if (p1 >= NUM_AIRPORTS) return CMD_ERROR;
 

	
 
	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Check if a valid, buildable airport was chosen for construction */
 
	const AirportSpec *as = AirportSpec::Get(p1);
 
	if (!as->IsAvailable()) return CMD_ERROR;
 

	
 
	Town *t = ClosestTownFromTile(tile, UINT_MAX);
 
	int w = as->size_x;
 
	int h = as->size_y;
 

	
 
	if (w > _settings_game.station.station_spread || h > _settings_game.station.station_spread) {
 
		return_cmd_error(STR_ERROR_STATION_TOO_SPREAD_OUT);
 
	}
 

	
 
	CommandCost cost = CheckFlatLand(TileArea(tile, w, h), flags);
 
	if (cost.Failed()) return cost;
 

	
 
	/* Go get the final noise level, that is base noise minus factor from distance to town center */
 
	Town *nearest = AirportGetNearestTown(as, tile);
 
	uint newnoise_level = GetAirportNoiseLevelForTown(as, nearest->xy, tile);
 

	
 
	/* Check if local auth would allow a new airport */
 
	StringID authority_refuse_message = STR_NULL;
 

	
 
	if (_settings_game.economy.station_noise_level) {
 
		/* do not allow to build a new airport if this raise the town noise over the maximum allowed by town */
 
		if ((nearest->noise_reached + newnoise_level) > nearest->MaxTownNoise()) {
 
			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_NOISE;
 
		}
 
	} else {
 
		uint num = 0;
 
		const Station *st;
 
		FOR_ALL_STATIONS(st) {
 
			if (st->town == t && (st->facilities & FACIL_AIRPORT) && st->airport_type != AT_OILRIG) num++;
 
		}
 
		if (num >= 2) {
 
			authority_refuse_message = STR_ERROR_LOCAL_AUTHORITY_REFUSES_AIRPORT;
 
		}
 
	}
 

	
 
	if (authority_refuse_message != STR_NULL) {
 
		SetDParam(0, t->index);
 
		return_cmd_error(authority_refuse_message);
 
	}
 

	
 
	Station *st = NULL;
 
	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p2, 0), TileArea(tile, w, h), &st);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Distant join */
 
	if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
 

	
 
	/* Find a deleted station close to us */
 
	if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_company) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TEST)) return CMD_ERROR;
 

	
 
		if (st->airport.tile != INVALID_TILE) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_AIRPORT);
 
		}
 
	} else {
 
		airport_upgrade = false;
 

	
 
		/* allocate and initialize new station */
 
		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
 

	
 
		if (flags & DC_EXEC) {
 
			st = new Station(tile);
 

	
 
			st->town = t;
 
			st->string_id = GenerateStationName(st, tile, !(GetAirport(p1)->flags & AirportFTAClass::AIRPLANES) ? STATIONNAMING_HELIPORT : STATIONNAMING_AIRPORT);
 

	
 
			if (Company::IsValidID(_current_company)) {
 
				SetBit(st->town->have_ratings, _current_company);
 
			}
 
		}
 
	}
 

	
 
	cost.AddCost(_price[PR_BUILD_STATION_AIRPORT] * w * h);
 

	
 
	if (flags & DC_EXEC) {
 
		/* Always add the noise, so there will be no need to recalculate when option toggles */
 
		nearest->noise_reached += newnoise_level;
 

	
 
		st->AddFacility(FACIL_AIRPORT, tile);
 
		st->airport_type = (byte)p1;
 
		st->airport_flags = 0;
 

	
 
		st->rect.BeforeAddRect(tile, w, h, StationRect::ADD_TRY);
 

	
 
		const AirportTileTable *it = as->table[0];
 
		do {
 
			TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
 
			MakeAirport(cur_tile, st->owner, st->index, it->gfx);
 
			SetStationTileRandomBits(cur_tile, GB(Random(), 0, 4));
 
			st->airport.Add(cur_tile);
 

	
 
			if (AirportTileSpec::Get(GetTranslatedAirportTileID(it->gfx))->animation_info != 0xFFFF) AddAnimatedTile(cur_tile);
 
		} while ((++it)->ti.x != -0x80);
 

	
 
		/* Only call the animation trigger after all tiles have been built */
 
		it = as->table[0];
 
		do {
 
			TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
 
			AirportTileAnimationTrigger(st, cur_tile, AAT_BUILT);
 
		} while ((++it)->ti.x != -0x80);
 

	
 
		/* if airport was demolished while planes were en-route to it, the
 
		 * positions can no longer be the same (v->u.air.pos), since different
 
		 * airports have different indexes. So update all planes en-route to this
 
		 * airport. Only update if
 
		 * 1. airport is upgraded
 
		 * 2. airport is added to existing station (unfortunately unavoideable)
 
		 */
 
		if (airport_upgrade) UpdateAirplanesOnNewStation(st);
 

	
 
		st->UpdateVirtCoord();
 
		UpdateStationAcceptance(st, false);
 
		st->RecomputeIndustriesNear();
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
 

	
 
		if (_settings_game.economy.station_noise_level) {
 
			SetWindowDirty(WC_TOWN_VIEW, st->town->index);
 
		}
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Remove an airport
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags)
 
{
 
	Station *st = Station::GetByTile(tile);
 

	
 
	if (_current_company != OWNER_WATER && !CheckOwnership(st->owner)) {
 
		return CMD_ERROR;
 
	}
 

	
 
	tile = st->airport.tile;
 

	
 
	const AirportSpec *as = st->GetAirportSpec();
 
	int w = as->size_x;
 
	int h = as->size_y;
 

	
 
	CommandCost cost(EXPENSES_CONSTRUCTION);
 

	
 
	const Aircraft *a;
 
	FOR_ALL_AIRCRAFT(a) {
 
		if (!a->IsNormalAircraft()) continue;
 
		if (a->targetairport == st->index && a->state != FLYING) return CMD_ERROR;
 
	}
 

	
 
	TILE_AREA_LOOP(tile_cur, st->airport) {
 
		if (!st->TileBelongsToAirport(tile_cur)) continue;
 

	
 
		CommandCost ret = EnsureNoVehicleOnGround(tile);
 
		CommandCost ret = EnsureNoVehicleOnGround(tile_cur);
 
		ret.SetGlobalErrorMessage();
 
		if (ret.Failed()) return ret;
 

	
 
		cost.AddCost(_price[PR_CLEAR_STATION_AIRPORT]);
 

	
 
		if (flags & DC_EXEC) {
 
			DeleteAnimatedTile(tile_cur);
 
			DoClearSquare(tile_cur);
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		const AirportSpec *as = st->GetAirportSpec();
 
		for (uint i = 0; i < as->nof_depots; ++i) {
 
			DeleteWindowById(
 
				WC_VEHICLE_DEPOT, st->GetHangarTile(i)
 
			);
 
		}
 

	
 
		/* Go get the final noise level, that is base noise minus factor from distance to town center.
 
		 * And as for construction, always remove it, even if the setting is not set, in order to avoid the
 
		 * need of recalculation */
 
		Town *nearest = AirportGetNearestTown(as, tile);
 
		nearest->noise_reached -= GetAirportNoiseLevelForTown(as, nearest->xy, tile);
 

	
 
		st->rect.AfterRemoveRect(st, tile, w, h);
 
		st->rect.AfterRemoveRect(st, tile, st->airport.w, st->airport.h);
 

	
 
		st->airport.Clear();
 
		st->facilities &= ~FACIL_AIRPORT;
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_PLANES);
 

	
 
		if (_settings_game.economy.station_noise_level) {
 
			SetWindowDirty(WC_TOWN_VIEW, st->town->index);
 
		}
 

	
 
		st->UpdateVirtCoord();
 
		st->RecomputeIndustriesNear();
 
		DeleteStationIfEmpty(st);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/**
 
 * Tests whether the company's vehicles have this station in orders
 
 * When company == INVALID_COMPANY, then check all vehicles
 
 * @param station station ID
 
 * @param company company ID, INVALID_COMPANY to disable the check
 
 */
 
bool HasStationInUse(StationID station, CompanyID company)
 
{
 
	const Vehicle *v;
 
	FOR_ALL_VEHICLES(v) {
 
		if (company == INVALID_COMPANY || v->owner == company) {
 
			const Order *order;
 
			FOR_VEHICLE_ORDERS(v, order) {
 
				if ((order->IsType(OT_GOTO_STATION) || order->IsType(OT_GOTO_WAYPOINT)) && order->GetDestination() == station) {
 
					return true;
 
				}
 
			}
 
		}
 
	}
 
	return false;
 
}
 

	
 
static const TileIndexDiffC _dock_tileoffs_chkaround[] = {
 
	{-1,  0},
 
	{ 0,  0},
 
	{ 0,  0},
 
	{ 0, -1}
 
};
 
static const byte _dock_w_chk[4] = { 2, 1, 2, 1 };
 
static const byte _dock_h_chk[4] = { 1, 2, 1, 2 };
 

	
 
/** Build a dock/haven.
 
 * @param tile tile where dock will be built
 
 * @param flags operation to perform
 
 * @param p1 (bit 0) - allow docks directly adjacent to other docks.
 
 * @param p2 bit 16-31: station ID to join (NEW_STATION if build new one)
 
 * @param text unused
 
 * @return the cost of this operation or an error
 
 */
 
CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	StationID station_to_join = GB(p2, 16, 16);
 
	bool reuse = (station_to_join != NEW_STATION);
 
	if (!reuse) station_to_join = INVALID_STATION;
 
	bool distant_join = (station_to_join != INVALID_STATION);
 

	
 
	if (distant_join && (!_settings_game.station.distant_join_stations || !Station::IsValidID(station_to_join))) return CMD_ERROR;
 

	
 
	DiagDirection direction = GetInclinedSlopeDirection(GetTileSlope(tile, NULL));
 
	if (direction == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	direction = ReverseDiagDir(direction);
 

	
 
	/* Docks cannot be placed on rapids */
 
	if (IsWaterTile(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 

	
 
	CommandCost ret = CheckIfAuthorityAllowsNewStation(tile, flags);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
 

	
 
	if (DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
 

	
 
	TileIndex tile_cur = tile + TileOffsByDiagDir(direction);
 

	
 
	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
 
		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	}
 

	
 
	if (MayHaveBridgeAbove(tile_cur) && IsBridgeAbove(tile_cur)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
 

	
 
	/* Get the water class of the water tile before it is cleared.*/
 
	WaterClass wc = GetWaterClass(tile_cur);
 

	
 
	if (DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR).Failed()) return CMD_ERROR;
 

	
 
	tile_cur += TileOffsByDiagDir(direction);
 
	if (!IsTileType(tile_cur, MP_WATER) || GetTileSlope(tile_cur, NULL) != SLOPE_FLAT) {
 
		return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
 
	}
 

	
 
	/* middle */
 
	Station *st = NULL;
 
	ret = FindJoiningStation(INVALID_STATION, station_to_join, HasBit(p1, 0),
 
			TileArea(tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
					_dock_w_chk[direction], _dock_h_chk[direction]), &st);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	/* Distant join */
 
	if (st == NULL && distant_join) st = Station::GetIfValid(station_to_join);
 

	
 
	/* Find a deleted station close to us */
 
	if (st == NULL && reuse) st = GetClosestDeletedStation(tile);
 

	
 
	if (st != NULL) {
 
		if (st->owner != _current_company) {
 
			return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_STATION);
 
		}
 

	
 
		if (!st->rect.BeforeAddRect(
 
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
				_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TEST)) return CMD_ERROR;
 

	
 
		if (st->dock_tile != INVALID_TILE) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_DOCK);
 
	} else {
 
		/* allocate and initialize new station */
 
		if (!Station::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
 

	
 
		if (flags & DC_EXEC) {
 
			st = new Station(tile);
 

	
 
			st->town = ClosestTownFromTile(tile, UINT_MAX);
 
			st->string_id = GenerateStationName(st, tile, STATIONNAMING_DOCK);
 

	
 
			if (Company::IsValidID(_current_company)) {
 
				SetBit(st->town->have_ratings, _current_company);
 
			}
 
		}
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		st->dock_tile = tile;
 
		st->AddFacility(FACIL_DOCK, tile);
 

	
 
		st->rect.BeforeAddRect(
 
				tile + ToTileIndexDiff(_dock_tileoffs_chkaround[direction]),
 
				_dock_w_chk[direction], _dock_h_chk[direction], StationRect::ADD_TRY);
 

	
 
		MakeDock(tile, st->owner, st->index, direction, wc);
 

	
 
		st->UpdateVirtCoord();
 
		UpdateStationAcceptance(st, false);
 
		st->RecomputeIndustriesNear();
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
 
	}
 

	
 
	return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_STATION_DOCK]);
 
}
 

	
 
/**
 
 * Remove a dock
 
 * @param tile TileIndex been queried
 
 * @param flags operation to perform
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveDock(TileIndex tile, DoCommandFlag flags)
 
{
 
	Station *st = Station::GetByTile(tile);
 
	if (!CheckOwnership(st->owner)) return CMD_ERROR;
 

	
 
	TileIndex tile1 = st->dock_tile;
 
	TileIndex tile2 = tile1 + TileOffsByDiagDir(GetDockDirection(tile1));
 

	
 
	CommandCost ret = EnsureNoVehicleOnGround(tile1);
 
	if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile2);
 
	ret.SetGlobalErrorMessage();
 
	if (ret.Failed()) return ret;
 

	
 
	if (flags & DC_EXEC) {
 
		DoClearSquare(tile1);
 
		MakeWaterKeepingClass(tile2, st->owner);
 

	
 
		st->rect.AfterRemoveTile(st, tile1);
 
		st->rect.AfterRemoveTile(st, tile2);
 

	
 
		MarkTileDirtyByTile(tile2);
 

	
 
		st->dock_tile = INVALID_TILE;
 
		st->facilities &= ~FACIL_DOCK;
 

	
 
		SetWindowWidgetDirty(WC_STATION_VIEW, st->index, SVW_SHIPS);
0 comments (0 inline, 0 general)