File diff r12647:3ada08b745f5 → r12648:24c912bd53f6
src/economy.cpp
Show inline comments
 
@@ -139,389 +139,391 @@ Money CalculateCompanyValue(const Compan
 
}
 

	
 
/** if update is set to true, the economy is updated with this score
 
 *  (also the house is updated, should only be true in the on-tick event)
 
 * @param update the economy with calculated score
 
 * @param c company been evaluated
 
 * @return actual score of this company
 
 * */
 
int UpdateCompanyRatingAndValue(Company *c, bool update)
 
{
 
	Owner owner = c->index;
 
	int score = 0;
 

	
 
	memset(_score_part[owner], 0, sizeof(_score_part[owner]));
 

	
 
	/* Count vehicles */
 
	{
 
		Vehicle *v;
 
		Money min_profit = 0;
 
		bool min_profit_first = true;
 
		uint num = 0;
 

	
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->owner != owner) continue;
 
			if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) {
 
				num++;
 
				if (v->age > 730) {
 
					/* Find the vehicle with the lowest amount of profit */
 
					if (min_profit_first || min_profit > v->profit_last_year) {
 
						min_profit = v->profit_last_year;
 
						min_profit_first = false;
 
					}
 
				}
 
			}
 
		}
 

	
 
		min_profit >>= 8; // remove the fract part
 

	
 
		_score_part[owner][SCORE_VEHICLES] = num;
 
		/* Don't allow negative min_profit to show */
 
		if (min_profit > 0)
 
			_score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit);
 
	}
 

	
 
	/* Count stations */
 
	{
 
		uint num = 0;
 
		const Station *st;
 

	
 
		FOR_ALL_STATIONS(st) {
 
			if (st->owner == owner) num += CountBits((byte)st->facilities);
 
		}
 
		_score_part[owner][SCORE_STATIONS] = num;
 
	}
 

	
 
	/* Generate statistics depending on recent income statistics */
 
	{
 
		int numec = min(c->num_valid_stat_ent, 12);
 
		if (numec != 0) {
 
			const CompanyEconomyEntry *cee = c->old_economy;
 
			Money min_income = cee->income + cee->expenses;
 
			Money max_income = cee->income + cee->expenses;
 

	
 
			do {
 
				min_income = min(min_income, cee->income + cee->expenses);
 
				max_income = max(max_income, cee->income + cee->expenses);
 
			} while (++cee, --numec);
 

	
 
			if (min_income > 0) {
 
				_score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income);
 
			}
 

	
 
			_score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income);
 
		}
 
	}
 

	
 
	/* Generate score depending on amount of transported cargo */
 
	{
 
		const CompanyEconomyEntry *cee;
 
		int numec;
 
		uint32 total_delivered;
 

	
 
		numec = min(c->num_valid_stat_ent, 4);
 
		if (numec != 0) {
 
			cee = c->old_economy;
 
			total_delivered = 0;
 
			do {
 
				total_delivered += cee->delivered_cargo;
 
			} while (++cee, --numec);
 

	
 
			_score_part[owner][SCORE_DELIVERED] = total_delivered;
 
		}
 
	}
 

	
 
	/* Generate score for variety of cargo */
 
	{
 
		uint num = CountBits(c->cargo_types);
 
		_score_part[owner][SCORE_CARGO] = num;
 
		if (update) c->cargo_types = 0;
 
	}
 

	
 
	/* Generate score for company's money */
 
	{
 
		if (c->money > 0) {
 
			_score_part[owner][SCORE_MONEY] = ClampToI32(c->money);
 
		}
 
	}
 

	
 
	/* Generate score for loan */
 
	{
 
		_score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan);
 
	}
 

	
 
	/* Now we calculate the score for each item.. */
 
	{
 
		int total_score = 0;
 
		int s;
 
		score = 0;
 
		for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) {
 
			/* Skip the total */
 
			if (i == SCORE_TOTAL) continue;
 
			/*  Check the score */
 
			s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed;
 
			score += s;
 
			total_score += _score_info[i].score;
 
		}
 

	
 
		_score_part[owner][SCORE_TOTAL] = score;
 

	
 
		/*  We always want the score scaled to SCORE_MAX (1000) */
 
		if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score;
 
	}
 

	
 
	if (update) {
 
		c->old_economy[0].performance_history = score;
 
		UpdateCompanyHQ(c, score);
 
		c->old_economy[0].company_value = CalculateCompanyValue(c);
 
	}
 

	
 
	InvalidateWindow(WC_PERFORMANCE_DETAIL, 0);
 
	return score;
 
}
 

	
 
