Changeset - r4000:702cb45b8eab
[Not reviewed]
master
0 44 0
tron - 18 years ago 2006-06-10 08:37:41
tron@openttd.org
(svn r5210) Many small changes which piled up: const, unsigned, variable scope, CSE for readability, DeMorgan, if cascades -> switch, whitespace, parentheses, bracing, misc.
43 files changed with 380 insertions and 390 deletions:
0 comments (0 inline, 0 general)
ai/ai.c
Show inline comments
 
@@ -94,39 +94,42 @@ int32 AI_DoCommandCc(TileIndex tile, uin
 
	/* The test already resets _cmd_text, so backup the pointer */
 
	tmp_cmdtext = _cmd_text;
 

	
 
	/* First, do a test-run to see if we can do this */
 
	res = DoCommand(tile, p1, p2, flags & ~DC_EXEC, procc);
 
	/* The command failed, or you didn't want to execute, or you are quering, return */
 
	if ((CmdFailed(res)) || !(flags & DC_EXEC) || (flags & DC_QUERY_COST)) {
 
	if (CmdFailed(res) || !(flags & DC_EXEC) || (flags & DC_QUERY_COST)) {
 
		return res;
 
	}
 

	
 
	/* Restore _cmd_text */
 
	_cmd_text = tmp_cmdtext;
 

	
 
	/* If we did a DC_EXEC, and the command did not return an error, execute it
 
	    over the network */
 
	 * over the network */
 
	if (flags & DC_AUTO)                  procc |= CMD_AUTO;
 
	if (flags & DC_NO_WATER)              procc |= CMD_NO_WATER;
 

	
 
	/* NetworkSend_Command needs _local_player to be set correctly, so
 
	    adjust it, and put it back right after the function */
 
	 * adjust it, and put it back right after the function */
 
	old_lp = _local_player;
 
	_local_player = _current_player;
 

	
 
#ifdef ENABLE_NETWORK
 
	/* Send the command */
 
	if (_networking)
 
	if (_networking) {
 
		/* Network is easy, send it to his handler */
 
		NetworkSend_Command(tile, p1, p2, procc, callback);
 
	else
 
	} else {
 
#else
 
	{
 
#endif
 
		/* If we execute BuildCommands directly in SP, we have a big problem with events
 
		 *  so we need to delay is for 1 tick */
 
		AI_PutCommandInQueue(_current_player, tile, p1, p2, procc, callback);
 
	}
 

	
 
	/* Set _local_player back */
 
	_local_player = old_lp;
 

	
 
	return res;
 
}
 
@@ -170,31 +173,29 @@ void AI_RunGameLoop(void)
 

	
 
	/* Don't do anything if we are a network-client
 
	 *  (too bad when a client joins, he thinks the AIs are real, so it wants to control
 
	 *   them.. this avoids that, while loading a network game in singleplayer, does make
 
	 *   the AIs to continue ;))
 
	 */
 
	if (_networking && !_network_server && !_ai.network_client)
 
		return;
 
	if (_networking && !_network_server && !_ai.network_client) return;
 

	
 
	/* New tick */
 
	_ai.tick++;
 

	
 
	/* Make sure the AI follows the difficulty rule.. */
 
	assert(_opt.diff.competitor_speed <= 4);
 
	if ((_ai.tick & ((1 << (4 - _opt.diff.competitor_speed)) - 1)) != 0)
 
		return;
 
	if ((_ai.tick & ((1 << (4 - _opt.diff.competitor_speed)) - 1)) != 0) return;
 

	
 
	/* Check for AI-client (so joining a network with an AI) */
 
	if (_ai.network_client && _ai_player[_ai.network_playas].active) {
 
		/* Run the script */
 
		AI_DequeueCommands(_ai.network_playas);
 
		AI_RunTick(_ai.network_playas);
 
	} else if (!_networking || _network_server) {
 
		/* Check if we want to run AIs (server or SP only) */
 
		Player *p;
 
		const Player* p;
 

	
 
		FOR_ALL_PLAYERS(p) {
 
			if (p->is_active && p->is_ai) {
 
				/* This should always be true, else something went wrong... */
 
				assert(_ai_player[p->index].active);
 

	
 
@@ -221,14 +222,15 @@ void AI_StartNewAI(PlayerID player)
 

	
 
/**
 
 * This AI player died. Give it some chance to make a final puf.
 
 */
 
void AI_PlayerDied(PlayerID player)
 
{
 
	if (_ai.network_client && _ai.network_playas == player)
 
	if (_ai.network_client && _ai.network_playas == player) {
 
		_ai.network_playas = OWNER_SPECTATOR;
 
	}
 

	
 
	/* Called if this AI died */
 
	_ai_player[player].active = false;
 
}
 

	
 
/**
 
@@ -251,12 +253,12 @@ void AI_Initialize(void)
 

	
 
/**
 
 * Deinitializer for AI-related stuff.
 
 */
 
void AI_Uninitialize(void)
 
{
 
	Player* p;
 
	const Player* p;
 

	
 
	FOR_ALL_PLAYERS(p) {
 
		if (p->is_active && p->is_ai) AI_PlayerDied(p->index);
 
	}
 
}
ai/default/default.c
Show inline comments
 
@@ -347,15 +347,15 @@ static void AiHandleReplaceRoadVeh(Playe
 
		BackupVehicleOrders(v, orderbak);
 
		tile = v->tile;
 

	
 
		if (!CmdFailed(DoCommand(0, v->index, 0, DC_EXEC, CMD_SELL_ROAD_VEH)) &&
 
			  !CmdFailed(DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_ROAD_VEH)) ) {
 
			VehicleID veh = _new_vehicle_id;
 

	
 
			AiRestoreVehicleOrders(GetVehicle(veh), orderbak);
 
			DoCommand(0, veh, 0, DC_EXEC, CMD_START_STOP_ROADVEH);
 

	
 
			DoCommand(0, veh, _ai_service_interval, DC_EXEC, CMD_CHANGE_SERVICE_INT);
 
		}
 
	}
 
}
 

	
 
static void AiHandleReplaceAircraft(Player *p)
 
@@ -1605,14 +1605,13 @@ clear_town_stuff:;
 
				}
 
				if (CmdFailed(ret)) return CMD_ERROR;
 
				total_cost += ret;
 
			}
 
		} else if (p->mode == 3) {
 
			//Clear stuff and then build single rail.
 
			if (GetTileSlope(c, NULL) != SLOPE_FLAT)
 
				return CMD_ERROR;
 
			if (GetTileSlope(c, NULL) != SLOPE_FLAT) return CMD_ERROR;
 
			ret = DoCommand(c, 0, 0, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_LANDSCAPE_CLEAR);
 
			if (CmdFailed(ret)) return CMD_ERROR;
 
			total_cost += ret + _price.build_rail;
 

	
 
			if (flag & DC_EXEC) {
 
				DoCommand(c, railtype, p->attr&1, flag | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, CMD_BUILD_SINGLE_RAIL);
 
@@ -1924,22 +1923,22 @@ static bool AiCheckRailPathBetter(AiRail
 

	
 
	return better;
 
}
 

	
 
static inline void AiCheckBuildRailBridgeHere(AiRailFinder *arf, TileIndex tile, const byte *p)
 
{
 
	TileIndex tile_new;
 
	Slope tileh;
 
	uint z;
 
	bool flag;
 

	
 
	int dir2 = p[0] & 3;
 

	
 
	tileh = GetTileSlope(tile, &z);
 
	if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
 
		tile_new = tile;
 
		TileIndex tile_new = tile;
 

	
 
		// Allow bridges directly over bottom tiles
 
		flag = z == 0;
 
		for (;;) {
 
			TileType type;
 

	
 
			if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
 
@@ -1974,15 +1973,13 @@ static inline void AiCheckBuildRailTunne
 

	
 
	if (GetTileSlope(tile, &z) == _dir_table_2[p[0] & 3] && z != 0) {
 
		int32 cost = DoCommand(tile, arf->player->ai.railtype_to_use, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 

	
 
		if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
 
			AiBuildRailRecursive(arf, _build_tunnel_endtile, p[0]&3);
 
			if (arf->depth == 1) {
 
				AiCheckRailPathBetter(arf, p);
 
			}
 
			if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
 
		}
 
	}
 
}
 

	
 

	
 
static void AiBuildRailRecursive(AiRailFinder *arf, TileIndex tile, int dir)
 
@@ -2006,12 +2003,13 @@ static void AiBuildRailRecursive(AiRailF
 
		return;
 
	}
 

	
 
	// Depth too deep?
 
	if (arf->depth >= 4) {
 
		uint dist = DistanceMaxPlusManhattan(tile, arf->final_tile);
 

	
 
		if (dist < arf->cur_best_dist) {
 
			// Store the tile that is closest to the final position.
 
			arf->cur_best_depth = arf->depth;
 
			arf->cur_best_dist = dist;
 
			arf->cur_best_tile = tile;
 
			arf->cur_best_dir = dir;
 
@@ -2034,15 +2032,13 @@ static void AiBuildRailRecursive(AiRailF
 
			if (!AiIsTileBanned(arf->player, tile, p[0]) &&
 
					!CmdFailed(DoCommand(tile, arf->player->ai.railtype_to_use, p[0], DC_AUTO | DC_NO_WATER | DC_NO_RAIL_OVERLAP, CMD_BUILD_SINGLE_RAIL))) {
 
				AiBuildRailRecursive(arf, tile, p[1]);
 
			}
 

	
 
			// At the bottom depth?
 
			if (arf->depth == 1) {
 
				AiCheckRailPathBetter(arf, p);
 
			}
 
			if (arf->depth == 1) AiCheckRailPathBetter(arf, p);
 

	
 
			p += 2;
 
		} while (!(p[0]&0x80));
 
	}
 

	
 
	AiCheckBuildRailBridgeHere(arf, tile, p);
 
@@ -2090,14 +2086,15 @@ static void AiBuildRailConstruct(Player 
 
		return;
 
	}
 

	
 
	// Didn't find anything to build?
 
	if (arf.best_ptr == NULL) {
 
		// Terraform some
 
		for (i=0; i!=5; i++)
 
		for (i = 0; i != 5; i++) {
 
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
 
		}
 

	
 
		if (++p->ai.state_counter == 21) {
 
			p->ai.state_counter = 40;
 
			p->ai.state_mode = 1;
 

	
 
			// Ban this tile
 
@@ -2109,22 +2106,22 @@ static void AiBuildRailConstruct(Player 
 
	p->ai.cur_tile_a += TileOffsByDir(p->ai.cur_dir_a);
 

	
 
	if (arf.best_ptr[0] & 0x80) {
 
		int i;
 
		int32 bridge_len = GetBridgeLength(arf.bridge_end_tile, p->ai.cur_tile_a);
 

	
 
		/*	Figure out what (rail)bridge type to build
 
				start with best bridge, then go down to worse and worse bridges
 
				unnecessary to check for worse bridge (i=0), since AI will always build that.
 
				AI is so fucked up that fixing this small thing will probably not solve a thing
 
		/* Figure out which (rail)bridge type to build
 
		 * start with best bridge, then go down to worse and worse bridges
 
		 * unnecessary to check for worst bridge (i=0), since AI will always build
 
		 * that. AI is so fucked up that fixing this small thing will probably not
 
		 * solve a thing
 
		*/
 
		for (i = MAX_BRIDGES - 1; i != 0; i--) {
 
			if (CheckBridge_Stuff(i, bridge_len)) {
 
				int32 cost = DoCommand(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO, CMD_BUILD_BRIDGE);
 
				if (!CmdFailed(cost) && cost < (p->player_money >> 5))
 
					break;
 
				if (!CmdFailed(cost) && cost < (p->player_money >> 5)) break;
 
			}
 
		}
 

	
 
		// Build it
 
		DoCommand(arf.bridge_end_tile, p->ai.cur_tile_a, i | (p->ai.railtype_to_use << 8), DC_AUTO | DC_EXEC, CMD_BUILD_BRIDGE);
 

	
 
@@ -2345,15 +2342,13 @@ static EngineID AiFindBestWagon(CargoID 
 
		if (!IsCompatibleRail(e->railtype, railtype) ||
 
				!(rvi->flags & RVI_WAGON) ||
 
				!HASBIT(e->player_avail, _current_player)) {
 
			continue;
 
		}
 

	
 
		if (rvi->cargo_type != cargo) {
 
			continue;
 
		}
 
		if (rvi->cargo_type != cargo) continue;
 

	
 
		/* max_speed of 0 indicates no speed limit */
 
		speed = rvi->max_speed == 0 ? 0xFFFF : rvi->max_speed;
 

	
 
		if (rvi->capacity >= best_capacity && speed >= best_speed) {
 
			best_capacity = rvi->capacity;
 
@@ -2371,13 +2366,13 @@ static void AiStateBuildRailVeh(Player *
 
	TileIndex tile;
 
	EngineID veh;
 
	int i;
 
	CargoID cargo;
 
	int32 cost;
 
	Vehicle *v;
 
	uint loco_id;
 
	VehicleID loco_id;
 

	
 
	ptr = _default_rail_track_data[p->ai.src.cur_building_rule]->data;
 
	while (ptr->mode != 0) ptr++;
 

	
 
	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 
@@ -2392,20 +2387,18 @@ static void AiStateBuildRailVeh(Player *
 
			cost = DoCommand(tile, veh, 0, DC_EXEC, CMD_BUILD_RAIL_VEHICLE);
 
			if (CmdFailed(cost)) goto handle_nocash;
 
			p->ai.wagon_list[i] = _new_vehicle_id;
 
			p->ai.wagon_list[i + 1] = INVALID_VEHICLE;
 
			return;
 
		}
 
		if (cargo == CT_MAIL)
 
			cargo = CT_PASSENGERS;
 
		if (++i == p->ai.num_wagons * 2 - 1)
 
			break;
 
		if (cargo == CT_MAIL) cargo = CT_PASSENGERS;
 
		if (++i == p->ai.num_wagons * 2 - 1) break;
 
	}
 

	
 
	// Which locomotive to build?
 
	veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, (cargo!=CT_PASSENGERS)?1:0, tile);
 
	veh = AiChooseTrainToBuild(p->ai.railtype_to_use, p->player_money, cargo != CT_PASSENGERS ? 1 : 0, tile);
 
	if (veh == INVALID_ENGINE) {
 
handle_nocash:
 
		// after a while, if AI still doesn't have cash, get out of this block by selling the wagons.
 
		if (++p->ai.state_counter == 1000) {
 
			for (i = 0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
 
				cost = DoCommand(tile, p->ai.wagon_list[i], 0, DC_EXEC, CMD_SELL_RAIL_WAGON);
 
@@ -2432,13 +2425,13 @@ handle_nocash:
 
	// Move the wagons onto the train
 
	for (i = 0; p->ai.wagon_list[i] != INVALID_VEHICLE; i++) {
 
		DoCommand(tile, p->ai.wagon_list[i] | (loco_id << 16), 0, DC_EXEC, CMD_MOVE_RAIL_VEHICLE);
 
	}
 

	
 
	for (i = 0; p->ai.order_list_blocks[i] != 0xFF; i++) {
 
		AiBuildRec *aib = (&p->ai.src) + p->ai.order_list_blocks[i];
 
		const AiBuildRec* aib = &p->ai.src + p->ai.order_list_blocks[i];
 
		bool is_pass = (
 
			p->ai.cargo_type == CT_PASSENGERS ||
 
			p->ai.cargo_type == CT_MAIL ||
 
			(_opt.landscape == LT_NORMAL && p->ai.cargo_type == CT_VALUABLES)
 
		);
 
		Order order;
 
@@ -2612,17 +2605,14 @@ clear_town_stuff:;
 
	return total_cost;
 
}
 

	
 
// Make sure the blocks are not too close to each other
 
static bool AiCheckBlockDistances(Player *p, TileIndex tile)
 
{
 
	AiBuildRec *aib;
 
	int num;
 

	
 
	num = p->ai.num_build_rec;
 
	aib = &p->ai.src;
 
	const AiBuildRec* aib = &p->ai.src;
 
	uint num = p->ai.num_build_rec;
 

	
 
	do {
 
		if (aib->cur_building_rule != 255) {
 
			if (DistanceManhattan(aib->use_tile, tile) < 9) return false;
 
		}
 
	} while (++aib, --num);
 
@@ -2832,22 +2822,22 @@ static bool AiBuildRoadHelper(TileIndex 
 
	};
 
	return !CmdFailed(DoCommand(tile, _road_bits[type], 0, flags, CMD_BUILD_ROAD));
 
}
 

	
 
static inline void AiCheckBuildRoadBridgeHere(AiRoadFinder *arf, TileIndex tile, const byte *p)
 
{
 
	TileIndex tile_new;
 
	Slope tileh;
 
	uint z;
 
	bool flag;
 

	
 
	int dir2 = p[0] & 3;
 

	
 
	tileh = GetTileSlope(tile, &z);
 
	if (tileh == _dir_table_1[dir2] || (tileh == SLOPE_FLAT && z != 0)) {
 
		tile_new = tile;
 
		TileIndex tile_new = tile;
 

	
 
		// Allow bridges directly over bottom tiles
 
		flag = z == 0;
 
		for (;;) {
 
			TileType type;
 

	
 
			if ((TileIndexDiff)tile_new < -TileOffsByDir(dir2)) return; // Wraping around map, no bridge possible!
 
@@ -2882,15 +2872,13 @@ static inline void AiCheckBuildRoadTunne
 

	
 
	if (GetTileSlope(tile, &z) == _dir_table_2[p[0] & 3] && z != 0) {
 
		int32 cost = DoCommand(tile, 0x200, 0, DC_AUTO, CMD_BUILD_TUNNEL);
 

	
 
		if (!CmdFailed(cost) && cost <= (arf->player->player_money>>4)) {
 
			AiBuildRoadRecursive(arf, _build_tunnel_endtile, p[0]&3);
 
			if (arf->depth == 1) {
 
				AiCheckRoadPathBetter(arf, p);
 
			}
 
			if (arf->depth == 1)  AiCheckRoadPathBetter(arf, p);
 
		}
 
	}
 
}
 

	
 

	
 

	
 
@@ -3029,13 +3017,12 @@ do_some_terraform:
 
	} else if (arf.best_ptr[0]&0x40) {
 
		// tunnel
 
		DoCommand(tile, 0x200, 0, DC_AUTO | DC_EXEC, CMD_BUILD_TUNNEL);
 
		p->ai.cur_tile_a = _build_tunnel_endtile;
 
		p->ai.state_counter = 0;
 
	} else {
 

	
 
		// road
 
		if (!AiBuildRoadHelper(tile, DC_EXEC | DC_AUTO | DC_NO_WATER | DC_AI_BUILDING, arf.best_ptr[0]))
 
			goto do_some_terraform;
 

	
 
		p->ai.cur_dir_a = arf.best_ptr[1];
 
		p->ai.cur_tile_a = tile;
 
@@ -3059,14 +3046,15 @@ static void AiBuildRoad(Player *p)
 
		p->ai.state_mode = 2;
 
		p->ai.state_counter = 0;
 
	} else if (p->ai.state_mode == 2) {
 
		uint i;
 

	
 
		// Terraform some and then try building again.
 
		for (i = 0; i != 4; i++)
 
		for (i = 0; i != 4; i++) {
 
			AiDoTerraformLand(p->ai.cur_tile_a, p->ai.cur_dir_a, 3, 0);
 
		}
 

	
 
		if (++p->ai.state_counter == 4) {
 
			p->ai.state_counter = 0;
 
			p->ai.state_mode = 0;
 
		}
 
	}
 
@@ -3153,13 +3141,13 @@ static StationID AiGetStationIdFromRoadB
 
}
 

	
 
static void AiStateBuildRoadVehicles(Player *p)
 
{
 
	const AiDefaultBlockData *ptr;
 
	TileIndex tile;
 
	uint loco_id;
 
	VehicleID loco_id;
 
	EngineID veh;
 
	uint i;
 

	
 
	ptr = _road_default_block_data[p->ai.src.cur_building_rule]->data;
 
	for (; ptr->mode != 0; ptr++) {}
 
	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 
@@ -3224,13 +3212,13 @@ static void AiStateDeleteRoadBlocks(Play
 
	p->ai.state = AIS_0;
 
}
 

	
 

	
 
static void AiStateAirportStuff(Player *p)
 
{
 
	Station *st;
 
	const Station* st;
 
	byte acc_planes;
 
	int i;
 
	AiBuildRec *aib;
 
	byte rule;
 

	
 
	// Here we look for an airport we could use instead of building a new
 
@@ -3446,13 +3434,13 @@ static StationID AiGetStationIdFromAircr
 
static void AiStateBuildAircraftVehicles(Player *p)
 
{
 
	const AiDefaultBlockData *ptr;
 
	TileIndex tile;
 
	EngineID veh;
 
	int i;
 
	uint loco_id;
 
	VehicleID loco_id;
 

	
 
	ptr = _airport_default_block_data[p->ai.src.cur_building_rule];
 
	for (;ptr->mode!=0;ptr++) {}
 

	
 
	tile = TILE_ADD(p->ai.src.use_tile, ToTileIndexDiff(ptr->tileoffs));
 

	
 
@@ -3661,33 +3649,26 @@ pos_3:
 
		if (!IsTileOwner(tile, _current_player)) return;
 

	
 
		if (IsLevelCrossing(tile)) goto is_rail_crossing;
 

	
 
		if (GetRoadTileType(tile) == ROAD_TILE_DEPOT) {
 
			DiagDirection dir;
 
			TileIndex t;
 

	
 
			// Check if there are any stations around.
 
			if (IsTileType(tile + TileDiffXY(-1, 0), MP_STATION) &&
 
					IsTileOwner(tile + TileDiffXY(-1, 0), _current_player)) {
 
				return;
 
			}
 

	
 
			if (IsTileType(tile + TileDiffXY(1, 0), MP_STATION) &&
 
					IsTileOwner(tile + TileDiffXY(1, 0), _current_player)) {
 
				return;
 
			}
 

	
 
			if (IsTileType(tile + TileDiffXY(0, -1), MP_STATION) &&
 
					IsTileOwner(tile + TileDiffXY(0, -1), _current_player)) {
 
				return;
 
			}
 

	
 
			if (IsTileType(tile + TileDiffXY(0, 1), MP_STATION) &&
 
					IsTileOwner(tile + TileDiffXY(0, 1), _current_player)) {
 
				return;
 
			}
 
			t = tile + TileDiffXY(-1, 0);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 

	
 
			t = tile + TileDiffXY(1, 0);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 

	
 
			t = tile + TileDiffXY(0, -1);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 

	
 
			t = tile + TileDiffXY(0, 1);
 
			if (IsTileType(t, MP_STATION) && IsTileOwner(t, _current_player)) return;
 

	
 
			dir = GetRoadDepotDirection(tile);
 

	
 
			DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
 
			DoCommand(
 
				TILE_MASK(tile + TileOffsByDir(dir)),
 
@@ -3878,14 +3859,13 @@ void AiDoGameLoop(Player *p)
 
	// Ugly hack to make sure the service interval of the AI is good, not looking
 
	//  to the patch-setting
 
	// Also, it takes into account the setting if the service-interval is in days
 
	//  or in %
 
	_ai_service_interval = _patches.servint_ispercent?80:180;
 

	
 
	if (IS_HUMAN_PLAYER(_current_player))
 
		return;
 
	if (IS_HUMAN_PLAYER(_current_player)) return;
 

	
 
	AiAdjustLoan(p);
 
	AiBuildCompanyHQ(p);
 

	
 
#if 0
 
	{
ai/trolly/build.c
Show inline comments
 
@@ -65,21 +65,22 @@ int AiNew_Build_Bridge(Player *p, TileIn
 
			type2 = type;
 
			type = bridge_type;
 
			// We found two bridges, exit
 
			if (type2 != 0) break;
 
		}
 
	}
 
	// There is only one bridge that can be build..
 
	// There is only one bridge that can be built
 
	if (type2 == 0 && type != 0) type2 = type;
 

	
 
	// Now, simply, build the bridge!
 
	if (p->ainew.tbt == AI_TRAIN)
 
		return AI_DoCommand(tile_a, tile_b, (0<<8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
 

	
 
	if (p->ainew.tbt == AI_TRAIN) {
 
		return AI_DoCommand(tile_a, tile_b, (0x00 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
 
	} else {
 
	return AI_DoCommand(tile_a, tile_b, (0x80 << 8) + type2, flag | DC_AUTO, CMD_BUILD_BRIDGE);
 
}
 
}
 

	
 

	
 
// Build the route part by part
 
// Basicly what this function do, is build that amount of parts of the route
 
//  that go in the same direction. It sets 'part' to the last part of the route builded.
 
//  The return value is the cost for the builded parts
 
@@ -99,34 +100,37 @@ int AiNew_Build_RoutePart(Player *p, Ai_
 
	int cost = 0;
 
	int res;
 
	// We need to calculate the direction with the parent of the parent.. so we skip
 
	//  the first pieces and the last piece
 
	if (part < 1) part = 1;
 
	// When we are done, stop it
 
	if (part >= PathFinderInfo->route_length - 1) { PathFinderInfo->position = -2; return 0; }
 
	if (part >= PathFinderInfo->route_length - 1) {
 
		PathFinderInfo->position = -2;
 
		return 0;
 
	}
 

	
 

	
 
	if (PathFinderInfo->rail_or_road) {
 
		// Tunnel code
 
		if ((AI_PATHFINDER_FLAG_TUNNEL & route_extra[part]) != 0) {
 
			cost += AI_DoCommand(route[part], 0, 0, flag, CMD_BUILD_TUNNEL);
 
			PathFinderInfo->position++;
 
			// TODO: problems!
 
			if (CmdFailed(cost)) {
 
				DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be build!");
 
				DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: tunnel could not be built!");
 
				return 0;
 
			}
 
			return cost;
 
		}
 
		// Bridge code
 
		if ((AI_PATHFINDER_FLAG_BRIDGE & route_extra[part]) != 0) {
 
			cost += AiNew_Build_Bridge(p, route[part], route[part-1], flag);
 
			PathFinderInfo->position++;
 
			// TODO: problems!
 
			if (CmdFailed(cost)) {
 
				DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be build!");
 
				DEBUG(ai,0)("[AiNew - BuildPath] We have a serious problem: bridge could not be built!");
 
				return 0;
 
			}
 
			return cost;
 
		}
 

	
 
		// Build normal rail
ai/trolly/pathfinder.c
Show inline comments
 
@@ -54,13 +54,14 @@ static bool IsRoad(TileIndex tile)
 
#define TILES_BETWEEN(a, b, c) (TileX(a) >= TileX(b) && TileX(a) <= TileX(c) && TileY(a) >= TileY(b) && TileY(a) <= TileY(c))
 

	
 

	
 
// Check if the current tile is in our end-area
 
static int32 AyStar_AiPathFinder_EndNodeCheck(AyStar *aystar, OpenListNode *current)
 
{
 
	Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
 
	const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
 

	
 
	// It is not allowed to have a station on the end of a bridge or tunnel ;)
 
	if (current->path.node.user_data[0] != 0) return AYSTAR_DONE;
 
	if (TILES_BETWEEN(current->path.node.tile, PathFinderInfo->end_tile_tl, PathFinderInfo->end_tile_br))
 
		if (IsTileType(current->path.node.tile, MP_CLEAR) || IsTileType(current->path.node.tile, MP_TREES))
 
			if (current->path.parent == NULL || TestCanBuildStationHere(current->path.node.tile, AiNew_GetDirection(current->path.parent->node.tile, current->path.node.tile)))
 
				return AYSTAR_FOUND_END_NODE;
 
@@ -152,26 +153,29 @@ void clean_AyStar_AiPathFinder(AyStar *a
 
	start_node.node.user_data[0] = 0;
 
	start_node.node.tile = PathFinderInfo->start_tile_tl;
 

	
 
	// Now we add all the starting tiles
 
	for (x = TileX(PathFinderInfo->start_tile_tl); x <= TileX(PathFinderInfo->start_tile_br); x++) {
 
		for (y = TileY(PathFinderInfo->start_tile_tl); y <= TileY(PathFinderInfo->start_tile_br); y++) {
 
			if (!(IsTileType(TileXY(x, y), MP_CLEAR) || IsTileType(TileXY(x, y), MP_TREES))) continue;
 
			if (!TestCanBuildStationHere(TileXY(x, y), TEST_STATION_NO_DIR)) continue;
 
			start_node.node.tile = TileXY(x, y);
 
			TileIndex tile = TileXY(x, y);
 

	
 
			if (!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) continue;
 
			if (!TestCanBuildStationHere(tile, TEST_STATION_NO_DIR)) continue;
 
			start_node.node.tile = tile;
 
			aystar->addstart(aystar, &start_node.node, 0);
 
		}
 
	}
 
}
 

	
 

	
 
// The h-value, simple calculation
 
static int32 AyStar_AiPathFinder_CalculateH(AyStar *aystar, AyStarNode *current, OpenListNode *parent)
 
{
 
	Ai_PathFinderInfo *PathFinderInfo = (Ai_PathFinderInfo*)aystar->user_target;
 
	const Ai_PathFinderInfo* PathFinderInfo = aystar->user_target;
 
	int r, r2;
 

	
 
	if (PathFinderInfo->end_direction != AI_PATHFINDER_NO_DIRECTION) {
 
		// The station is pointing to a direction, add a tile towards that direction, so the H-value is more accurate
 
		r = DistanceManhattan(current->tile, PathFinderInfo->end_tile_tl + TileOffsByDir(PathFinderInfo->end_direction));
 
		r2 = DistanceManhattan(current->tile, PathFinderInfo->end_tile_br + TileOffsByDir(PathFinderInfo->end_direction));
 
	} else {
 
		// No direction, so just get the fastest route to the station
 
@@ -444,36 +448,39 @@ static int32 AyStar_AiPathFinder_Calcula
 
	if ((AI_PATHFINDER_FLAG_BRIDGE & current->user_data[0]) != 0) {
 
		// That means for every length a penalty
 
		res += AI_PATHFINDER_BRIDGE_PENALTY * GetBridgeLength(current->tile, parent->path.node.tile);
 
		// Check if we are going up or down, first for the starting point
 
		// In user_data[0] is at the 8th bit the direction
 
		if (!HASBIT(BRIDGE_NO_FOUNDATION, parent_tileh)) {
 
			if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15)
 
			if (GetBridgeFoundation(parent_tileh, (current->user_data[0] >> 8) & 1) < 15) {
 
				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 
		}
 
		}
 
		// Second for the end point
 
		if (!HASBIT(BRIDGE_NO_FOUNDATION, tileh)) {
 
			if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15)
 
			if (GetBridgeFoundation(tileh, (current->user_data[0] >> 8) & 1) < 15) {
 
				res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 
		}
 
		}
 
		if (parent_tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 
		if (tileh == SLOPE_FLAT) res += AI_PATHFINDER_BRIDGE_GOES_UP_PENALTY;
 
	}
 

	
 
	//  To prevent the AI from taking the fastest way in tiles, but not the fastest way
 
	//    in speed, we have to give a good penalty to direction changing
 
	//  This way, we get almost the fastest way in tiles, and a very good speed on the track
 
	if (!PathFinderInfo->rail_or_road) {
 
		if (parent->path.parent != NULL &&
 
				AiNew_GetDirection(current->tile, parent->path.node.tile) != AiNew_GetDirection(parent->path.node.tile, parent->path.parent->node.tile)) {
 
			// When road exists, we don't like turning, but its free, so don't be to piggy about it
 
			if (IsRoad(parent->path.node.tile))
 
			if (IsRoad(parent->path.node.tile)) {
 
				res += AI_PATHFINDER_DIRECTION_CHANGE_ON_EXISTING_ROAD_PENALTY;
 
			else
 
			} else {
 
				res += AI_PATHFINDER_DIRECTION_CHANGE_PENALTY;
 
		}
 
		}
 
	} else {
 
		// For rail we have 1 exeption: diagonal rail..
 
		// So we fetch 2 raildirection. That of the current one, and of the one before that
 
		if (parent->path.parent != NULL && parent->path.parent->parent != NULL) {
 
			int dir1 = AiNew_GetRailDirection(parent->path.parent->node.tile, parent->path.node.tile, current->tile);
 
			int dir2 = AiNew_GetRailDirection(parent->path.parent->parent->node.tile, parent->path.parent->node.tile, parent->path.node.tile);
ai/trolly/trolly.c
Show inline comments
 
@@ -125,22 +125,25 @@ static void AiNew_State_WakeUp(Player *p
 
			// Check all vehicles once in a while
 
			p->ainew.action = AI_ACTION_CHECK_ALL_VEHICLES;
 
			p->ainew.last_vehiclecheck_date = _date;
 
		} else if (c < 100 && !_patches.ai_disable_veh_roadveh) {
 
			// Do we have any spots for road-vehicles left open?
 
			if (GetFreeUnitNumber(VEH_Road) <= _patches.max_roadveh) {
 
				if (c < 85)
 
				if (c < 85) {
 
					p->ainew.action = AI_ACTION_TRUCK_ROUTE;
 
				else
 
				} else {
 
					p->ainew.action = AI_ACTION_BUS_ROUTE;
 
			}
 
		}/* else if (c < 200 && !_patches.ai_disable_veh_train) {
 
			}
 
#if 0
 
		} else if (c < 200 && !_patches.ai_disable_veh_train) {
 
			if (GetFreeUnitNumber(VEH_Train) <= _patches.max_trains) {
 
				p->ainew.action = AI_ACTION_TRAIN_ROUTE;
 
			}
 
		}*/
 
#endif
 
		}
 

	
 
		p->ainew.counter = 0;
 
	}
 

	
 
	if (p->ainew.counter++ > AI_MAX_TRIES_FOR_SAME_ROUTE) {
 
		p->ainew.action = AI_ACTION_NONE;
 
@@ -205,14 +208,14 @@ static void AiNew_State_ActionDone(Playe
 

	
 

	
 
// Check if a city or industry is good enough to start a route there
 
static bool AiNew_Check_City_or_Industry(Player *p, int ic, byte type)
 
{
 
	if (type == AI_CITY) {
 
		Town *t = GetTown(ic);
 
		Station *st;
 
		const Town* t = GetTown(ic);
 
		const Station* st;
 
		uint count = 0;
 
		int j = 0;
 

	
 
		// We don't like roadconstructions, don't even true such a city
 
		if (t->road_build_months != 0) return false;
 

	
 
@@ -267,14 +270,14 @@ static bool AiNew_Check_City_or_Industry
 
		if (count * AI_CHECKCITY_CARGO_PER_STATION > t->max_pass) return false;
 

	
 
		// All check are okay, so we can build here!
 
		return true;
 
	}
 
	if (type == AI_INDUSTRY) {
 
		Industry *i = GetIndustry(ic);
 
		Station *st;
 
		const Industry* i = GetIndustry(ic);
 
		const Station* st;
 
		int count = 0;
 
		int j = 0;
 

	
 
		if (i->town != NULL && i->town->ratings[_current_player] < 0 && AI_CHANCE16(1,4)) return false;
 

	
 
		// No limits on delevering stations!
 
@@ -376,17 +379,18 @@ static void AiNew_State_LocateRoute(Play
 
	}
 

	
 
	// We are going to locate a city from where we are going to connect
 
	if (p->ainew.from_ic == -1) {
 
		if (p->ainew.temp == -1) {
 
			// First, we pick a random spot to search from
 
			if (p->ainew.from_type == AI_CITY)
 
			if (p->ainew.from_type == AI_CITY) {
 
				p->ainew.temp = AI_RandomRange(_total_towns);
 
			else
 
			} else {
 
				p->ainew.temp = AI_RandomRange(_total_industries);
 
		}
 
		}
 

	
 
		if (!AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.from_type)) {
 
			// It was not a valid city
 
			//  increase the temp with one, and return. We will come back later here
 
			//  to try again
 
			p->ainew.temp++;
 
@@ -411,26 +415,28 @@ static void AiNew_State_LocateRoute(Play
 
		return;
 
	}
 

	
 
	// Find a to-city
 
	if (p->ainew.temp == -1) {
 
		// First, we pick a random spot to search to
 
		if (p->ainew.to_type == AI_CITY)
 
		if (p->ainew.to_type == AI_CITY) {
 
			p->ainew.temp = AI_RandomRange(_total_towns);
 
		else
 
		} else {
 
			p->ainew.temp = AI_RandomRange(_total_industries);
 
	}
 
	}
 

	
 
	// The same city is not allowed
 
	// Also check if the city is valid
 
	if (p->ainew.temp != p->ainew.from_ic && AiNew_Check_City_or_Industry(p, p->ainew.temp, p->ainew.to_type)) {
 
		// Maybe it is valid..
 

	
 
		// We need to know if they are not to far apart from eachother..
 
		// We do that by checking how much cargo we have to move and how long the route
 
		//   is.
 
		/* We need to know if they are not to far apart from eachother..
 
		 * We do that by checking how much cargo we have to move and how long the
 
		 * route is.
 
		 */
 

	
 
		if (p->ainew.from_type == AI_CITY && p->ainew.tbt == AI_BUS) {
 
			const Town* town_from = GetTown(p->ainew.from_ic);
 
			const Town* town_temp = GetTown(p->ainew.temp);
 
			uint distance = DistanceManhattan(town_from->xy, town_temp->xy);
 
			int max_cargo;
 
@@ -467,13 +473,13 @@ static void AiNew_State_LocateRoute(Play
 
			// TODO: in max_cargo, also check other cargo (beside [0])
 
			// First we check if the from_ic produces cargo that this ic accepts
 
			if (ind_from->produced_cargo[0] != CT_INVALID && ind_from->total_production[0] != 0) {
 
				for (i = 0; i < lengthof(ind_temp->accepts_cargo); i++) {
 
					if (ind_temp->accepts_cargo[i] == CT_INVALID) break;
 
					if (ind_from->produced_cargo[0] == ind_temp->accepts_cargo[i]) {
 
						// Found a compatbiel industry
 
						// Found a compatible industry
 
						max_cargo = ind_from->total_production[0] - ind_from->total_transported[0];
 
						found = true;
 
						p->ainew.from_deliver = true;
 
						p->ainew.to_deliver = false;
 
						break;
 
					}
 
@@ -669,13 +675,13 @@ static void AiNew_State_FindStation(Play
 
					found_spot[i] = new_tile;
 
					found_best[i++] = accepts[p->ainew.cargo];
 
				}
 
			}
 
		}
 

	
 
		// If i is still zero, we did not found anything :(
 
		// If i is still zero, we did not find anything
 
		if (i == 0) {
 
			p->ainew.state = AI_STATE_NOTHING;
 
			return;
 
		}
 

	
 
		// Go through all the found_best and check which has the highest value
 
@@ -750,39 +756,37 @@ static void AiNew_State_FindPath(Player 
 
		} else {
 
			p->ainew.path_info.end_tile_tl = p->ainew.to_tile;
 
			p->ainew.path_info.end_tile_br = p->ainew.to_tile;
 
			p->ainew.path_info.end_direction = p->ainew.to_direction;
 
		}
 

	
 
		if (p->ainew.tbt == AI_TRAIN)
 
			p->ainew.path_info.rail_or_road = true;
 
		else
 
			p->ainew.path_info.rail_or_road = false;
 
		p->ainew.path_info.rail_or_road = (p->ainew.tbt == AI_TRAIN);
 

	
 
		// First, clean the pathfinder with our new begin and endpoints
 
		clean_AyStar_AiPathFinder(p->ainew.pathfinder, &p->ainew.path_info);
 

	
 
		p->ainew.temp = 0;
 
	}
 

	
 
	// Start the pathfinder
 
	r = p->ainew.pathfinder->main(p->ainew.pathfinder);
 
	// If it return: no match, stop it...
 
	if (r == AYSTAR_NO_PATH) {
 
	switch (r) {
 
		case AYSTAR_NO_PATH:
 
		DEBUG(ai,1)("[AiNew] PathFinder found no route!");
 
		// Start all over again...
 
			// Start all over again
 
		p->ainew.state = AI_STATE_NOTHING;
 
		return;
 
	}
 
	if (r == AYSTAR_FOUND_END_NODE) {
 
		// We found the end-point
 
			break;
 

	
 
		case AYSTAR_FOUND_END_NODE: // We found the end-point
 
		p->ainew.temp = -1;
 
		p->ainew.state = AI_STATE_FIND_DEPOT;
 
		return;
 
			break;
 

	
 
		// In any other case, we are still busy finding the route
 
		default: break;
 
	}
 
	// In any other case, we are still busy finding the route...
 
}
 

	
 

	
 
// This function tries to locate a good place for a depot!
 
static void AiNew_State_FindDepot(Player *p)
 
{
 
@@ -897,16 +901,17 @@ static int AiNew_HowManyVehicles(Player 
 
		i = AiNew_PickVehicle(p);
 
		if (i == INVALID_ENGINE) return 0;
 
		// Passenger run.. how long is the route?
 
		length = p->ainew.path_info.route_length;
 
		// Calculating tiles a day a vehicle moves is not easy.. this is how it must be done!
 
		tiles_a_day = RoadVehInfo(i)->max_speed * DAY_TICKS / 256 / 16;
 
		if (p->ainew.from_deliver)
 
		if (p->ainew.from_deliver) {
 
			max_cargo = GetIndustry(p->ainew.from_ic)->total_production[0];
 
		else
 
		} else {
 
			max_cargo = GetIndustry(p->ainew.to_ic)->total_production[0];
 
		}
 

	
 
		// This is because moving 60% is more than we can dream of!
 
		max_cargo *= 0.6;
 
		// We want all the cargo to be gone in a month.. so, we know the cargo it delivers
 
		//  we know what the vehicle takes with him, and we know the time it takes him
 
		//  to get back here.. now let's do some math!
 
@@ -1106,13 +1111,13 @@ static void AiNew_State_BuildDepot(Playe
 
{
 
	int res = 0;
 
	assert(p->ainew.state == AI_STATE_BUILD_DEPOT);
 

	
 
	if (IsTileType(p->ainew.depot_tile, MP_STREET) && GetRoadTileType(p->ainew.depot_tile) == ROAD_TILE_DEPOT) {
 
		if (IsTileOwner(p->ainew.depot_tile, _current_player)) {
 
			// The depot is already builded!
 
			// The depot is already built
 
			p->ainew.state = AI_STATE_BUILD_VEHICLE;
 
			return;
 
		} else {
 
			// There is a depot, but not of our team! :(
 
			p->ainew.state = AI_STATE_NOTHING;
 
			return;
aystar.c
Show inline comments
 
@@ -22,53 +22,54 @@
 

	
 
int _aystar_stats_open_size;
 
int _aystar_stats_closed_size;
 

	
 
// This looks in the Hash if a node exists in ClosedList
 
//  If so, it returns the PathNode, else NULL
 
static PathNode *AyStarMain_ClosedList_IsInList(AyStar *aystar, AyStarNode *node)
 
static PathNode* AyStarMain_ClosedList_IsInList(AyStar* aystar, const AyStarNode* node)
 
{
 
	return (PathNode*)Hash_Get(&aystar->ClosedListHash, node->tile, node->direction);
 
}
 

	
 
// This adds a node to the ClosedList
 
//  It makes a copy of the data
 
static void AyStarMain_ClosedList_Add(AyStar *aystar, PathNode *node)
 
static void AyStarMain_ClosedList_Add(AyStar* aystar, const PathNode* node)
 
{
 
	// Add a node to the ClosedList
 
	PathNode *new_node = malloc(sizeof(PathNode));
 
	PathNode* new_node = malloc(sizeof(*new_node));
 
	*new_node = *node;
 
	Hash_Set(&aystar->ClosedListHash, node->node.tile, node->node.direction, new_node);
 
}
 

	
 
// Checks if a node is in the OpenList
 
//   If so, it returns the OpenListNode, else NULL
 
static OpenListNode *AyStarMain_OpenList_IsInList(AyStar *aystar, AyStarNode *node)
 
static OpenListNode* AyStarMain_OpenList_IsInList(AyStar* aystar, const AyStarNode* node)
 
{
 
	return (OpenListNode*)Hash_Get(&aystar->OpenListHash, node->tile, node->direction);
 
}
 

	
 
// Gets the best node from OpenList
 
//  returns the best node, or NULL of none is found
 
// Also it deletes the node from the OpenList
 
static OpenListNode *AyStarMain_OpenList_Pop(AyStar *aystar)
 
{
 
	// Return the item the Queue returns.. the best next OpenList item.
 
	OpenListNode* res = (OpenListNode*)aystar->OpenListQueue.pop(&aystar->OpenListQueue);
 
	if (res != NULL)
 
	if (res != NULL) {
 
		Hash_Delete(&aystar->OpenListHash, res->path.node.tile, res->path.node.direction);
 
	}
 

	
 
	return res;
 
}
 

	
 
// Adds a node to the OpenList
 
//  It makes a copy of node, and puts the pointer of parent in the struct
 
static void AyStarMain_OpenList_Add(AyStar *aystar, PathNode *parent, AyStarNode *node, int f, int g)
 
static void AyStarMain_OpenList_Add(AyStar* aystar, PathNode* parent, const AyStarNode* node, int f, int g)
 
{
 
	// Add a new Node to the OpenList
 
	OpenListNode* new_node = malloc(sizeof(OpenListNode));
 
	OpenListNode* new_node = malloc(sizeof(*new_node));
 
	new_node->g = g;
 
	new_node->path.parent = parent;
 
	new_node->path.node = *node;
 
	Hash_Set(&aystar->OpenListHash, node->tile, node->direction, new_node);
 

	
 
	// Add it to the queue
 
@@ -77,13 +78,14 @@ static void AyStarMain_OpenList_Add(AySt
 

	
 
/*
 
 * Checks one tile and calculate his f-value
 
 *  return values:
 
 *	AYSTAR_DONE : indicates we are done
 
 */
 
int AyStarMain_CheckTile(AyStar *aystar, AyStarNode *current, OpenListNode *parent) {
 
int AyStarMain_CheckTile(AyStar* aystar, AyStarNode* current, OpenListNode* parent)
 
{
 
	int new_f, new_g, new_h;
 
	PathNode *closedlist_parent;
 
	OpenListNode *check;
 

	
 
	// Check the new node against the ClosedList
 
	if (AyStarMain_ClosedList_IsInList(aystar, current) != NULL) return AYSTAR_DONE;
 
@@ -108,23 +110,25 @@ int AyStarMain_CheckTile(AyStar *aystar,
 
	new_f = new_g + new_h;
 

	
 
	// Get the pointer to the parent in the ClosedList (the currentone is to a copy of the one in the OpenList)
 
	closedlist_parent = AyStarMain_ClosedList_IsInList(aystar, &parent->path.node);
 

	
 
	// Check if this item is already in the OpenList
 
	if ((check = AyStarMain_OpenList_IsInList(aystar, current)) != NULL) {
 
	check = AyStarMain_OpenList_IsInList(aystar, current);
 
	if (check != NULL) {
 
		uint i;
 
		// Yes, check if this g value is lower..
 
		if (new_g > check->g) return AYSTAR_DONE;
 
		aystar->OpenListQueue.del(&aystar->OpenListQueue, check, 0);
 
		// It is lower, so change it to this item
 
		check->g = new_g;
 
		check->path.parent = closedlist_parent;
 
		/* Copy user data, will probably have changed */
 
		for (i=0;i<lengthof(current->user_data);i++)
 
		for (i = 0; i < lengthof(current->user_data); i++) {
 
			check->path.node.user_data[i] = current->user_data[i];
 
		}
 
		// Readd him in the OpenListQueue
 
		aystar->OpenListQueue.push(&aystar->OpenListQueue, check, new_f);
 
	} else {
 
		// A new node, add him to the OpenList
 
		AyStarMain_OpenList_Add(aystar, closedlist_parent, current, new_f, new_g);
 
	}
 
@@ -140,21 +144,20 @@ int AyStarMain_CheckTile(AyStar *aystar,
 
 *	has been found.
 
 *	AYSTAR_LIMIT_REACHED : Indicates that the max_nodes limit has been
 
 *	reached.
 
 *	AYSTAR_FOUND_END_NODE : indicates we found the end. Path_found now is true, and in path is the path found.
 
 *	AYSTAR_STILL_BUSY : indicates we have done this tile, did not found the path yet, and have items left to try.
 
 */
 
int AyStarMain_Loop(AyStar *aystar) {
 
int AyStarMain_Loop(AyStar* aystar)
 
{
 
	int i, r;
 

	
 
	// Get the best node from OpenList
 
	OpenListNode *current = AyStarMain_OpenList_Pop(aystar);
 
	// If empty, drop an error
 
	if (current == NULL) {
 
		return AYSTAR_EMPTY_OPENLIST;
 
	}
 
	if (current == NULL) return AYSTAR_EMPTY_OPENLIST;
 

	
 
	// Check for end node and if found, return that code
 
	if (aystar->EndNodeCheck(aystar, current) == AYSTAR_FOUND_END_NODE) {
 
		if (aystar->FoundEndNode != NULL)
 
			aystar->FoundEndNode(aystar, current);
 
		free(current);
 
@@ -185,13 +188,14 @@ int AyStarMain_Loop(AyStar *aystar) {
 
	}
 
}
 

	
 
/*
 
 * This function frees the memory it allocated
 
 */
 
void AyStarMain_Free(AyStar *aystar) {
 
void AyStarMain_Free(AyStar* aystar)
 
{
 
	aystar->OpenListQueue.free(&aystar->OpenListQueue, false);
 
	/* 2nd argument above is false, below is true, to free the values only
 
	 * once */
 
	delete_Hash(&aystar->OpenListHash, true);
 
	delete_Hash(&aystar->ClosedListHash, true);
 
#ifdef AYSTAR_DEBUG
 
@@ -200,13 +204,14 @@ void AyStarMain_Free(AyStar *aystar) {
 
}
 

	
 
/*
 
 * This function make the memory go back to zero
 
 *  This function should be called when you are using the same instance again.
 
 */
 
void AyStarMain_Clear(AyStar *aystar) {
 
void AyStarMain_Clear(AyStar* aystar)
 
{
 
	// Clean the Queue, but not the elements within. That will be done by
 
	// the hash.
 
	aystar->OpenListQueue.clear(&aystar->OpenListQueue, false);
 
	// Clean the hashes
 
	clear_Hash(&aystar->OpenListHash, true);
 
	clear_Hash(&aystar->ClosedListHash, true);
 
@@ -229,51 +234,52 @@ void AyStarMain_Clear(AyStar *aystar) {
 
int AyStarMain_Main(AyStar *aystar) {
 
	int r, i = 0;
 
	// Loop through the OpenList
 
	//  Quit if result is no AYSTAR_STILL_BUSY or is more than loops_per_tick
 
	while ((r = aystar->loop(aystar)) == AYSTAR_STILL_BUSY && (aystar->loops_per_tick == 0 || ++i < aystar->loops_per_tick)) { }
 
#ifdef AYSTAR_DEBUG
 
	if (r == AYSTAR_FOUND_END_NODE)
 
		printf("[AyStar] Found path!\n");
 
	else if (r == AYSTAR_EMPTY_OPENLIST)
 
		printf("[AyStar] OpenList run dry, no path found\n");
 
	else if (r == AYSTAR_LIMIT_REACHED)
 
		printf("[AyStar] Exceeded search_nodes, no path found\n");
 
	switch (r) {
 
		case AYSTAR_FOUND_END_NODE: printf("[AyStar] Found path!\n"); break;
 
		case AYSTAR_EMPTY_OPENLIST: printf("[AyStar] OpenList run dry, no path found\n"); break;
 
		case AYSTAR_LIMIT_REACHED:  printf("[AyStar] Exceeded search_nodes, no path found\n"); break;
 
		default: break;
 
	}
 
#endif
 
	if (r != AYSTAR_STILL_BUSY) {
 
		/* We're done, clean up */
 
		_aystar_stats_open_size = aystar->OpenListHash.size;
 
		_aystar_stats_closed_size = aystar->ClosedListHash.size;
 
		aystar->clear(aystar);
 
	}
 

	
 
	// Check result-value
 
	if (r == AYSTAR_FOUND_END_NODE) return AYSTAR_FOUND_END_NODE;
 
	// Check if we have some left in the OpenList
 
	if (r == AYSTAR_EMPTY_OPENLIST || r == AYSTAR_LIMIT_REACHED) return AYSTAR_NO_PATH;
 

	
 
	// Return we are still busy
 
	return AYSTAR_STILL_BUSY;
 
	switch (r) {
 
		case AYSTAR_FOUND_END_NODE: return AYSTAR_FOUND_END_NODE;
 
		case AYSTAR_EMPTY_OPENLIST:
 
		case AYSTAR_LIMIT_REACHED:  return AYSTAR_NO_PATH;
 
		default:                    return AYSTAR_STILL_BUSY;
 
	}
 
}
 

	
 
/*
 
 * Adds a node from where to start an algorithm. Multiple nodes can be added
 
 * if wanted. You should make sure that clear() is called before adding nodes
 
 * if the AyStar has been used before (though the normal main loop calls
 
 * clear() automatically when the algorithm finishes
 
 * g is the cost for starting with this node.
 
 */
 
void AyStarMain_AddStartNode(AyStar *aystar, AyStarNode *start_node, uint g) {
 
void AyStarMain_AddStartNode(AyStar* aystar, AyStarNode* start_node, uint g)
 
{
 
#ifdef AYSTAR_DEBUG
 
	printf("[AyStar] Starting A* Algorithm from node (%d, %d, %d)\n",
 
		TileX(start_node->tile), TileY(start_node->tile), start_node->direction);
 
#endif
 
	AyStarMain_OpenList_Add(aystar, NULL, start_node, 0, g);
 
}
 

	
 
void init_AyStar(AyStar* aystar, Hash_HashProc hash, uint num_buckets) {
 
void init_AyStar(AyStar* aystar, Hash_HashProc hash, uint num_buckets)
 
{
 
	// Allocated the Hash for the OpenList and ClosedList
 
	init_Hash(&aystar->OpenListHash, hash, num_buckets);
 
	init_Hash(&aystar->ClosedListHash, hash, num_buckets);
 

	
 
	// Set up our sorting queue
 
	//  BinaryHeap allocates a block of 1024 nodes
clear_cmd.c
Show inline comments
 
@@ -139,14 +139,13 @@ static bool TerraformTileHeight(Terrafor
 

	
 
	mod = ts->modheight;
 
	count = ts->modheight_count;
 

	
 
	for (;;) {
 
		if (count == 0) {
 
			if (ts->modheight_count >= 576)
 
				return false;
 
			if (ts->modheight_count >= 576) return false;
 
			ts->modheight_count++;
 
			break;
 
		}
 
		if (mod->tile == tile) break;
 
		mod++;
 
		count--;
 
@@ -187,12 +186,13 @@ static bool TerraformTileHeight(Terrafor
 
 * @param p1 corners to terraform.
 
 * @param p2 direction; eg up or down
 
 */
 
int32 CmdTerraformLand(TileIndex tile, uint32 flags, uint32 p1, uint32 p2)
 
{
 
	TerraformerState ts;
 
	TileIndex t;
 
	int direction;
 

	
 
	TerraformerHeightMod modheight_data[576];
 
	TileIndex tile_table_data[625];
 

	
 
	SET_EXPENSES_TYPE(EXPENSES_CONSTRUCTION);
 
@@ -207,34 +207,38 @@ int32 CmdTerraformLand(TileIndex tile, u
 
	ts.tile_table = tile_table_data;
 

	
 
	/* Make an extra check for map-bounds cause we add tiles to the originating tile */
 
	if (tile + TileDiffXY(1, 1) >= MapSize()) return CMD_ERROR;
 

	
 
	if (p1 & 1) {
 
		if (!TerraformTileHeight(&ts, tile + TileDiffXY(1, 0),
 
				TileHeight(tile + TileDiffXY(1, 0)) + direction))
 
		t = tile + TileDiffXY(1, 0);
 
		if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
 
					return CMD_ERROR;
 
	}
 
	}
 

	
 
	if (p1 & 2) {
 
		if (!TerraformTileHeight(&ts, tile + TileDiffXY(1, 1),
 
				TileHeight(tile + TileDiffXY(1, 1)) + direction))
 
		t = tile + TileDiffXY(1, 1);
 
		if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
 
					return CMD_ERROR;
 
	}
 
	}
 

	
 
	if (p1 & 4) {
 
		if (!TerraformTileHeight(&ts, tile + TileDiffXY(0, 1),
 
				TileHeight(tile + TileDiffXY(0, 1)) + direction))
 
		t = tile + TileDiffXY(0, 1);
 
		if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
 
					return CMD_ERROR;
 
	}
 
	}
 

	
 
	if (p1 & 8) {
 
		if (!TerraformTileHeight(&ts, tile + TileDiffXY(0, 0),
 
				TileHeight(tile + TileDiffXY(0, 0)) + direction))
 
		t = tile + TileDiffXY(0, 0);
 
		if (!TerraformTileHeight(&ts, t, TileHeight(t) + direction)) {
 
					return CMD_ERROR;
 
	}
 
	}
 

	
 
	{ /* Check if tunnel or track would take damage */
 
		int count;
 
		TileIndex *ti = ts.tile_table;
 

	
 
		for (count = ts.tile_table_count; count != 0; count--, ti++) {
 
@@ -427,14 +431,13 @@ int32 CmdSellLandArea(TileIndex tile, ui
 
	if (!IsOwnedLandTile(tile)) return CMD_ERROR;
 
	if (!CheckTileOwnership(tile) && _current_player != OWNER_WATER) return CMD_ERROR;
 

	
 

	
 
	if (!EnsureNoVehicle(tile)) return CMD_ERROR;
 

	
 
	if (flags & DC_EXEC)
 
		DoClearSquare(tile);
 
	if (flags & DC_EXEC) DoClearSquare(tile);
 

	
 
	return - _price.purchase_land * 2;
 
}
 

	
 

	
 
#include "table/clear_land.h"
command.c
Show inline comments
 
@@ -311,13 +311,16 @@ bool IsValidCommand(uint cmd)
 

	
 
	return
 
		cmd < lengthof(_command_proc_table) &&
 
		_command_proc_table[cmd].proc != NULL;
 
}
 

	
 
byte GetCommandFlags(uint cmd) {return _command_proc_table[cmd & 0xFF].flags;}
 
byte GetCommandFlags(uint cmd)
 
{
 
	return _command_proc_table[cmd & 0xFF].flags;
 
}
 

	
 

	
 
static int _docommand_recursive;
 

	
 
int32 DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 flags, uint procc)
 
{
 
@@ -341,14 +344,16 @@ int32 DoCommand(TileIndex tile, uint32 p
 
		res = proc(tile, flags & ~DC_EXEC, p1, p2);
 
		if (CmdFailed(res)) {
 
			if (res & 0xFFFF) _error_message = res & 0xFFFF;
 
			goto error;
 
		}
 

	
 
		if (_docommand_recursive == 1) {
 
			if (!(flags&DC_QUERY_COST) && res != 0 && !CheckPlayerHasMoney(res))
 
		if (_docommand_recursive == 1 &&
 
				!(flags & DC_QUERY_COST) &&
 
				res != 0 &&
 
				!CheckPlayerHasMoney(res)) {
 
				goto error;
 
		}
 

	
 
		if (!(flags & DC_EXEC)) {
 
			_docommand_recursive--;
 
			_cmd_text = NULL;
 
@@ -493,13 +498,15 @@ bool DoCommandP(TileIndex tile, uint32 p
 
		_cmd_text = NULL;
 
		return true;
 
	}
 
#endif /* ENABLE_NETWORK */
 

	
 
	// update last build coordinate of player.
 
	if ( tile != 0 && _current_player < MAX_PLAYERS) GetPlayer(_current_player)->last_build_coordinate = tile;
 
	if (tile != 0 && _current_player < MAX_PLAYERS) {
 
		GetPlayer(_current_player)->last_build_coordinate = tile;
 
	}
 

	
 
	/* Actually try and execute the command. If no cost-type is given
 
	 * use the construction one */
 
	_yearly_expenses_type = EXPENSES_CONSTRUCTION;
 
	res2 = proc(tile, flags|DC_EXEC, p1, p2);
 

	
 
@@ -514,14 +521,13 @@ bool DoCommandP(TileIndex tile, uint32 p
 
		}
 
	}
 

	
 
	SubtractMoneyFromPlayer(res2);
 

	
 
	if (IsLocalPlayer() && _game_mode != GM_EDITOR) {
 
		if (res2 != 0)
 
			ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
 
		if (res2 != 0) ShowCostOrIncomeAnimation(x, y, GetSlopeZ(x, y), res2);
 
		if (_additional_cash_required) {
 
			SetDParam(0, _additional_cash_required);
 
			ShowErrorMessage(STR_0003_NOT_ENOUGH_CASH_REQUIRES, error_part1, x,y);
 
			if (res2 == 0) goto callb_err;
 
		}
 
	}
depot.h
Show inline comments
 
@@ -69,14 +69,13 @@ static inline bool IsValidDepot(const De
 

	
 
/**
 
 * Check if a tile is a depot of the given type.
 
 */
 
static inline bool IsTileDepotType(TileIndex tile, TransportType type)
 
{
 
	switch (type)
 
	{
 
	switch (type) {
 
		case TRANSPORT_RAIL:
 
			return IsTileType(tile, MP_RAILWAY) && (_m[tile].m5 & 0xFC) == 0xC0;
 

	
 
		case TRANSPORT_ROAD:
 
			return IsTileType(tile, MP_STREET) && (_m[tile].m5 & 0xF0) == 0x20;
 

	
elrail.c
Show inline comments
 
@@ -191,14 +191,15 @@ static void DrawCatenaryRailway(const Ti
 
		/* We cycle through all the existing tracks at a PCP and see what
 
		   PPPs we want to have, or may not have at all */
 
		for (k = 0; k < NUM_TRACKS_AT_PCP; k++) {
 
			/* Next to us, we have a bridge head, don't worry about that one, if it shows away from us */
 
			if (TrackSourceTile[i][k] == TS_NEIGHBOUR &&
 
			    IsBridgeTile(neighbour) && IsBridgeRamp(neighbour) &&
 
			    GetBridgeRampDirection(neighbour) == ReverseDiagDir(i)
 
			   ) continue;
 
			    GetBridgeRampDirection(neighbour) == ReverseDiagDir(i)) {
 
				continue;
 
			}
 

	
 
			/* We check whether the track in question (k) is present in the tile
 
			   (TrackSourceTile) */
 
			if (HASBIT(trackconfig[TrackSourceTile[i][k]], TracksAtPCP[i][k])) {
 
				/* track found, if track is in the neighbour tile, adjust the number
 
				   of the PCP for preferred/allowed determination*/
functions.h
Show inline comments
 
@@ -202,13 +202,13 @@ void ShowFeederIncomeAnimation(int x, in
 
void DrawFoundation(TileInfo *ti, uint f);
 

	
 
bool CheckIfAuthorityAllows(TileIndex tile);
 
Town *ClosestTownFromTile(TileIndex tile, uint threshold);
 
void ChangeTownRating(Town *t, int add, int max);
 

	
 
int GetTownRadiusGroup(const Town *t, TileIndex tile);
 
uint GetTownRadiusGroup(const Town* t, TileIndex tile);
 
void ShowNetworkChatQueryWindow(byte desttype, byte dest);
 
void ShowNetworkGiveMoneyWindow(byte player);
 
void ShowNetworkNeedGamePassword(void);
 
void ShowNetworkNeedCompanyPassword(void);
 
int FindFirstBit(uint32 x);
 
void ShowHighscoreTable(int difficulty, int8 rank);
landscape.c
Show inline comments
 
@@ -392,13 +392,13 @@ void InitializeLandscape(void)
 
	}
 
	for (x = 0; x < sizex; x++) MakeVoid(sizex * y + x);
 
}
 

	
 
void ConvertGroundTilesIntoWaterTiles(void)
 
{
 
	TileIndex tile = 0;
 
	TileIndex tile;
 

	
 
	for (tile = 0; tile < MapSize(); ++tile) {
 
		if (IsTileType(tile, MP_CLEAR) && GetTileMaxZ(tile) == 0) {
 
			MakeWater(tile);
 
		}
 
	}
map.h
Show inline comments
 
@@ -64,17 +64,17 @@ static inline TileIndexDiff TileDiffXY(i
 

	
 
static inline TileIndex TileVirtXY(uint x, uint y)
 
{
 
	return (y >> 4 << MapLogX()) + (x >> 4);
 
}
 

	
 
typedef enum {
 
	OWNER_TOWN			= 0xf,	// a town owns the tile
 
typedef enum Owner {
 
	OWNER_TOWN      = 0x0F, // a town owns the tile
 
	OWNER_NONE			= 0x10,	// nobody owns the tile
 
	OWNER_WATER			= 0x11,	// "water" owns the tile
 
	OWNER_SPECTATOR	= 0xff,	// spectator in MP or in scenario editor
 
	OWNER_SPECTATOR = 0xFF, // spectator in MP or in scenario editor
 
} Owner;
 

	
 
enum {
 
	INVALID_TILE = (TileIndex)-1
 
};
 

	
misc_gui.c
Show inline comments
 
@@ -727,13 +727,14 @@ void CheckRedrawStationCoverage(const Wi
 
}
 

	
 

	
 
void UnclickSomeWindowButtons(Window *w, uint32 mask)
 
{
 
	uint32 x = w->click_state & mask;
 
	int i = 0;
 
	uint i = 0;
 

	
 
	w->click_state ^= x;
 
	do {
 
		if (x & 1) InvalidateWidget(w, i);
 
	} while (i++, x >>= 1);
 
}
 

	
 
@@ -1248,14 +1249,14 @@ static void SaveLoadDlgWndProc(Window *w
 
				ttd_strlcpy(&o_dir.name[0], _path.personal_dir, sizeof(o_dir.name));
 
		}
 
		break;
 
		}
 

	
 
	case WE_PAINT: {
 
		int y,pos;
 
		const FiosItem *item;
 
		int pos;
 
		int y;
 

	
 
		SetVScrollCount(w, _fios_num);
 
		DrawWindowWidgets(w);
 
		DrawFiosTexts(w->width);
 

	
 
		if (_savegame_sort_dirty) {
 
@@ -1268,26 +1269,26 @@ static void SaveLoadDlgWndProc(Window *w
 
			_savegame_sort_order & SORT_DESCENDING ? DOWNARROW : UPARROW,
 
			_savegame_sort_order & SORT_BY_NAME ? w->widget[2].right - 9 : w->widget[3].right - 9,
 
			15, 16
 
		);
 

	
 
		y = w->widget[7].top + 1;
 
		pos = w->vscroll.pos;
 
		while (pos < _fios_num) {
 
			item = _fios_list + pos;
 
		for (pos = w->vscroll.pos; pos < _fios_num; pos++) {
 
			const FiosItem* item = _fios_list + pos;
 

	
 
			DoDrawStringTruncated(item->title, 4, y, _fios_colors[item->type], w->width - 18);
 
			pos++;
 
			y += 10;
 
			if (y >= w->vscroll.cap * 10 + w->widget[7].top + 1) break;
 
		}
 

	
 
		if (_saveload_mode == SLD_SAVE_GAME || _saveload_mode == SLD_SAVE_SCENARIO) {
 
			DrawEditBox(w, &WP(w,querystr_d), 10);
 
		}
 
		break;
 
	}
 

	
 
	case WE_CLICK:
 
		switch (e->click.widget) {
 
		case 2: /* Sort save names by name */
 
			_savegame_sort_order = (_savegame_sort_order == SORT_BY_NAME) ?
 
				SORT_BY_NAME | SORT_DESCENDING : SORT_BY_NAME;
 
			_savegame_sort_dirty = true;
music/qtmidi.c
Show inline comments
 
@@ -63,20 +63,18 @@ enum {
 
 *              stored.
 
 * @return Wether the conversion was successful.
 
 */
 
static bool PathToFSSpec(const char *path, FSSpec *spec)
 
{
 
	FSRef ref;
 
	assert(spec);
 
	assert(path);
 
	assert(spec != NULL);
 
	assert(path != NULL);
 

	
 
	if (noErr != FSPathMakeRef((UInt8*) path, &ref, NULL))
 
		return false;
 

	
 
	return (noErr ==
 
			FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, spec, NULL));
 
	return
 
		FSPathMakeRef((UInt8*)path, &ref, NULL) == noErr &&
 
		FSGetCatalogInfo(&ref, kFSCatInfoNone, NULL, NULL, spec, NULL) == noErr;
 
}
 

	
 

	
 
/**
 
 * Sets the @c OSType of a given file to @c 'Midi', but only if it's not
 
 * already set.
 
@@ -88,13 +86,13 @@ static void SetMIDITypeIfNeeded(const FS
 
	FInfo info;
 
	assert(spec);
 

	
 
	if (noErr != FSpGetFInfo(spec, &info)) return;
 

	
 
	/* Set file type to 'Midi' if the file is _not_ an alias. */
 
	if ((info.fdType != midiType) && !(info.fdFlags & kIsAlias)) {
 
	if (info.fdType != midiType && !(info.fdFlags & kIsAlias)) {
 
		info.fdType = midiType;
 
		FSpSetFInfo(spec, &info);
 
		DEBUG(driver, 3) ("qtmidi: changed filetype to 'Midi'");
 
	}
 
}
 

	
 
@@ -112,40 +110,37 @@ static bool LoadMovieForMIDIFile(const c
 
	int ret;
 
	char magic[4];
 
	FSSpec fsspec;
 
	short refnum = 0;
 
	short resid  = 0;
 

	
 
	assert(path);
 
	assert(moov);
 
	assert(path != NULL);
 
	assert(moov != NULL);
 

	
 
	DEBUG(driver, 2) ("qtmidi: begin loading '%s'...", path);
 

	
 
	/*
 
	 * XXX Manual check for MIDI header ('MThd'), as I don't know how to make
 
	 * QuickTime load MIDI files without a .mid suffix without knowing it's
 
	 * a MIDI file and setting the OSType of the file to the 'Midi' value.
 
	 * Perhahaps ugly, but it seems that it does the Right Thing(tm).
 
	 */
 
	if ((fd = open(path, O_RDONLY, 0)) == -1)
 
		return false;
 
	fd = open(path, O_RDONLY, 0);
 
	if (fd == -1) return false;
 
	ret = read(fd, magic, 4);
 
	close(fd);
 
	if (ret < 4) return false;
 

	
 
	DEBUG(driver, 3) ("qtmidi: header is '%c%c%c%c'",
 
			magic[0], magic[1], magic[2], magic[3]);
 
	DEBUG(driver, 3) ("qtmidi: header is '%.4s'", magic);
 
	if (magic[0] != 'M' || magic[1] != 'T' || magic[2] != 'h' || magic[3] != 'd')
 
		return false;
 

	
 
	if (!PathToFSSpec(path, &fsspec))
 
		return false;
 
	if (!PathToFSSpec(path, &fsspec)) return false;
 
	SetMIDITypeIfNeeded(&fsspec);
 

	
 
	if (noErr != OpenMovieFile(&fsspec, &refnum, fsRdPerm))
 
		return false;
 
	if (OpenMovieFile(&fsspec, &refnum, fsRdPerm) != noErr) return false;
 
	DEBUG(driver, 1) ("qtmidi: '%s' successfully opened", path);
 

	
 
	if (noErr != NewMovieFromFile(moov, refnum, &resid, NULL,
 
				newMovieActive | newMovieDontAskUnresolvedDataRefs, NULL))
 
	{
 
		CloseMovieFile(refnum);
 
@@ -179,19 +174,19 @@ static void InitQuickTimeIfNeeded(void)
 
	DEBUG(driver, 2) ("qtmidi: trying to initialize Quicktime");
 
	/* Be polite: check wether QuickTime is available and initialize it. */
 
	_quicktime_started =
 
		(noErr == Gestalt(gestaltQuickTime, &dummy)) &&
 
		(noErr == EnterMovies());
 
	DEBUG(driver, 1) ("qtmidi: Quicktime was %s initialized",
 
			_quicktime_started ? "successfully" : "NOT");
 
		_quicktime_started ? "successfully" : "NOT"
 
	);
 
}
 

	
 

	
 
/** Possible states of the QuickTime music driver. */
 
enum
 
{
 
enum {
 
	QT_STATE_IDLE, /**< No file loaded. */
 
	QT_STATE_PLAY, /**< File loaded, playing. */
 
	QT_STATE_STOP, /**< File loaded, stopped. */
 
};
 

	
 

	
 
@@ -244,13 +239,13 @@ static bool SongIsPlaying(void)
 
			if (IsMovieDone(_quicktime_movie) ||
 
					(GetMovieTime(_quicktime_movie, NULL) >=
 
					 GetMovieDuration(_quicktime_movie)))
 
				_quicktime_state = QT_STATE_STOP;
 
	}
 

	
 
	return (_quicktime_state == QT_STATE_PLAY);
 
	return _quicktime_state == QT_STATE_PLAY;
 
}
 

	
 

	
 
/**
 
 * Stops the MIDI player.
 
 *
network.c
Show inline comments
 
@@ -1239,17 +1239,15 @@ void NetworkUDPGameLoop(void)
 
{
 
	if (_network_udp_server) {
 
		NetworkUDPReceive(_udp_server_socket);
 
		if (_udp_master_socket != INVALID_SOCKET) {
 
			NetworkUDPReceive(_udp_master_socket);
 
		}
 
	}
 
	else if (_udp_client_socket != INVALID_SOCKET) {
 
	} else if (_udp_client_socket != INVALID_SOCKET) {
 
		NetworkUDPReceive(_udp_client_socket);
 
		if (_network_udp_broadcast > 0)
 
			_network_udp_broadcast--;
 
		if (_network_udp_broadcast > 0) _network_udp_broadcast--;
 
	}
 
}
 

	
 
// The main loop called from ttd.c
 
//  Here we also have to do StateGameLoop if needed!
 
void NetworkGameLoop(void)
news_gui.c
Show inline comments
 
@@ -218,27 +218,24 @@ static void NewsWindowProc(Window *w, Wi
 
}
 

	
 
// returns the correct index in the array
 
// (to deal with overflows)
 
static byte increaseIndex(byte i)
 
{
 
	if (i == INVALID_NEWS)
 
		return 0;
 
	if (i == INVALID_NEWS) return 0;
 
	i++;
 
	if (i >= MAX_NEWS)
 
		i = i % MAX_NEWS;
 
	if (i >= MAX_NEWS) i = i % MAX_NEWS;
 
	return i;
 
}
 

	
 
void AddNewsItem(StringID string, uint32 flags, uint data_a, uint data_b)
 
{
 
	NewsItem *ni;
 
	Window *w;
 

	
 
	if (_game_mode == GM_MENU)
 
		return;
 
	if (_game_mode == GM_MENU) return;
 

	
 
	// check the rare case that the oldest (to be overwritten) news item is open
 
	if (_total_news==MAX_NEWS && (_oldest_news == _current_news || _oldest_news == _forced_news))
 
		MoveToNexItem();
 

	
 
	_forced_news = INVALID_NEWS;
npf.c
Show inline comments
 
@@ -274,14 +274,13 @@ static int32 NPFRoadPathCost(AyStar* as,
 
			}
 
			break;
 

	
 
		case MP_STREET:
 
			cost = NPF_TILE_LENGTH;
 
			/* Increase the cost for level crossings */
 
			if (IsLevelCrossing(tile))
 
				cost += _patches.npf_crossing_penalty;
 
			if (IsLevelCrossing(tile)) cost += _patches.npf_crossing_penalty;
 
			break;
 

	
 
		default:
 
			break;
 
	}
 

	
 
@@ -404,21 +403,16 @@ static int32 NPFRailPathCost(AyStar* as,
 
	return cost;
 
}
 

	
 
/* Will find any depot */
 
static int32 NPFFindDepot(AyStar* as, OpenListNode *current)
 
{
 
	TileIndex tile = current->path.node.tile;
 

	
 
	/* It's not worth caching the result with NPF_FLAG_IS_TARGET here as below,
 
	 * since checking the cache not that much faster than the actual check */
 
	if (IsTileDepotType(tile, as->user_data[NPF_TYPE])) {
 
		return AYSTAR_FOUND_END_NODE;
 
	} else {
 
		return AYSTAR_DONE;
 
	}
 
	return IsTileDepotType(current->path.node.tile, as->user_data[NPF_TYPE]) ?
 
		AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
 
}
 

	
 
/* Will find a station identified using the NPFFindStationOrTileData */
 
static int32 NPFFindStationOrTile(AyStar* as, OpenListNode *current)
 
{
 
	NPFFindStationOrTileData* fstd = (NPFFindStationOrTileData*)as->user_target;
 
@@ -679,20 +673,18 @@ static NPFFoundTargetData NPFRouteIntern
 

	
 
	/* Initialize procs */
 
	_npf_aystar.CalculateH = heuristic_proc;
 
	_npf_aystar.EndNodeCheck = target_proc;
 
	_npf_aystar.FoundEndNode = NPFSaveTargetData;
 
	_npf_aystar.GetNeighbours = NPFFollowTrack;
 
	if (type == TRANSPORT_RAIL)
 
		_npf_aystar.CalculateG = NPFRailPathCost;
 
	else if (type == TRANSPORT_ROAD)
 
		_npf_aystar.CalculateG = NPFRoadPathCost;
 
	else if (type == TRANSPORT_WATER)
 
		_npf_aystar.CalculateG = NPFWaterPathCost;
 
	else
 
		assert(0);
 
	switch (type) {
 
		default: NOT_REACHED();
 
		case TRANSPORT_RAIL:  _npf_aystar.CalculateG = NPFRailPathCost;  break;
 
		case TRANSPORT_ROAD:  _npf_aystar.CalculateG = NPFRoadPathCost;  break;
 
		case TRANSPORT_WATER: _npf_aystar.CalculateG = NPFWaterPathCost; break;
 
	}
 

	
 
	/* Initialize Start Node(s) */
 
	start1->user_data[NPF_TRACKDIR_CHOICE] = INVALID_TRACKDIR;
 
	start1->user_data[NPF_NODE_FLAGS] = 0;
 
	_npf_aystar.addstart(&_npf_aystar, start1, 0);
 
	if (start2) {
oldloader.c
Show inline comments
 
@@ -185,18 +185,17 @@ static inline uint32 ReadUint32(Loadgame
 
 * Loads a chunk from the old savegame
 
 *
 
 */
 
static bool LoadChunk(LoadgameState *ls, void *base, const OldChunks *chunks)
 
{
 
	const OldChunks *chunk = chunks;
 
	byte *ptr;
 
	byte *base_ptr = base;
 
	uint i;
 

	
 
	while (chunk->type != OC_END) {
 
		ptr = chunk->ptr;
 
		byte* ptr = chunk->ptr;
 
		uint i;
 

	
 
		for (i = 0; i < chunk->amount; i++) {
 
			if (ls->failed) return false;
 

	
 
			/* Handle simple types */
 
			if (GetOldChunkType(chunk->type) != 0) {
openttd.c
Show inline comments
 
@@ -1010,20 +1010,24 @@ void BeforeSaveGame(void)
 

	
 
static void ConvertTownOwner(void)
 
{
 
	TileIndex tile;
 

	
 
	for (tile = 0; tile != MapSize(); tile++) {
 
		if (IsTileType(tile, MP_STREET)) {
 
		switch (GetTileType(tile)) {
 
			case MP_STREET:
 
			if (IsLevelCrossing(tile) && GetCrossingRoadOwner(tile) & 0x80) {
 
				SetCrossingRoadOwner(tile, OWNER_TOWN);
 
			}
 
				/* FALLTHROUGH */
 

	
 
			case MP_TUNNELBRIDGE:
 
			if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
 
		} else if (IsTileType(tile, MP_TUNNELBRIDGE)) {
 
			if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
 
				break;
 

	
 
			default: break;
 
		}
 
	}
 
}
 

	
 
// before savegame version 4, the name of the company determined if it existed
 
static void CheckIsPlayerActive(void)
order_cmd.c
Show inline comments
 
@@ -186,13 +186,13 @@ int32 CmdInsertOrder(TileIndex tile, uin
 
			const Station *st;
 

	
 
			if (!IsStationIndex(new_order.station)) return CMD_ERROR;
 
			st = GetStation(new_order.station);
 

	
 
			if (!IsValidStation(st) ||
 
					(st->airport_type != AT_OILRIG && !(IsBuoy(st)) && !CheckOwnership(st->owner))) {
 
					(st->airport_type != AT_OILRIG && !IsBuoy(st) && !CheckOwnership(st->owner))) {
 
				return CMD_ERROR;
 
			}
 

	
 
			switch (v->type) {
 
				case VEH_Train:
 
					if (!(st->facilities & FACIL_TRAIN)) return CMD_ERROR;
order_gui.c
Show inline comments
 
@@ -465,15 +465,13 @@ static void OrdersWndProc(Window *w, Win
 
		uint i;
 

	
 
		for (i = 0; i < lengthof(_order_keycodes); i++) {
 
			if (e->keypress.keycode == _order_keycodes[i]) {
 
				e->keypress.cont = false;
 
				//see if the button is disabled
 
				if (!(HASBIT(w->disabled_state, (i + 4)))) {
 
					_order_button_proc[i](w, v);
 
				}
 
				if (!HASBIT(w->disabled_state, i + 4)) _order_button_proc[i](w, v);
 
				break;
 
			}
 
		}
 
		break;
 
	}
 

	
pathfind.c
Show inline comments
 
@@ -177,13 +177,13 @@ static void TPFMode2(TrackPathFinder* tp
 
				return;
 
			}
 
			tpf->rd.pft_var6 = (byte)i;
 
		}
 

	
 
continue_here:;
 
		tpf->the_dir = HASBIT(_otherdir_mask[direction],i) ? (i+8) : i;
 
		tpf->the_dir = i + (HASBIT(_otherdir_mask[direction], i) ? 8 : 0);
 

	
 
		if (!tpf->enum_proc(tile, tpf->userdata, tpf->the_dir, tpf->rd.cur_length, NULL)) {
 
			TPFMode2(tpf, tile, _tpf_new_direction[tpf->the_dir]);
 
		}
 

	
 
		tpf->rd = rd;
 
@@ -751,14 +751,13 @@ start_at:
 
				bits = GetTileTrackStatus(tile, TRANSPORT_RAIL) & _tpfmode1_and[direction];
 
				bits = (bits | (bits >> 8)) & 0x3F;
 

	
 
				// Check that the tile contains exactly one track
 
				if (bits == 0 || KILL_FIRST_BIT(bits) != 0) break;
 

	
 
				/* Check the rail type only if the train is *NOT* on top of
 
				 * a bridge. */
 
				/* Check the rail type only if the train is *NOT* on top of a bridge. */
 
				if (!(IsBridgeTile(tile) && IsBridgeMiddle(tile) && GetBridgeAxis(tile) == DiagDirToAxis(direction))) {
 
					if (IsTileType(tile, MP_STREET) ? !HASBIT(tpf->railtypes, GetRailTypeCrossing(tile)) : !HASBIT(tpf->railtypes, GetRailType(tile))) {
 
						bits = 0;
 
						break;
 
					}
 
				}
pathfind.h
Show inline comments
 
@@ -34,13 +34,12 @@ typedef struct RememberData {
 
	uint16 cur_length;
 
	byte depth;
 
	byte pft_var6;
 
} RememberData;
 

	
 
struct TrackPathFinder {
 

	
 
	int num_links_left;
 
	TrackPathFinderLink *new_link;
 

	
 
	TPFEnumProc *enum_proc;
 

	
 
	void *userdata;
player_gui.c
Show inline comments
 
@@ -268,13 +268,13 @@ static void SelectPlayerColorWndProc(Win
 
		y = 17;
 
		pos = w->vscroll.pos;
 

	
 
		for (i = 0; i != 16; i++) {
 
			if (!(used_colors & 1) && --pos < 0 && pos >= -8) {
 
				DrawString(x + 30, y, STR_00D1_DARK_BLUE + i, 2);
 
				DrawSprite(((GENERAL_SPRITE_COLOR(i) | PALETTE_MODIFIER_COLOR) | SPR_VEH_BUS_SIDE_VIEW), x + 14, y + 4);
 
				DrawSprite(GENERAL_SPRITE_COLOR(i) | PALETTE_MODIFIER_COLOR | SPR_VEH_BUS_SIDE_VIEW, x + 14, y + 4);
 
				y += 14;
 
			}
 
			used_colors >>= 1;
 
		}
 
	} break;
 

	
players.c
Show inline comments
 
@@ -263,13 +263,13 @@ void GetNameOfOwner(PlayerID owner, Tile
 
	SetDParam(2, owner);
 

	
 
	if (owner != OWNER_TOWN) {
 
		if (owner >= 8)
 
			SetDParam(0, STR_0150_SOMEONE);
 
		else {
 
			Player *p = GetPlayer(owner);
 
			const Player* p = GetPlayer(owner);
 
			SetDParam(0, p->name_1);
 
			SetDParam(1, p->name_2);
 
		}
 
	} else {
 
		Town *t = ClosestTownFromTile(tile, (uint)-1);
 
		SetDParam(0, STR_TOWN);
 
@@ -476,14 +476,13 @@ static Player *AllocatePlayer(void)
 

	
 
Player *DoStartupNewPlayer(bool is_ai)
 
{
 
	Player *p;
 

	
 
	p = AllocatePlayer();
 
	if (p == NULL)
 
		return NULL;
 
	if (p == NULL) return NULL;
 

	
 
	// Make a color
 
	p->player_color = GeneratePlayerColor();
 
	_player_colors[p->index] = p->player_color;
 
	p->name_1 = STR_SV_UNNAMED;
 
	p->is_active = true;
 
@@ -528,42 +527,45 @@ static void MaybeStartNewPlayer(void)
 
	uint n;
 
	Player *p;
 

	
 
	// count number of competitors
 
	n = 0;
 
	FOR_ALL_PLAYERS(p) {
 
		if (p->is_active && p->is_ai)
 
			n++;
 
		if (p->is_active && p->is_ai) n++;
 
	}
 

	
 
	// when there's a lot of computers in game, the probability that a new one starts is lower
 
	if (n < (uint)_opt.diff.max_no_competitors)
 
		if (n < (_network_server ? InteractiveRandomRange(_opt.diff.max_no_competitors + 2) : RandomRange(_opt.diff.max_no_competitors + 2)) )
 
			/* Send a command to all clients to start  up a new AI. Works fine for Multiplayer and Singleplayer */
 
	if (n < (uint)_opt.diff.max_no_competitors &&
 
			n < (_network_server ?
 
				InteractiveRandomRange(_opt.diff.max_no_competitors + 2) :
 
				RandomRange(_opt.diff.max_no_competitors + 2)
 
			)) {
 
		/* Send a command to all clients to start up a new AI.
 
		 * Works fine for Multiplayer and Singleplayer */
 
			DoCommandP(0, 1, 0, NULL, CMD_PLAYER_CTRL);
 
	}
 

	
 
	// The next AI starts like the difficulty setting said, with +2 month max
 
	_next_competitor_start = _opt.diff.competitor_start_time * 90 * DAY_TICKS + 1;
 
	_next_competitor_start += _network_server ? InteractiveRandomRange(60 * DAY_TICKS) : RandomRange(60 * DAY_TICKS);
 
}
 

	
 
void InitializePlayers(void)
 
{
 
	int i;
 
	uint i;
 

	
 
	memset(_players, 0, sizeof(_players));
 
	for (i = 0; i != MAX_PLAYERS; i++)
 
		_players[i].index=i;
 
	for (i = 0; i != MAX_PLAYERS; i++) _players[i].index = i;
 
	_cur_player_tick_index = 0;
 
}
 

	
 
void OnTick_Players(void)
 
{
 
	Player *p;
 

	
 
	if (_game_mode == GM_EDITOR)
 
		return;
 
	if (_game_mode == GM_EDITOR) return;
 

	
 
	p = GetPlayer(_cur_player_tick_index);
 
	_cur_player_tick_index = (_cur_player_tick_index + 1) % MAX_PLAYERS;
 
	if (p->name_1 != 0) GenerateCompanyName(p);
 

	
 
	if (AI_AllowNewAI() && _game_mode != GM_MENU && !--_next_competitor_start)
 
@@ -813,21 +815,26 @@ int32 CmdPlayerCtrl(TileIndex tile, uint
 

	
 
		if (!(flags & DC_EXEC) || pid >= MAX_PLAYERS) return 0;
 

	
 
		p = DoStartupNewPlayer(false);
 

	
 
#ifdef ENABLE_NETWORK
 
		if (_networking && !_network_server && _local_player == OWNER_SPECTATOR)
 
		if (_networking && !_network_server && _local_player == OWNER_SPECTATOR) {
 
			/* In case we are a client joining a server... */
 
			DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
 
		}
 
#endif /* ENABLE_NETWORK */
 

	
 
		if (p != NULL) {
 
			if (_local_player == OWNER_SPECTATOR && (!_ai.network_client || _ai.network_playas == OWNER_SPECTATOR)) {
 
			if (_local_player == OWNER_SPECTATOR &&
 
					(!_ai.network_client || _ai.network_playas == OWNER_SPECTATOR)) {
 
				/* Check if we do not want to be a spectator in network */
 
				if (!_networking || (_network_server && !_network_dedicated) || _network_playas != OWNER_SPECTATOR || _ai.network_client) {
 
				if (!_networking ||
 
						(_network_server && !_network_dedicated) ||
 
						_network_playas != OWNER_SPECTATOR ||
 
						_ai.network_client) {
 
					if (_ai.network_client) {
 
						/* As ai-network-client, we have our own rulez (disable GUI and stuff) */
 
						_ai.network_playas = p->index;
 
						_local_player      = OWNER_SPECTATOR;
 
						if (_ai.network_playas != OWNER_SPECTATOR) {
 
							/* If we didn't join the game as a spectator, activate the AI */
 
@@ -979,14 +986,13 @@ int8 SaveHighScoreValue(const Player *p)
 
{
 
	HighScore *hs = _highscore_table[_opt.diff_level];
 
	uint i;
 
	uint16 score = p->old_economy[0].performance_history;
 

	
 
	/* Exclude cheaters from the honour of being in the highscore table */
 
	if (CheatHasBeenUsed())
 
		return -1;
 
	if (CheatHasBeenUsed()) return -1;
 

	
 
	for (i = 0; i < lengthof(_highscore_table[0]); i++) {
 
		/* You are in the TOP5. Move all values one down and save us there */
 
		if (hs[i].score <= score) {
 
			// move all elements one down starting from the replaced one
 
			memmove(&hs[i + 1], &hs[i], sizeof(HighScore) * (lengthof(_highscore_table[0]) - i - 1));
 
@@ -1244,15 +1250,16 @@ static void SaveLoad_PLYR(Player* p)
 

	
 
	SlObject(p, _player_desc);
 

	
 
	// Write AI?
 
	if (!IS_HUMAN_PLAYER(p->index)) {
 
		SlObject(&p->ai, _player_ai_desc);
 
		for (i = 0; i != p->ai.num_build_rec; i++)
 
		for (i = 0; i != p->ai.num_build_rec; i++) {
 
			SlObject(&p->ai.src + i, _player_ai_build_rec_desc);
 
	}
 
	}
 

	
 
	// Write economy
 
	SlObject(&p->cur_economy, _player_economy_desc);
 

	
 
	// Write old economy entries.
 
	for (i = 0; i < p->num_valid_stat_ent; i++) {
rail_cmd.c
Show inline comments
 
@@ -722,13 +722,13 @@ static int32 CmdSignalTrackHelper(TileIn
 
	bool error = true;
 
	TileIndex end_tile;
 

	
 
	int mode = p2 & 0x1;
 
	Track track = GB(p2, 4, 3);
 
	Trackdir trackdir = TrackToTrackdir(track);
 
	byte semaphores = (HASBIT(p2, 3)) ? 8 : 0;
 
	byte semaphores = (HASBIT(p2, 3) ? 8 : 0);
 
	byte signal_density = (p2 >> 24);
 

	
 
	if (p1 >= MapSize()) return CMD_ERROR;
 
	end_tile = p1;
 
	if (signal_density == 0 || signal_density > 20) return CMD_ERROR;
 

	
road_cmd.c
Show inline comments
 
@@ -738,26 +738,25 @@ static void DrawRoadBits(TileInfo* ti, R
 
		AddSortableSpriteToDraw(drts->image, x, y, 2, 2, 0x10, z);
 
	}
 
}
 

	
 
static void DrawTile_Road(TileInfo *ti)
 
{
 
	PalSpriteID image;
 

	
 
	switch (GetRoadTileType(ti->tile)) {
 
		case ROAD_TILE_NORMAL:
 
			DrawRoadBits(ti, GetRoadBits(ti->tile));
 
			break;
 

	
 
		case ROAD_TILE_CROSSING: {
 
			PalSpriteID image;
 

	
 
			if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, ti->tileh);
 

	
 
			image = GetRailTypeInfo(GetRailTypeCrossing(ti->tile))->base_sprites.crossing;
 

	
 
			if (GetCrossingRoadAxis(ti->tile) == AXIS_X) image++;
 

	
 
			if (IsCrossingBarred(ti->tile)) image += 2;
 

	
 
			if (IsOnSnow(ti->tile)) {
 
				image += 8;
 
			} else {
 
				if (GetGroundType(ti->tile) == RGT_BARREN) image |= PALETTE_TO_BARE_LAND;
 
@@ -799,18 +798,14 @@ static void DrawTile_Road(TileInfo *ti)
 
		}
 
	}
 
}
 

	
 
void DrawRoadDepotSprite(int x, int y, int image)
 
{
 
	uint32 ormod;
 
	const DrawRoadSeqStruct *dtss;
 

	
 
	ormod = PLAYER_SPRITE_COLOR(_local_player);
 

	
 
	dtss = _road_display_datas[image];
 
	const DrawRoadSeqStruct* dtss = _road_display_datas[image];
 
	uint32 ormod = PLAYER_SPRITE_COLOR(_local_player);
 

	
 
	x += 33;
 
	y += 17;
 

	
 
	DrawSprite(dtss++->image, x, y);
 

	
road_map.h
Show inline comments
 
@@ -15,13 +15,13 @@ typedef enum RoadTileType {
 
	ROAD_TILE_DEPOT
 
} RoadTileType;
 

	
 
static inline RoadTileType GetRoadTileType(TileIndex t)
 
{
 
	assert(IsTileType(t, MP_STREET));
 
	return (RoadTileType)(GB(_m[t].m5, 4, 4));
 
	return (RoadTileType)GB(_m[t].m5, 4, 4);
 
}
 

	
 
static inline bool IsLevelCrossing(TileIndex t)
 
{
 
	return GetRoadTileType(t) == ROAD_TILE_CROSSING;
 
}
 
@@ -31,13 +31,13 @@ static inline bool IsLevelCrossingTile(T
 
	return IsTileType(t, MP_STREET) && IsLevelCrossing(t);
 
}
 

	
 
static inline RoadBits GetRoadBits(TileIndex t)
 
{
 
	assert(GetRoadTileType(t) == ROAD_TILE_NORMAL);
 
	return (RoadBits)(GB(_m[t].m5, 0, 4));
 
	return (RoadBits)GB(_m[t].m5, 0, 4);
 
}
 

	
 
static inline void SetRoadBits(TileIndex t, RoadBits r)
 
{
 
	assert(GetRoadTileType(t) == ROAD_TILE_NORMAL); // XXX incomplete
 
	SB(_m[t].m5, 0, 4, r);
roadveh_gui.c
Show inline comments
 
@@ -412,16 +412,15 @@ static void RoadVehViewWndProc(Window *w
 
		DeleteWindowById(WC_VEHICLE_ORDERS, w->window_number);
 
		DeleteWindowById(WC_VEHICLE_DETAILS, w->window_number);
 
		break;
 

	
 
	case WE_MOUSELOOP:
 
		{
 
			Vehicle *v;
 
			uint32 h;
 
			v = GetVehicle(w->window_number);
 
			h = IsRoadVehInDepotStopped(v) ? (1 << 7) | (1 << 8) : (1 << 11) | (1 << 12);
 
			const Vehicle* v = GetVehicle(w->window_number);
 
			uint32 h = IsRoadVehInDepotStopped(v) ? 1 << 7 | 1 << 8 : 1 << 11 | 1 << 12;
 

	
 
			if (h != w->hidden_state) {
 
				w->hidden_state = h;
 
				SetWindowDirty(w);
 
			}
 
		}
 
	}
 
@@ -1004,16 +1003,17 @@ static void PlayerRoadVehWndProc(Window 
 
			assert(v->type == VEH_Road && v->owner == owner);
 

	
 
			DrawRoadVehImage(v, x + 22, y + 6, INVALID_VEHICLE);
 
			DrawVehicleProfitButton(v, x, y + 13);
 

	
 
			SetDParam(0, v->unitnumber);
 
			if (IsRoadVehInDepot(v))
 
			if (IsRoadVehInDepot(v)) {
 
				str = STR_021F;
 
			else
 
			} else {
 
				str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2;
 
			}
 
			DrawString(x, y + 2, str, 0);
 

	
 
			SetDParam(0, v->profit_this_year);
 
			SetDParam(1, v->profit_last_year);
 
			DrawString(x + 24, y + 18, STR_0198_PROFIT_THIS_YEAR_LAST_YEAR, 0);
 

	
settings.c
Show inline comments
 
@@ -709,15 +709,17 @@ static void ini_load_settings(IniFile *i
 

	
 
/** Save the values of settings to the inifile.
 
 * @param ini pointer to IniFile structure
 
 * @param sd read-only SettingDesc structure which contains the unmodified,
 
 *        loaded values of the configuration file and various information about it
 
 * @param grpname holds the name of the group (eg. [network]) where these will be saved
 
 * The function works as follows: for each item in the SettingDesc structure we have
 
 * a look if the value has changed since we started the game (the original values
 
 * are reloaded when saving). If settings indeed have changed, we get these and save them.*/
 
 * The function works as follows: for each item in the SettingDesc structure we
 
 * have a look if the value has changed since we started the game (the original
 
 * values are reloaded when saving). If settings indeed have changed, we get
 
 * these and save them.
 
 */
 
static void ini_save_settings(IniFile *ini, const SettingDesc *sd, const char *grpname, void *object)
 
{
 
	IniGroup *group_def = NULL, *group;
 
	IniItem *item;
 
	char buf[512];
 
	const char *s;
 
@@ -891,34 +893,34 @@ static void ini_save_setting_list(IniFil
 

	
 
/** Settings-macro usage:
 
 * The list might look daunting at first, but is in general easy to understand.
 
 * We have two types of list:
 
 * 1. SDTG_something
 
 * 2. SDT_something
 
 * The 'G' stands for global, so this is the one you will use for a SettingDescGlobVarList
 
 * section meaning global variables. The other uses a Base/Offset and runtime variable
 
 * selection mechanism, known from the saveload convention (it also has global so it
 
 * should not be hard).
 
 * Of each type there are again two versions, the normal one and one prefixed with 'COND'.
 
 * COND means that the setting is only valid in certain savegame versions (since patches
 
 * are saved to the savegame, this bookkeeping is necessary.
 
 * The 'G' stands for global, so this is the one you will use for a
 
 * SettingDescGlobVarList section meaning global variables. The other uses a
 
 * Base/Offset and runtime variable selection mechanism, known from the saveload * convention (it also has global so it should not be hard).
 
 * Of each type there are again two versions, the normal one and one prefixed
 
 * with 'COND'.
 
 * COND means that the setting is only valid in certain savegame versions
 
 * (since patches are saved to the savegame, this bookkeeping is necessary.
 
 * Now there are a lot of types. Easy ones are:
 
 * - VAR:  any number type, 'type' field specifies what number. eg int8 or uint32
 
 * - BOOL: a boolean number type
 
 * - STR:  a string or character. 'type' field specifies what string. Normal, string, or quoted
 
 * A bit more difficult to use are MMANY (meaning ManyOfMany) and OMANY (OneOfMany)
 
 * These are actually normal numbers, only bitmasked. In MMANY several bits can be
 
 * set, in the other only one.
 
 * These are actually normal numbers, only bitmasked. In MMANY several bits can
 
 * be set, in the other only one.
 
 * The most complex type is INTLIST. This is basically an array of numbers. If
 
 * the intlist is only valid in certain savegame versions because for example
 
 * it has grown in size its length cannot be automatically be calculated so
 
 * use SDT(G)_CONDLISTO() meaning Old.
 
 * If nothing fits you, you can use the GENERAL macros, but it exposes the internal
 
 * structure somewhat so it needs a little looking. There are _NULL() macros as
 
 * well, these fill up space so you can add more patches there (in place) and you
 
 * DON'T have to increase the savegame version. */
 
 * If nothing fits you, you can use the GENERAL macros, but it exposes the
 
 * internal structure somewhat so it needs a little looking. There are _NULL()
 
 * macros as well, these fill up space so you can add more patches there (in
 
 * place) and you DON'T have to increase the savegame version. */
 

	
 
#define NSD_GENERAL(name, def, cmd, guiflags, min, max, many, str, proc)\
 
	{name, (const void*)(def), cmd, guiflags, min, max, many, str, proc}
 

	
 
/* Macros for various objects to go in the configuration file.
 
 * This section is for global variables */
 
@@ -1215,17 +1217,17 @@ static const SettingDesc _gameopt_settin
 
};
 

	
 
/* Some patches do not need to be synchronised when playing in multiplayer.
 
 * These include for example the GUI settings and will not be saved with the
 
 * savegame.
 
 * It is also a bit tricky since you would think that service_interval
 
 * for example doesn't need to be synched. Every client assigns the service_interval
 
 * value to the v->service_interval, meaning that every client assigns his value. If
 
 * the setting was player-based, that would mean that vehicles could decide on
 
 * different moments that they are heading back to a service depot, causing desyncs
 
 * on a massive scale. */
 
 * for example doesn't need to be synched. Every client assigns the
 
 * service_interval value to the v->service_interval, meaning that every client
 
 * assigns his value. If the setting was player-based, that would mean that
 
 * vehicles could decide on different moments that they are heading back to a
 
 * service depot, causing desyncs on a massive scale. */
 
const SettingDesc _patch_settings[] = {
 
	/***************************************************************************/
 
	/* User-interface section of the GUI-configure patches window */
 
	SDT_BOOL(Patches, vehicle_speed,                 S, 0,  true,    STR_CONFIG_PATCHES_VEHICLESPEED,          NULL),
 
	SDT_BOOL(Patches, status_long_date,              S, 0,  true,    STR_CONFIG_PATCHES_LONGDATE,              NULL),
 
	SDT_BOOL(Patches, show_finances,                 S, 0,  true,    STR_CONFIG_PATCHES_SHOWFINANCES,          NULL),
 
@@ -1345,14 +1347,14 @@ const SettingDesc _patch_settings[] = {
 
	* station, leave through the other side, turn around, enter the
 
	* station on another platform and exit the station on the right side
 
	* again, just because the sign at the right side was red. If we take
 
	* a typical 5 length station, this detour is 10 or 11 tiles (not
 
	* sure), so we set the default penalty at 10 (the station tile
 
	* penalty will further prevent this.
 
	* We give presignal exits (and combo's) a different (larger) penalty, because we really
 
	* don't want trains waiting in front of a presignal exit. */
 
	 * We give presignal exits (and combo's) a different (larger) penalty, because
 
	 * we really don't want trains waiting in front of a presignal exit. */
 
	SDT_VAR(Patches, npf_rail_firstred_penalty,     SLE_UINT, 0, 0, (10 * NPF_TILE_LENGTH), 0, 100000, STR_NULL, NULL),
 
	SDT_VAR(Patches, npf_rail_firstred_exit_penalty,SLE_UINT, 0, 0, (100 * NPF_TILE_LENGTH),0, 100000, STR_NULL, NULL),
 
	/* This penalty is for when the last signal before the target is red.
 
	 * This is useful for train stations, where there are multiple
 
	 * platforms to choose from, which lie in different signal blocks.
 
	 * Every target in a occupied signal block (ie an occupied platform)
ship_gui.c
Show inline comments
 
@@ -561,16 +561,15 @@ static void ShipViewWndProc(Window *w, W
 
			DeleteWindowById(WC_VEHICLE_REFIT, w->window_number);
 
			DeleteWindowById(WC_VEHICLE_DETAILS, w->window_number);
 
			break;
 

	
 
		case WE_MOUSELOOP:
 
		{
 
			Vehicle *v;
 
			uint32 h;
 
			v = GetVehicle(w->window_number);
 
			h = IsShipInDepot(v) ? 1 << 7 : 1 << 11;
 
			const Vehicle* v = GetVehicle(w->window_number);
 
			uint32 h = IsShipInDepot(v) ? 1 << 7 : 1 << 11;
 

	
 
			if (h != w->hidden_state) {
 
				w->hidden_state = h;
 
				SetWindowDirty(w);
 
			}
 
		}
 
	}
 
@@ -1009,16 +1008,17 @@ static void PlayerShipsWndProc(Window *w
 
			assert(v->type == VEH_Ship);
 

	
 
			DrawShipImage(v, x + 19, y + 6, INVALID_VEHICLE);
 
			DrawVehicleProfitButton(v, x, y + 13);
 

	
 
			SetDParam(0, v->unitnumber);
 
			if (IsShipInDepot(v))
 
			if (IsShipInDepot(v)) {
 
				str = STR_021F;
 
			else
 
			} else {
 
				str = v->age > v->max_age - 366 ? STR_00E3 : STR_00E2;
 
			}
 
			DrawString(x, y + 2, str, 0);
 

	
 
			SetDParam(0, v->profit_this_year);
 
			SetDParam(1, v->profit_last_year);
 
			DrawString(x + 12, y + 28, STR_0198_PROFIT_THIS_YEAR_LAST_YEAR, 0);
 

	
smallmap_gui.c
Show inline comments
 
@@ -935,52 +935,50 @@ static const Widget _extra_view_port_wid
 
static void ExtraViewPortWndProc(Window *w, WindowEvent *e)
 
{
 
	switch (e->event) {
 
	case WE_CREATE: /* Disable zoom in button */
 
		w->disabled_state = (1 << 5);
 
		break;
 

	
 
	case WE_PAINT:
 
		// set the number in the title bar
 
		SetDParam(0, (w->window_number+1));
 
		SetDParam(0, w->window_number + 1);
 

	
 
		DrawWindowWidgets(w);
 
		DrawWindowViewport(w);
 
		break;
 

	
 
	case WE_CLICK: {
 
	case WE_CLICK:
 
		switch (e->click.widget) {
 
		case 5: /* zoom in */
 
			DoZoomInOutWindow(ZOOM_IN, w);
 
			break;
 
		case 6: /* zoom out */
 
			DoZoomInOutWindow(ZOOM_OUT, w);
 
			break;
 
			case 5: DoZoomInOutWindow(ZOOM_IN,  w); break;
 
			case 6: DoZoomInOutWindow(ZOOM_OUT, w); break;
 

	
 
		case 7: { /* location button (move main view to same spot as this view) 'Paste Location' */
 
			Window *w2 = FindWindowById(WC_MAIN_WINDOW, 0);
 
			int x = WP(w, vp_d).scrollpos_x; // Where is the main looking at
 
			int y = WP(w, vp_d).scrollpos_y;
 

	
 
			// set this view to same location. Based on the center, adjusting for zoom
 
			WP(w2, vp_d).scrollpos_x =  x - (w2->viewport->virtual_width -  w->viewport->virtual_width) / 2;
 
			WP(w2, vp_d).scrollpos_y =  y - (w2->viewport->virtual_height - w->viewport->virtual_height) / 2;
 
		} break;
 

	
 
		case 8: { /* inverse location button (move this view to same spot as main view) 'Copy Location' */
 
			const Window* w2 = FindWindowById(WC_MAIN_WINDOW, 0);
 
			int x = WP(w2, const vp_d).scrollpos_x;
 
			int y = WP(w2, const vp_d).scrollpos_y;
 

	
 
			WP(w, vp_d).scrollpos_x =  x + (w2->viewport->virtual_width -  w->viewport->virtual_width) / 2;
 
			WP(w, vp_d).scrollpos_y =  y + (w2->viewport->virtual_height - w->viewport->virtual_height) / 2;
 
		} break;
 
		}
 
	} break;
 
		break;
 

	
 
	case WE_RESIZE:
 
		w->viewport->width  += e->sizing.diff.x;
 
		w->viewport->height += e->sizing.diff.y;
 

	
 
		w->viewport->virtual_width  += e->sizing.diff.x;
 
		w->viewport->virtual_height += e->sizing.diff.y;
 
		break;
 
	}
 
}
 

	
station_cmd.c
Show inline comments
 
@@ -1911,13 +1911,13 @@ int32 CmdBuildDock(TileIndex tile, uint3
 
		return_cmd_error(STR_304B_SITE_UNSUITABLE);
 
	}
 

	
 
	cost = DoCommand(tile_cur, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
 
	if (CmdFailed(cost)) return CMD_ERROR;
 

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

	
 
	/* middle */
 
	st = GetStationAround(
stdafx.h
Show inline comments
 
@@ -66,17 +66,15 @@
 
// by default we use [] var arrays
 
#define VARARRAY_SIZE
 

	
 

	
 
// Stuff for GCC
 
#if defined(__GNUC__)
 
# define NORETURN              __attribute((noreturn))
 
# define NORETURN __attribute__ ((noreturn))
 
# define FORCEINLINE inline
 
# define CDECL
 
//#include <alloca.h>
 
//#include <malloc.h>
 
# define __int64 long long
 
# define NOT_REACHED() assert(0)
 
# define GCC_PACK __attribute__((packed))
 

	
 
# if (__GNUC__ == 2)
 
#  undef VARARRAY_SIZE
town_cmd.c
Show inline comments
 
@@ -1060,23 +1060,26 @@ static const byte _num_initial_towns[3] 
 
bool GenerateTowns(void)
 
{
 
	uint num = 0;
 
	uint n = ScaleByMapSize(_num_initial_towns[_opt.diff.number_towns] + (Random() & 7));
 

	
 
	do {
 
		if (CreateRandomTown(20, 0) != NULL) 	//try 20 times to create a random-sized town for the first loop.
 
			num++;
 
		// try 20 times to create a random-sized town for the first loop.
 
		if (CreateRandomTown(20, 0) != NULL) num++;
 
	} while (--n);
 

	
 
	// give it a last try, but now more aggressive
 
	if (num == 0 && CreateRandomTown(10000, 0) == NULL) {
 
		Town *t;
 
		FOR_ALL_TOWNS(t) { if (IsValidTown(t)) {num = 1; break;}}
 
		const Town* t;
 

	
 
		FOR_ALL_TOWNS(t) if (IsValidTown(t)) return true;
 

	
 
		//XXX can we handle that more gracefully?
 
		if (num == 0 && _game_mode != GM_EDITOR) error("Could not generate any town");
 
		if (num == 0 && _game_mode != GM_EDITOR) {
 
			error("Could not generate any town");
 
		}
 
		return false;
 
	}
 

	
 
	return true;
 
}
 

	
 
@@ -1099,25 +1102,24 @@ static bool CheckBuildHouseMode(TileInde
 
	if (b)
 
		return false;
 

	
 
	return !CmdFailed(DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
 
}
 

	
 
int GetTownRadiusGroup(const Town *t, TileIndex tile)
 

	
 
uint GetTownRadiusGroup(const Town* t, TileIndex tile)
 
{
 
	uint dist;
 
	int i,smallest;
 
	uint dist = DistanceSquare(tile, t->xy);
 
	uint smallest;
 
	uint i;
 

	
 
	dist = DistanceSquare(tile, t->xy);
 
	if (t->fund_buildings_months && dist <= 25)
 
		return 4;
 
	if (t->fund_buildings_months && dist <= 25) return 4;
 

	
 
	smallest = 0;
 
	for (i = 0; i != lengthof(t->radius); i++) {
 
		if (dist < t->radius[i])
 
			smallest = i;
 
		if (dist < t->radius[i]) smallest = i;
 
	}
 

	
 
	return smallest;
 
}
 

	
 
static bool CheckFree2x2Area(TileIndex tile)
 
@@ -1157,14 +1159,13 @@ static void DoBuildTownHouse(Town *t, Ti
 

	
 
	// Get the town zone type
 
	{
 
		uint rad = GetTownRadiusGroup(t, tile);
 

	
 
		int land = _opt.landscape;
 
		if (land == LT_HILLY && z >= _opt.snow_line)
 
			land = -1;
 
		if (land == LT_HILLY && z >= _opt.snow_line) land = -1;
 

	
 
		bitmask = (1 << rad) + (1 << (land + 12));
 
	}
 

	
 
	// bits 0-4 are used
 
	// bits 11-15 are used
 
@@ -1256,14 +1257,12 @@ static void DoBuildTownHouse(Town *t, Ti
 
				construction_counter = GB(r, 2, 2);
 
			}
 
		}
 
		size_flags = GB(_housetype_extra_flags[house], 2, 3);
 
		MakeTownHouse(tile, t->index, construction_counter, construction_stage, size_flags, house);
 
	}
 

	
 
	// ENDING
 
}
 

	
 
static bool BuildTownHouse(Town *t, TileIndex tile)
 
{
 
	int32 r;
 

	
 
@@ -1707,33 +1706,29 @@ static void UpdateTownAmounts(Town *t)
 

	
 
	InvalidateWindow(WC_TOWN_VIEW, t->index);
 
}
 

	
 
static void UpdateTownUnwanted(Town *t)
 
{
 
	Player *p;
 
	const Player* p;
 

	
 
	FOR_ALL_PLAYERS(p) {
 
		if (t->unwanted[p->index] > 0)
 
			t->unwanted[p->index]--;
 
		if (t->unwanted[p->index] > 0) t->unwanted[p->index]--;
 
	}
 
}
 

	
 
bool CheckIfAuthorityAllows(TileIndex tile)
 
{
 
	Town *t;
 

	
 
	if (_current_player >= MAX_PLAYERS)
 
		return true;
 
	if (_current_player >= MAX_PLAYERS) return true;
 

	
 
	t = ClosestTownFromTile(tile, _patches.dist_local_authority);
 
	if (t == NULL)
 
		return true;
 
	if (t == NULL) return true;
 

	
 
	if (t->ratings[_current_player] > -200)
 
		return true;
 
	if (t->ratings[_current_player] > -200) return true;
 

	
 
	_error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
 
	SetDParam(0, t->index);
 

	
 
	return false;
 
}
 
@@ -1834,18 +1829,16 @@ bool CheckforTownRating(uint32 flags, To
 

	
 
void TownsMonthlyLoop(void)
 
{
 
	Town *t;
 

	
 
	FOR_ALL_TOWNS(t) if (t->xy != 0) {
 
		if (t->road_build_months != 0)
 
			t->road_build_months--;
 
		if (t->road_build_months != 0) t->road_build_months--;
 

	
 
		if (t->exclusive_counter != 0)
 
			if (--t->exclusive_counter == 0)
 
				t->exclusivity = (byte)-1;
 
			if (--t->exclusive_counter == 0) t->exclusivity = (byte)-1;
 

	
 
		UpdateTownGrowRate(t);
 
		UpdateTownAmounts(t);
 
		UpdateTownUnwanted(t);
 
	}
 
}
train_gui.c
Show inline comments
 
@@ -337,13 +337,13 @@ static void ShowBuildTrainWindow(TileInd
 
	w = AllocateWindowDesc(&_new_rail_vehicle_desc);
 
	w->window_number = tile;
 
	w->vscroll.cap = 8;
 
	w->widget[2].unkA = (w->vscroll.cap << 8) + 1;
 

	
 
	w->resize.step_height = 14;
 
	w->resize.height = w->height - 14 * 4; /* Minimum of 4 vehicles in the display */
 
	w->resize.height = w->height - 14 * 4; // Minimum of 4 vehicles in the display
 

	
 
	if (tile != 0) {
 
		w->caption_color = GetTileOwner(tile);
 
		WP(w,buildtrain_d).railtype = GetRailType(tile);
 
	} else {
 
		w->caption_color = _local_player;
 
@@ -1046,16 +1046,15 @@ static void TrainViewWndProc(Window *w, 
 
		DeleteWindowById(WC_VEHICLE_REFIT, w->window_number);
 
		DeleteWindowById(WC_VEHICLE_ORDERS, w->window_number);
 
		DeleteWindowById(WC_VEHICLE_DETAILS, w->window_number);
 
		break;
 

	
 
	case WE_MOUSELOOP: {
 
		Vehicle *v;
 
		const Vehicle* v = GetVehicle(w->window_number);
 
		uint32 h;
 

	
 
		v = GetVehicle(w->window_number);
 
		assert(v->type == VEH_Train);
 
		h = CheckTrainStoppedInDepot(v) >= 0 ? (1 << 9)| (1 << 7) : (1 << 12) | (1 << 13);
 
		if (h != w->hidden_state) {
 
			w->hidden_state = h;
 
			SetWindowDirty(w);
 
		}
tunnelbridge_cmd.c
Show inline comments
 
@@ -235,19 +235,21 @@ int32 CmdBuildBridge(TileIndex end_tile,
 
		if (x > sx) uintswap(x,sx);
 
	} else {
 
		return_cmd_error(STR_500A_START_AND_END_MUST_BE_IN);
 
	}
 

	
 
	/* set and test bridge length, availability */
 
	bridge_len = (sx + sy - x - y) - 1;
 
	bridge_len = sx + sy - x - y - 1;
 
	if (!CheckBridge_Stuff(bridge_type, bridge_len)) return_cmd_error(STR_5015_CAN_T_BUILD_BRIDGE_HERE);
 

	
 
	/* retrieve landscape height and ensure it's on land */
 
	tile_start = TileXY(x, y);
 
	tile_end = TileXY(sx, sy);
 
	if (IsClearWaterTile(tile_start) || IsClearWaterTile(tile_end)) return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
 
	if (IsClearWaterTile(tile_start) || IsClearWaterTile(tile_end)) {
 
		return_cmd_error(STR_02A0_ENDS_OF_BRIDGE_MUST_BOTH);
 
	}
 

	
 
	tileh_start = GetTileSlope(tile_start, &z_start);
 
	tileh_end = GetTileSlope(tile_end, &z_end);
 

	
 
	if (HASBIT(BRIDGE_FULL_LEVELED_FOUNDATION, tileh_start)) {
 
		z_start += TILE_HEIGHT;
 
@@ -322,13 +324,13 @@ int32 CmdBuildBridge(TileIndex end_tile,
 
			return_cmd_error(STR_5009_LEVEL_LAND_OR_WATER_REQUIRED);
 
		}
 

	
 
		switch (GetTileType(tile)) {
 
			case MP_WATER:
 
				if (!EnsureNoVehicle(tile)) return_cmd_error(STR_980E_SHIP_IN_THE_WAY);
 
				if (!(IsWater(tile) || IsCoast(tile))) goto not_valid_below;
 
				if (!IsWater(tile) && !IsCoast(tile)) goto not_valid_below;
 
				transport_under = TRANSPORT_WATER;
 
				owner_under = GetTileOwner(tile);
 
				break;
 

	
 
			case MP_RAILWAY:
 
				if (GetRailTileType(tile) != RAIL_TILE_NORMAL ||
 
@@ -505,13 +507,12 @@ int32 CmdBuildTunnel(TileIndex start_til
 
			UpdateSignalsOnSegment(start_tile, direction);
 
			YapfNotifyTrackLayoutChange(start_tile, DiagDirToAxis(direction) == AXIS_X ? TRACK_X : TRACK_Y);
 
		} else {
 
			MakeRoadTunnel(start_tile, _current_player, direction);
 
			MakeRoadTunnel(end_tile,   _current_player, ReverseDiagDir(direction));
 
		}
 

	
 
	}
 

	
 
	return cost;
 
}
 

	
 
TileIndex CheckTunnelBusy(TileIndex tile, uint *length)
 
@@ -658,14 +659,15 @@ static int32 DoClearBridge(TileIndex til
 
	if (!EnsureNoVehicle(tile) || !EnsureNoVehicle(endtile)) return CMD_ERROR;
 

	
 
	direction = GetBridgeRampDirection(tile);
 
	delta = TileOffsByDir(direction);
 

	
 
	/*	Make sure there's no vehicle on the bridge
 
			Omit tile and endtile, since these are already checked, thus solving the problem
 
			of bridges over water, or higher bridges, where z is not increased, eg level bridge
 
	 * Omit tile and endtile, since these are already checked, thus solving the
 
	 * problem of bridges over water, or higher bridges, where z is not increased,
 
	 * eg level bridge
 
	*/
 
	/* Bridges on slopes might have their Z-value offset..correct this */
 
	v = FindVehicleBetween(
 
		tile    + delta,
 
		endtile - delta,
 
		GetBridgeHeightRamp(tile) + TILE_HEIGHT
 
@@ -734,16 +736,16 @@ static int32 ClearTile_TunnelBridge(Tile
 
	return CMD_ERROR;
 
}
 

	
 
int32 DoConvertTunnelBridgeRail(TileIndex tile, RailType totype, bool exec)
 
{
 
	TileIndex endtile;
 
	uint length;
 
	Vehicle *v;
 

	
 
	if (IsTunnel(tile) && GetTunnelTransportType(tile) == TRANSPORT_RAIL) {
 
		uint length;
 

	
 
		if (!CheckTileOwnership(tile)) return CMD_ERROR;
 

	
 
		if (GetRailType(tile) == totype) return CMD_ERROR;
 

	
 
		endtile = CheckTunnelBusy(tile, &length);
 
		if (endtile == INVALID_TILE) return CMD_ERROR;
 
@@ -780,17 +782,16 @@ int32 DoConvertTunnelBridgeRail(TileInde
 
			// notify YAPF about the track layout change
 
			for (tracks = GetRailBitsUnderBridge(tile); tracks != TRACK_BIT_NONE; tracks = KILL_FIRST_BIT(tracks))
 
				YapfNotifyTrackLayoutChange(tile, FIND_FIRST_BIT(tracks));
 
		}
 
		return _price.build_rail >> 1;
 
	} else if (IsBridge(tile) && IsBridgeRamp(tile) && GetBridgeTransportType(tile) == TRANSPORT_RAIL) {
 
		uint z = TilePixelHeight(tile) + TILE_HEIGHT;
 
		const Vehicle* v;
 
		TileIndexDiff delta;
 
		int32 cost;
 
		uint z = TilePixelHeight(tile);
 

	
 
		z += TILE_HEIGHT;
 

	
 
		if (!CheckTileOwnership(tile)) return CMD_ERROR;
 

	
 
		endtile = GetOtherBridgeEnd(tile);
 
		// Make sure there's no vehicle on the bridge
 
		v = FindVehicleBetween(tile, endtile, z);
 
@@ -825,15 +826,16 @@ int32 DoConvertTunnelBridgeRail(TileInde
 
				MarkTileDirtyByTile(tile);
 
			}
 
			cost += _price.build_rail >> 1;
 
		}
 

	
 
		return cost;
 
	} else
 
	} else {
 
		return CMD_ERROR;
 
}
 
}
 

	
 

	
 
// fast routine for getting the height of a middle bridge tile. 'tile' MUST be a middle bridge tile.
 
uint GetBridgeHeight(TileIndex t)
 
{
 
	return GetBridgeHeightRamp(GetSouthernBridgeEnd(t));
video/cocoa_v.m
Show inline comments
 
@@ -661,14 +661,12 @@ static bool QZ_PollEvent(void)
 
	}
 

	
 
	return true;
 
}
 

	
 

	
 

	
 

	
 
static void QZ_GameLoop(void)
 
{
 
	uint32 next_tick = GetTick() + 30;
 
	uint32 cur_ticks;
 
	uint32 pal_tick = 0;
 
#ifdef _DEBUG
video/win32_v.c
Show inline comments
 
@@ -646,19 +646,21 @@ static const uint16 default_resolutions[
 
	{1680, 1050},
 
	{1920, 1200}
 
};
 

	
 
static void FindResolutions(void)
 
{
 
	int i = 0, n = 0;
 
	uint n = 0;
 
	uint i;
 
	DEVMODE dm;
 

	
 
	while (EnumDisplaySettings(NULL, i++, &dm) != 0) {
 
	for (i = 0; EnumDisplaySettings(NULL, i, &dm) != 0; i++) {
 
		if (dm.dmBitsPerPel == 8 && IS_INT_INSIDE(dm.dmPelsWidth, 640, MAX_SCREEN_WIDTH + 1) &&
 
				IS_INT_INSIDE(dm.dmPelsHeight, 480, MAX_SCREEN_HEIGHT + 1)){
 
			int j;
 
			uint j;
 

	
 
			for (j = 0; j < n; j++) {
 
				if (_resolutions[j][0] == dm.dmPelsWidth && _resolutions[j][1] == dm.dmPelsHeight) break;
 
			}
 

	
 
			/* In the previous loop we have checked already existing/added resolutions if
 
			 * they are the same as the new ones. If this is not the case (j == n); we have
viewport.c
Show inline comments
 
@@ -543,12 +543,13 @@ void *AddStringToDraw(int x, int y, Stri
 
	*vd->last_string = ss;
 
	vd->last_string = &ss->next;
 

	
 
	return ss;
 
}
 

	
 

	
 
static void DrawSelectionSprite(uint32 image, const TileInfo *ti)
 
{
 
	if (_added_tile_sprite && !(_thd.drawstyle & HT_LINE)) { // draw on real ground
 
		DrawGroundSpriteAt(image, ti->x, ti->y, ti->z + 7);
 
	} else { // draw on top of foundation
 
		AddSortableSpriteToDraw(image, ti->x, ti->y, 0x10, 0x10, 1, ti->z + 7);
waypoint.c
Show inline comments
 
@@ -214,14 +214,15 @@ int32 CmdBuildTrainWaypoint(TileIndex ti
 

	
 
	if (flags & DC_EXEC) {
 
		const StationSpec *statspec = NULL;
 
		MakeRailWaypoint(tile, GetTileOwner(tile), axis, GetRailType(tile), wp->index);
 
		MarkTileDirtyByTile(tile);
 

	
 
		if (GB(p1, 0, 8) < GetNumCustomStations(STAT_CLASS_WAYP))
 
		if (GB(p1, 0, 8) < GetNumCustomStations(STAT_CLASS_WAYP)) {
 
			statspec = GetCustomStationSpec(STAT_CLASS_WAYP, GB(p1, 0, 8));
 
		}
 

	
 
		if (statspec != NULL) {
 
			SetCustomWaypointSprite(tile);
 
			wp->stat_id = GB(p1, 0, 8);
 
			wp->grfid = statspec->grfid;
 
			wp->localidx = statspec->localidx;
 
@@ -234,14 +235,13 @@ int32 CmdBuildTrainWaypoint(TileIndex ti
 
		}
 

	
 
		wp->deleted = 0;
 
		wp->xy = tile;
 
		wp->build_date = _date;
 

	
 
		if (wp->town_index == 0)
 
			MakeDefaultWaypointName(wp);
 
		if (wp->town_index == 0) MakeDefaultWaypointName(wp);
 

	
 
		UpdateWaypointSign(wp);
 
		RedrawWaypointSign(wp);
 
	}
 

	
 
	return _price.build_train_depot;
window.c
Show inline comments
 
@@ -1453,15 +1453,15 @@ void InputLoop(void)
 
	int click;
 
	int mousewheel;
 

	
 
	_current_player = _local_player;
 

	
 
	// Handle pressed keys
 
	if (_pressed_key) {
 
		uint32 key = _pressed_key; _pressed_key = 0;
 
		HandleKeypress(key);
 
	if (_pressed_key != 0) {
 
		HandleKeypress(_pressed_key);
 
		_pressed_key = 0;
 
	}
 

	
 
	// Mouse event?
 
	click = 0;
 
	if (_left_button_down && !_left_button_clicked) {
 
		_left_button_clicked = true;
0 comments (0 inline, 0 general)