Changeset - r12109:90df01928018
[Not reviewed]
src/ai/api/ai_vehicle.cpp
Show inline comments
 
@@ -37,29 +37,29 @@
 
	return num;
 
}
 

	
 
/* static */ int AIVehicle::GetLength(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 

	
 
	const Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	switch (v->type) {
 
		case VEH_ROAD: {
 
			uint total_length = 0;
 
			for (const Vehicle *u = v; u != NULL; u = u->Next()) {
 
				total_length += ((const RoadVehicle *)u)->rcache.cached_veh_length;
 
				total_length += ::RoadVehicle::From(u)->rcache.cached_veh_length;
 
			}
 
			return total_length;
 
		}
 
		case VEH_TRAIN: return ((const Train *)v)->tcache.cached_total_length;
 
		case VEH_TRAIN: return ::Train::From(v)->tcache.cached_total_length;
 
		default: return -1;
 
	}
 
}
 

	
 
/* static */ VehicleID AIVehicle::BuildVehicle(TileIndex depot, EngineID engine_id)
 
{
 
	EnforcePrecondition(INVALID_VEHICLE, AIEngine::IsValidEngine(engine_id));
 

	
 
	::VehicleType type = ::Engine::Get(engine_id)->type;
 

	
 
	EnforcePreconditionCustomError(INVALID_VEHICLE, !AIGameSettings::IsDisabledVehicleType((AIVehicle::VehicleType)type), AIVehicle::ERR_VEHICLE_BUILD_DISABLED);
 

	
 
@@ -77,29 +77,29 @@
 

	
 
	/* In case of test-mode, we return VehicleID 0 */
 
	return 0;
 
}
 

	
 
/* static */ bool AIVehicle::_MoveWagonInternal(VehicleID source_vehicle_id, int source_wagon, bool move_attached_wagons, int dest_vehicle_id, int dest_wagon)
 
{
 
	EnforcePrecondition(false, IsValidVehicle(source_vehicle_id) && source_wagon < GetNumWagons(source_vehicle_id));
 
	EnforcePrecondition(false, dest_vehicle_id == -1 || (IsValidVehicle(dest_vehicle_id) && dest_wagon < GetNumWagons(dest_vehicle_id)));
 
	EnforcePrecondition(false, ::Vehicle::Get(source_vehicle_id)->type == VEH_TRAIN);
 
	EnforcePrecondition(false, dest_vehicle_id == -1 || ::Vehicle::Get(dest_vehicle_id)->type == VEH_TRAIN);
 

	
 
	const Train *v = (const Train *)::Vehicle::Get(source_vehicle_id);
 
	const Train *v = ::Train::Get(source_vehicle_id);
 
	while (source_wagon-- > 0) v = GetNextUnit(v);
 
	const Train *w = NULL;
 
	if (dest_vehicle_id != -1) {
 
		w = (const Train *)::Vehicle::Get(dest_vehicle_id);
 
		w = ::Train::Get(dest_vehicle_id);
 
		while (dest_wagon-- > 0) w = GetNextUnit(w);
 
	}
 

	
 
	return AIObject::DoCommand(0, v->index | ((w == NULL ? INVALID_VEHICLE : w->index) << 16), move_attached_wagons ? 1 : 0, CMD_MOVE_RAIL_VEHICLE);
 
}
 

	
 
/* static */ bool AIVehicle::MoveWagon(VehicleID source_vehicle_id, int source_wagon, int dest_vehicle_id, int dest_wagon)
 
{
 
	return _MoveWagonInternal(source_vehicle_id, source_wagon, false, dest_vehicle_id, dest_wagon);
 
}
 

	
 
/* static */ bool AIVehicle::MoveWagonChain(VehicleID source_vehicle_id, int source_wagon, int dest_vehicle_id, int dest_wagon)
 
@@ -128,25 +128,25 @@
 
{
 
	EnforcePrecondition(false, IsValidVehicle(vehicle_id));
 

	
 
	const Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	return AIObject::DoCommand(0, vehicle_id, v->type == VEH_TRAIN ? 1 : 0, GetCmdSellVeh(v));
 
}
 

	
 
/* static */ bool AIVehicle::_SellWagonInternal(VehicleID vehicle_id, int wagon, bool sell_attached_wagons)
 
{
 
	EnforcePrecondition(false, IsValidVehicle(vehicle_id) && wagon < GetNumWagons(vehicle_id));
 
	EnforcePrecondition(false, ::Vehicle::Get(vehicle_id)->type == VEH_TRAIN);
 

	
 
	const Train *v = (const Train *)::Vehicle::Get(vehicle_id);
 
	const Train *v = ::Train::Get(vehicle_id);
 
	while (wagon-- > 0) v = GetNextUnit(v);
 

	
 
	return AIObject::DoCommand(0, v->index, sell_attached_wagons ? 1 : 0, CMD_SELL_RAIL_WAGON);
 
}
 

	
 
/* static */ bool AIVehicle::SellWagon(VehicleID vehicle_id, int wagon)
 
{
 
	return _SellWagonInternal(vehicle_id, wagon, false);
 
}
 

	
 
/* static */ bool AIVehicle::SellWagonChain(VehicleID vehicle_id, int wagon)
 
{
 
@@ -235,25 +235,25 @@
 
	if (!IsValidVehicle(vehicle_id)) return INVALID_ENGINE;
 

	
 
	return ::Vehicle::Get(vehicle_id)->engine_type;
 
}
 

	
 
/* static */ EngineID AIVehicle::GetWagonEngineType(VehicleID vehicle_id, int wagon)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return INVALID_ENGINE;
 
	if (wagon >= GetNumWagons(vehicle_id)) return INVALID_ENGINE;
 

	
 
	const Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	if (v->type == VEH_TRAIN) {
 
		while (wagon-- > 0) v = GetNextUnit((const Train *)v);
 
		while (wagon-- > 0) v = GetNextUnit(::Train::From(v));
 
	}
 
	return v->engine_type;
 
}
 

	
 
/* static */ int32 AIVehicle::GetUnitNumber(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 

	
 
	return ::Vehicle::Get(vehicle_id)->unitnumber;
 
}
 

	
 
/* static */ char *AIVehicle::GetName(VehicleID vehicle_id)
 
@@ -273,25 +273,25 @@
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 

	
 
	return ::Vehicle::Get(vehicle_id)->age;
 
}
 

	
 
/* static */ int32 AIVehicle::GetWagonAge(VehicleID vehicle_id, int wagon)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 
	if (wagon >= GetNumWagons(vehicle_id)) return -1;
 

	
 
	const Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	if (v->type == VEH_TRAIN) {
 
		while (wagon-- > 0) v = GetNextUnit((const Train *)v);
 
		while (wagon-- > 0) v = GetNextUnit(::Train::From(v));
 
	}
 
	return v->age;
 
}
 

	
 
/* static */ int32 AIVehicle::GetMaxAge(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 

	
 
	return ::Vehicle::Get(vehicle_id)->max_age;
 
}
 

	
 
/* static */ int32 AIVehicle::GetAgeLeft(VehicleID vehicle_id)
 
@@ -360,25 +360,25 @@
 
		case VEH_TRAIN:    return VT_RAIL;
 
		case VEH_SHIP:     return VT_WATER;
 
		case VEH_AIRCRAFT: return VT_AIR;
 
		default:           return VT_INVALID;
 
	}
 
}
 

	
 
/* static */ AIRoad::RoadType AIVehicle::GetRoadType(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return AIRoad::ROADTYPE_INVALID;
 
	if (GetVehicleType(vehicle_id) != VT_ROAD) return AIRoad::ROADTYPE_INVALID;
 

	
 
	return (AIRoad::RoadType)((RoadVehicle*)::Vehicle::Get(vehicle_id))->roadtype;
 
	return (AIRoad::RoadType)(::RoadVehicle::Get(vehicle_id))->roadtype;
 
}
 

	
 
/* static */ int32 AIVehicle::GetCapacity(VehicleID vehicle_id, CargoID cargo)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return -1;
 
	if (!AICargo::IsValidCargo(cargo)) return -1;
 

	
 
	uint32 amount = 0;
 
	for (const Vehicle *v = ::Vehicle::Get(vehicle_id); v != NULL; v = v->Next()) {
 
		if (v->cargo_type == cargo) amount += v->cargo_cap;
 
	}
 

	
 
@@ -403,25 +403,25 @@
 
	if (!IsValidVehicle(vehicle_id)) return AIGroup::GROUP_INVALID;
 

	
 
	return ::Vehicle::Get(vehicle_id)->group_id;
 
}
 

	
 
/* static */ bool AIVehicle::IsArticulated(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return false;
 
	if (GetVehicleType(vehicle_id) != VT_ROAD && GetVehicleType(vehicle_id) != VT_RAIL) return false;
 

	
 
	const Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	switch (v->type) {
 
		case VEH_ROAD: return RoadVehHasArticPart(v);
 
		case VEH_TRAIN: return EngineHasArticPart(v);
 
		case VEH_ROAD: return ::RoadVehHasArticPart(v);
 
		case VEH_TRAIN: return ::EngineHasArticPart(v);
 
		default: NOT_REACHED();
 
	}
 
}
 

	
 
/* static */ bool AIVehicle::HasSharedOrders(VehicleID vehicle_id)
 
{
 
	if (!IsValidVehicle(vehicle_id)) return false;
 

	
 
	Vehicle *v = ::Vehicle::Get(vehicle_id);
 
	return v->orders.list != NULL && v->orders.list->GetNumVehicles() > 1;
 
}
src/aircraft_gui.cpp
Show inline comments
 
@@ -58,25 +58,25 @@ void DrawAircraftDetails(const Vehicle *
 
	}
 

	
 
	SetDParam(0, feeder_share);
 
	DrawString(left, right, y + 33 + y_offset, STR_FEEDER_CARGO_VALUE);
 
}
 

	
 

	
 
void DrawAircraftImage(const Vehicle *v, int x, int y, VehicleID selection)
 
{
 
	SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
 
	DrawSprite(v->GetImage(DIR_W), pal, x + 25, y + 10);
 
	if (v->subtype == AIR_HELICOPTER) {
 
		const Aircraft *a = (const Aircraft *)v;
 
		const Aircraft *a = Aircraft::From(v);
 
		SpriteID rotor_sprite = GetCustomRotorSprite(a, true);
 
		if (rotor_sprite == 0) rotor_sprite = SPR_ROTOR_STOPPED;
 
		DrawSprite(rotor_sprite, PAL_NONE, x + 25, y + 5);
 
	}
 
	if (v->index == selection) {
 
		DrawFrameRect(x - 1, y - 1, x + 58, y + 21, COLOUR_WHITE, FR_BORDERONLY);
 
	}
 
}
 

	
 