/*  use INVALID_OWNER as new_owner to delete the company. */
 
void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner)
 
{
 
	Town *t;
 
	CompanyID old = _current_company;
 

	
 
	assert(old_owner != new_owner);
 

	
 
	{
 
		Company *c;
 
		uint i;
 

	
 
		/* See if the old_owner had shares in other companies */
 
		_current_company = old_owner;
 
		FOR_ALL_COMPANIES(c) {
 
			for (i = 0; i < 4; i++) {
 
				if (c->share_owners[i] == old_owner) {
 
					/* Sell his shares */
 
					CommandCost res = DoCommand(0, c->index, 0, DC_EXEC, CMD_SELL_SHARE_IN_COMPANY);
 
					/* Because we are in a DoCommand, we can't just execute an other one and
 
					 *  expect the money to be removed. We need to do it ourself! */
 
					SubtractMoneyFromCompany(res);
 
				}
 
			}
 
		}
 

	
 
		/* Sell all the shares that people have on this company */
 
		c = Company::Get(old_owner);
 
		for (i = 0; i < 4; i++) {
 
			_current_company = c->share_owners[i];
 
			if (_current_company != INVALID_OWNER) {
 
				/* Sell the shares */
 
				CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC, CMD_SELL_SHARE_IN_COMPANY);
 
				/* Because we are in a DoCommand, we can't just execute an other one and
 
				 *  expect the money to be removed. We need to do it ourself! */
 
				SubtractMoneyFromCompany(res);
 
			}
 
		}
 
	}
 

	
 
	_current_company = old_owner;
 

	
 
	/* Temporarily increase the company's money, to be sure that
 
	 * removing his/her property doesn't fail because of lack of money.
 
	 * Not too drastically though, because it could overflow */
 
	if (new_owner == INVALID_OWNER) {
 
		Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p
 
	}
 

	
 
	if (new_owner == INVALID_OWNER) {
 
		Subsidy *s;
 
		FOR_ALL_SUBSIDIES(s) {
 
			if (s->IsAwarded() && Station::Get(s->dst)->owner == old_owner) {
 
				s->cargo_type = CT_INVALID;
 
	Subsidy *s;
 
	FOR_ALL_SUBSIDIES(s) {
 
		if (s->awarded == old_owner) {
 
			if (new_owner == INVALID_OWNER) {
 
				DeleteSubsidy(s);
 
			} else {
 
				s->awarded = new_owner;
 
			}
 
		}
 
	}
 

	
 
	/* Take care of rating in towns */
 
	FOR_ALL_TOWNS(t) {
 
		/* If a company takes over, give the ratings to that company. */
 
		if (new_owner != INVALID_OWNER) {
 
			if (HasBit(t->have_ratings, old_owner)) {
 
				if (HasBit(t->have_ratings, new_owner)) {
 
					/* use max of the two ratings. */
 
					t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]);
 
				} else {
 
					SetBit(t->have_ratings, new_owner);
 
					t->ratings[new_owner] = t->ratings[old_owner];
 
				}
 
			}
 
		}
 

	
 
		/* Reset the ratings for the old owner */
 
		t->ratings[old_owner] = RATING_INITIAL;
 
		ClrBit(t->have_ratings, old_owner);
 
	}
 

	
 
	{
 
		FreeUnitIDGenerator unitidgen[] = {
 
			FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD,     new_owner),
 
			FreeUnitIDGenerator(VEH_SHIP,  new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner)
 
		};
 

	
 
		Vehicle *v;
 
		FOR_ALL_VEHICLES(v) {
 
			if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) {
 
				if (new_owner == INVALID_OWNER) {
 
					if (v->Previous() == NULL) delete v;
 
				} else {
 
					v->owner = new_owner;
 
					v->colourmap = PAL_NONE;
 
					if (v->IsEngineCountable()) Company::Get(new_owner)->num_engines[v->engine_type]++;
 
					if (v->IsPrimaryVehicle()) v->unitnumber = unitidgen[v->type].NextID();
 
				}
 
			}
 
		}
 
	}
 

	
 
	/*  Change ownership of tiles */
 
	{
 
		TileIndex tile = 0;
 
		do {
 
			ChangeTileOwner(tile, old_owner, new_owner);
 
		} while (++tile != MapSize());
 

	
 
		if (new_owner != INVALID_OWNER) {
 
			/* Update all signals because there can be new segment that was owned by two companies
 
			 * and signals were not propagated
 
			 * Similiar with crossings - it is needed to bar crossings that weren't before
 
			 * because of different owner of crossing and approaching train */
 
			tile = 0;
 

	
 
			do {
 
				if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) {
 
					TrackBits tracks = GetTrackBits(tile);
 
					do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT
 
						Track track = RemoveFirstTrack(&tracks);
 
						if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner);
 
					} while (tracks != TRACK_BIT_NONE);
 
				} else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) {
 
					UpdateLevelCrossing(tile);
 
				}
 
			} while (++tile != MapSize());
 
		}
 

	
 
		/* update signals in buffer */
 
		UpdateSignalsInBuffer();
 
	}
 

	
 
	/* convert owner of stations (including deleted ones, but excluding buoys) */
 
	Station *st;
 
	FOR_ALL_STATIONS(st) {
 
		if (st->owner == old_owner) {
 
			/* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately
 
			 * also, drawing station window would cause reading invalid company's colour */
 
			st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
 
		}
 
	}
 

	
 
	/* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */
 
	Waypoint *wp;
 
	FOR_ALL_WAYPOINTS(wp) {
 
		if (wp->owner == old_owner) {
 
			wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
 
		}
 
	}
 

	
 
	/* In all cases clear replace engine rules.
 
	 * Even if it was copied, it could interfere with new owner's rules */
 
	RemoveAllEngineReplacementForCompany(Company::Get(old_owner));
 

	
 
	if (new_owner == INVALID_OWNER) {
 
		RemoveAllGroupsForCompany(old_owner);
 
	} else {
 
		Group *g;
 
		FOR_ALL_GROUPS(g) {
 
			if (g->owner == old_owner) g->owner = new_owner;
 
		}
 
	}
 

	
 
	Sign *si;
 
	FOR_ALL_SIGNS(si) {
 
		if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner;
 
	}
 

	
 
	/* Change colour of existing windows */
 
	if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner);
 

	
 
	_current_company = old;
 

	
 
	MarkWholeScreenDirty();
 
}
 

	
 
static void ChangeNetworkOwner(Owner current_owner, Owner new_owner)
 
{
 
#ifdef ENABLE_NETWORK
 
	if (!_networking) return;
 

	
 
	if (current_owner == _local_company) {
 
		SetLocalCompany(new_owner);
 
	}
 

	
 
	if (!_network_server) return;
 

	
 
	NetworkServerChangeOwner(current_owner, new_owner);
 
#endif /* ENABLE_NETWORK */
 
}
 

	
 
static void CompanyCheckBankrupt(Company *c)
 
{
 
	/*  If the company has money again, it does not go bankrupt */
 
	if (c->money >= 0) {
 
		c->quarters_of_bankrupcy = 0;
 
		return;
 
	}
 

	
 
	c->quarters_of_bankrupcy++;
 

	
 
	CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1);
 
	cni->FillData(c);
 

	
 
	switch (c->quarters_of_bankrupcy) {
 
		case 0:
 
		case 1:
 
			free(cni);
 
			break;
 

	
 
		case 2:
 
			SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
 
			SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
 
			SetDParamStr(2, cni->company_name);
 
			AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_TROUBLE, cni);
 
			AI::BroadcastNewEvent(new AIEventCompanyInTrouble(c->index));
 
			break;
 
		case 3: {
 
			/* XXX - In multiplayer, should we ask other companies if it wants to take
 
		          over when it is a human company? -- TrueLight */
 
			if (!c->is_ai) {
 
				SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE);
 
				SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION);
 
				SetDParamStr(2, cni->company_name);
 
				AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, NS_COMPANY_TROUBLE, cni);
 
				break;
 
			}
 

	
 
			/* Check if the company has any value.. if not, declare it bankrupt
 
			 *  right now */
 
			Money val = CalculateCompanyValue(c);
 
			if (val > 0) {
 
				c->bankrupt_value = val;
 
				c->bankrupt_asked = 1 << c->index; // Don't ask the owner
 
				c->bankrupt_timeout = 0;
 
				free(cni);
 
				break;
 
			}
 
			/* Else, falltrue to case 4... */
 
		}
 
		default:
 
		case 4:
 
			if (!_networking && _local_company == c->index) {
 
				/* If we are in offline mode, leave the company playing. Eg. there
 
				 * is no THE-END, otherwise mark the client as spectator to make sure
 
				 * he/she is no long in control of this company. However... when you
 
				 * join another company (cheat) the "unowned" company can bankrupt. */
 
				c->bankrupt_asked = MAX_UVALUE(CompanyMask);
 
@@ -727,520 +729,513 @@ void StartupIndustryDailyChanges(bool in
 
	 * on the overall total number of changes performed */
 
	_economy.industry_daily_increment = (1 << map_size) / 31;
 

	
 
	if (init_counter) {
 
		/* A new game or a savegame from an older version will require the counter to be initialized */
 
		_economy.industry_daily_change_counter = 0;
 
	}
 
}
 

	
 
void StartupEconomy()
 
{
 
	int i;
 

	
 
	assert(sizeof(_price) == NUM_PRICES * sizeof(Money));
 

	
 
	/* Setup price bases */
 
	for (i = 0; i < NUM_PRICES; i++) {
 
		Money price = _price_base_specs[i].start_price;
 

	
 
		/* Apply difficulty settings */
 
		uint mod = 1;
 
		switch (_price_base_specs[i].category) {
 
			case PCAT_RUNNING:
 
				mod = _settings_game.difficulty.vehicle_costs;
 
				break;
 

	
 
			case PCAT_CONSTRUCTION:
 
				mod = _settings_game.difficulty.construction_cost;
 
				break;
 

	
 
			default: break;
 
		}
 
		if (mod < 1) {
 
			price = price * 3 >> 2;
 
		} else if (mod > 1) {
 
			price = price * 9 >> 3;
 
		}
 

	
 
		/* Apply newgrf modifiers */
 
		if (price_base_multiplier[i] > 8) {
 
			price <<= price_base_multiplier[i] - 8;
 
		} else {
 
			price >>= 8 - price_base_multiplier[i];
 
		}
 

	
 
		/* Store start value */
 
		((Money*)&_price)[i] = price;
 
		_price_frac[i] = 0;
 
	}
 

	
 
	_economy.interest_rate = _settings_game.difficulty.initial_interest;
 
	_economy.infl_amount = _settings_game.difficulty.initial_interest;
 
	_economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1);
 
	_economy.max_loan_unround = _economy.max_loan = _settings_game.difficulty.max_loan;
 
	_economy.fluct = GB(Random(), 0, 8) + 168;
 

	
 
	StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too
 

	
 
}
 

	
 