/**
 
 * This is the Callback method after the construction attempt of an aircraft
 
 * @param success indicates completion (or not) of the operation
src/articulated_vehicles.cpp
Show inline comments
 
@@ -199,25 +199,25 @@ bool IsArticulatedVehicleCarryingDiffere
 

	
 
	do {
 
		if (v->cargo_cap > 0 && v->cargo_type != CT_INVALID) {
 
			if (first_cargo == CT_INVALID) first_cargo = v->cargo_type;
 
			if (first_cargo != v->cargo_type) {
 
				if (cargo_type != NULL) *cargo_type = CT_INVALID;
 
				return true;
 
			}
 
		}
 

	
 
		switch (v->type) {
 
			case VEH_TRAIN:
 
				v = (EngineHasArticPart((const Train *)v) ? GetNextArticPart((const Train *)v) : NULL);
 
				v = (EngineHasArticPart(Train::From(v)) ? GetNextArticPart(Train::From(v)) : NULL);
 
				break;
 

	
 
			case VEH_ROAD:
 
				v = (RoadVehHasArticPart(v) ? v->Next() : NULL);
 
				break;
 

	
 
			default:
 
				v = NULL;
 
				break;
 
		}
 
	} while (v != NULL);
 

	
 
@@ -247,25 +247,25 @@ void CheckConsistencyOfArticulatedVehicl
 
	memset(real_default_capacity, 0, sizeof(real_default_capacity));
 

	
 
	do {
 
		uint32 refit_mask = GetAvailableVehicleCargoTypes(v->engine_type, v->type, true);
 
		real_refit_union |= refit_mask;
 
		if (refit_mask != 0) real_refit_intersection &= refit_mask;
 

	
 
		assert(v->cargo_type < NUM_CARGO);
 
		real_default_capacity[v->cargo_type] += v->cargo_cap;
 

	
 
		switch (v->type) {
 
			case VEH_TRAIN:
 
				v = (EngineHasArticPart((const Train *)v) ? GetNextArticPart((const Train *)v) : NULL);
 
				v = (EngineHasArticPart(Train::From(v)) ? GetNextArticPart(Train::From(v)) : NULL);
 
				break;
 

	
 
			case VEH_ROAD:
 
				v = (RoadVehHasArticPart(v) ? v->Next() : NULL);
 
				break;
 

	
 
			default:
 
				v = NULL;
 
				break;
 
		}
 
	} while (v != NULL);
 

	
 
@@ -296,48 +296,48 @@ void AddArticulatedParts(Vehicle *first,
 
		/* In the (very rare) case the GRF reported wrong number of articulated parts
 
		 * and we run out of available vehicles, bail out. */
 
		if (!Vehicle::CanAllocateItem()) return;
 

	
 
		EngineID engine_type = GetNewEngineID(GetEngineGRF(first->engine_type), type, GB(callback, 0, 7));
 
		bool flip_image = HasBit(callback, 7);
 

	
 
		const Engine *e_artic = Engine::Get(engine_type);
 
		switch (type) {
 
			default: NOT_REACHED();
 

	
 
			case VEH_TRAIN: {
 
				Train *front = (Train *)first;
 
				Train *front = Train::From(first);
 
				Train *t = new Train();
 
				v->SetNext(t);
 
				v = t;
 

	
 
				t->subtype = 0;
 
				t->track = front->track;
 
				t->railtype = front->railtype;
 
				t->tcache.first_engine = front->engine_type;
 

	
 
				t->spritenum = e_artic->u.rail.image_index;
 
				if (e_artic->CanCarryCargo()) {
 
					t->cargo_type = e_artic->GetDefaultCargoType();
 
					t->cargo_cap = e_artic->u.rail.capacity;  // Callback 36 is called when the consist is finished
 
				} else {
 
					t->cargo_type = front->cargo_type; // Needed for livery selection
 
					t->cargo_cap = 0;
 
				}
 

	
 
				SetArticulatedPart(t);
 
			} break;
 

	
 
			case VEH_ROAD: {
 
				RoadVehicle *front = (RoadVehicle *)first;
 
				RoadVehicle *front = RoadVehicle::From(first);
 
				RoadVehicle *rv = new RoadVehicle();
 
				v->SetNext(rv);
 
				v = rv;
 

	
 
				rv->subtype = 0;
 
				rv->rcache.first_engine = front->engine_type;
 
				rv->rcache.cached_veh_length = 8; // Callback is called when the consist is finished
 
				rv->state = RVSB_IN_DEPOT;
 

	
 
				rv->roadtype = front->roadtype;
 
				rv->compatible_roadtypes = front->compatible_roadtypes;
 

	
src/autoreplace_cmd.cpp
Show inline comments
 
@@ -83,49 +83,49 @@ bool CheckAutoreplaceValidity(EngineID f
 
}
 

	
 
/** Transfer cargo from a single (articulated )old vehicle to the new vehicle chain
 
 * @param old_veh Old vehicle that will be sold
 
 * @param new_head Head of the completely constructed new vehicle chain
 
 * @param part_of_chain The vehicle is part of a train
 
 */
 
static void TransferCargo(Vehicle *old_veh, Vehicle *new_head, bool part_of_chain)
 
{
 
	assert(!part_of_chain || new_head->IsPrimaryVehicle());
 
	/* Loop through source parts */
 
	for (Vehicle *src = old_veh; src != NULL; src = src->Next()) {
 
		if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != ((Train *)old_veh)->other_multiheaded_part && !IsArticulatedPart(src)) {
 
		if (!part_of_chain && src->type == VEH_TRAIN && src != old_veh && src != Train::From(old_veh)->other_multiheaded_part && !IsArticulatedPart(src)) {
 
			/* Skip vehicles, which do not belong to old_veh */
 
			src = GetLastEnginePart((Train *)src);
 
			src = GetLastEnginePart(Train::From(src));
 
			continue;
 
		}
 
		if (src->cargo_type >= NUM_CARGO || src->cargo.Count() == 0) continue;
 

	
 
		/* Find free space in the new chain */
 
		for (Vehicle *dest = new_head; dest != NULL && src->cargo.Count() > 0; dest = dest->Next()) {
 
			if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != ((Train *)new_head)->other_multiheaded_part && !IsArticulatedPart(dest)) {
 
			if (!part_of_chain && dest->type == VEH_TRAIN && dest != new_head && dest != Train::From(new_head)->other_multiheaded_part && !IsArticulatedPart(dest)) {
 
				/* Skip vehicles, which do not belong to new_head */
 
				dest = GetLastEnginePart((Train *)dest);
 
				dest = GetLastEnginePart(Train::From(dest));
 
				continue;
 
			}
 
			if (dest->cargo_type != src->cargo_type) continue;
 

	
 
			uint amount = min(src->cargo.Count(), dest->cargo_cap - dest->cargo.Count());
 
			if (amount <= 0) continue;
 

	
 
			src->cargo.MoveTo(&dest->cargo, amount);
 
		}
 
	}
 

	
 
	/* Update train weight etc., the old vehicle will be sold anyway */
 
	if (part_of_chain && new_head->type == VEH_TRAIN) TrainConsistChanged((Train *)new_head, true);
 
	if (part_of_chain && new_head->type == VEH_TRAIN) TrainConsistChanged(Train::From(new_head), true);
 
}
 

	
 
/**
 
 * Tests whether refit orders that applied to v will also apply to the new vehicle type
 
 * @param v The vehicle to be replaced
 
 * @param engine_type The type we want to replace with
 
 * @return true iff all refit orders stay valid
 
 */
 
static bool VerifyAutoreplaceRefitForOrders(const Vehicle *v, EngineID engine_type)
 
{
 
	const Order *o;
 
	const Vehicle *u;
 
@@ -260,25 +260,25 @@ static CommandCost BuildReplacementVehic
 
	if (cost.Failed()) return cost;
 

	
 
	Vehicle *new_veh = Vehicle::Get(_new_vehicle_id);
 
	*new_vehicle = new_veh;
 

	
 
	/* Refit the vehicle if needed */
 
	if (refit_cargo != CT_NO_REFIT) {
 
		cost.AddCost(DoCommand(0, new_veh->index, refit_cargo, DC_EXEC, GetCmdRefitVeh(new_veh)));
 
		assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
 
	}
 

	
 
	/* Try to reverse the vehicle, but do not care if it fails as the new type might not be reversible */
 
	if (new_veh->type == VEH_TRAIN && HasBit(((Train *)old_veh)->flags, VRF_REVERSE_DIRECTION)) {
 
	if (new_veh->type == VEH_TRAIN && HasBit(Train::From(old_veh)->flags, VRF_REVERSE_DIRECTION)) {
 
		DoCommand(0, new_veh->index, true, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
 
	}
 

	
 
	return cost;
 
}
 

	
 
/** Issue a start/stop command
 
 * @param v a vehicle
 
 * @param evaluate_callback shall the start/stop callback be evaluated?
 
 * @return success or error
 
 */
 
static inline CommandCost StartStopVehicle(const Vehicle *v, bool evaluate_callback)
 
@@ -394,54 +394,54 @@ static CommandCost ReplaceFreeUnit(Vehic
 
 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
 
 * @return cost or error
 
 */
 
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
 
{
 
	Vehicle *old_head = *chain;
 
	assert(old_head->IsPrimaryVehicle());
 

	
 
	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
 

	
 
	if (old_head->type == VEH_TRAIN) {
 
		/* Store the length of the old vehicle chain, rounded up to whole tiles */
 
		uint16 old_total_length = (((Train *)old_head)->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE * TILE_SIZE;
 
		uint16 old_total_length = (Train::From(old_head)->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE * TILE_SIZE;
 

	
 
		int num_units = 0; ///< Number of units in the chain
 
		for (Train *w = (Train *)old_head; w != NULL; w = GetNextUnit(w)) num_units++;
 
		for (Train *w = Train::From(old_head); w != NULL; w = GetNextUnit(w)) num_units++;
 

	
 
		Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
 
		Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
 
		Money *new_costs = MallocT<Money>(num_units);   ///< Costs for buying and refitting the new vehicles
 

	
 
		/* Collect vehicles and build replacements
 
		 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
 
		int i;
 
		Train *w;
 
		for (w = (Train *)old_head, i = 0; w != NULL; w = GetNextUnit(w), i++) {
 
		for (w = Train::From(old_head), i = 0; w != NULL; w = GetNextUnit(w), i++) {
 
			assert(i < num_units);
 
			old_vehs[i] = w;
 

	
 
			CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
 
			cost.AddCost(ret);
 
			if (cost.Failed()) break;
 

	
 
			new_costs[i] = ret.GetCost();
 
			if (new_vehs[i] != NULL) *nothing_to_do = false;
 
		}
 
		Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);
 

	
 
		/* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
 
		if (cost.Succeeded()) {
 
			/* Separate the head, so we can start constructing the new chain */
 
			Train *second = GetNextUnit((Train *)old_head);
 
			Train *second = GetNextUnit(Train::From(old_head));
 
			if (second != NULL) cost.AddCost(MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));
 

	
 
			assert(GetNextUnit(new_head) == NULL);
 

	
 
			/* Append engines to the new chain
 
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
 
			 * OTOH the vehicle attach callback is more expensive this way :s */
 
			Train *last_engine = NULL; ///< Shall store the last engine unit after this step
 
			if (cost.Succeeded()) {
 
				for (int i = num_units - 1; i > 0; i--) {
 
					Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);
 

	
 
@@ -529,28 +529,28 @@ static CommandCost ReplaceChain(Vehicle 
 
					if ((flags & DC_EXEC) != 0) {
 
						old_vehs[i] = NULL;
 
						if (i == 0) old_head = NULL;
 
					}
 
				}
 
			}
 

	
 
			/* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
 
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
 
			 * Note: The vehicle attach callback is disabled here :) */
 
			if ((flags & DC_EXEC) == 0) {
 
				/* Separate the head, so we can reattach the old vehicles */
 
				Train *second = GetNextUnit((Train *)old_head);
 
				Train *second = GetNextUnit(Train::From(old_head));
 
				if (second != NULL) MoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);
 

	
 
				assert(GetNextUnit((Train *)old_head) == NULL);
 
				assert(GetNextUnit(Train::From(old_head)) == NULL);
 

	
 
				for (int i = num_units - 1; i > 0; i--) {
 
					CommandCost ret = MoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
 
					assert(ret.Succeeded());
 
				}
 
			}
 
		}
 

	
 
		/* Finally undo buying of new vehicles */
 
		if ((flags & DC_EXEC) == 0) {
 
			for (int i = num_units - 1; i >= 0; i--) {
 
				if (new_vehs[i] != NULL) {
 
@@ -623,25 +623,25 @@ CommandCost CmdAutoreplaceVehicle(TileIn
 
	} else {
 
		if (!v->IsPrimaryVehicle()) return CMD_ERROR;
 
	}
 

	
 
	const Company *c = Company::Get(_current_company);
 
	bool wagon_removal = c->settings.renew_keep_length;
 

	
 
	/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
 
	Vehicle *w = v;
 
	bool any_replacements = false;
 
	while (w != NULL && !any_replacements) {
 
		any_replacements = (GetNewEngineType(w, c) != INVALID_ENGINE);
 
		w = (!free_wagon && w->type == VEH_TRAIN ? GetNextUnit((Train *)w) : NULL);
 
		w = (!free_wagon && w->type == VEH_TRAIN ? GetNextUnit(Train::From(w)) : NULL);
 
	}
 

	
 
	if (any_replacements) {
 
		bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);
 

	
 
		/* Stop the vehicle */
 
		if (!was_stopped) cost.AddCost(StartStopVehicle(v, true));
 
		if (cost.Failed()) return cost;
 

	
 
		assert(v->IsStoppedInDepot());
 

	
 
		/* We have to construct the new vehicle chain to test whether it is valid.
src/depot_gui.cpp
Show inline comments
 
@@ -263,25 +263,25 @@ struct DepotWindow : Window {
 
	 */
 
	void DrawVehicleInDepot(Window *w, const Vehicle *v, int x, int y)
 
	{
 
		byte diff_x = 0, diff_y = 0;
 

	
 
		int sprite_y = y + this->resize.step_height - GetVehicleListHeight(v->type);
 

	
 
		switch (v->type) {
 
			case VEH_TRAIN:
 
				DrawTrainImage(v, x + 21, sprite_y, this->sel, this->hscroll.cap + 4, this->hscroll.pos);
 

	
 
				/* Number of wagons relative to a standard length wagon (rounded up) */
 
				SetDParam(0, (((const Train *)v)->tcache.cached_total_length + 7) / 8);
 
				SetDParam(0, (Train::From(v)->tcache.cached_total_length + 7) / 8);
 
				DrawString(this->widget[DEPOT_WIDGET_MATRIX].left, this->widget[DEPOT_WIDGET_MATRIX].right - 1, y + 4, STR_TINY_BLACK, TC_FROMSTRING, SA_RIGHT); // Draw the counter
 
				break;
 

	
 
			case VEH_ROAD:     DrawRoadVehImage( v, x + 24, sprite_y, this->sel, 1); break;
 
			case VEH_SHIP:     DrawShipImage(    v, x + 19, sprite_y - 1, this->sel); break;
 
			case VEH_AIRCRAFT: {
 
				const Sprite *spr = GetSprite(v->GetImage(DIR_W), ST_NORMAL);
 
				DrawAircraftImage(v, x + 12,
 
									y + max(spr->height + spr->y_offs - 14, 0), // tall sprites needs an y offset
 
									this->sel);
 
			} break;
 
			default: NOT_REACHED();
 
@@ -319,25 +319,25 @@ struct DepotWindow : Window {
 
			DEPOT_WIDGET_SELL_CHAIN,
 
			DEPOT_WIDGET_SELL_ALL,
 
			DEPOT_WIDGET_BUILD,
 
			DEPOT_WIDGET_CLONE,
 
			DEPOT_WIDGET_AUTOREPLACE,
 
			WIDGET_LIST_END);
 

	
 
		/* determine amount of items for scroller */
 
		if (this->type == VEH_TRAIN) {
 
			hnum = 8;
 
			for (uint num = 0; num < this->vehicle_list.Length(); num++) {
 
				const Vehicle *v = this->vehicle_list[num];
 
				hnum = max(hnum, ((const Train *)v)->tcache.cached_total_length);
 
				hnum = max(hnum, Train::From(v)->tcache.cached_total_length);
 
			}
 
			/* Always have 1 empty row, so people can change the setting of the train */
 
			SetVScrollCount(w, this->vehicle_list.Length() + this->wagon_list.Length() + 1);
 
			SetHScrollCount(w, WagonLengthToPixels(hnum));
 
		} else {
 
			SetVScrollCount(w, (this->vehicle_list.Length() + this->hscroll.cap - 1) / this->hscroll.cap);
 
		}
 

	
 
		/* locate the depot struct */
 
		if (this->type == VEH_AIRCRAFT) {
 
			SetDParam(0, GetStationIndex(tile)); // Airport name
 
		} else {
 
@@ -441,25 +441,25 @@ struct DepotWindow : Window {
 
				d->head = d->wagon = v;
 

	
 
				/* either pressed the flag or the number, but only when it's a loco */
 
				if (x < 0 && IsFrontEngine(v)) return (x >= -10) ? MODE_START_STOP : MODE_SHOW_VEHICLE;
 

	
 
				skip = (skip * 8) / _traininfo_vehicle_width;
 
				x = (x * 8) / _traininfo_vehicle_width;
 

	
 
				/* Skip vehicles that are scrolled off the list */
 
				x += skip;
 

	
 
				/* find the vehicle in this row that was clicked */
 
				while (v != NULL && (x -= ((const Train *)v)->tcache.cached_veh_length) >= 0) v = v->Next();
 
				while (v != NULL && (x -= Train::From(v)->tcache.cached_veh_length) >= 0) v = v->Next();
 

	
 
				/* if an articulated part was selected, find its parent */
 
				while (v != NULL && IsArticulatedPart(v)) v = v->Previous();
 

	
 
				d->wagon = v;
 

	
 
				return MODE_DRAG_VEHICLE;
 
				}
 
				break;
 

	
 
			case VEH_ROAD:
 
				if (xm >= 24) return MODE_DRAG_VEHICLE;
 
@@ -505,29 +505,29 @@ struct DepotWindow : Window {
 
				if (this->type == VEH_TRAIN && sel != INVALID_VEHICLE) {
 
					this->sel = INVALID_VEHICLE;
 
					TrainDepotMoveVehicle(v, sel, gdvp.head);
 
				} else if (v != NULL) {
 
					int image = v->GetImage(DIR_W);
 

	
 
					this->sel = v->index;
 
					this->SetDirty();
 
					SetObjectToPlaceWnd(image, GetVehiclePalette(v), HT_DRAG, this);
 

	
 
					switch (v->type) {
 
						case VEH_TRAIN:
 
							_cursor.short_vehicle_offset = 16 - ((const Train *)v)->tcache.cached_veh_length * 2;
 
							_cursor.short_vehicle_offset = 16 - Train::From(v)->tcache.cached_veh_length * 2;
 
							break;
 

	
 
						case VEH_ROAD:
 
							_cursor.short_vehicle_offset = 16 - ((const RoadVehicle *)v)->rcache.cached_veh_length * 2;
 
							_cursor.short_vehicle_offset = 16 - RoadVehicle::From(v)->rcache.cached_veh_length * 2;
 
							break;
 

	
 
						default:
 
							_cursor.short_vehicle_offset = 0;
 
							break;
 
					}
 
					_cursor.vehchain = _ctrl_pressed;
 
				}
 
			} break;
 

	
 
			case MODE_SHOW_VEHICLE: // show info window
 
				ShowVehicleViewWindow(v);
src/disaster_cmd.cpp
Show inline comments
 
@@ -304,27 +304,26 @@ static bool DisasterTick_Ufo(DisasterVeh
 
		FOR_ALL_ROADVEHICLES(u) {
 
			if (IsRoadVehFront(u)) {
 
				v->dest_tile = u->index;
 
				v->age = 0;
 
				return true;
 
			}
 
		}
 

	
 
		delete v;
 
		return false;
 
	} else {
 
		/* Target a vehicle */
 
		Vehicle *u_tmp = Vehicle::Get(v->dest_tile);
 
		assert(u_tmp != NULL && u_tmp->type == VEH_ROAD && IsRoadVehFront(u_tmp));
 
		RoadVehicle *u = (RoadVehicle *)u_tmp;
 
		RoadVehicle *u = RoadVehicle::Get(v->dest_tile);
 
		assert(u != NULL && u->type == VEH_ROAD && IsRoadVehFront(u));
 

	
 
		uint dist = Delta(v->x_pos, u->x_pos) + Delta(v->y_pos, u->y_pos);
 

	
 
		if (dist < TILE_SIZE && !(u->vehstatus & VS_HIDDEN) && u->breakdown_ctr == 0) {
 
			u->breakdown_ctr = 3;
 
			u->breakdown_delay = 140;
 
		}
 

	
 
		v->direction = GetDirectionTowards(v, u->x_pos, u->y_pos);
 
		GetNewVehiclePosResult gp = GetNewVehiclePos(v);
 

	
 
		byte z = v->z_pos;
src/economy.cpp
Show inline comments
 
@@ -1305,25 +1305,25 @@ static void LoadUnloadVehicle(Vehicle *v
 
				ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
 
			}
 

	
 
			continue;
 
		}
 

	
 
		/* Do not pick up goods when we have no-load set. */
 
		if (u->current_order.GetLoadType() & OLFB_NO_LOAD) continue;
 

	
 
		/* update stats */
 
		int t;
 
		switch (u->type) {
 
			case VEH_TRAIN: t = ((Train *)u)->tcache.cached_max_speed; break;
 
			case VEH_TRAIN: t = Train::From(u)->tcache.cached_max_speed; break;
 
			case VEH_ROAD:  t = u->max_speed / 2;           break;
 
			default:        t = u->max_speed;               break;
 
		}
 

	
 
		/* if last speed is 0, we treat that as if no vehicle has ever visited the station. */
 
		ge->last_speed = min(t, 255);
 
		ge->last_age = _cur_year - u->build_year;
 
		ge->days_since_pickup = 0;
 

	
 
		/* If there's goods waiting at the station, and the vehicle
 
		 * has capacity for it, load it on the vehicle. */
 
		int cap_left = v->cargo_cap - v->cargo.Count();
 
@@ -1414,25 +1414,25 @@ static void LoadUnloadVehicle(Vehicle *v
 
				}
 
			} else if (cargo_not_full != 0) {
 
				finished_loading = false;
 
			}
 
		}
 
		unloading_time = 20;
 

	
 
		SB(v->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading);
 
	}
 

	
 
	if (v->type == VEH_TRAIN) {
 
		/* Each platform tile is worth 2 rail vehicles. */
 
		int overhang = ((Train *)v)->tcache.cached_total_length - st->GetPlatformLength(v->tile) * TILE_SIZE;
 
		int overhang = Train::From(v)->tcache.cached_total_length - st->GetPlatformLength(v->tile) * TILE_SIZE;
 
		if (overhang > 0) {
 
			unloading_time <<= 1;
 
			unloading_time += (overhang * unloading_time) / 8;
 
		}
 
	}
 

	
 
	/* Calculate the loading indicator fill percent and display
 
	 * In the Game Menu do not display indicators
 
	 * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 )
 
	 * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0
 
	 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything
 
	 */
src/newgrf_engine.cpp
Show inline comments
 
@@ -425,27 +425,27 @@ static void VehicleSetTriggers(const Res
 
	if (v != NULL) v->waiting_triggers = triggers;
 
}
 

	
 

	
 
static uint8 LiveryHelper(EngineID engine, const Vehicle *v)
 
{
 
	const Livery *l;
 

	
 
	if (v == NULL) {
 
		if (!Company::IsValidID(_current_company)) return 0;
 
		l = GetEngineLivery(engine, _current_company, INVALID_ENGINE, NULL);
 
	} else if (v->type == VEH_TRAIN) {
 
		l = GetEngineLivery(v->engine_type, v->owner, ((const Train *)v)->tcache.first_engine, v);
 
		l = GetEngineLivery(v->engine_type, v->owner, Train::From(v)->tcache.first_engine, v);
 
	} else if (v->type == VEH_ROAD) {
 
		l = GetEngineLivery(v->engine_type, v->owner, ((const RoadVehicle *)v)->rcache.first_engine, v);
 
		l = GetEngineLivery(v->engine_type, v->owner, RoadVehicle::From(v)->rcache.first_engine, v);
 
	} else {
 
		l = GetEngineLivery(v->engine_type, v->owner, INVALID_ENGINE, v);
 
	}
 

	
 
	return l->colour1 + l->colour2 * 16;
 
}
 

	
 
/**
 
 * Helper to get the position of a vehicle within a chain of vehicles.
 
 * @param v the vehicle to get the position of.
 
 * @param consecutive whether to look at the whole chain or the vehicles
 
 *                    with the same 'engine type'.
 
@@ -525,25 +525,25 @@ static uint32 VehicleGetVariable(const R
 
				byte cargo_classes = 0;
 
				uint8 common_cargos[NUM_CARGO];
 
				uint8 common_subtypes[256];
 
				byte user_def_data = 0;
 
				CargoID common_cargo_type = CT_INVALID;
 
				uint8 common_subtype = 0xFF; // Return 0xFF if nothing is carried
 

	
 
				/* Reset our arrays */
 
				memset(common_cargos, 0, sizeof(common_cargos));
 
				memset(common_subtypes, 0, sizeof(common_subtypes));
 

	
 
				for (u = v; u != NULL; u = u->Next()) {
 
					if (v->type == VEH_TRAIN) user_def_data |= ((const Train *)u)->tcache.user_def_data;
 
					if (v->type == VEH_TRAIN) user_def_data |= Train::From(u)->tcache.user_def_data;
 

	
 
					/* Skip empty engines */
 
					if (u->cargo_cap == 0) continue;
 

	
 
					cargo_classes |= GetCargo(u->cargo_type)->classes;
 
					common_cargos[u->cargo_type]++;
 
				}
 

	
 
				/* Pick the most common cargo type */
 
				uint common_cargo_best_amount = 0;
 
				for (CargoID cargo = 0; cargo < NUM_CARGO; cargo++) {
 
					if (common_cargos[cargo] > common_cargo_best_amount) {
 
@@ -581,25 +581,25 @@ static uint32 VehicleGetVariable(const R
 
				SetBit(v->vcache.cache_valid, 3);
 
			}
 
			return v->vcache.cached_var43;
 

	
 
		case 0x44: // Aircraft information
 
			if (v->type != VEH_AIRCRAFT) return UINT_MAX;
 

	
 
			{
 
				const Vehicle *w = v->Next();
 
				uint16 altitude = v->z_pos - w->z_pos; // Aircraft height - shadow height
 
				byte airporttype = ATP_TTDP_LARGE;
 

	
 
				const Station *st = GetTargetAirportIfValid((Aircraft *)v);
 
				const Station *st = GetTargetAirportIfValid(Aircraft::From(v));
 

	
 
				if (st != NULL) {
 
					switch (st->airport_type) {
 
						/* Note, Helidepot and Helistation are treated as small airports
 
						 * as they are at ground level. */
 
						case AT_HELIDEPOT:
 
						case AT_HELISTATION:
 
						case AT_COMMUTER:
 
						case AT_SMALL:         airporttype = ATP_TTDP_SMALL; break;
 
						case AT_METROPOLITAN:
 
						case AT_INTERNATIONAL:
 
						case AT_INTERCON:
 
@@ -659,25 +659,25 @@ static uint32 VehicleGetVariable(const R
 
				uint count = 0;
 
				for (; v != NULL; v = v->Next()) {
 
					if (Engine::Get(v->engine_type)->internal_id == parameter) count++;
 
				}
 
				return count;
 
			}
 

	
 
		case 0xFE:
 
		case 0xFF: {
 
			uint16 modflags = 0;
 

	
 
			if (v->type == VEH_TRAIN) {
 
				const Train *t = (const Train *)v;
 
				const Train *t = Train::From(v);
 
				const Train *u = IsTrainWagon(v) && HasBit(v->vehicle_flags, VRF_POWEREDWAGON) ? t->First() : t;
 
				RailType railtype = GetRailType(v->tile);
 
				bool powered = IsTrainEngine(v) || (IsTrainWagon(v) && HasBit(v->vehicle_flags, VRF_POWEREDWAGON));
 
				bool has_power = powered && HasPowerOnRail(u->railtype, railtype);
 
				bool is_electric = powered && u->railtype == RAILTYPE_ELECTRIC;
 

	
 
				if (has_power) SetBit(modflags, 5);
 
				if (is_electric && !has_power) SetBit(modflags, 6);
 
				if (HasBit(t->flags, VRF_TOGGLE_REVERSE)) SetBit(modflags, 8);
 
			}
 
			if (HasBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE)) SetBit(modflags, 10);
 

	
 
@@ -727,25 +727,25 @@ static uint32 VehicleGetVariable(const R
 
		case 0x3E: return v->cargo.Source();
 
		case 0x3F: return v->cargo.DaysInTransit();
 
		case 0x40: return v->age;
 
		case 0x41: return GB(v->age, 8, 8);
 
		case 0x42: return v->max_age;
 
		case 0x43: return GB(v->max_age, 8, 8);
 
		case 0x44: return Clamp(v->build_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
 
		case 0x45: return v->unitnumber;
 
		case 0x46: return Engine::Get(v->engine_type)->internal_id;
 
		case 0x47: return GB(Engine::Get(v->engine_type)->internal_id, 8, 8);
 
		case 0x48:
 
			if (v->type != VEH_TRAIN || v->spritenum != 0xFD) return v->spritenum;
 
			return HasBit(((Train *)v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
 
			return HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION) ? 0xFE : 0xFD;
 

	
 
		case 0x49: return v->day_counter;
 
		case 0x4A: return v->breakdowns_since_last_service;
 
		case 0x4B: return v->breakdown_ctr;
 
		case 0x4C: return v->breakdown_delay;
 
		case 0x4D: return v->breakdown_chance;
 
		case 0x4E: return v->reliability;
 
		case 0x4F: return GB(v->reliability, 8, 8);
 
		case 0x50: return v->reliability_spd_dec;
 
		case 0x51: return GB(v->reliability_spd_dec, 8, 8);
 
		case 0x52: return ClampToI32(v->GetDisplayProfitThisYear());
 
		case 0x53: return GB(ClampToI32(v->GetDisplayProfitThisYear()),  8, 24);
 
@@ -759,54 +759,54 @@ static uint32 VehicleGetVariable(const R
 
		case 0x5C: return ClampToI32(v->value);
 
		case 0x5D: return GB(ClampToI32(v->value),  8, 24);
 
		case 0x5E: return GB(ClampToI32(v->value), 16, 16);
 
		case 0x5F: return GB(ClampToI32(v->value), 24,  8);
 
		case 0x72: return v->cargo_subtype;
 
		case 0x7A: return v->random_bits;
 
		case 0x7B: return v->waiting_triggers;
 
	}
 

	
 
	/* Vehicle specific properties */
 
	switch (v->type) {
 
		case VEH_TRAIN: {
 
			Train *t = (Train *)v;
 
			Train *t = Train::From(v);
 
			switch (variable - 0x80) {
 
				case 0x62: return t->track;
 
				case 0x66: return t->railtype;
 
				case 0x73: return t->tcache.cached_veh_length;
 
				case 0x74: return t->tcache.cached_power;
 
				case 0x75: return GB(t->tcache.cached_power,  8, 24);
 
				case 0x76: return GB(t->tcache.cached_power, 16, 16);
 
				case 0x77: return GB(t->tcache.cached_power, 24,  8);
 
				case 0x7C: return t->First()->index;
 
				case 0x7D: return GB(t->First()->index, 8, 8);
 
				case 0x7F: return 0; // Used for vehicle reversing hack in TTDP
 
			}
 
		} break;
 

	
 
		case VEH_ROAD: {
 
			RoadVehicle *rv = (RoadVehicle *)v;
 
			RoadVehicle *rv = RoadVehicle::From(v);
 
			switch (variable - 0x80) {
 
				case 0x62: return rv->state;
 
				case 0x64: return rv->blocked_ctr;
 
				case 0x65: return GB(rv->blocked_ctr, 8, 8);
 
				case 0x66: return rv->overtaking;
 
				case 0x67: return rv->overtaking_ctr;
 
				case 0x68: return rv->crashed_ctr;
 
				case 0x69: return GB(rv->crashed_ctr, 8, 8);
 
			}
 
		} break;
 

	
 
		case VEH_AIRCRAFT: {
 
			Aircraft *a = (Aircraft *)v;
 
			Aircraft *a = Aircraft::From(v);
 
			switch (variable - 0x80) {
 
				case 0x62: return MapAircraftMovementState(a);  // Current movement state
 
				case 0x63: return a->targetairport;             // Airport to which the action refers
 
				case 0x66: return MapAircraftMovementAction(a); // Current movement action
 
			}
 
		} break;
 

	
 
		default: break;
 
	}
 

	
 
	DEBUG(grf, 1, "Unhandled vehicle property 0x%X, type 0x%X", variable, (uint)v->type);
 

	
 
@@ -877,28 +877,28 @@ static const SpriteGroup *GetVehicleSpri
 
	const SpriteGroup *group;
 
	CargoID cargo;
 

	
 
	if (v == NULL) {
 
		cargo = CT_PURCHASE;
 
	} else {
 
		cargo = v->cargo_type;
 

	
 
		if (v->type == VEH_TRAIN) {
 
			/* We always use cached value, except for callbacks because the override spriteset
 
			 * to use may be different than the one cached. It happens for callback 0x15 (refit engine),
 
			 * as v->cargo_type is temporary changed to the new type */
 
			group = use_cache ? ((const Train *)v)->tcache.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, ((const Train *)v)->tcache.first_engine);
 
			group = use_cache ? Train::From(v)->tcache.cached_override : GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, Train::From(v)->tcache.first_engine);
 
			if (group != NULL) return group;
 
		} else if (v->type == VEH_ROAD) {
 
			group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, ((const RoadVehicle *)v)->rcache.first_engine);
 
			group = GetWagonOverrideSpriteSet(v->engine_type, v->cargo_type, RoadVehicle::From(v)->rcache.first_engine);
 
			if (group != NULL) return group;
 
		}
 
	}
 

	
 
	const Engine *e = Engine::Get(engine);
 

	
 
	assert(cargo < lengthof(e->group));
 
	group = e->group[cargo];
 
	if (group != NULL) return group;
 

	
 
	/* Fall back to the default set if the selected cargo type is not defined */
 
	return e->group[CT_DEFAULT];
 
@@ -943,25 +943,25 @@ SpriteID GetRotorOverrideSprite(EngineID
 
	return group->GetResult() + (info_view ? 0 : (v->Next()->Next()->state % group->GetNumResults()));
 
}
 

	
 

	
 
/**
 
 * Check if a wagon is currently using a wagon override
 
 * @param v The wagon to check
 
 * @return true if it is using an override, false otherwise
 
 */
 
bool UsesWagonOverride(const Vehicle *v)
 
{
 
	assert(v->type == VEH_TRAIN);
 
	return ((const Train *)v)->tcache.cached_override != NULL;
 
	return Train::From(v)->tcache.cached_override != NULL;
 
}
 

	
 
/**
 
 * Evaluate a newgrf callback for vehicles
 
 * @param callback The callback to evalute
 
 * @param param1   First parameter of the callback
 
 * @param param2   Second parameter of the callback
 
 * @param engine   Engine type of the vehicle to evaluate the callback for
 
 * @param v        The vehicle to evaluate the callback for, or NULL if it doesnt exist yet
 
 * @return The value the callback returned, or CALLBACK_FAILED if it failed
 
 */
 
uint16 GetVehicleCallback(CallbackID callback, uint32 param1, uint32 param2, EngineID engine, const Vehicle *v)
src/npf.cpp
Show inline comments
 
@@ -416,25 +416,25 @@ static int32 NPFRailPathCost(AyStar *as,
 
/* Will find any depot */
 
static int32 NPFFindDepot(AyStar *as, OpenListNode *current)
 
{
 
	/* 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 */
 
	return IsDepotTypeTile(current->path.node.tile, (TransportType)as->user_data[NPF_TYPE]) ?
 
		AYSTAR_FOUND_END_NODE : AYSTAR_DONE;
 
}
 

	
 
/** Find any safe and free tile. */
 
static int32 NPFFindSafeTile(AyStar *as, OpenListNode *current)
 
{
 
	const Train *v = (const Train *)((NPFFindStationOrTileData*)as->user_target)->v;
 
	const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
 

	
 
	return
 
		IsSafeWaitingPosition(v, current->path.node.tile, current->path.node.direction, true, _settings_game.pf.forbid_90_deg) &&
 
		IsWaitingPositionFree(v, current->path.node.tile, current->path.node.direction, _settings_game.pf.forbid_90_deg) ?
 
			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;
 
	AyStarNode *node = &current->path.node;
 
@@ -497,25 +497,25 @@ static void ClearPathReservation(const P
 
 */
 
static void NPFSaveTargetData(AyStar *as, OpenListNode *current)
 
{
 
	NPFFoundTargetData *ftd = (NPFFoundTargetData*)as->user_path;
 
	ftd->best_trackdir = (Trackdir)current->path.node.user_data[NPF_TRACKDIR_CHOICE];
 
	ftd->best_path_dist = current->g;
 
	ftd->best_bird_dist = 0;
 
	ftd->node = current->path.node;
 
	ftd->res_okay = false;
 

	
 
	if (as->user_target != NULL && ((NPFFindStationOrTileData*)as->user_target)->reserve_path && as->user_data[NPF_TYPE] == TRANSPORT_RAIL) {
 
		/* Path reservation is requested. */
 
		const Train *v = (const Train *)((NPFFindStationOrTileData*)as->user_target)->v;
 
		const Train *v = Train::From(((NPFFindStationOrTileData *)as->user_target)->v);
 

	
 
		const PathNode *target = FindSafePosition(&current->path, v);
 
		ftd->node = target->node;
 

	
 
		/* If the target is a station skip to platform end. */
 
		if (IsRailwayStationTile(target->node.tile)) {
 
			DiagDirection dir = TrackdirToExitdir(target->node.direction);
 
			uint len = GetStationByTile(target->node.tile)->GetPlatformLength(target->node.tile, dir);
 
			TileIndex end_tile = TILE_ADD(target->node.tile, (len - 1) * TileOffsByDiagDir(dir));
 

	
 
			/* Update only end tile, trackdir of a station stays the same. */
 
			ftd->node.tile = end_tile;
src/openttd.cpp
Show inline comments
 
@@ -1110,57 +1110,57 @@ void StateGameLoop()
 
		ClearStorageChanges(true);
 

	
 
		CallWindowTickEvent();
 
		NewsLoop();
 
	} else {
 
		if (_debug_desync_level > 1) {
 
			Vehicle *v;
 
			FOR_ALL_VEHICLES(v) {
 
				if (v != v->First()) continue;
 

	
 
				switch (v->type) {
 
					case VEH_ROAD: {
 
						RoadVehicle *rv = (RoadVehicle *)v;
 
						RoadVehicle *rv = RoadVehicle::From(v);
 
						RoadVehicleCache cache = rv->rcache;
 
						RoadVehUpdateCache(rv);
 

	
 
						if (memcmp(&cache, &rv->rcache, sizeof(RoadVehicleCache)) != 0) {
 
							DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
 
						}
 
					} break;
 

	
 
					case VEH_TRAIN: {
 
						uint length = 0;
 
						Train *t = (Train *)v;
 
						Train *t = Train::From(v);
 
						for (Vehicle *u = t; u != NULL; u = u->Next()) length++;
 

	
 
						TrainCache *wagons = MallocT<TrainCache>(length);
 
						length = 0;
 
						for (Train *u = t; u != NULL; u = u->Next()) wagons[length++] = u->tcache;
 

	
 
						TrainConsistChanged(t, true);
 

	
 
						length = 0;
 
						for (Train *u = t; u != NULL; u = u->Next()) {
 
							if (memcmp(&wagons[length], &u->tcache, sizeof(TrainCache)) != 0) {
 
								DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
 
							}
 
							length++;
 
						}
 

	
 
						free(wagons);
 
					} break;
 

	
 
					case VEH_AIRCRAFT: {
 
						Aircraft *a = (Aircraft *)v;
 
						Aircraft *a = Aircraft::From(v);
 
						AircraftCache cache = a->acache;
 
						UpdateAircraftCache(a);
 

	
 
						if (memcmp(&cache, &a->acache, sizeof(AircraftCache)) != 0) {
 
							DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
 
						}
 
					} break;
 

	
 
					default:
 
						break;
 
				}
 
			}
src/order_cmd.cpp
Show inline comments
 
@@ -12,24 +12,25 @@
 
#include "station_map.h"
 
#include "vehicle_base.h"
 
#include "strings_func.h"
 
#include "functions.h"
 
#include "window_func.h"
 
#include "newgrf_cargo.h"
 
#include "timetable.h"
 
#include "vehicle_func.h"
 
#include "depot_base.h"
 
#include "settings_type.h"
 
#include "core/pool_func.hpp"
 
#include "aircraft.h"
 
#include "roadveh.h"
 

	
 
#include "table/strings.h"
 

	
 
/* DestinationID must be at least as large as every these below, because it can
 
 * be any of them
 
 */
 
assert_compile(sizeof(DestinationID) >= sizeof(DepotID));
 
assert_compile(sizeof(DestinationID) >= sizeof(WaypointID));
 
assert_compile(sizeof(DestinationID) >= sizeof(StationID));
 

	
 
TileIndex _backup_orders_tile;
 
BackuppedOrders _backup_orders_data;
 
@@ -725,25 +726,25 @@ CommandCost CmdSkipToOrder(TileIndex til
 
	VehicleOrderID sel_ord = p2;
 

	
 
	Vehicle *v = Vehicle::GetIfValid(veh_id);
 

	
 
	if (v == NULL || !CheckOwnership(v->owner) || sel_ord == v->cur_order_index ||
 
			sel_ord >= v->GetNumOrders() || v->GetNumOrders() < 2) {
 
		return CMD_ERROR;
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		v->cur_order_index = sel_ord;
 

	
 
		if (v->type == VEH_ROAD) ClearSlot((RoadVehicle *)v);
 
		if (v->type == VEH_ROAD) ClearSlot(RoadVehicle::From(v));
 

	
 
		if (v->current_order.IsType(OT_LOADING)) v->LeaveStation();
 

	
 
		InvalidateVehicleOrder(v, 0);
 
	}
 

	
 
	/* We have an aircraft/ship, they have a mini-schedule, so update them all */
 
	if (v->type == VEH_AIRCRAFT) InvalidateWindowClasses(WC_AIRCRAFT_LIST);
 
	if (v->type == VEH_SHIP) InvalidateWindowClasses(WC_SHIPS_LIST);
 

	
 
	return CommandCost();
 
}
 
@@ -1351,25 +1352,25 @@ CommandCost CmdRestoreOrderIndex(TileInd
 
}
 

	
 

	
 
static TileIndex GetStationTileForVehicle(const Vehicle *v, const Station *st)
 
{
 
	if (!CanVehicleUseStation(v, st)) return INVALID_TILE;
 

	
 
	switch (v->type) {
 
		default: NOT_REACHED();
 
		case VEH_TRAIN:     return st->train_tile;
 
		case VEH_AIRCRAFT:  return st->airport_tile;
 
		case VEH_SHIP:      return st->dock_tile;
 
		case VEH_ROAD:      return st->GetPrimaryRoadStop((RoadVehicle *)v)->xy;
 
		case VEH_ROAD:      return st->GetPrimaryRoadStop(RoadVehicle::From(v))->xy;
 
	}
 
}
 

	
 

	
 
/**
 
 *
 
 * Check the orders of a vehicle, to see if there are invalid orders and stuff
 
 *
 
 */
 
void CheckOrders(const Vehicle *v)
 
{
 
	/* Does the user wants us to check things? */
 
@@ -1606,25 +1607,25 @@ bool UpdateOrderDest(Vehicle *v, const O
 
				TileIndex location;
 
				DestinationID destination;
 
				bool reverse;
 

	
 
				if (v->FindClosestDepot(&location, &destination, &reverse)) {
 
					v->dest_tile = location;
 
					v->current_order.MakeGoToDepot(destination, v->current_order.GetDepotOrderType(), v->current_order.GetNonStopType(), (OrderDepotActionFlags)(v->current_order.GetDepotActionType() & ~ODATFB_NEAREST_DEPOT), v->current_order.GetRefitCargo(), v->current_order.GetRefitSubtype());
 

	
 
					/* If there is no depot in front, reverse automatically (trains only) */
 
					if (v->type == VEH_TRAIN && reverse) DoCommand(v->tile, v->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
 

	
 
					if (v->type == VEH_AIRCRAFT) {
 
						Aircraft *a = (Aircraft *)v;
 
						Aircraft *a = Aircraft::From(v);
 
						if (a->state == FLYING && a->targetairport != destination) {
 
							/* The aircraft is now heading for a different hangar than the next in the orders */
 
							extern void AircraftNextAirportPos_and_Order(Aircraft *a);
 
							AircraftNextAirportPos_and_Order(a);
 
						}
 
					}
 
				} else {
 
					if (conditional_depth > v->GetNumOrders()) return false;
 

	
 
					UpdateVehicleTimetable(v, true);
 
					v->IncrementOrderIndex();
 

	
 
@@ -1725,31 +1726,31 @@ bool ProcessOrders(Vehicle *v)
 
	}
 

	
 
	/* Get the current order */
 
	if (v->cur_order_index >= v->GetNumOrders()) v->cur_order_index = 0;
 

	
 
	const Order *order = v->GetOrder(v->cur_order_index);
 

	
 
	/* If no order, do nothing. */
 
	if (order == NULL || (v->type == VEH_AIRCRAFT && order->IsType(OT_DUMMY) && !CheckForValidOrders(v))) {
 
		if (v->type == VEH_AIRCRAFT) {
 
			/* Aircraft do something vastly different here, so handle separately */
 
			extern void HandleMissingAircraftOrders(Aircraft *v);
 
			HandleMissingAircraftOrders((Aircraft *)v);
 
			HandleMissingAircraftOrders(Aircraft::From(v));
 
			return false;
 
		}
 

	
 
		v->current_order.Free();
 
		v->dest_tile = 0;
 
		if (v->type == VEH_ROAD) ClearSlot((RoadVehicle *)v);
 
		if (v->type == VEH_ROAD) ClearSlot(RoadVehicle::From(v));
 
		return false;
 
	}
 

	
 
	/* If it is unchanged, keep it. */
 
	if (order->Equals(v->current_order) && (v->type == VEH_AIRCRAFT || v->dest_tile != 0) &&
 
			(v->type != VEH_SHIP || !order->IsType(OT_GOTO_STATION) || Station::Get(order->GetDestination())->dock_tile != INVALID_TILE)) {
 
		return false;
 
	}
 

	
 
	/* Otherwise set it, and determine the destination tile. */
 
	v->current_order = *order;
 

	
src/pbs.cpp
Show inline comments
 
@@ -226,25 +226,25 @@ struct FindTrainOnTrackInfo {
 

	
 
	/** Init the best location to NULL always! */
 
	FindTrainOnTrackInfo() : best(NULL) {}
 
};
 

	
 
/** Callback for Has/FindVehicleOnPos to find a train on a specific track. */
 
static Vehicle *FindTrainOnTrackEnum(Vehicle *v, void *data)
 
{
 
	FindTrainOnTrackInfo *info = (FindTrainOnTrackInfo *)data;
 

	
 
	if (v->type != VEH_TRAIN || (v->vehstatus & VS_CRASHED)) return NULL;
 

	
 
	Train *t = (Train *)v;
 
	Train *t = Train::From(v);
 
	if (HasBit((TrackBits)t->track, TrackdirToTrack(info->res.trackdir))) {
 
		t = t->First();
 

	
 
		/* ALWAYS return the lowest ID (anti-desync!) */
 
		if (info->best == NULL || t->index < info->best->index) info->best = t;
 
		return t;
 
	}
 

	
 
	return NULL;
 
}
 

	
 
/**
src/rail_cmd.cpp
Show inline comments
 
@@ -83,25 +83,25 @@ const byte _track_sloped_sprites[14] = {
 
 *               01abcdef => rail w/ signals
 
 *               10uuuuuu => unused
 
 *               11uuuudd => rail depot
 
 */
 

	
 

	
 
Vehicle *EnsureNoTrainOnTrackProc(Vehicle *v, void *data)
 
{
 
	TrackBits rail_bits = *(TrackBits *)data;
 

	
 
	if (v->type != VEH_TRAIN) return NULL;
 

	
 
	Train *t = (Train *)v;
 
	Train *t = Train::From(v);
 
	if ((t->track != rail_bits) && !TracksOverlap(t->track | rail_bits)) return NULL;
 

	
 
	_error_message = VehicleInTheWayErrMsg(v);
 
	return v;
 
}
 

	
 
/**
 
 * Tests if a vehicle interacts with the specified track.
 
 * All track bits interact except parallel TRACK_BIT_HORZ or TRACK_BIT_VERT.
 
 *
 
 * @param tile The tile.
 
 * @param track The track.
 
@@ -1226,25 +1226,25 @@ CommandCost CmdRemoveSingleSignal(TileIn
 
CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit
 
}
 

	
 
/** Update power of train under which is the railtype being converted */
 
Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data)
 
{
 
	/* Similiar checks as in TrainPowerChanged() */
 

	
 
	if (v->type == VEH_TRAIN && !IsArticulatedPart(v)) {
 
		const RailVehicleInfo *rvi = RailVehInfo(v->engine_type);
 
		if (GetVehicleProperty(v, 0x0B, rvi->power) != 0) TrainPowerChanged((Train *)v->First());
 
		if (GetVehicleProperty(v, 0x0B, rvi->power) != 0) TrainPowerChanged(Train::From(v)->First());
 
	}
 

	
 
	return NULL;
 
}
 

	
 
/** Convert one rail type to the other. You can convert normal rail to
 
 * monorail/maglev easily or vice-versa.
 
 * @param tile end tile of rail conversion drag
 
 * @param flags operation to perform
 
 * @param p1 start tile of drag
 
 * @param p2 new railtype to convert to
 
 */
 
@@ -2452,25 +2452,25 @@ int TicksToLeaveDepot(const Train *v)
 
/** Tile callback routine when vehicle enters tile
 
 * @see vehicle_enter_tile_proc */
 
static VehicleEnterTileStatus VehicleEnter_Track(Vehicle *u, TileIndex tile, int x, int y)
 
{
 
	byte fract_coord;
 
	byte fract_coord_leave;
 
	DiagDirection dir;
 
	int length;
 

	
 
	/* this routine applies only to trains in depot tiles */
 
	if (u->type != VEH_TRAIN || !IsRailDepotTile(tile)) return VETSB_CONTINUE;
 

	
 
	Train *v = (Train *)u;
 
	Train *v = Train::From(u);
 

	
 
	/* depot direction */
 
	dir = GetRailDepotDirection(tile);
 

	
 
	/* calculate the point where the following wagon should be activated
 
	 * this depends on the length of the current vehicle */
 
	length = v->tcache.cached_veh_length;
 

	
 
	fract_coord_leave =
 
		((_fractcoords_enter[dir] & 0x0F) + // x
 
			(length + 1) * _deltacoord_leaveoffset[dir]) +
 
		(((_fractcoords_enter[dir] >> 4) +  // y
src/road_cmd.cpp
Show inline comments
 
@@ -1532,25 +1532,25 @@ static void GetTileDesc_Road(TileIndex t
 
 * vehicle should be travelling in in order to enter the depot.
 
 */
 
static const byte _roadveh_enter_depot_dir[4] = {
 
	TRACKDIR_X_SW, TRACKDIR_Y_NW, TRACKDIR_X_NE, TRACKDIR_Y_SE
 
};
 

	
 
static VehicleEnterTileStatus VehicleEnter_Road(Vehicle *v, TileIndex tile, int x, int y)
 
{
 
	switch (GetRoadTileType(tile)) {
 
		case ROAD_TILE_DEPOT: {
 
			if (v->type != VEH_ROAD) break;
 

	
 
			RoadVehicle *rv = (RoadVehicle *)v;
 
			RoadVehicle *rv = RoadVehicle::From(v);
 
			if (rv->frame == RVC_DEPOT_STOP_FRAME &&
 
					_roadveh_enter_depot_dir[GetRoadDepotDirection(tile)] == rv->state) {
 
				rv->state = RVSB_IN_DEPOT;
 
				rv->vehstatus |= VS_HIDDEN;
 
				rv->direction = ReverseDir(rv->direction);
 
				if (rv->Next() == NULL) VehicleEnterDepot(rv);
 
				rv->tile = tile;
 

	
 
				InvalidateWindowData(WC_VEHICLE_DEPOT, rv->tile);
 
				return VETSB_ENTERED_WORMHOLE;
 
			}
 
		} break;
src/roadveh_cmd.cpp
Show inline comments
 
@@ -753,25 +753,25 @@ static RoadVehicle *RoadVehFindCloseTo(R
 

	
 
	/* This code protects a roadvehicle from being blocked for ever
 
	 * If more than 1480 / 74 days a road vehicle is blocked, it will
 
	 * drive just through it. The ultimate backup-code of TTD.
 
	 * It can be disabled. */
 
	if (rvf.best_diff == UINT_MAX) {
 
		front->blocked_ctr = 0;
 
		return NULL;
 
	}
 

	
 
	if (++front->blocked_ctr > 1480) return NULL;
 

	
 
	return (RoadVehicle *)rvf.best;
 
	return RoadVehicle::From(rvf.best);
 
}
 

	
 
static void RoadVehArrivesAt(const RoadVehicle *v, Station *st)
 
{
 
	if (IsCargoInClass(v->cargo_type, CC_PASSENGERS)) {
 
		/* Check if station was ever visited before */
 
		if (!(st->had_vehicle_of_type & HVOT_BUS)) {
 
			st->had_vehicle_of_type |= HVOT_BUS;
 
			SetDParam(0, st->index);
 
			AddVehicleNewsItem(
 
				v->roadtype == ROADTYPE_ROAD ? STR_NEWS_FIRST_ROAD_BUS_ARRIVAL : STR_NEWS_FIRST_ROAD_PASSENGER_TRAM_ARRIVAL,
 
				(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
src/roadveh_gui.cpp
Show inline comments
 
@@ -121,25 +121,25 @@ static inline int RoadVehLengthToPixels(
 

	
 
void DrawRoadVehImage(const Vehicle *v, int x, int y, VehicleID selection, int count)
 
{
 
	/* Road vehicle lengths are measured in eighths of the standard length, so
 
	 * count is the number of standard vehicles that should be drawn. If it is
 
	 * 0, we draw enough vehicles for 10 standard vehicle lengths. */
 
	int max_length = (count == 0) ? 80 : count * 8;
 

	
 
	/* Width of highlight box */
 
	int highlight_w = 0;
 

	
 
	for (int dx = 0; v != NULL && dx < max_length ; v = v->Next()) {
 
		int width = ((const RoadVehicle *)v)->rcache.cached_veh_length;
 
		int width = RoadVehicle::From(v)->rcache.cached_veh_length;
 

	
 
		if (dx + width > 0 && dx <= max_length) {
 
			SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
 
			DrawSprite(v->GetImage(DIR_W), pal, x + 14 + RoadVehLengthToPixels(dx), y + 6);
 

	
 
			if (v->index == selection) {
 
				/* Set the highlight position */
 
				highlight_w = RoadVehLengthToPixels(width);
 
			} else if (_cursor.vehchain && highlight_w != 0) {
 
				highlight_w += RoadVehLengthToPixels(width);
 
			}
 
		}
src/saveload/afterload.cpp
Show inline comments
 
@@ -903,27 +903,27 @@ bool AfterLoadGame()
 
					default: NOT_REACHED();
 
					case DIAGDIR_NE: if ((v->x_pos & 0xF) !=  0)            continue; break;
 
					case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
 
					case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
 
					case DIAGDIR_NW: if ((v->y_pos & 0xF) !=  0)            continue; break;
 
				}
 
			} else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
 
				v->tile = GetNorthernBridgeEnd(v->tile);
 
			} else {
 
				continue;
 
			}
 
			if (v->type == VEH_TRAIN) {
 
				((Train *)v)->track = TRACK_BIT_WORMHOLE;
 
				Train::From(v)->track = TRACK_BIT_WORMHOLE;
 
			} else {
 
				((RoadVehicle *)v)->state = RVSB_WORMHOLE;
 
				RoadVehicle::From(v)->state = RVSB_WORMHOLE;
 
			}
 
		}
 
	}
 

	
 
	/* Elrails got added in rev 24 */
 
	if (CheckSavegameVersion(24)) {
 
		RailType min_rail = RAILTYPE_ELECTRIC;
 

	
 
		Train *v;
 
		FOR_ALL_TRAINS(v) {
 
			RailType rt = RailVehInfo(v->engine_type)->railtype;
 

	
src/saveload/oldloader_sl.cpp
Show inline comments
 
@@ -168,25 +168,25 @@ void FixOldVehicles()
 
			case 0xfd: break;
 
			case 0xff: v->spritenum = 0xfe; break;
 
			default:   v->spritenum >>= 1; break;
 
		}
 

	
 
		/* Vehicle-subtype is different in TTD(Patch) */
 
		if (v->type == VEH_EFFECT) v->subtype = v->subtype >> 1;
 

	
 
		v->name = CopyFromOldName(_old_vehicle_names[v->index]);
 

	
 
		/* We haven't used this bit for stations for ages */
 
		if (v->type == VEH_ROAD) {
 
			RoadVehicle *rv = (RoadVehicle *)v;
 
			RoadVehicle *rv = RoadVehicle::From(v);
 
			if (rv->state != RVSB_IN_DEPOT && rv->state != RVSB_WORMHOLE) {
 
				ClrBit(rv->state, RVS_IS_STOPPING);
 
			}
 
		}
 

	
 
		/* The subtype should be 0, but it sometimes isn't :( */
 
		if (v->type == VEH_ROAD || v->type == VEH_SHIP) v->subtype = 0;
 

	
 
		/* Sometimes primary vehicles would have a nothing (invalid) order
 
		 * or vehicles that could not have an order would still have a
 
		 * (loading) order which causes assertions and the like later on.
 
		 */
 
@@ -1307,25 +1307,25 @@ bool LoadOldVehicle(LoadgameState *ls, i
 
			}
 
			v->cur_image = sprite;
 

	
 
			switch (v->type) {
 
				case VEH_TRAIN: {
 
					static const byte spriteset_rail[] = {
 
						  0,   2,   4,   4,   8,  10,  12,  14,  16,  18,  20,  22,  40,  42,  44,  46,
 
						 48,  52,  54,  66,  68,  70,  72,  74,  76,  78,  80,  82,  84,  86, 120, 122,
 
						124, 126, 128, 130, 132, 134, 136, 138, 140
 
					};
 
					if (v->spritenum / 2 >= lengthof(spriteset_rail)) return false;
 
					v->spritenum = spriteset_rail[v->spritenum / 2]; // adjust railway sprite set offset
 
					((Train *)v)->railtype = type == 0x25 ? 1 : 0; // monorail / rail
 
					Train::From(v)->railtype = type == 0x25 ? 1 : 0; // monorail / rail
 
					break;
 
				}
 

	
 
				case VEH_ROAD:
 
					if (v->spritenum >= 22) v->spritenum += 12;
 
					break;
 

	
 
				case VEH_SHIP:
 
					v->spritenum += 2;
 

	
 
					switch (v->spritenum) {
 
						case 2: // oil tanker && cargo type != oil
src/saveload/vehicle_sl.cpp
Show inline comments
 
@@ -233,26 +233,26 @@ void AfterLoadVehicles(bool part_of_load
 
{
 
	Vehicle *v;
 

	
 
	FOR_ALL_VEHICLES(v) {
 
		/* Reinstate the previous pointer */
 
		if (v->Next() != NULL) v->Next()->previous = v;
 
		if (v->NextShared() != NULL) v->NextShared()->previous_shared = v;
 

	
 
		v->UpdateDeltaXY(v->direction);
 

	
 
		if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID;
 
		v->first = NULL;
 
		if (v->type == VEH_TRAIN) ((Train *)v)->tcache.first_engine = INVALID_ENGINE;
 
		if (v->type == VEH_ROAD)  ((RoadVehicle *)v)->rcache.first_engine = INVALID_ENGINE;
 
		if (v->type == VEH_TRAIN) Train::From(v)->tcache.first_engine = INVALID_ENGINE;
 
		if (v->type == VEH_ROAD)  RoadVehicle::From(v)->rcache.first_engine = INVALID_ENGINE;
 

	
 
		v->cargo.InvalidateCache();
 
	}
 

	
 
	/* AfterLoadVehicles may also be called in case of NewGRF reload, in this
 
	 * case we may not convert orders again. */
 
	if (part_of_load) {
 
		/* Create shared vehicle chain for very old games (pre 5,2) and create
 
		 * OrderList from shared vehicle chains. For this to work correctly, the
 
		 * following conditions must be fulfilled:
 
		 * a) both next_shared and previous_shared are not set for pre 5,2 games
 
		 * b) both next_shared and previous_shared are set for later games
 
@@ -299,76 +299,76 @@ void AfterLoadVehicles(bool part_of_load
 
			for (Vehicle *u = v; u != NULL; u = u->next_shared) {
 
				u->orders.list = v->orders.list;
 
			}
 
		}
 
	}
 

	
 
	CheckValidVehicles();
 

	
 
	FOR_ALL_VEHICLES(v) {
 
		assert(v->first != NULL);
 

	
 
		if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) {
 
			if (IsFrontEngine(v)) ((Train *)v)->tcache.last_speed = v->cur_speed; // update displayed train speed
 
			TrainConsistChanged((Train *)v, false);
 
			if (IsFrontEngine(v)) Train::From(v)->tcache.last_speed = v->cur_speed; // update displayed train speed
 
			TrainConsistChanged(Train::From(v), false);
 
		} else if (v->type == VEH_ROAD && IsRoadVehFront(v)) {
 
			RoadVehUpdateCache((RoadVehicle *)v);
 
			RoadVehUpdateCache(RoadVehicle::From(v));
 
		}
 
	}
 

	
 
	/* Stop non-front engines */
 
	if (CheckSavegameVersion(112)) {
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
 
				if (IsTrainEngine(v)) v->vehstatus |= VS_STOPPED;
 
				/* cur_speed is now relevant for non-front parts - nonzero breaks
 
				 * moving-wagons-inside-depot- and autoreplace- code */
 
				v->cur_speed = 0;
 
			}
 
			/* trains weren't stopping gradually in old OTTD versions (and TTO/TTD)
 
			 * other vehicle types didn't have zero speed while stopped (even in 'recent' OTTD versions) */
 
			if ((v->vehstatus & VS_STOPPED) && (v->type != VEH_TRAIN || CheckSavegameVersionOldStyle(2, 1))) {
 
				v->cur_speed = 0;
 
			}
 
		}
 
	}
 

	
 
	FOR_ALL_VEHICLES(v) {
 
		switch (v->type) {
 
			case VEH_ROAD: {
 
				RoadVehicle *rv = (RoadVehicle *)v;
 
				RoadVehicle *rv = RoadVehicle::From(v);
 
				rv->roadtype = HasBit(EngInfo(v->First()->engine_type)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
 
				rv->compatible_roadtypes = RoadTypeToRoadTypes(rv->roadtype);
 
			}
 
				/* FALL THROUGH */
 
			case VEH_TRAIN:
 
			case VEH_SHIP:
 
				v->cur_image = v->GetImage(v->direction);
 
				break;
 

	
 
			case VEH_AIRCRAFT:
 
				if (IsNormalAircraft(v)) {
 
					v->cur_image = v->GetImage(v->direction);
 

	
 
					/* The plane's shadow will have the same image as the plane */
 
					Vehicle *shadow = v->Next();
 
					shadow->cur_image = v->cur_image;
 

	
 
					/* In the case of a helicopter we will update the rotor sprites */
 
					if (v->subtype == AIR_HELICOPTER) {
 
						Vehicle *rotor = shadow->Next();
 
						rotor->cur_image = GetRotorImage((Aircraft *)v);
 
						rotor->cur_image = GetRotorImage(Aircraft::From(v));
 
					}
 

	
 
					UpdateAircraftCache((Aircraft *)v);
 
					UpdateAircraftCache(Aircraft::From(v));
 
				}
 
				break;
 
			default: break;
 
		}
 

	
 
		v->coord.left = INVALID_COORD;
 
		VehicleMove(v, false);
 
	}
 
}
 

	
 
static uint8  _cargo_days;
 
static uint16 _cargo_source;
src/signal.cpp
Show inline comments
 
@@ -175,25 +175,25 @@ public:
 
		return true;
 
	}
 
};
 

	
 
static SmallSet<Trackdir, SIG_TBU_SIZE> _tbuset("_tbuset");         ///< set of signals that will be updated
 
static SmallSet<DiagDirection, SIG_TBD_SIZE> _tbdset("_tbdset");    ///< set of open nodes in current signal block
 
static SmallSet<DiagDirection, SIG_GLOB_SIZE> _globset("_globset"); ///< set of places to be updated in following runs
 

	
 

	
 
/** Check whether there is a train on rail, not in a depot */
 
static Vehicle *TrainOnTileEnum(Vehicle *v, void *)
 
{
 
	if (v->type != VEH_TRAIN || ((Train *)v)->track == TRACK_BIT_DEPOT) return NULL;
 
	if (v->type != VEH_TRAIN || Train::From(v)->track == TRACK_BIT_DEPOT) return NULL;
 

	
 
	return v;
 
}
 

	
 

	
 
/**
 
 * Perform some operations before adding data into Todo set
 
 * The new and reverse direction is removed from _globset, because we are sure
 
 * it doesn't need to be checked again
 
 * Also, remove reverse direction from _tbdset
 
 * This is the 'core' part so the graph seaching won't enter any tile twice
 
 *
src/station_cmd.cpp
Show inline comments
 
@@ -1479,25 +1479,25 @@ CommandCost CmdBuildRoadStop(TileIndex t
 
		UpdateStationVirtCoordDirty(st);
 
		UpdateStationAcceptance(st, false);
 
		InvalidateWindowData(WC_SELECT_STATION, 0, 0);
 
		InvalidateWindowData(WC_STATION_LIST, st->owner, 0);
 
		InvalidateWindowWidget(WC_STATION_VIEW, st->index, SVW_ROADVEHS);
 
	}
 
	return cost;
 
}
 

	
 

	
 
static Vehicle *ClearRoadStopStatusEnum(Vehicle *v, void *)
 
{
 
	if (v->type == VEH_ROAD) ((RoadVehicle *)v)->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
 
	if (v->type == VEH_ROAD) RoadVehicle::From(v)->state &= RVSB_ROAD_STOP_TRACKDIR_MASK;
 

	
 
	return NULL;
 
}
 

	
 

	
 
/** Remove a bus station
 
 * @param st Station to remove
 
 * @param flags operation to perform
 
 * @param tile TileIndex been queried
 
 * @return cost or failure of operation
 
 */
 
static CommandCost RemoveRoadStop(Station *st, DoCommandFlag flags, TileIndex tile)
 
@@ -2608,25 +2608,25 @@ static bool ClickTile_Station(TileIndex 
 
}
 

	
 
static VehicleEnterTileStatus VehicleEnter_Station(Vehicle *v, TileIndex tile, int x, int y)
 
{
 
	StationID station_id = GetStationIndex(tile);
 

	
 
	if (v->type == VEH_TRAIN) {
 
		if (!v->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
 
		if (!IsRailwayStation(tile) || !IsFrontEngine(v)) return VETSB_CONTINUE;
 

	
 
		int station_ahead;
 
		int station_length;
 
		int stop = GetTrainStopLocation(station_id, tile, (Train *)v, &station_ahead, &station_length);
 
		int stop = GetTrainStopLocation(station_id, tile, Train::From(v), &station_ahead, &station_length);
 

	
 
		/* Stop whenever that amount of station ahead + the distance from the
 
		 * begin of the platform to the stop location is longer than the length
 
		 * of the platform. Station ahead 'includes' the current tile where the
 
		 * vehicle is on, so we need to substract that. */
 
		if (!IsInsideBS(stop + station_ahead, station_length, TILE_SIZE)) return VETSB_CONTINUE;
 

	
 
		DiagDirection dir = DirToDiagDir(v->direction);
 

	
 
		x &= 0xF;
 
		y &= 0xF;
 

	
 
@@ -2636,25 +2636,25 @@ static VehicleEnterTileStatus VehicleEnt
 
			stop &= TILE_SIZE - 1;
 

	
 
			if (x == stop) return VETSB_ENTERED_STATION | (VehicleEnterTileStatus)(station_id << VETS_STATION_ID_OFFSET); // enter station
 
			if (x < stop) {
 
				uint16 spd;
 

	
 
				v->vehstatus |= VS_TRAIN_SLOWING;
 
				spd = max(0, (stop - x) * 20 - 15);
 
				if (spd < v->cur_speed) v->cur_speed = spd;
 
			}
 
		}
 
	} else if (v->type == VEH_ROAD) {
 
		RoadVehicle *rv = (RoadVehicle *)v;
 
		RoadVehicle *rv = RoadVehicle::From(v);
 
		if (rv->state < RVSB_IN_ROAD_STOP && !IsReversingRoadTrackdir((Trackdir)rv->state) && rv->frame == 0) {
 
			if (IsRoadStop(tile) && IsRoadVehFront(v)) {
 
				/* Attempt to allocate a parking bay in a road stop */
 
				RoadStop *rs = GetRoadStopByTile(tile, GetRoadStopType(tile));
 

	
 
				if (IsDriveThroughStopTile(tile)) {
 
					if (!rv->current_order.ShouldStopAtStation(v, station_id)) return VETSB_CONTINUE;
 

	
 
					/* Vehicles entering a drive-through stop from the 'normal' side use first bay (bay 0). */
 
					byte side = ((DirToDiagDir(rv->direction) == ReverseDiagDir(GetRoadStopDir(tile))) == (rv->overtaking == 0)) ? 0 : 1;
 

	
 
					if (!rs->IsFreeBay(side)) return VETSB_CANNOT_ENTER;
src/train_cmd.cpp
Show inline comments
 
@@ -1716,25 +1716,25 @@ static Vehicle *TrainOnTileEnum(Vehicle 
 
 * Checks if a train is approaching a rail-road crossing
 
 * @param v vehicle on tile
 
 * @param data tile with crossing we are testing
 
 * @return v if it is approaching a crossing, NULL otherwise
 
 */
 
static Vehicle *TrainApproachingCrossingEnum(Vehicle *v, void *data)
 
{
 
	/* not a train || not front engine || crashed */
 
	if (v->type != VEH_TRAIN || !IsFrontEngine(v) || (v->vehstatus & VS_CRASHED)) return NULL;
 

	
 
	TileIndex tile = *(TileIndex*)data;
 

	
 
	if (TrainApproachingCrossingTile((Train *)v) != tile) return NULL;
 
	if (TrainApproachingCrossingTile(Train::From(v)) != tile) return NULL;
 

	
 
	return v;
 
}
 

	
 

	
 
/**
 
 * Finds a vehicle approaching rail-road crossing
 
 * @param tile tile to test
 
 * @return true if a vehicle is approaching the crossing
 
 * @pre tile is a rail-road crossing
 
 */
 
static bool TrainApproachingCrossing(TileIndex tile)
 
@@ -1791,25 +1791,25 @@ static inline void MaybeBarCrossingWithS
 
}
 

	
 

	
 
/**
 
 * Advances wagons for train reversing, needed for variable length wagons.
 
 * This one is called before the train is reversed.
 
 * @param v First vehicle in chain
 
 */
 
static void AdvanceWagonsBeforeSwap(Train *v)
 
{
 
	Train *base = v;
 
	Train *first = base; // first vehicle to move
 
	Train *last = (Train *)GetLastVehicleInChain(v); // last vehicle to move
 
	Train *last = Train::From(GetLastVehicleInChain(v)); // last vehicle to move
 
	uint length = CountVehiclesInChain(v);
 

	
 
	while (length > 2) {
 
		last = last->Previous();
 
		first = first->Next();
 

	
 
		int differential = base->tcache.cached_veh_length - last->tcache.cached_veh_length;
 

	
 
		/* do not update images now
 
		 * negative differential will be handled in AdvanceWagonsAfterSwap() */
 
		for (int i = 0; i < differential; i++) TrainController(first, last->Next());
 

	
 
@@ -1840,25 +1840,25 @@ static void AdvanceWagonsAfterSwap(Train
 

	
 
		if (d <= 0) {
 
			leave->vehstatus &= ~VS_HIDDEN; // move it out of the depot
 
			leave->track = TrackToTrackBits(GetRailDepotTrack(leave->tile));
 
			for (int i = 0; i >= d; i--) TrainController(leave, NULL); // maybe move it, and maybe let another wagon leave
 
		}
 
	} else {
 
		dep = NULL; // no vehicle in a depot, so no vehicle leaving a depot
 
	}
 

	
 
	Train *base = v;
 
	Train *first = base; // first vehicle to move
 
	Train *last = (Train *)GetLastVehicleInChain(v); // last vehicle to move
 
	Train *last = Train::From(GetLastVehicleInChain(v)); // last vehicle to move
 
	uint length = CountVehiclesInChain(v);
 

	
 
	/* we have to make sure all wagons that leave a depot because of train reversing are moved coorectly
 
	 * they have already correct spacing, so we have to make sure they are moved how they should */
 
	bool nomove = (dep == NULL); // if there is no vehicle leaving a depot, limit the number of wagons moved immediatelly
 

	
 
	while (length > 2) {
 
		/* we reached vehicle (originally) in front of a depot, stop now
 
		 * (we would move wagons that are alredy moved with new wagon length) */
 
		if (base == dep) break;
 

	
 
		/* the last wagon was that one leaving a depot, so do not move it anymore */
 
@@ -3550,34 +3550,34 @@ struct TrainCollideChecker {
 
};
 

	
 
static Vehicle *FindTrainCollideEnum(Vehicle *v, void *data)
 
{
 
	TrainCollideChecker *tcc = (TrainCollideChecker*)data;
 

	
 
	if (v->type != VEH_TRAIN) return NULL;
 

	
 
	/* get first vehicle now to make most usual checks faster */
 
	Vehicle *coll = v->First();
 

	
 
	/* can't collide with own wagons && can't crash in depot && the same height level */
 
	if (coll != tcc->v && ((Train *)v)->track != TRACK_BIT_DEPOT && abs(v->z_pos - tcc->v->z_pos) < 6) {
 
	if (coll != tcc->v && Train::From(v)->track != TRACK_BIT_DEPOT && abs(v->z_pos - tcc->v->z_pos) < 6) {
 
		int x_diff = v->x_pos - tcc->v->x_pos;
 
		int y_diff = v->y_pos - tcc->v->y_pos;
 

	
 
		/* needed to disable possible crash of competitor train in station by building diagonal track at its end */
 
		if (x_diff * x_diff + y_diff * y_diff > 25) return NULL;
 

	
 
		/* crash both trains */
 
		tcc->num += TrainCrashed((Train *)tcc->v);
 
		tcc->num += TrainCrashed((Train *)coll);
 
		tcc->num += TrainCrashed(Train::From(tcc->v));
 
		tcc->num += TrainCrashed(Train::From(coll));
 

	
 
		/* Try to reserve all tiles directly under the crashed trains.
 
		 * As there might be more than two trains involved, we have to do that for all vehicles */
 
		const Train *u;
 
		FOR_ALL_TRAINS(u) {
 
			if ((u->vehstatus & VS_CRASHED) && (u->track & TRACK_BIT_DEPOT) == TRACK_BIT_NONE) {
 
				TrackBits trackbits = u->track;
 
				if ((trackbits & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
 
					/* Vehicle is inside a wormhole, v->track contains no useful value then. */
 
					trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(u->tile));
 
				}
 
				TryReserveRailTrack(u->tile, TrackBitsToTrack(trackbits));
 
@@ -3623,26 +3623,26 @@ static bool CheckTrainCollision(Train *v
 
	);
 

	
 
	ModifyStationRatingAround(v->tile, v->owner, -160, 30);
 
	SndPlayVehicleFx(SND_13_BIG_CRASH, v);
 
	return true;
 
}
 

	
 
static Vehicle *CheckVehicleAtSignal(Vehicle *v, void *data)
 
{
 
	DiagDirection exitdir = *(DiagDirection *)data;
 

	
 
	/* front engine of a train, not inside wormhole or depot, not crashed */
 
	if (v->type == VEH_TRAIN && IsFrontEngine(v) && (((Train *)v)->track & TRACK_BIT_MASK) != 0 && !(v->vehstatus & VS_CRASHED)) {
 
		if (v->cur_speed <= 5 && TrainExitDir(v->direction, ((Train *)v)->track) == exitdir) return v;
 
	if (v->type == VEH_TRAIN && IsFrontEngine(v) && (Train::From(v)->track & TRACK_BIT_MASK) && !(v->vehstatus & VS_CRASHED)) {
 
		if (v->cur_speed <= 5 && TrainExitDir(v->direction, Train::From(v)->track) == exitdir) return v;
 
	}
 

	
 
	return NULL;
 
}
 

	
 
static void TrainController(Train *v, Vehicle *nomove)
 
{
 
	Train *first = v->First();
 
	Train *prev;
 
	bool direction_changed = false; // has direction of any part changed?
 

	
 
	/* For every vehicle after and including the given vehicle */
 
@@ -3933,29 +3933,29 @@ reverse_train_direction:
 
}
 

	
 
/** Collect trackbits of all crashed train vehicles on a tile
 
 * @param v Vehicle passed from Find/HasVehicleOnPos()
 
 * @param data trackdirbits for the result
 
 * @return NULL to iterate over all vehicles on the tile.
 
 */
 
static Vehicle *CollectTrackbitsFromCrashedVehiclesEnum(Vehicle *v, void *data)
 
{
 
	TrackBits *trackbits = (TrackBits *)data;
 

	
 
	if (v->type == VEH_TRAIN && (v->vehstatus & VS_CRASHED) != 0) {
 
		if ((((Train *)v)->track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
 
		if ((Train::From(v)->track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
 
			/* Vehicle is inside a wormhole, v->track contains no useful value then. */
 
			*trackbits |= DiagDirToDiagTrackBits(GetTunnelBridgeDirection(v->tile));
 
		} else {
 
			*trackbits |= ((Train *)v)->track;
 
			*trackbits |= Train::From(v)->track;
 
		}
 
	}
 

	
 
	return NULL;
 
}
 

	
 
/**
 
 * Deletes/Clears the last wagon of a crashed train. It takes the engine of the
 
 * train, then goes to the last wagon and deletes that. Each call to this function
 
 * will remove the last wagon of a crashed train. If this wagon was on a crossing,
 
 * or inside a tunnel/bridge, recalculate the signals as they might need updating
 
 * @param v the Vehicle of which last wagon is to be removed
src/train_gui.cpp
Show inline comments
 
@@ -71,25 +71,25 @@ void DrawTrainImage(const Vehicle *v, in
 
	/* Position of highlight box */
 
	int highlight_l = 0;
 
	int highlight_r = 0;
 

	
 
	if (!FillDrawPixelInfo(&tmp_dpi, x - 2, y - 1, count + 1, 14)) return;
 

	
 
	count = (count * 8) / _traininfo_vehicle_width;
 

	
 
	old_dpi = _cur_dpi;
 
	_cur_dpi = &tmp_dpi;
 

	
 
	do {
 
		int width = ((const Train *)v)->tcache.cached_veh_length;
 
		int width = Train::From(v)->tcache.cached_veh_length;
 

	
 
		if (dx + width > 0) {
 
			if (dx <= count) {
 
				SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
 
				DrawSprite(v->GetImage(DIR_W), pal, 16 + WagonLengthToPixels(dx), 7 + (is_custom_sprite(RailVehInfo(v->engine_type)->image_index) ? _traininfo_vehicle_pitch : 0));
 
				if (v->index == selection) {
 
					/* Set the highlight position */
 
					highlight_l = WagonLengthToPixels(dx) + 1;
 
					highlight_r = WagonLengthToPixels(dx + width) + 1;
 
				} else if (_cursor.vehchain && highlight_r != 0) {
 
					highlight_r += WagonLengthToPixels(width);
 
				}
 
@@ -227,25 +227,25 @@ void DrawTrainDetails(const Vehicle *v, 
 
	/* draw the first 3 details tabs */
 
	if (det_tab != TDW_TAB_TOTALS) {
 
		const Vehicle *u = v;
 
		int x = 1;
 
		for (;;) {
 
			if (--vscroll_pos < 0 && vscroll_pos >= -vscroll_cap) {
 
				int dx = 0;
 

	
 
				u = v;
 
				do {
 
					SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
 
					DrawSprite(u->GetImage(DIR_W), pal, x + WagonLengthToPixels(4 + dx), y + 6 + (is_custom_sprite(RailVehInfo(u->engine_type)->image_index) ? _traininfo_vehicle_pitch : 0));
 
					dx += ((const Train *)u)->tcache.cached_veh_length;
 
					dx += Train::From(u)->tcache.cached_veh_length;
 
					u = u->Next();
 
				} while (u != NULL && IsArticulatedPart(u) && u->cargo_cap == 0);
 

	
 
				int px = x + WagonLengthToPixels(dx) + 2;
 
				int py = y + 2;
 
				switch (det_tab) {
 
					default: NOT_REACHED();
 

	
 
					case TDW_TAB_CARGO:
 
						TrainDetailsCargoTab(v, px, right, py);
 
						break;
 

	
src/tunnelbridge_cmd.cpp
Show inline comments
 
@@ -1376,25 +1376,25 @@ static const byte _tunnel_fractcoord_7[4
 
static VehicleEnterTileStatus VehicleEnter_TunnelBridge(Vehicle *v, TileIndex tile, int x, int y)
 
{
 
	int z = GetSlopeZ(x, y) - v->z_pos;
 

	
 
	if (abs(z) > 2) return VETSB_CANNOT_ENTER;
 
	const DiagDirection dir = GetTunnelBridgeDirection(tile);
 

	
 
	if (IsTunnel(tile)) {
 
		byte fc;
 
		DiagDirection vdir;
 

	
 
		if (v->type == VEH_TRAIN) {
 
			Train *t = (Train *)v;
 
			Train *t = Train::From(v);
 
			fc = (x & 0xF) + (y << 4);
 

	
 
			vdir = DirToDiagDir(t->direction);
 

	
 
			if (t->track != TRACK_BIT_WORMHOLE && dir == vdir) {
 
				if (IsFrontEngine(t) && fc == _tunnel_fractcoord_1[dir]) {
 
					if (!PlayVehicleSound(t, VSE_TUNNEL) && RailVehInfo(t->engine_type)->engclass == 0) {
 
						SndPlayVehicleFx(SND_05_TRAIN_THROUGH_TUNNEL, v);
 
					}
 
					return VETSB_CONTINUE;
 
				}
 
				if (fc == _tunnel_fractcoord_2[dir]) {
 
@@ -1405,25 +1405,25 @@ static VehicleEnterTileStatus VehicleEnt
 
				}
 
			}
 

	
 
			if (dir == ReverseDiagDir(vdir) && fc == _tunnel_fractcoord_3[dir] && z == 0) {
 
				/* We're at the tunnel exit ?? */
 
				t->tile = tile;
 
				t->track = (TrackBits)_exit_tunnel_track[dir];
 
				assert(t->track);
 
				t->vehstatus &= ~VS_HIDDEN;
 
				return VETSB_ENTERED_WORMHOLE;
 
			}
 
		} else if (v->type == VEH_ROAD) {
 
			RoadVehicle *rv = (RoadVehicle *)v;
 
			RoadVehicle *rv = RoadVehicle::From(v);
 
			fc = (x & 0xF) + (y << 4);
 
			vdir = DirToDiagDir(v->direction);
 

	
 
			/* Enter tunnel? */
 
			if (rv->state != RVSB_WORMHOLE && dir == vdir) {
 
				if (fc == _tunnel_fractcoord_4[dir] ||
 
						fc == _tunnel_fractcoord_5[dir]) {
 
					rv->tile = tile;
 
					rv->state = RVSB_WORMHOLE;
 
					rv->vehstatus |= VS_HIDDEN;
 
					return VETSB_ENTERED_WORMHOLE;
 
				} else {
 
@@ -1455,63 +1455,63 @@ static VehicleEnterTileStatus VehicleEnt
 
		}
 

	
 
		if (DirToDiagDir(v->direction) == dir) {
 
			switch (dir) {
 
				default: NOT_REACHED();
 
				case DIAGDIR_NE: if ((x & 0xF) != 0)             return VETSB_CONTINUE; break;
 
				case DIAGDIR_SE: if ((y & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
 
				case DIAGDIR_SW: if ((x & 0xF) != TILE_SIZE - 1) return VETSB_CONTINUE; break;
 
				case DIAGDIR_NW: if ((y & 0xF) != 0)             return VETSB_CONTINUE; break;
 
			}
 
			switch (v->type) {
 
				case VEH_TRAIN: {
 
					Train *t = (Train *)v;
 
					Train *t = Train::From(v);
 
					t->track = TRACK_BIT_WORMHOLE;
 
					ClrBit(t->flags, VRF_GOINGUP);
 
					ClrBit(t->flags, VRF_GOINGDOWN);
 
				} break;
 

	
 
				case VEH_ROAD:
 
					((RoadVehicle *)v)->state = RVSB_WORMHOLE;
 
					RoadVehicle::From(v)->state = RVSB_WORMHOLE;
 
					break;
 

	
 
				case VEH_SHIP:
 
					((Ship *)v)->state = TRACK_BIT_WORMHOLE;
 
					Ship::From(v)->state = TRACK_BIT_WORMHOLE;
 
					break;
 

	
 
				default: NOT_REACHED();
 
			}
 
			return VETSB_ENTERED_WORMHOLE;
 
		} else if (DirToDiagDir(v->direction) == ReverseDiagDir(dir)) {
 
			v->tile = tile;
 
			switch (v->type) {
 
				case VEH_TRAIN: {
 
					Train *t = (Train *)v;
 
					Train *t = Train::From(v);
 
					if (t->track == TRACK_BIT_WORMHOLE) {
 
						t->track = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
 
						return VETSB_ENTERED_WORMHOLE;
 
					}
 
				} break;
 

	
 
				case VEH_ROAD: {
 
					RoadVehicle *rv = (RoadVehicle *)v;
 
					RoadVehicle *rv = RoadVehicle::From(v);
 
					if (rv->state == RVSB_WORMHOLE) {
 
						rv->state = _road_exit_tunnel_state[dir];
 
						rv->frame = 0;
 
						return VETSB_ENTERED_WORMHOLE;
 
					}
 
				} break;
 

	
 
				case VEH_SHIP: {
 
					Ship *ship = (Ship *)v;
 
					Ship *ship = Ship::From(v);
 
					if (ship->state == TRACK_BIT_WORMHOLE) {
 
						ship->state = (DiagDirToAxis(dir) == AXIS_X ? TRACK_BIT_X : TRACK_BIT_Y);
 
						return VETSB_ENTERED_WORMHOLE;
 
					}
 
				} break;
 

	
 
				default: NOT_REACHED();
 
			}
 
		}
 
	}
 
	return VETSB_CONTINUE;
 
}
src/vehicle.cpp
Show inline comments
 
@@ -515,27 +515,27 @@ void Vehicle::PreDestructor()
 
		HideFillingPercent(&this->fill_percent_te_id);
 
	}
 

	
 
	if (IsEngineCountable(this)) {
 
		Company::Get(this->owner)->num_engines[this->engine_type]--;
 
		if (this->owner == _local_company) InvalidateAutoreplaceWindow(this->engine_type, this->group_id);
 

	
 
		DeleteGroupHighlightOfVehicle(this);
 
		if (Group::IsValidID(this->group_id)) Group::Get(this->group_id)->num_engines[this->engine_type]--;
 
		if (this->IsPrimaryVehicle()) DecreaseGroupNumVehicle(this->group_id);
 
	}
 

	
 
	if (this->type == VEH_ROAD) ClearSlot((RoadVehicle *)this);
 
	if (this->type == VEH_ROAD) ClearSlot(RoadVehicle::From(this));
 
	if (this->type == VEH_AIRCRAFT && this->IsPrimaryVehicle()) {
 
		Aircraft *a = (Aircraft *)this;
 
		Aircraft *a = Aircraft::From(this);
 
		Station *st = GetTargetAirportIfValid(a);
 
		if (st != NULL) {
 
			const AirportFTA *layout = st->Airport()->layout;
 
			CLRBITS(st->airport_flags, layout[a->previous_pos].block | layout[a->pos].block);
 
		}
 
	}
 

	
 
	if (this->type != VEH_TRAIN || (this->type == VEH_TRAIN && (IsFrontEngine(this) || IsFreeWagon(this)))) {
 
		InvalidateWindowData(WC_VEHICLE_DEPOT, this->tile);
 
	}
 

	
 
	if (this->IsPrimaryVehicle()) {
 
@@ -975,42 +975,42 @@ uint8 CalcPercentVehicleFilled(const Veh
 
void VehicleEnterDepot(Vehicle *v)
 
{
 
	switch (v->type) {
 
		case VEH_TRAIN:
 
			InvalidateWindowClasses(WC_TRAINS_LIST);
 
			/* Clear path reservation */
 
			SetDepotWaypointReservation(v->tile, false);
 
			if (_settings_client.gui.show_track_reservation) MarkTileDirtyByTile(v->tile);
 

	
 
			if (!IsFrontEngine(v)) v = v->First();
 
			UpdateSignalsOnSegment(v->tile, INVALID_DIAGDIR, v->owner);
 
			v->load_unload_time_rem = 0;
 
			ClrBit(((Train *)v)->flags, VRF_TOGGLE_REVERSE);
 
			TrainConsistChanged((Train *)v, true);
 
			ClrBit(Train::From(v)->flags, VRF_TOGGLE_REVERSE);
 
			TrainConsistChanged(Train::From(v), true);
 
			break;
 

	
 
		case VEH_ROAD:
 
			InvalidateWindowClasses(WC_ROADVEH_LIST);
 
			if (!IsRoadVehFront(v)) v = v->First();
 
			break;
 

	
 
		case VEH_SHIP:
 
			InvalidateWindowClasses(WC_SHIPS_LIST);
 
			static_cast<Ship*>(v)->state = TRACK_BIT_DEPOT;
 
			Ship::From(v)->state = TRACK_BIT_DEPOT;
 
			RecalcShipStuff(v);
 
			break;
 

	
 
		case VEH_AIRCRAFT:
 
			InvalidateWindowClasses(WC_AIRCRAFT_LIST);
 
			HandleAircraftEnterHangar((Aircraft *)v);
 
			HandleAircraftEnterHangar(Aircraft::From(v));
 
			break;
 
		default: NOT_REACHED();
 
	}
 

	
 
	if (v->type != VEH_TRAIN) {
 
		/* Trains update the vehicle list when the first unit enters the depot and calls VehicleEnterDepot() when the last unit enters.
 
		 * We only increase the number of vehicles when the first one enters, so we will not need to search for more vehicles in the depot */
 
		InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
 
	}
 
	InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
 

	
 
	v->vehstatus |= VS_HIDDEN;
 
@@ -1420,27 +1420,27 @@ static SpriteID GetEngineColourMap(Engin
 
	if (v != NULL) const_cast<Vehicle *>(v)->colourmap = map;
 
	return map;
 
}
 

	
 
SpriteID GetEnginePalette(EngineID engine_type, CompanyID company)
 
{
 
	return GetEngineColourMap(engine_type, company, INVALID_ENGINE, NULL);
 
}
 

	
 
SpriteID GetVehiclePalette(const Vehicle *v)
 
{
 
	if (v->type == VEH_TRAIN) {
 
		return GetEngineColourMap(v->engine_type, v->owner, ((const Train *)v)->tcache.first_engine, v);
 
		return GetEngineColourMap(v->engine_type, v->owner, Train::From(v)->tcache.first_engine, v);
 
	} else if (v->type == VEH_ROAD) {
 
		return GetEngineColourMap(v->engine_type, v->owner, ((const RoadVehicle *)v)->rcache.first_engine, v);
 
		return GetEngineColourMap(v->engine_type, v->owner, RoadVehicle::From(v)->rcache.first_engine, v);
 
	}
 

	
 
	return GetEngineColourMap(v->engine_type, v->owner, INVALID_ENGINE, v);
 
}
 

	
 

	
 
void Vehicle::BeginLoading()
 
{
 
	assert(IsTileType(tile, MP_STATION) || type == VEH_SHIP);
 

	
 
	if (this->current_order.IsType(OT_GOTO_STATION) &&
 
			this->current_order.GetDestination() == this->last_station_visited) {
 
@@ -1484,25 +1484,25 @@ void Vehicle::LeaveStation()
 
	st->loading_vehicles.remove(this);
 

	
 
	HideFillingPercent(&this->fill_percent_te_id);
 

	
 
	if (this->type == VEH_TRAIN && !(this->vehstatus & VS_CRASHED)) {
 
		/* Trigger station animation (trains only) */
 
		if (IsTileType(this->tile, MP_STATION)) StationAnimationTrigger(st, this->tile, STAT_ANIM_TRAIN_DEPARTS);
 

	
 
		/* Try to reserve a path when leaving the station as we
 
		 * might not be marked as wanting a reservation, e.g.
 
		 * when an overlength train gets turned around in a station. */
 
		if (UpdateSignalsOnSegment(this->tile, TrackdirToExitdir(this->GetVehicleTrackdir()), this->owner) == SIGSEG_PBS || _settings_game.pf.reserve_paths) {
 
			TryPathReserve((Train *)this, true, true);
 
			TryPathReserve(Train::From(this), true, true);
 
		}
 
	}
 
}
 

	
 

	
 
void Vehicle::HandleLoading(bool mode)
 
{
 
	switch (this->current_order.GetType()) {
 
		case OT_LOADING: {
 
			uint wait_time = max(this->current_order.wait_time - this->lateness_counter, 0);
 

	
 
			/* Not the first call for this tick, or still loading */
 
@@ -1568,25 +1568,25 @@ CommandCost Vehicle::SendToDepot(DoComma
 
	if (flags & DC_EXEC) {
 
		if (this->current_order.IsType(OT_LOADING)) this->LeaveStation();
 

	
 
		this->dest_tile = location;
 
		this->current_order.MakeGoToDepot(destination, ODTF_MANUAL);
 
		if (!(command & DEPOT_SERVICE)) this->current_order.SetDepotActionType(ODATFB_HALT);
 
		InvalidateWindowWidget(WC_VEHICLE_VIEW, this->index, VVW_WIDGET_START_STOP_VEH);
 

	
 
		/* If there is no depot in front, reverse automatically (trains only) */
 
		if (this->type == VEH_TRAIN && reverse) DoCommand(this->tile, this->index, 0, DC_EXEC, CMD_REVERSE_TRAIN_DIRECTION);
 

	
 
		if (this->type == VEH_AIRCRAFT) {
 
			Aircraft *a = (Aircraft *)this;
 
			Aircraft *a = Aircraft::From(this);
 
			if (a->state == FLYING && a->targetairport != destination) {
 
				/* The aircraft is now heading for a different hangar than the next in the orders */
 
				extern void AircraftNextAirportPos_and_Order(Aircraft *a);
 
				AircraftNextAirportPos_and_Order(a);
 
			}
 
		}
 
	}
 

	
 
	return CommandCost();
 

	
 
}
 

	
 
@@ -1738,16 +1738,16 @@ bool CanVehicleUseStation(EngineID engin
 
			return false;
 
	}
 
}
 

	
 
/**
 
 * Can this station be used by the given vehicle?
 
 * @param v the vehicle to test
 
 * @param st the station to test for
 
 * @return true if and only if the vehicle can use this station.
 
 */
 
bool CanVehicleUseStation(const Vehicle *v, const Station *st)
 
{
 
	if (v->type == VEH_ROAD) return st->GetPrimaryRoadStop((const RoadVehicle *)v) != NULL;
 
	if (v->type == VEH_ROAD) return st->GetPrimaryRoadStop(RoadVehicle::From(v)) != NULL;
 

	
 
	return CanVehicleUseStation(v->engine_type, st);
 
}
src/vehicle_base.h
Show inline comments
 
@@ -564,24 +564,46 @@ struct SpecializedVehicle : public Vehic
 
	{
 
		return (T *)Vehicle::Get(index);
 
	}
 

	
 
	/**
 
	 * Returns vehicle if the index is a valid index for this vehicle type
 
	 * @return pointer to vehicle with given index if it's a vehicle of this type
 
	 */
 
	static FORCEINLINE T *GetIfValid(size_t index)
 
	{
 
		return IsValidID(index) ? Get(index) : NULL ;
 
	}
 

	
 
	/**
 
	 * Converts a Vehicle to SpecializedVehicle with type checking.
 
	 * @param v Vehicle pointer
 
	 * @return pointer to SpecializedVehicle
 
	 */
 
	static FORCEINLINE T *From(Vehicle *v)
 
	{
 
		assert(v->type == Type);
 
		return (T *)v;
 
	}
 

	
 
	/**
 
	 * Converts a const Vehicle to const SpecializedVehicle with type checking.
 
	 * @param v Vehicle pointer
 
	 * @return pointer to SpecializedVehicle
 
	 */
 
	static FORCEINLINE const T *From(const Vehicle *v)
 
	{
 
		assert(v->type == Type);
 
		return (const T *)v;
 
	}
 
};
 

	
 
#define FOR_ALL_VEHICLES_OF_TYPE(name, var) FOR_ALL_ITEMS_FROM(name, vehicle_index, var, 0) if (var->type == name::EXPECTED_TYPE)
 

	
 
/**
 
 * Disasters, like submarines, skyrangers and their shadows, belong to this class.
 
 */
 
struct DisasterVehicle : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
 
	uint16 image_override;
 
	VehicleID big_ufo_destroyer_target;
 

	
 
	/** We don't want GCC to zero our struct! It already is zeroed and has an index! */
src/vehicle_cmd.cpp
Show inline comments
 
@@ -58,33 +58,33 @@ const uint32 _send_to_depot_proc_table[]
 
 * @return result of operation.  Nothing if everything went well
 
 */
 
CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
 
{
 
	/* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */
 
	if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0);
 

	
 
	Vehicle *v = Vehicle::GetIfValid(p1);
 
	if (v == NULL || !CheckOwnership(v->owner) || !v->IsPrimaryVehicle()) return CMD_ERROR;
 

	
 
	switch (v->type) {
 
		case VEH_TRAIN:
 
			if ((v->vehstatus & VS_STOPPED) && ((Train *)v)->tcache.cached_power == 0) return_cmd_error(STR_TRAIN_START_NO_CATENARY);
 
			if ((v->vehstatus & VS_STOPPED) && Train::From(v)->tcache.cached_power == 0) return_cmd_error(STR_TRAIN_START_NO_CATENARY);
 
			break;
 

	
 
		case VEH_SHIP:
 
		case VEH_ROAD:
 
			break;
 

	
 
		case VEH_AIRCRAFT: {
 
			Aircraft *a = (Aircraft *)v;
 
			Aircraft *a = Aircraft::From(v);
 
			/* cannot stop airplane when in flight, or when taking off / landing */
 
			if (a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT);
 
		} break;
 

	
 
		default: return CMD_ERROR;
 
	}
 

	
 
	/* Check if this vehicle can be started/stopped. The callback will fail or
 
	 * return 0xFF if it can. */
 
	uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v);
 
	if (callback != CALLBACK_FAILED && GB(callback, 0, 8) != 0xFF && HasBit(p2, 0)) {
 
		StringID error = GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + callback);
 
@@ -143,25 +143,25 @@ CommandCost CmdMassStartStopVehicle(Tile
 
	} else {
 
		/* Get the list of vehicles in the depot */
 
		BuildDepotVehicleList(vehicle_type, tile, &list, NULL);
 
	}
 

	
 
	for (uint i = 0; i < list.Length(); i++) {
 
		const Vehicle *v = list[i];
 

	
 
		if (!!(v->vehstatus & VS_STOPPED) != start_stop) continue;
 

	
 
		if (!vehicle_list_window) {
 
			if (vehicle_type == VEH_TRAIN) {
 
				if (CheckTrainInDepot((const Train *)v, false) == -1) continue;
 
				if (CheckTrainInDepot(Train::From(v), false) == -1) continue;
 
			} else {
 
				if (!(v->vehstatus & VS_HIDDEN)) continue;
 
			}
 
		}
 

	
 
		CommandCost ret = DoCommand(tile, v->index, 0, flags, CMD_START_STOP_VEHICLE);
 

	
 
		if (CmdSucceeded(ret)) {
 
			return_value = CommandCost();
 
			/* We know that the command is valid for at least one vehicle.
 
			 * If we haven't set DC_EXEC, then there is no point in continueing because it will be valid */
 
			if (!(flags & DC_EXEC)) break;
 
@@ -340,25 +340,25 @@ CommandCost CmdCloneVehicle(TileIndex ti
 
	Vehicle *w_rear = NULL;
 

	
 
	/*
 
	 * v_front is the front engine in the original vehicle
 
	 * v is the car/vehicle of the original vehicle, that is currently being copied
 
	 * w_front is the front engine of the cloned vehicle
 
	 * w is the car/vehicle currently being cloned
 
	 * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains
 
	 */
 

	
 
	if (!CheckOwnership(v->owner)) return CMD_ERROR;
 

	
 
	if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || ((Train *)v)->crash_anim_pos >= 4400)) return CMD_ERROR;
 
	if (v->type == VEH_TRAIN && (!IsFrontEngine(v) || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR;
 

	
 
	/* check that we can allocate enough vehicles */
 
	if (!(flags & DC_EXEC)) {
 
		int veh_counter = 0;
 
		do {
 
			veh_counter++;
 
		} while ((v = v->Next()) != NULL);
 

	
 
		if (!Vehicle::CanAllocateItem(veh_counter)) {
 
			return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME);
 
		}
 
	}
 
@@ -372,47 +372,47 @@ CommandCost CmdCloneVehicle(TileIndex ti
 
		}
 

	
 
		CommandCost cost = DoCommand(tile, v->engine_type, build_argument, flags, GetCmdBuildVeh(v));
 
		build_argument = 3; // ensure that we only assign a number to the first engine
 

	
 
		if (CmdFailed(cost)) return cost;
 

	
 
		total_cost.AddCost(cost);
 

	
 
		if (flags & DC_EXEC) {
 
			w = Vehicle::Get(_new_vehicle_id);
 

	
 
			if (v->type == VEH_TRAIN && HasBit(((Train *)v)->flags, VRF_REVERSE_DIRECTION)) {
 
				SetBit(((Train *)w)->flags, VRF_REVERSE_DIRECTION);
 
			if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) {
 
				SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION);
 
			}
 

	
 
			if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
 
				/* this s a train car
 
				 * add this unit to the end of the train */
 
				CommandCost result = DoCommand(0, (w_rear->index << 16) | w->index, 1, flags, CMD_MOVE_RAIL_VEHICLE);
 
				if (CmdFailed(result)) {
 
					/* The train can't be joined to make the same consist as the original.
 
					 * Sell what we already made (clean up) and return an error.           */
 
					DoCommand(w_front->tile, w_front->index, 1, flags, GetCmdSellVeh(w_front));
 
					DoCommand(w_front->tile, w->index,       1, flags, GetCmdSellVeh(w));
 
					return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE
 
				}
 
			} else {
 
				/* this is a front engine or not a train. */
 
				w_front = w;
 
				w->service_interval = v->service_interval;
 
			}
 
			w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop
 
		}
 
	} while (v->type == VEH_TRAIN && (v = GetNextVehicle((Train *)v)) != NULL);
 
	} while (v->type == VEH_TRAIN && (v = GetNextVehicle(Train::From(v))) != NULL);
 

	
 
	if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) {
 
		/* for trains this needs to be the front engine due to the callback function */
 
		_new_vehicle_id = w_front->index;
 
	}
 

	
 
	if (flags & DC_EXEC) {
 
		/* Cloned vehicles belong to the same group */
 
		DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP);
 
	}
 

	
 

	
 
@@ -428,50 +428,50 @@ CommandCost CmdCloneVehicle(TileIndex ti
 
	 * vehicles in a different loop. */
 
	do {
 
		do {
 
			if (flags & DC_EXEC) {
 
				assert(w != NULL);
 

	
 
				if (w->cargo_type != v->cargo_type || w->cargo_subtype != v->cargo_subtype) {
 
					CommandCost cost = DoCommand(0, w->index, v->cargo_type | (v->cargo_subtype << 8) | 1U << 16 , flags, GetCmdRefitVeh(v));
 
					if (CmdSucceeded(cost)) total_cost.AddCost(cost);
 
				}
 

	
 
				if (w->type == VEH_TRAIN && EngineHasArticPart(w)) {
 
					w = GetNextArticPart((Train *)w);
 
					w = GetNextArticPart(Train::From(w));
 
				} else if (w->type == VEH_ROAD && RoadVehHasArticPart(w)) {
 
					w = w->Next();
 
				} else {
 
					break;
 
				}
 
			} else {
 
				const Engine *e = Engine::Get(v->engine_type);
 
				CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID);
 

	
 
				if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) {
 
					total_cost.AddCost(GetRefitCost(v->engine_type));
 
				}
 
			}
 

	
 
			if (v->type == VEH_TRAIN && EngineHasArticPart(v)) {
 
				v = GetNextArticPart((Train *)v);
 
				v = GetNextArticPart(Train::From(v));
 
			} else if (v->type == VEH_ROAD && RoadVehHasArticPart(v)) {
 
				v = v->Next();
 
			} else {
 
				break;
 
			}
 
		} while (v != NULL);
 

	
 
		if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle((Train *)w);
 
	} while (v->type == VEH_TRAIN && (v = GetNextVehicle((Train *)v)) != NULL);
 
		if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = GetNextVehicle(Train::From(w));
 
	} while (v->type == VEH_TRAIN && (v = GetNextVehicle(Train::From(v))) != NULL);
 

	
 
	if (flags & DC_EXEC) {
 
		/*
 
		 * Set the orders of the vehicle. Cannot do it earlier as we need
 
		 * the vehicle refitted before doing this, otherwise the moved
 
		 * cargo types might not match (passenger vs non-passenger)
 
		 */
 
		DoCommand(0, (v_front->index << 16) | w_front->index, p2 & 1 ? CO_SHARE : CO_COPY, flags, CMD_CLONE_ORDER);
 

	
 
		/* Now clone the vehicle's name, if it has one. */
 
		if (v_front->name != NULL) CloneVehicleName(v_front, w_front);
 
	}
src/vehicle_gui.cpp
Show inline comments
 
@@ -594,25 +594,25 @@ static int CDECL VehicleCargoSorter(cons
 
/** Sort vehicles by their reliability */
 
static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
 
{
 
	int r = (*a)->reliability - (*b)->reliability;
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
}
 

	
 
/** Sort vehicles by their max speed */
 
static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
 
{
 
	int r = 0;
 
	if ((*a)->type == VEH_TRAIN && (*b)->type == VEH_TRAIN) {
 
		r = ((const Train *)(*a))->tcache.cached_max_speed - ((const Train *)(*b))->tcache.cached_max_speed;
 
		r = Train::From(*a)->tcache.cached_max_speed - Train::From(*b)->tcache.cached_max_speed;
 
	} else {
 
		r = (*a)->max_speed - (*b)->max_speed;
 
	}
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
}
 

	
 
/** Sort vehicles by model */
 
static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
 
{
 
	int r = (*a)->engine_type - (*b)->engine_type;
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
}
 
@@ -627,31 +627,31 @@ static int CDECL VehicleValueSorter(cons
 
	for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
 

	
 
	int r = ClampToI32(diff);
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
}
 

	
 
/** Sort vehicles by their length */
 
static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
 
{
 
	int r = 0;
 
	switch ((*a)->type) {
 
		case VEH_TRAIN:
 
			r = ((const Train *)(*a))->tcache.cached_total_length - ((const Train *)(*b))->tcache.cached_total_length;
 
			r = Train::From(*a)->tcache.cached_total_length - Train::From(*b)->tcache.cached_total_length;
 
			break;
 

	
 
		case VEH_ROAD: {
 
			const RoadVehicle *u;
 
			for (u = (const RoadVehicle *)*a; u != NULL; u = u->Next()) r += u->rcache.cached_veh_length;
 
			for (u = (const RoadVehicle *)*b; u != NULL; u = u->Next()) r -= u->rcache.cached_veh_length;
 
			for (u = RoadVehicle::From(*a); u != NULL; u = u->Next()) r += u->rcache.cached_veh_length;
 
			for (u = RoadVehicle::From(*b); u != NULL; u = u->Next()) r -= u->rcache.cached_veh_length;
 
		} break;
 

	
 
		default: NOT_REACHED();
 
	}
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
}
 

	
 
/** Sort vehicles by the time they can still live */
 
static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
 
{
 
	int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
 
	return (r != 0) ? r : VehicleNumberSorter(a, b);
 
@@ -1462,28 +1462,28 @@ struct VehicleDetailsWindow : Window {
 

	
 
		/* Draw running cost */
 
		SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
 
		SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_AGE : STR_AGE_RED);
 
		SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
 
		SetDParam(3, v->GetDisplayRunningCost());
 
		DrawString(2, this->width - 2, 15, STR_VEHICLE_INFO_AGE_RUNNING_COST_YR);
 

	
 
		/* Draw max speed */
 
		switch (v->type) {
 
			case VEH_TRAIN:
 
				SetDParam(2, v->GetDisplayMaxSpeed());
 
				SetDParam(1, ((const Train *)v)->tcache.cached_power);
 
				SetDParam(0, ((const Train *)v)->tcache.cached_weight);
 
				SetDParam(3, ((const Train *)v)->tcache.cached_max_te / 1000);
 
				DrawString(2, this->width - 2, 25, (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && ((const Train *)v)->railtype != RAILTYPE_MAGLEV) ?
 
				SetDParam(1, Train::From(v)->tcache.cached_power);
 
				SetDParam(0, Train::From(v)->tcache.cached_weight);
 
				SetDParam(3, Train::From(v)->tcache.cached_max_te / 1000);
 
				DrawString(2, this->width - 2, 25, (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && Train::From(v)->railtype != RAILTYPE_MAGLEV) ?
 
					STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE :
 
					STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED);
 
				break;
 

	
 
			case VEH_ROAD:
 
			case VEH_SHIP:
 
			case VEH_AIRCRAFT:
 
				SetDParam(0, v->GetDisplayMaxSpeed());
 
				DrawString(2, this->width - 2, 25, STR_VEHICLE_INFO_MAX_SPEED);
 
				break;
 

	
 
			default: NOT_REACHED();
 
@@ -1934,37 +1934,37 @@ struct VehicleViewWindow : Window {
 

	
 
		/* draw widgets & caption */
 
		SetDParam(0, v->index);
 
		this->DrawWidgets();
 

	
 
		if (v->vehstatus & VS_CRASHED) {
 
			str = STR_VEHICLE_STATUS_CRASHED;
 
		} else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
 
			str = STR_VEHICLE_STATUS_BROKEN_DOWN;
 
		} else if (v->vehstatus & VS_STOPPED) {
 
			if (v->type == VEH_TRAIN) {
 
				if (v->cur_speed == 0) {
 
					if (((const Train *)v)->tcache.cached_power == 0) {
 
					if (Train::From(v)->tcache.cached_power == 0) {
 
						str = STR_TRAIN_NO_POWER;
 
					} else {
 
						str = STR_VEHICLE_STATUS_STOPPED;
 
					}
 
				} else {
 
					SetDParam(0, v->GetDisplaySpeed());
 
					str = STR_TRAIN_STOPPING + _settings_client.gui.vehicle_speed;
 
				}
 
			} else { // no train
 
				str = STR_VEHICLE_STATUS_STOPPED;
 
			}
 
		} else if (v->type == VEH_TRAIN && HasBit(((const Train *)v)->flags, VRF_TRAIN_STUCK)) {
 
		} else if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_TRAIN_STUCK)) {
 
			str = STR_TRAIN_STUCK;
 
		} else { // vehicle is in a "normal" state, show current order
 
			switch (v->current_order.GetType()) {
 
				case OT_GOTO_STATION: {
 
					SetDParam(0, v->current_order.GetDestination());
 
					SetDParam(1, v->GetDisplaySpeed());
 
					str = STR_HEADING_FOR_STATION + _settings_client.gui.vehicle_speed;
 
				} break;
 

	
 
				case OT_GOTO_DEPOT: {
 
					if (v->type == VEH_AIRCRAFT) {
 
						/* Aircrafts always go to a station, even if you say depot */
src/vehicle_type.h
Show inline comments
 
@@ -19,24 +19,26 @@ enum VehicleType {
 
	VEH_END,
 
	VEH_INVALID = 0xFF,
 
};
 
DECLARE_POSTFIX_INCREMENT(VehicleType);
 
/** It needs to be 8bits, because we save and load it as such */
 
typedef SimpleTinyEnumT<VehicleType, byte> VehicleTypeByte;
 

	
 
struct Vehicle;
 
struct Train;
 
struct RoadVehicle;
 
struct Ship;
 
struct Aircraft;
 
struct EffectVehicle;
 
struct DisasterVehicle;
 

	
 
struct BaseVehicle
 
{
 
	VehicleTypeByte type;    ///< Type of vehicle
 
};
 

	
 
static const VehicleID INVALID_VEHICLE = 0xFFFF;
 

	
 
/** Pathfinding option states */
 
enum {
 
	VPF_OPF  = 0, ///< The Original PathFinder
 
	VPF_NTP  = 0, ///< New Train Pathfinder, replacing OPF for trains
src/vehiclelist.cpp
Show inline comments
 
@@ -20,25 +20,25 @@ void BuildDepotVehicleList(VehicleType t
 
	engines->Clear();
 
	if (wagons != NULL && wagons != engines) wagons->Clear();
 

	
 
	const Vehicle *v;
 
	FOR_ALL_VEHICLES(v) {
 
		/* General tests for all vehicle types */
 
		if (v->type != type) continue;
 
		if (v->tile != tile) continue;
 

	
 
		switch (type) {
 
			case VEH_TRAIN:
 
				if (IsArticulatedPart(v) || IsRearDualheaded(v)) continue;
 
				if (((const Train *)v)->track != TRACK_BIT_DEPOT) continue;
 
				if (Train::From(v)->track != TRACK_BIT_DEPOT) continue;
 
				if (wagons != NULL && IsFreeWagon(v->First())) {
 
					if (individual_wagons || IsFreeWagon(v)) *wagons->Append() = v;
 
					continue;
 
				}
 
				break;
 

	
 
			default:
 
				if (!v->IsInDepot()) continue;
 
				break;
 
		}
 

	
 
		if (!v->IsPrimaryVehicle()) continue;
src/water_cmd.cpp
Show inline comments
 
@@ -804,40 +804,40 @@ static void FloodVehicle(Vehicle *v)
 
				u->vehstatus |= VS_CRASHED;
 
				MarkSingleVehicleDirty(u);
 
			}
 

	
 
			switch (v->type) {
 
				default: NOT_REACHED();
 
				case VEH_TRAIN:
 
					if (IsFrontEngine(v)) {
 
						pass += 4; // driver
 
						/* FreeTrainTrackReservation() calls GetVehicleTrackdir() that doesn't like crashed vehicles.
 
						 * In this case, v->direction matches v->u.rail.track, so we can do this (it wasn't crashed before) */
 
						v->vehstatus &= ~VS_CRASHED;
 
						FreeTrainTrackReservation((Train *)v);
 
						FreeTrainTrackReservation(Train::From(v));
 
						v->vehstatus |= VS_CRASHED;
 
					}
 
					((Train *)v)->crash_anim_pos = 4000; // max 4440, disappear pretty fast
 
					Train::From(v)->crash_anim_pos = 4000; // max 4440, disappear pretty fast
 
					InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
 
					break;
 

	
 
				case VEH_ROAD:
 
					if (IsRoadVehFront(v)) pass += 1; // driver
 
					((RoadVehicle *)v)->crashed_ctr = 2000; // max 2220, disappear pretty fast
 
					RoadVehicle::From(v)->crashed_ctr = 2000; // max 2220, disappear pretty fast
 
					InvalidateWindowClassesData(WC_ROADVEH_LIST, 0);
 
					break;
 

	
 
				case VEH_AIRCRAFT:
 
					pass += 2; // driver
 
					((Aircraft *)v)->crashed_counter = 9000; // max 10000, disappear pretty fast
 
					Aircraft::From(v)->crashed_counter = 9000; // max 10000, disappear pretty fast
 
					InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0);
 
					break;
 
			}
 
		} else {
 
			return;
 
		}
 

	
 
		InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
 
		InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
 

	
 
		AI::NewEvent(v->owner, new AIEventVehicleCrashed(v->index, v->tile, AIEventVehicleCrashed::CRASH_FLOODED));
 
		SetDParam(0, pass);
src/yapf/follow_track.hpp
Show inline comments
 
@@ -46,46 +46,46 @@ struct CFollowTrackT
 
	}
 

	
 
	FORCEINLINE CFollowTrackT(Owner o, RailTypes railtype_override = INVALID_RAILTYPES, CPerformanceTimer *pPerf = NULL)
 
	{
 
		m_veh = NULL;
 
		Init(o, railtype_override, pPerf);
 
	}
 

	
 
	FORCEINLINE void Init(const Vehicle *v, RailTypes railtype_override, CPerformanceTimer *pPerf)
 
	{
 
		assert(!IsRailTT() || (v != NULL && v->type == VEH_TRAIN));
 
		m_veh = v;
 
		Init(v != NULL ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? ((const Train *)v)->compatible_railtypes : railtype_override, pPerf);
 
		Init(v != NULL ? v->owner : INVALID_OWNER, IsRailTT() && railtype_override == INVALID_RAILTYPES ? Train::From(v)->compatible_railtypes : railtype_override, pPerf);
 
	}
 

	
 
	FORCEINLINE void Init(Owner o, RailTypes railtype_override, CPerformanceTimer *pPerf)
 
	{
 
		assert((!IsRoadTT() || m_veh != NULL) && (!IsRailTT() || railtype_override != INVALID_RAILTYPES));
 
		m_veh_owner = o;
 
		m_pPerf = pPerf;
 
		/* don't worry, all is inlined so compiler should remove unnecessary initializations */
 
		m_new_tile = INVALID_TILE;
 
		m_new_td_bits = TRACKDIR_BIT_NONE;
 
		m_exitdir = INVALID_DIAGDIR;
 
		m_is_station = m_is_bridge = m_is_tunnel = false;
 
		m_tiles_skipped = 0;
 
		m_err = EC_NONE;
 
		m_railtypes = railtype_override;
 
	}
 

	
 
	FORCEINLINE static TransportType TT() {return Ttr_type_;}
 
	FORCEINLINE static bool IsWaterTT() {return TT() == TRANSPORT_WATER;}
 
	FORCEINLINE static bool IsRailTT() {return TT() == TRANSPORT_RAIL;}
 
	FORCEINLINE bool IsTram() {return IsRoadTT() && HasBit(((const RoadVehicle *)m_veh)->compatible_roadtypes, ROADTYPE_TRAM);}
 
	FORCEINLINE bool IsTram() {return IsRoadTT() && HasBit(RoadVehicle::From(m_veh)->compatible_roadtypes, ROADTYPE_TRAM);}
 
	FORCEINLINE static bool IsRoadTT() {return TT() == TRANSPORT_ROAD;}
 
	FORCEINLINE static bool Allow90degTurns() {return T90deg_turns_allowed_;}
 
	FORCEINLINE static bool DoTrackMasking() {return IsRailTT() && Tmask_reserved_tracks;}
 

	
 
	/** Tests if a tile is a road tile with a single tramtrack (tram can reverse) */
 
	FORCEINLINE DiagDirection GetSingleTramBit(TileIndex tile)
 
	{
 
		assert(IsTram()); // this function shouldn't be called in other cases
 

	
 
		if (IsNormalRoadTile(tile)) {
 
			RoadBits rb = GetRoadBits(tile, ROADTYPE_TRAM);
 
			switch (rb) {
 
@@ -97,25 +97,25 @@ struct CFollowTrackT
 
			}
 
		}
 
		return INVALID_DIAGDIR;
 
	}
 

	
 
	/** main follower routine. Fills all members and return true on success.
 
	 *  Otherwise returns false if track can't be followed. */
 
	inline bool Follow(TileIndex old_tile, Trackdir old_td)
 
	{
 
		m_old_tile = old_tile;
 
		m_old_td = old_td;
 
		m_err = EC_NONE;
 
		assert(((TrackStatusToTrackdirBits(GetTileTrackStatus(m_old_tile, TT(), IsRoadTT() && m_veh != NULL ? ((const RoadVehicle *)m_veh)->compatible_roadtypes : 0)) & TrackdirToTrackdirBits(m_old_td)) != 0) ||
 
		assert(((TrackStatusToTrackdirBits(GetTileTrackStatus(m_old_tile, TT(), IsRoadTT() && m_veh != NULL ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0)) & TrackdirToTrackdirBits(m_old_td)) != 0) ||
 
		       (IsTram() && GetSingleTramBit(m_old_tile) != INVALID_DIAGDIR)); // Disable the assertion for single tram bits
 
		m_exitdir = TrackdirToExitdir(m_old_td);
 
		if (ForcedReverse()) return true;
 
		if (!CanExitOldTile()) return false;
 
		FollowTileExit();
 
		if (!QueryNewTileTrackStatus()) return TryReverse();
 
		if (!CanEnterNewTile()) return false;
 
		m_new_td_bits &= DiagdirReachesTrackdirs(m_exitdir);
 
		if (m_new_td_bits == TRACKDIR_BIT_NONE) {
 
			m_err = EC_NO_WAY;
 
			return false;
 
		}
 
@@ -198,25 +198,25 @@ protected:
 
		} else {
 
			m_is_station = false;
 
		}
 
	}
 

	
 
	/** stores track status (available trackdirs) for the new tile into m_new_td_bits */
 
	FORCEINLINE bool QueryNewTileTrackStatus()
 
	{
 
		CPerfStart perf(*m_pPerf);
 
		if (IsRailTT() && IsPlainRailTile(m_new_tile)) {
 
			m_new_td_bits = (TrackdirBits)(GetTrackBits(m_new_tile) * 0x101);
 
		} else {
 
			m_new_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(m_new_tile, TT(), IsRoadTT() && m_veh != NULL ? ((const RoadVehicle *)m_veh)->compatible_roadtypes : 0));
 
			m_new_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(m_new_tile, TT(), IsRoadTT() && m_veh != NULL ? RoadVehicle::From(m_veh)->compatible_roadtypes : 0));
 

	
 
			if (IsTram() && m_new_td_bits == 0) {
 
				/* GetTileTrackStatus() returns 0 for single tram bits.
 
				 * As we cannot change it there (easily) without breaking something, change it here */
 
				switch (GetSingleTramBit(m_new_tile)) {
 
					case DIAGDIR_NE:
 
					case DIAGDIR_SW:
 
						m_new_td_bits = TRACKDIR_BIT_X_NE | TRACKDIR_BIT_X_SW;
 
						break;
 

	
 
					case DIAGDIR_NW:
 
					case DIAGDIR_SE:
src/yapf/yapf_costrail.hpp
Show inline comments
 
@@ -238,26 +238,26 @@ public:
 
				}
 
			}
 
		}
 
		return cost;
 
	}
 

	
 
	FORCEINLINE int PlatformLengthPenalty(int platform_length)
 
	{
 
		int cost = 0;
 
		const Vehicle *v = Yapf().GetVehicle();
 
		assert(v != NULL);
 
		assert(v->type == VEH_TRAIN);
 
		assert(((const Train *)v)->tcache.cached_total_length != 0);
 
		int missing_platform_length = (((const Train *)v)->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE - platform_length;
 
		assert(Train::From(v)->tcache.cached_total_length != 0);
 
		int missing_platform_length = (Train::From(v)->tcache.cached_total_length + TILE_SIZE - 1) / TILE_SIZE - platform_length;
 
		if (missing_platform_length < 0) {
 
			/* apply penalty for longer platform than needed */
 
			cost += Yapf().PfGetSettings().rail_longer_platform_penalty + Yapf().PfGetSettings().rail_longer_platform_per_tile_penalty * -missing_platform_length;
 
		} else if (missing_platform_length > 0) {
 
			/* apply penalty for shorter platform than needed */
 
			cost += Yapf().PfGetSettings().rail_shorter_platform_penalty + Yapf().PfGetSettings().rail_shorter_platform_per_tile_penalty * missing_platform_length;
 
		}
 
		return cost;
 
	}
 

	
 
public:
 
	FORCEINLINE void SetMaxCost(int max_cost)
src/yapf/yapf_destrail.hpp
Show inline comments
 
@@ -4,26 +4,26 @@
 

	
 
#ifndef  YAPF_DESTRAIL_HPP
 
#define  YAPF_DESTRAIL_HPP
 

	
 
class CYapfDestinationRailBase
 
{
 
protected:
 
	RailTypes m_compatible_railtypes;
 

	
 
public:
 
	void SetDestination(const Vehicle *v, bool override_rail_type = false)
 
	{
 
		m_compatible_railtypes = ((const Train *)v)->compatible_railtypes;
 
		if (override_rail_type) m_compatible_railtypes |= GetRailTypeInfo(((const Train *)v)->railtype)->compatible_railtypes;
 
		m_compatible_railtypes = Train::From(v)->compatible_railtypes;
 
		if (override_rail_type) m_compatible_railtypes |= GetRailTypeInfo(Train::From(v)->railtype)->compatible_railtypes;
 
	}
 

	
 
	bool IsCompatibleRailType(RailType rt)
 
	{
 
		return HasBit(m_compatible_railtypes, rt);
 
	}
 

	
 
	RailTypes GetCompatibleRailTypes() const
 
	{
 
		return m_compatible_railtypes;
 
	}
 
};
 
@@ -82,26 +82,26 @@ public:
 
	}
 

	
 
	/** Called by YAPF to detect if node ends in the desired destination */
 
	FORCEINLINE bool PfDetectDestination(Node& n)
 
	{
 
		return PfDetectDestination(n.GetLastTile(), n.GetLastTrackdir());
 
	}
 

	
 
	/** Called by YAPF to detect if node ends in the desired destination */
 
	FORCEINLINE bool PfDetectDestination(TileIndex tile, Trackdir td)
 
	{
 
		return
 
			IsSafeWaitingPosition((const Train *)Yapf().GetVehicle(), tile, td, true, !TrackFollower::Allow90degTurns()) &&
 
			IsWaitingPositionFree((const Train *)Yapf().GetVehicle(), tile, td, !TrackFollower::Allow90degTurns());
 
			IsSafeWaitingPosition(Train::From(Yapf().GetVehicle()), tile, td, true, !TrackFollower::Allow90degTurns()) &&
 
			IsWaitingPositionFree(Train::From(Yapf().GetVehicle()), tile, td, !TrackFollower::Allow90degTurns());
 
	}
 

	
 
	/** Called by YAPF to calculate cost estimate. Calculates distance to the destination
 
	 *  adds it to the actual cost from origin and stores the sum to the Node::m_estimate. */
 
	FORCEINLINE bool PfCalcEstimate(Node& n)
 
	{
 
		n.m_estimate = n.m_cost;
 
		return true;
 
	}
 
};
 

	
 
template <class Types>
src/yapf/yapf_rail.cpp
Show inline comments
 
@@ -45,25 +45,25 @@ protected:
 
		return *static_cast<Tpf*>(this);
 
	}
 

	
 
private:
 
	TileIndex m_res_dest;         ///< The reservation target tile
 
	Trackdir  m_res_dest_td;      ///< The reservation target trackdir
 
	Node      *m_res_node;        ///< The reservation target node
 
	TileIndex m_res_fail_tile;    ///< The tile where the reservation failed
 
	Trackdir  m_res_fail_td;      ///< The trackdir where the reservation failed
 

	
 
	bool FindSafePositionProc(TileIndex tile, Trackdir td)
 
	{
 
		if (IsSafeWaitingPosition((const Train *)Yapf().GetVehicle(), tile, td, true, !TrackFollower::Allow90degTurns())) {
 
		if (IsSafeWaitingPosition(Train::From(Yapf().GetVehicle()), tile, td, true, !TrackFollower::Allow90degTurns())) {
 
			m_res_dest = tile;
 
			m_res_dest_td = td;
 
			return false;   // Stop iterating segment
 
		}
 
		return true;
 
	}
 

	
 
	/** Reserve a railway platform. Tile contains the failed tile on abort. */
 
	bool ReserveRailwayStationPlatform(TileIndex &tile, DiagDirection dir)
 
	{
 
		TileIndex     start = tile;
 
		TileIndexDiff diff = TileOffsByDiagDir(dir);
 
@@ -140,25 +140,25 @@ public:
 
	/** Try to reserve the path till the reservation target. */
 
	bool TryReservePath(PBSTileInfo *target)
 
	{
 
		m_res_fail_tile = INVALID_TILE;
 

	
 
		if (target != NULL) {
 
			target->tile = m_res_dest;
 
			target->trackdir = m_res_dest_td;
 
			target->okay = false;
 
		}
 

	
 
		/* Don't bother if the target is reserved. */
 
		if (!IsWaitingPositionFree((const Train *)Yapf().GetVehicle(), m_res_dest, m_res_dest_td)) return false;
 
		if (!IsWaitingPositionFree(Train::From(Yapf().GetVehicle()), m_res_dest, m_res_dest_td)) return false;
 

	
 
		for (Node *node = m_res_node; node->m_parent != NULL; node = node->m_parent) {
 
			node->IterateTiles(Yapf().GetVehicle(), Yapf(), *this, &CYapfReserveTrack<Types>::ReserveSingleTrack);
 
			if (m_res_fail_tile != INVALID_TILE) {
 
				/* Reservation failed, undo. */
 
				Node *fail_node = m_res_node;
 
				TileIndex stop_tile = m_res_fail_tile;
 
				do {
 
					/* If this is the node that failed, stop at the failed tile. */
 
					m_res_fail_tile = fail_node == node ? stop_tile : INVALID_TILE;
 
					fail_node->IterateTiles(Yapf().GetVehicle(), Yapf(), *this, &CYapfReserveTrack<Types>::UnreserveSingleTrack);
 
				} while (fail_node != node && (fail_node = fail_node->m_parent) != NULL);
 
@@ -402,25 +402,25 @@ public:
 
			DumpState(pf1, pf2);
 
		}
 
#endif
 

	
 
		return result1;
 
	}
 

	
 
	FORCEINLINE Trackdir ChooseRailTrack(const Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks, bool *path_not_found, bool reserve_track, PBSTileInfo *target)
 
	{
 
		if (target != NULL) target->tile = INVALID_TILE;
 

	
 
		/* set origin and destination nodes */
 
		PBSTileInfo origin = FollowTrainReservation((const Train *)v);
 
		PBSTileInfo origin = FollowTrainReservation(Train::From(v));
 
		Yapf().SetOrigin(origin.tile, origin.trackdir, INVALID_TILE, INVALID_TRACKDIR, 1, true);
 
		Yapf().SetDestination(v);
 

	
 
		/* find the best path */
 
		bool path_found = Yapf().FindPath(v);
 
		if (path_not_found != NULL) {
 
			/* tell controller that the path was only 'guessed'
 
			 * treat the path as found if stopped on the first two way signal(s) */
 
			*path_not_found = !(path_found || Yapf().m_stopped_on_first_two_way_signal);
 
		}
 

	
 
		/* if path not found - return INVALID_TRACKDIR */
 
@@ -527,27 +527,27 @@ Trackdir YapfChooseRailTrack(const Vehic
 
	/* check if non-default YAPF type needed */
 
	if (_settings_game.pf.forbid_90_deg) {
 
		pfnChooseRailTrack = &CYapfRail2::stChooseRailTrack; // Trackdir, forbid 90-deg
 
	}
 

	
 
	Trackdir td_ret = pfnChooseRailTrack(v, tile, enterdir, tracks, path_not_found, reserve_track, target);
 

	
 
	return td_ret;
 
}
 

	
 
bool YapfCheckReverseTrain(const Vehicle *vt)
 
{
 
	const Train *v = (const Train *)vt;
 
	const Train *v = Train::From(vt);
 
	/* last wagon */
 
	const Train *last_veh = (const Train *)GetLastVehicleInChain(v);
 
	const Train *last_veh = Train::From(GetLastVehicleInChain(v));
 

	
 
	/* get trackdirs of both ends */
 
	Trackdir td = v->GetVehicleTrackdir();
 
	Trackdir td_rev = ReverseTrackdir(last_veh->GetVehicleTrackdir());
 

	
 
	/* tiles where front and back are */
 
	TileIndex tile = v->tile;
 
	TileIndex tile_rev = last_veh->tile;
 

	
 
	int reverse_penalty = 0;
 

	
 
	if (v->track == TRACK_BIT_WORMHOLE) {
 
@@ -593,25 +593,25 @@ bool YapfCheckReverseTrain(const Vehicle
 
	bool reverse = pfnCheckReverseTrain(v, tile, td, tile_rev, td_rev, reverse_penalty);
 

	
 
	return reverse;
 
}
 

	
 
bool YapfFindNearestRailDepotTwoWay(const Vehicle *v, int max_distance, int reverse_penalty, TileIndex *depot_tile, bool *reversed)
 
{
 
	*depot_tile = INVALID_TILE;
 
	*reversed = false;
 

	
 
	const Vehicle *last_veh = GetLastVehicleInChain(v);
 

	
 
	PBSTileInfo origin = FollowTrainReservation((const Train *)v);
 
	PBSTileInfo origin = FollowTrainReservation(Train::From(v));
 
	TileIndex last_tile = last_veh->tile;
 
	Trackdir td_rev = ReverseTrackdir(last_veh->GetVehicleTrackdir());
 

	
 
	typedef bool (*PfnFindNearestDepotTwoWay)(const Vehicle*, TileIndex, Trackdir, TileIndex, Trackdir, int, int, TileIndex*, bool*);
 
	PfnFindNearestDepotTwoWay pfnFindNearestDepotTwoWay = &CYapfAnyDepotRail1::stFindNearestDepotTwoWay;
 

	
 
	/* check if non-default YAPF type needed */
 
	if (_settings_game.pf.forbid_90_deg) {
 
		pfnFindNearestDepotTwoWay = &CYapfAnyDepotRail2::stFindNearestDepotTwoWay; // Trackdir, forbid 90-deg
 
	}
 

	
 
	bool ret = pfnFindNearestDepotTwoWay(v, origin.tile, origin.trackdir, last_tile, td_rev, max_distance, reverse_penalty, depot_tile, reversed);
src/yapf/yapf_road.cpp
Show inline comments
 
@@ -290,31 +290,31 @@ public:
 
	}
 

	
 
	FORCEINLINE Trackdir ChooseRoadTrack(const Vehicle *v, TileIndex tile, DiagDirection enterdir)
 
	{
 
		/* handle special case - when next tile is destination tile */
 
		if (tile == v->dest_tile) {
 
			/* choose diagonal trackdir reachable from enterdir */
 
			return DiagDirToDiagTrackdir(enterdir);
 
		}
 
		/* our source tile will be the next vehicle tile (should be the given one) */
 
		TileIndex src_tile = tile;
 
		/* get available trackdirs on the start tile */
 
		TrackdirBits src_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, ((const RoadVehicle *)v)->compatible_roadtypes));
 
		TrackdirBits src_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, RoadVehicle::From(v)->compatible_roadtypes));
 
		/* select reachable trackdirs only */
 
		src_trackdirs &= DiagdirReachesTrackdirs(enterdir);
 

	
 
		/* get available trackdirs on the destination tile */
 
		TileIndex dest_tile = v->dest_tile;
 
		TrackdirBits dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(dest_tile, TRANSPORT_ROAD, ((const RoadVehicle *)v)->compatible_roadtypes));
 
		TrackdirBits dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(dest_tile, TRANSPORT_ROAD, RoadVehicle::From(v)->compatible_roadtypes));
 

	
 
		/* set origin and destination nodes */
 
		Yapf().SetOrigin(src_tile, src_trackdirs);
 
		Yapf().SetDestination(dest_tile, dest_trackdirs);
 

	
 
		/* find the best path */
 
		Yapf().FindPath(v);
 

	
 
		/* if path not found - return INVALID_TRACKDIR */
 
		Trackdir next_trackdir = INVALID_TRACKDIR;
 
		Node *pNode = Yapf().GetBestNode();
 
		if (pNode != NULL) {
 
@@ -340,50 +340,50 @@ public:
 
	FORCEINLINE uint DistanceToTile(const Vehicle *v, TileIndex dst_tile)
 
	{
 
		/* handle special case - when current tile is the destination tile */
 
		if (dst_tile == v->tile) {
 
			/* distance is zero in this case */
 
			return 0;
 
		}
 

	
 
		if (!SetOriginFromVehiclePos(v)) return UINT_MAX;
 

	
 
		/* set destination tile, trackdir
 
		 *   get available trackdirs on the destination tile */
 
		TrackdirBits dst_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, TRANSPORT_ROAD, ((const RoadVehicle *)v)->compatible_roadtypes));
 
		TrackdirBits dst_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, TRANSPORT_ROAD, RoadVehicle::From(v)->compatible_roadtypes));
 
		Yapf().SetDestination(dst_tile, dst_td_bits);
 

	
 
		/* if path not found - return distance = UINT_MAX */
 
		uint dist = UINT_MAX;
 

	
 
		/* find the best path */
 
		if (!Yapf().FindPath(v)) return dist;
 

	
 
		Node *pNode = Yapf().GetBestNode();
 
		if (pNode != NULL) {
 
			/* path was found
 
			 * get the path cost estimate */
 
			dist = pNode->GetCostEstimate();
 
		}
 

	
 
		return dist;
 
	}
 

	
 
	/** Return true if the valid origin (tile/trackdir) was set from the current vehicle position. */
 
	FORCEINLINE bool SetOriginFromVehiclePos(const Vehicle *v)
 
	{
 
		/* set origin (tile, trackdir) */
 
		TileIndex src_tile = v->tile;
 
		Trackdir src_td = v->GetVehicleTrackdir();
 
		if ((TrackStatusToTrackdirBits(GetTileTrackStatus(src_tile, TRANSPORT_ROAD, ((const RoadVehicle *)v)->compatible_roadtypes)) & TrackdirToTrackdirBits(src_td)) == 0) {
 
		if ((TrackStatusToTrackdirBits(GetTileTrackStatus(src_tile, TRANSPORT_ROAD, RoadVehicle::From(v)->compatible_roadtypes)) & TrackdirToTrackdirBits(src_td)) == 0) {
 
			/* sometimes the roadveh is not on the road (it resides on non-existing track)
 
			 * how should we handle that situation? */
 
			return false;
 
		}
 
		Yapf().SetOrigin(src_tile, TrackdirToTrackdirBits(src_td));
 
		return true;
 
	}
 

	
 
	static Depot *stFindNearestDepot(const Vehicle *v, TileIndex tile, Trackdir td)
 
	{
 
		Tpf pf;
 
		return pf.FindNearestDepot(v, tile, td);
 
@@ -462,25 +462,25 @@ uint YapfRoadVehDistanceToTile(const Veh
 
	/* convert distance to tiles */
 
	if (dist != UINT_MAX) {
 
		dist = (dist + YAPF_TILE_LENGTH - 1) / YAPF_TILE_LENGTH;
 
	}
 

	
 
	return dist;
 
}
 

	
 
Depot *YapfFindNearestRoadDepot(const Vehicle *v)
 
{
 
	TileIndex tile = v->tile;
 
	Trackdir trackdir = v->GetVehicleTrackdir();
 
	if ((TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, ((const RoadVehicle *)v)->compatible_roadtypes)) & TrackdirToTrackdirBits(trackdir)) == 0) {
 
	if ((TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, RoadVehicle::From(v)->compatible_roadtypes)) & TrackdirToTrackdirBits(trackdir)) == 0) {
 
		return NULL;
 
	}
 

	
 
	/* handle the case when our vehicle is already in the depot tile */
 
	if (IsRoadDepotTile(tile)) {
 
		/* only what we need to return is the Depot* */
 
		return GetDepotByTile(tile);
 
	}
 

	
 
	/* default is YAPF type 2 */
 
	typedef Depot *(*PfnFindNearestDepot)(const Vehicle*, TileIndex, Trackdir);
 
	PfnFindNearestDepot pfnFindNearestDepot = &CYapfRoadAnyDepot2::stFindNearestDepot;
0 comments (0 inline, 0 general)