void ResetEconomy()
 
{
 
	/* Test if resetting the economy is needed. */
 
	bool needed = false;
 

	
 
	const CargoSpec *cs;
 
	FOR_ALL_CARGOSPECS(cs) {
 
		if (_cargo_payment_rates[cs->Index()] == 0) {
 
			needed = true;
 
			break;
 
		}
 
	}
 

	
 
	if (!needed) return;
 

	
 
	/* Remember old unrounded maximum loan value. NewGRF has the ability
 
	 * to change all the other inflation affected base costs. */
 
	Money old_value = _economy.max_loan_unround;
 

	
 
	/* Reset the economy */
 
	StartupEconomy();
 
	InitializeLandscapeVariables(false);
 

	
 
	/* Reapply inflation, ignoring the year */
 
	while (old_value > _economy.max_loan_unround) {
 
		AddInflation(false);
 
	}
 
}
 

	
 
Money GetPriceByIndex(uint8 index)
 
{
 
	if (index > NUM_PRICES) return 0;
 

	
 
	return ((Money*)&_price)[index];
 
}
 

	
 
Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type)
 
{
 
	const CargoSpec *cs = CargoSpec::Get(cargo_type);
 

	
 
	/* Use callback to calculate cargo profit, if available */
 
	if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) {
 
		uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24);
 
		uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs);
 
		if (callback != CALLBACK_FAILED) {
 
			int result = GB(callback, 0, 14);
 

	
 
			/* Simulate a 15 bit signed value */
 
			if (HasBit(callback, 14)) result = 0x4000 - result;
 

	
 
			/* "The result should be a signed multiplier that gets multiplied
 
			 * by the amount of cargo moved and the price factor, then gets
 
			 * divided by 8192." */
 
			return result * num_pieces * _cargo_payment_rates[cargo_type] / 8192;
 
		}
 
	}
 

	
 
	/* zero the distance (thus income) if it's the bank and very short transport. */
 
	if (_settings_game.game_creation.landscape == LT_TEMPERATE && cs->label == 'VALU' && dist < 10) return 0;
 

	
 

	
 
	static const int MIN_TIME_FACTOR = 31;
 
	static const int MAX_TIME_FACTOR = 255;
 

	
 
	const int days1 = cs->transit_days[0];
 
	const int days2 = cs->transit_days[1];
 
	const int days_over_days1 = max(   transit_days - days1, 0);
 
	const int days_over_days2 = max(days_over_days1 - days2, 0);
 

	
 
	/*
 
	 * The time factor is calculated based on the time it took
 
	 * (transit_days) compared two cargo-depending values. The
 
	 * range is divided into three parts:
 
	 *
 
	 *  - constant for fast transits
 
	 *  - linear decreasing with time with a slope of -1 for medium transports
 
	 *  - linear decreasing with time with a slope of -2 for slow transports
 
	 *
 
	 */
 
	const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR);
 

	
 
	return BigMulS(dist * time_factor * num_pieces, _cargo_payment_rates[cargo_type], 21);
 
}
 

	
 
/** The industries we've currently brought cargo to. */
 
static SmallIndustryList _cargo_delivery_destinations;
 

	
 
/**
 
 * Transfer goods from station to industry.
 
 * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo.
 
 * @param st The station that accepted the cargo
 
 * @param cargo_type Type of cargo delivered
 
 * @param nun_pieces Amount of cargo delivered
 
 */
 
static void DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, int num_pieces)
 
{
 
	/* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo.
 
	 * This fails in three cases:
 
	 *  1) The station accepts the cargo because there are enough houses around it accepting the cargo.
 
	 *  2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance.
 
	 *  3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour)
 
	 */
 

	
 
	for (uint i = 0; i < st->industries_near.Length(); i++) {
 
		Industry *ind = st->industries_near[i];
 
		const IndustrySpec *indspec = GetIndustrySpec(ind->type);
 

	
 
		uint cargo_index;
 
		for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
 
			if (cargo_type == ind->accepts_cargo[cargo_index]) break;
 
		}
 
		/* Check if matching cargo has been found */
 
		if (cargo_index >= lengthof(ind->accepts_cargo)) continue;
 

	
 
		/* Check if industry temporarily refuses acceptance */
 
		if (HasBit(indspec->callback_flags, CBM_IND_REFUSE_CARGO)) {
 
			uint16 res = GetIndustryCallback(CBID_INDUSTRY_REFUSE_CARGO, 0, GetReverseCargoTranslation(cargo_type, indspec->grf_prop.grffile), ind, ind->type, ind->xy);
 
			if (res == 0) continue;
 
		}
 

	
 
		/* Insert the industry into _cargo_delivery_destinations, if not yet contained */
 
		_cargo_delivery_destinations.Include(ind);
 

	
 
		ind->incoming_cargo_waiting[cargo_index] = min(num_pieces + ind->incoming_cargo_waiting[cargo_index], 0xFFFF);
 

	
 
		return;
 
	}
 
}
 

	
 
/**
 
 * Delivers goods to industries/towns and calculates the payment
 
 * @param num_pieces amount of cargo delivered
 
 * @param source Originstation of the cargo
 
 * @param dest Station the cargo has been unloaded
 
 * @param source_tile The origin of the cargo for distance calculation
 
 * @param days_in_transit Travel time
 
 * @param company The company delivering the cargo
 
 * The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery
 
 * @param src_type Type of source of cargo (industry, town, headquarters)
 
 * @param src Index of source of cargo
 
 * @return Revenue for delivering cargo
 
 * @note The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery
 
 */
 
static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID source, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company)
 
static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src)
 
{
 
	bool subsidised = false;
 

	
 
	assert(num_pieces > 0);
 

	
 
	/* Update company statistics */
 
	company->cur_economy.delivered_cargo += num_pieces;
 
	SetBit(company->cargo_types, cargo_type);
 

	
 
	const Station *s_to = Station::Get(dest);
 

	
 
	if (source != INVALID_STATION) {
 
		const Station *s_from = Station::Get(source);
 

	
 
		/* Check if a subsidy applies. */
 
		subsidised = CheckSubsidised(s_from, s_to, cargo_type, company->index);
 
	}
 
	const Station *st = Station::Get(dest);
 

	
 
	/* Increase town's counter for some special goods types */
 
	const CargoSpec *cs = CargoSpec::Get(cargo_type);
 
	if (cs->town_effect == TE_FOOD) s_to->town->new_act_food += num_pieces;
 
	if (cs->town_effect == TE_WATER) s_to->town->new_act_water += num_pieces;
 
	if (cs->town_effect == TE_FOOD) st->town->new_act_food += num_pieces;
 
	if (cs->town_effect == TE_WATER) st->town->new_act_water += num_pieces;
 

	
 
	/* Give the goods to the industry. */
 
	DeliverGoodsToIndustry(s_to, cargo_type, num_pieces);
 
	DeliverGoodsToIndustry(st, cargo_type, num_pieces);
 

	
 
	/* Determine profit */
 
	Money profit = GetTransportedGoodsIncome(num_pieces, DistanceManhattan(source_tile, s_to->xy), days_in_transit, cargo_type);
 
	Money profit = GetTransportedGoodsIncome(num_pieces, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type);
 

	
 
	/* Modify profit if a subsidy is in effect */
 
	if (subsidised) {
 
	if (CheckSubsidised(cargo_type, company->index, src_type, src, st))  {
 
		switch (_settings_game.difficulty.subsidy_multiplier) {
 
			case 0:  profit += profit >> 1; break;
 
			case 1:  profit *= 2; break;
 
			case 2:  profit *= 3; break;
 
			default: profit *= 4; break;
 
		}
 
	}
 

	
 
	return profit;
 
}
 

	
 
/**
 
 * Inform the industry about just delivered cargo
 
 * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo.
 
 * @param i The industry to process
 
 */
 
static void TriggerIndustryProduction(Industry *i)
 
{
 
	const IndustrySpec *indspec = GetIndustrySpec(i->type);
 
	uint16 callback = indspec->callback_flags;
 

	
 
	i->was_cargo_delivered = true;
 
	i->last_cargo_accepted_at = _date;
 

	
 
	if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
 
		if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) {
 
			IndustryProductionCallback(i, 0);
 
		} else {
 
			InvalidateWindow(WC_INDUSTRY_VIEW, i->index);
 
		}
 
	} else {
 
		for (uint cargo_index = 0; cargo_index < lengthof(i->incoming_cargo_waiting); cargo_index++) {
 
			uint cargo_waiting = i->incoming_cargo_waiting[cargo_index];
 
			if (cargo_waiting == 0) continue;
 

	
 
			i->produced_cargo_waiting[0] = min(i->produced_cargo_waiting[0] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][0] / 256), 0xFFFF);
 
			i->produced_cargo_waiting[1] = min(i->produced_cargo_waiting[1] + (cargo_waiting * indspec->input_cargo_multiplier[cargo_index][1] / 256), 0xFFFF);
 

	
 
			i->incoming_cargo_waiting[cargo_index] = 0;
 
		}
 
	}
 

	
 
	TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO);
 
	StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO);
 
}
 

	
 
/**
 
 * Makes us a new cargo payment helper.
 
 * @param front The front of the train
 
 * @param destinations List to add the destinations of 'our' cargo to
 
 */
 
CargoPayment::CargoPayment(Vehicle *front) :
 
	front(front),
 
	current_station(front->last_station_visited)
 
{
 
}
 

	
 
CargoPayment::~CargoPayment()
 
{
 
	if (this->CleaningPool()) return;
 

	
 
	this->front->cargo_payment = NULL;
 

	
 
	if (this->visual_profit == 0) return;
 

	
 
	CompanyID old_company = _current_company;
 
	_current_company = this->front->owner;
 

	
 
	SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit));
 
	this->front->profit_this_year += this->visual_profit << 8;
 

	
 
	if (this->route_profit != 0) {
 
		if (IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) {
 
			SndPlayVehicleFx(SND_14_CASHTILL, this->front);
 
		}
 

	
 
		ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, -this->visual_profit);
 
	} else {
 
		ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, this->visual_profit);
 
	}
 

	
 
	_current_company = old_company;
 
}
 

	
 
/**
 
 * Handle payment for final delivery of the given cargo packet.
 
 * @param cp The cargo packet to pay for.
 
 * @param count The number of packets to pay for.
 
 */
 
void CargoPayment::PayFinalDelivery(CargoPacket *cp, uint count)
 
{
 
	if (this->owner == NULL) {
 
		this->owner = Company::Get(this->front->owner);
 
	}
 

	
 
	/* Handle end of route payment */
 
	Money profit = DeliverGoods(count, this->ct, cp->source, this->current_station, cp->source_xy, cp->days_in_transit, this->owner);
 
	Money profit = DeliverGoods(count, this->ct, this->current_station, cp->source_xy, cp->days_in_transit, this->owner, cp->source_type, cp->source_id);
 
	this->route_profit += profit;
 

	
 
	/* The vehicle's profit is whatever route profit there is minus feeder shares. */
 
	this->visual_profit += profit - cp->feeder_share;
 
}
 

	
 
/**
 
 * Handle payment for transfer of the given cargo packet.
 
 * @param cp The cargo packet to pay for.
 
 * @param count The number of packets to pay for.
 
 */
 
void CargoPayment::PayTransfer(CargoPacket *cp, uint count)
 
{
 
	Money profit = GetTransportedGoodsIncome(
 
		count,
 
		/* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */
 
		DistanceManhattan(cp->loaded_at_xy, Station::Get(this->current_station)->xy),
 
		cp->days_in_transit,
 
		this->ct);
 

	
 
	this->visual_profit += profit; // accumulate transfer profits for whole vehicle
 
	cp->feeder_share    += profit; // account for the (virtual) profit already made for the cargo packet
 
}
 

	
 
/**
 
 * Prepare the vehicle to be unloaded.
 
 * @param front_v the vehicle to be unloaded
 
 */
 
void PrepareUnload(Vehicle *front_v)
 
{
 
	/* At this moment loading cannot be finished */
 
	ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED);
 

	
 
	/* Start unloading in at the first possible moment */
 
	front_v->load_unload_time_rem = 1;
 

	
 
	if ((front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
 
		for (Vehicle *v = front_v; v != NULL; v = v->Next()) {
 
			if (v->cargo_cap > 0 && !v->cargo.Empty()) {
 
				SetBit(v->vehicle_flags, VF_CARGO_UNLOADING);
 
			}
 
		}
 
	}
 

	
 
	assert(front_v->cargo_payment == NULL);
 
	front_v->cargo_payment = new CargoPayment(front_v);
 
}
 

	
 
/**
 
 * Loads/unload the vehicle if possible.
 
 * @param v the vehicle to be (un)loaded
 
 * @param cargo_left the amount of each cargo type that is
 
 *                   virtually left on the platform to be
 
 *                   picked up by another vehicle when all
 
 *                   previous vehicles have loaded.
 
 */
 
static void LoadUnloadVehicle(Vehicle *v, int *cargo_left)
 
{
 
	assert(v->current_order.IsType(OT_LOADING));
 
	assert(v->load_unload_time_rem != 0);
 

	
 
	/* We have not waited enough time till the next round of loading/unloading */
 
	if (--v->load_unload_time_rem != 0) {
 
		if (_settings_game.order.improved_load && (v->current_order.GetLoadType() & OLFB_FULL_LOAD)) {
 
			/* 'Reserve' this cargo for this vehicle, because we were first. */
 
			for (; v != NULL; v = v->Next()) {
 
				int cap_left = v->cargo_cap - v->cargo.Count();
 
				if (cap_left > 0) cargo_left[v->cargo_type] -= cap_left;
 
			}
 
		}
 
		return;
 
	}
 

	
 
	StationID last_visited = v->last_station_visited;
 
	Station *st = Station::Get(last_visited);
 

	
 
	if (v->type == VEH_TRAIN && (!IsTileType(v->tile, MP_STATION) || GetStationIndex(v->tile) != st->index)) {
 
		/* The train reversed in the station. Take the "easy" way
 
		 * out and let the train just leave as it always did. */
 
		SetBit(v->vehicle_flags, VF_LOADING_FINISHED);
 
		return;
 
	}
 

	
 
	int unloading_time = 0;
 
	Vehicle *u = v;
 
	int result = 0;
 

	
 
	bool completely_emptied = true;
 
	bool anything_unloaded = false;
 
	bool anything_loaded   = false;
 
	uint32 cargo_not_full  = 0;
 
	uint32 cargo_full      = 0;
 

	
 
	v->cur_speed = 0;
 

	
 
	CargoPayment *payment = v->cargo_payment;
 

	
 
	for (; v != NULL; v = v->Next()) {
 
		if (v->cargo_cap == 0) continue;
 

	
 
		byte load_amount = EngInfo(v->engine_type)->load_amount;
 

	
 
		/* The default loadamount for mail is 1/4 of the load amount for passengers */
 
		if (v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft()) load_amount = (load_amount + 3) / 4;
 

	
 
		if (_settings_game.order.gradual_loading && HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_LOAD_AMOUNT)) {
 
			uint16 cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v);
 
			if (cb_load_amount != CALLBACK_FAILED && GB(cb_load_amount, 0, 8) != 0) load_amount = GB(cb_load_amount, 0, 8);
 
		}
 

	
 
		GoodsEntry *ge = &st->goods[v->cargo_type];
 

	
 
		if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (u->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) {
 
			uint cargo_count = v->cargo.Count();
 
			uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, load_amount) : cargo_count;
 
			bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here?
 
			bool accepted  = false; // Is the cargo accepted by the station?
 

	
 
			payment->SetCargo(v->cargo_type);
 

	
 
			if (HasBit(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE) && !(u->current_order.GetUnloadType() & OUFB_TRANSFER)) {
 
				/* The cargo has reached it's final destination, the packets may now be destroyed */
 
				remaining = v->cargo.MoveTo(NULL, amount_unloaded, CargoList::MTA_FINAL_DELIVERY, payment, last_visited);
 

	
 
				result |= 1;
 
				accepted = true;
 
			}
 

	
 
			/* The !accepted || v->cargo.Count == cargo_count clause is there
 
			 * to make it possible to force unload vehicles at the station where
 
			 * they were loaded, but to not force unload the vehicle when the
 
			 * station is still accepting the cargo in the vehicle. It doesn't
 
			 * accept cargo that was loaded at the same station. */
 
			if ((u->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) && (!accepted || v->cargo.Count() == cargo_count)) {
 
				remaining = v->cargo.MoveTo(&ge->cargo, amount_unloaded, u->current_order.GetUnloadType() & OUFB_TRANSFER ? CargoList::MTA_TRANSFER : CargoList::MTA_UNLOAD, payment);
 
				SetBit(ge->acceptance_pickup, GoodsEntry::PICKUP);
 

	
 
				result |= 2;
 
			} else if (!accepted) {
 
				/* The order changed while unloading (unset unload/transfer) or the
 
				 * station does not accept our goods. */
 
				ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING);
 

	
 
				/* Say we loaded something, otherwise we'll think we didn't unload
 
				 * something and we didn't load something, so we must be finished
 
				 * at this station. Setting the unloaded means that we will get a
 
				 * retry for loading in the next cycle. */
 
				anything_unloaded = true;
 
				continue;
 
			}
 

	
 
			/* Deliver goods to the station */
 
			st->time_since_unload = 0;
 

	
 
			unloading_time += amount_unloaded;
 

	
 
			anything_unloaded = true;
 
			if (_settings_game.order.gradual_loading && remaining) {
 
				completely_emptied = false;
 
			} else {
 
				/* We have finished unloading (cargo count == 0) */
 
				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::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();
 
		if (!ge->cargo.Empty() && cap_left > 0) {
 
			uint cap = cap_left;
 
			uint count = ge->cargo.Count();
 

	
 
			/* Skip loading this vehicle if another train/vehicle is already handling
 
			 * the same cargo type at this station */