2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file subsidy.cpp Handling of subsidies. */
11 #include "company_func.h"
14 #include "news_func.h"
16 #include "station_base.h"
17 #include "strings_func.h"
18 #include "window_func.h"
19 #include "subsidy_base.h"
20 #include "subsidy_func.h"
21 #include "core/pool_func.hpp"
22 #include "core/random_func.hpp"
23 #include "core/container_func.hpp"
24 #include "game/game.hpp"
25 #include "command_func.h"
26 #include "string_func.h"
28 #include "subsidy_cmd.h"
29 #include "timer/timer.h"
30 #include "timer/timer_game_economy.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 SubsidyPool
_subsidy_pool("Subsidy"); ///< Pool for the subsidies.
37 INSTANTIATE_POOL_METHODS(Subsidy
)
40 * Marks subsidy as awarded, creates news and AI event
41 * @param company awarded company
43 void Subsidy::AwardTo(CompanyID company
)
45 assert(!this->IsAwarded());
47 this->awarded
= company
;
48 this->remaining
= _settings_game
.difficulty
.subsidy_duration
* CalendarTime::MONTHS_IN_YEAR
;
50 SetDParam(0, company
);
51 std::string company_name
= GetString(STR_COMPANY_NAME
);
54 std::pair
<NewsReferenceType
, NewsReferenceType
> reftype
= SetupSubsidyDecodeParam(this, SubsidyDecodeParamType::NewsAwarded
, 1);
56 SetDParamStr(0, company_name
);
58 STR_NEWS_SERVICE_SUBSIDY_AWARDED_HALF
+ _settings_game
.difficulty
.subsidy_multiplier
,
59 NT_SUBSIDIES
, NF_NORMAL
,
60 reftype
.first
, this->src
, reftype
.second
, this->dst
62 AI::BroadcastNewEvent(new ScriptEventSubsidyAwarded(this->index
));
63 Game::NewEvent(new ScriptEventSubsidyAwarded(this->index
));
65 InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
69 * Setup the string parameters for printing the subsidy at the screen, and compute the news reference for the subsidy.
70 * @param s %Subsidy being printed.
71 * @param mode Type of subsidy news message to decide on parameter format.
72 * @param parameter_offset The location/index in the String DParams to start decoding the subsidy's parameters. Defaults to 0.
73 * @return Reference of the subsidy in the news system.
75 std::pair
<NewsReferenceType
, NewsReferenceType
> SetupSubsidyDecodeParam(const Subsidy
*s
, SubsidyDecodeParamType mode
, uint parameter_offset
)
77 NewsReferenceType reftype1
= NR_NONE
;
78 NewsReferenceType reftype2
= NR_NONE
;
80 /* Always use the plural form of the cargo name - trying to decide between plural or singular causes issues for translations */
81 const CargoSpec
*cs
= CargoSpec::Get(s
->cargo_type
);
82 SetDParam(parameter_offset
, cs
->name
);
84 switch (s
->src_type
) {
85 case SourceType::Industry
:
86 reftype1
= NR_INDUSTRY
;
87 SetDParam(parameter_offset
+ 1, STR_INDUSTRY_NAME
);
89 case SourceType::Town
:
91 SetDParam(parameter_offset
+ 1, STR_TOWN_NAME
);
93 default: NOT_REACHED();
95 SetDParam(parameter_offset
+ 2, s
->src
);
97 switch (s
->dst_type
) {
98 case SourceType::Industry
:
99 reftype2
= NR_INDUSTRY
;
100 SetDParam(parameter_offset
+ 4, STR_INDUSTRY_NAME
);
102 case SourceType::Town
:
104 SetDParam(parameter_offset
+ 4, STR_TOWN_NAME
);
106 default: NOT_REACHED();
108 SetDParam(parameter_offset
+ 5, s
->dst
);
110 /* If the subsidy is being offered or awarded, the news item mentions the subsidy duration. */
111 if (mode
== SubsidyDecodeParamType::NewsOffered
|| mode
== SubsidyDecodeParamType::NewsAwarded
) {
112 SetDParam(parameter_offset
+ 7, _settings_game
.difficulty
.subsidy_duration
);
115 return std::pair
<NewsReferenceType
, NewsReferenceType
>(reftype1
, reftype2
);
119 * Sets a flag indicating that given town/industry is part of subsidised route.
120 * @param type is it a town or an industry?
121 * @param index index of town/industry
122 * @param flag flag to set
124 static inline void SetPartOfSubsidyFlag(SourceType type
, SourceID index
, PartOfSubsidy flag
)
127 case SourceType::Industry
: Industry::Get(index
)->part_of_subsidy
|= flag
; return;
128 case SourceType::Town
: Town::Get(index
)->cache
.part_of_subsidy
|= flag
; return;
129 default: NOT_REACHED();
133 /** Perform a full rebuild of the subsidies cache. */
134 void RebuildSubsidisedSourceAndDestinationCache()
136 for (Town
*t
: Town::Iterate()) t
->cache
.part_of_subsidy
= POS_NONE
;
138 for (Industry
*i
: Industry::Iterate()) i
->part_of_subsidy
= POS_NONE
;
140 for (const Subsidy
*s
: Subsidy::Iterate()) {
141 SetPartOfSubsidyFlag(s
->src_type
, s
->src
, POS_SRC
);
142 SetPartOfSubsidyFlag(s
->dst_type
, s
->dst
, POS_DST
);
147 * Delete the subsidies associated with a given cargo source type and id.
148 * @param type Cargo source type of the id.
149 * @param index Id to remove.
151 void DeleteSubsidyWith(SourceType type
, SourceID index
)
155 for (Subsidy
*s
: Subsidy::Iterate()) {
156 if ((s
->src_type
== type
&& s
->src
== index
) || (s
->dst_type
== type
&& s
->dst
== index
)) {
163 InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
164 RebuildSubsidisedSourceAndDestinationCache();
169 * Check whether a specific subsidy already exists.
170 * @param cargo Cargo type.
171 * @param src_type Type of source of the cargo, affects interpretation of \a src.
172 * @param src Id of the source.
173 * @param dst_type Type of the destination of the cargo, affects interpretation of \a dst.
174 * @param dst Id of the destination.
175 * @return \c true if the subsidy already exists, \c false if not.
177 static bool CheckSubsidyDuplicate(CargoID cargo
, SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
179 for (const Subsidy
*s
: Subsidy::Iterate()) {
180 if (s
->cargo_type
== cargo
&&
181 s
->src_type
== src_type
&& s
->src
== src
&&
182 s
->dst_type
== dst_type
&& s
->dst
== dst
) {
190 * Checks if the source and destination of a subsidy are inside the distance limit.
191 * @param src_type Type of \a src.
192 * @param src Index of source.
193 * @param dst_type Type of \a dst.
194 * @param dst Index of destination.
195 * @return True if they are inside the distance limit.
197 static bool CheckSubsidyDistance(SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
199 TileIndex tile_src
= (src_type
== SourceType::Town
) ? Town::Get(src
)->xy
: Industry::Get(src
)->location
.tile
;
200 TileIndex tile_dst
= (dst_type
== SourceType::Town
) ? Town::Get(dst
)->xy
: Industry::Get(dst
)->location
.tile
;
202 return (DistanceManhattan(tile_src
, tile_dst
) <= SUBSIDY_MAX_DISTANCE
);
206 * Creates a subsidy with the given parameters.
207 * @param cid Subsidised cargo.
208 * @param src_type Type of \a src.
209 * @param src Index of source.
210 * @param dst_type Type of \a dst.
211 * @param dst Index of destination.
213 void CreateSubsidy(CargoID cid
, SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
215 Subsidy
*s
= new Subsidy();
217 s
->src_type
= src_type
;
219 s
->dst_type
= dst_type
;
221 s
->remaining
= SUBSIDY_OFFER_MONTHS
;
222 s
->awarded
= INVALID_COMPANY
;
224 std::pair
<NewsReferenceType
, NewsReferenceType
> reftype
= SetupSubsidyDecodeParam(s
, SubsidyDecodeParamType::NewsOffered
);
225 AddNewsItem(STR_NEWS_SERVICE_SUBSIDY_OFFERED
, NT_SUBSIDIES
, NF_NORMAL
, reftype
.first
, s
->src
, reftype
.second
, s
->dst
);
226 SetPartOfSubsidyFlag(s
->src_type
, s
->src
, POS_SRC
);
227 SetPartOfSubsidyFlag(s
->dst_type
, s
->dst
, POS_DST
);
228 AI::BroadcastNewEvent(new ScriptEventSubsidyOffer(s
->index
));
229 Game::NewEvent(new ScriptEventSubsidyOffer(s
->index
));
231 InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
235 * Create a new subsidy.
236 * @param flags type of operation
237 * @param cid CargoID of subsidy.
238 * @param src_type SourceType of source.
239 * @param src SourceID of source.
240 * @param dst_type SourceType of destination.
241 * @param dst SourceID of destination.
242 * @return the cost of this operation or an error
244 CommandCost
CmdCreateSubsidy(DoCommandFlag flags
, CargoID cid
, SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
246 if (!Subsidy::CanAllocateItem()) return CMD_ERROR
;
248 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
250 if (cid
>= NUM_CARGO
|| !::CargoSpec::Get(cid
)->IsValid()) return CMD_ERROR
;
253 case SourceType::Town
:
254 if (!Town::IsValidID(src
)) return CMD_ERROR
;
256 case SourceType::Industry
:
257 if (!Industry::IsValidID(src
)) return CMD_ERROR
;
263 case SourceType::Town
:
264 if (!Town::IsValidID(dst
)) return CMD_ERROR
;
266 case SourceType::Industry
:
267 if (!Industry::IsValidID(dst
)) return CMD_ERROR
;
273 if (flags
& DC_EXEC
) {
274 CreateSubsidy(cid
, src_type
, src
, dst_type
, dst
);
277 return CommandCost();
281 * Tries to create a passenger subsidy between two towns.
282 * @return True iff the subsidy was created.
284 bool FindSubsidyPassengerRoute()
286 if (!Subsidy::CanAllocateItem()) return false;
288 /* Pick a random TPE_PASSENGER type */
289 uint32_t r
= RandomRange(static_cast<uint
>(CargoSpec::town_production_cargoes
[TPE_PASSENGERS
].size()));
290 CargoID cid
= CargoSpec::town_production_cargoes
[TPE_PASSENGERS
][r
]->Index();
292 const Town
*src
= Town::GetRandom();
293 if (src
->cache
.population
< SUBSIDY_PAX_MIN_POPULATION
||
294 src
->GetPercentTransported(cid
) > SUBSIDY_MAX_PCT_TRANSPORTED
) {
298 const Town
*dst
= Town::GetRandom();
299 if (dst
->cache
.population
< SUBSIDY_PAX_MIN_POPULATION
|| src
== dst
) {
303 if (DistanceManhattan(src
->xy
, dst
->xy
) > SUBSIDY_MAX_DISTANCE
) return false;
304 if (CheckSubsidyDuplicate(cid
, SourceType::Town
, src
->index
, SourceType::Town
, dst
->index
)) return false;
306 CreateSubsidy(cid
, SourceType::Town
, src
->index
, SourceType::Town
, dst
->index
);
311 bool FindSubsidyCargoDestination(CargoID cid
, SourceType src_type
, SourceID src
);
315 * Tries to create a cargo subsidy with a town as source.
316 * @return True iff the subsidy was created.
318 bool FindSubsidyTownCargoRoute()
320 if (!Subsidy::CanAllocateItem()) return false;
322 SourceType src_type
= SourceType::Town
;
324 /* Select a random town. */
325 const Town
*src_town
= Town::GetRandom();
326 if (src_town
->cache
.population
< SUBSIDY_CARGO_MIN_POPULATION
) return false;
328 /* Calculate the produced cargo of houses around town center. */
329 CargoArray town_cargo_produced
{};
330 TileArea ta
= TileArea(src_town
->xy
, 1, 1).Expand(SUBSIDY_TOWN_CARGO_RADIUS
);
331 for (TileIndex tile
: ta
) {
332 if (IsTileType(tile
, MP_HOUSE
)) {
333 AddProducedCargo(tile
, town_cargo_produced
);
337 /* Passenger subsidies are not handled here. */
338 for (const CargoSpec
*cs
: CargoSpec::town_production_cargoes
[TPE_PASSENGERS
]) {
339 town_cargo_produced
[cs
->Index()] = 0;
342 uint8_t cargo_count
= town_cargo_produced
.GetCount();
344 /* No cargo produced at all? */
345 if (cargo_count
== 0) return false;
347 /* Choose a random cargo that is produced in the town. */
348 uint8_t cargo_number
= RandomRange(cargo_count
);
350 for (cid
= 0; cid
< NUM_CARGO
; cid
++) {
351 if (town_cargo_produced
[cid
] > 0) {
352 if (cargo_number
== 0) break;
357 /* Avoid using invalid NewGRF cargoes. */
358 if (!CargoSpec::Get(cid
)->IsValid() ||
359 _settings_game
.linkgraph
.GetDistributionType(cid
) != DT_MANUAL
) {
363 /* Quit if the percentage transported is large enough. */
364 if (src_town
->GetPercentTransported(cid
) > SUBSIDY_MAX_PCT_TRANSPORTED
) return false;
366 SourceID src
= src_town
->index
;
368 return FindSubsidyCargoDestination(cid
, src_type
, src
);
372 * Tries to create a cargo subsidy with an industry as source.
373 * @return True iff the subsidy was created.
375 bool FindSubsidyIndustryCargoRoute()
377 if (!Subsidy::CanAllocateItem()) return false;
379 SourceType src_type
= SourceType::Industry
;
381 /* Select a random industry. */
382 const Industry
*src_ind
= Industry::GetRandom();
383 if (src_ind
== nullptr) return false;
389 /* Randomize cargo type */
390 int num_cargos
= std::count_if(std::begin(src_ind
->produced
), std::end(src_ind
->produced
), [](const auto &p
) { return IsValidCargoID(p
.cargo
); });
391 if (num_cargos
== 0) return false; // industry produces nothing
392 int cargo_num
= RandomRange(num_cargos
) + 1;
394 auto it
= std::begin(src_ind
->produced
);
395 for (/* nothing */; it
!= std::end(src_ind
->produced
); ++it
) {
396 if (IsValidCargoID(it
->cargo
)) cargo_num
--;
397 if (cargo_num
== 0) break;
399 assert(it
!= std::end(src_ind
->produced
)); // indicates loop didn't end as intended
402 trans
= it
->history
[LAST_MONTH
].PctTransported();
403 total
= it
->history
[LAST_MONTH
].production
;
405 /* Quit if no production in this industry
406 * or if the pct transported is already large enough
407 * or if the cargo is automatically distributed */
408 if (total
== 0 || trans
> SUBSIDY_MAX_PCT_TRANSPORTED
||
409 !IsValidCargoID(cid
) ||
410 _settings_game
.linkgraph
.GetDistributionType(cid
) != DT_MANUAL
) {
414 SourceID src
= src_ind
->index
;
416 return FindSubsidyCargoDestination(cid
, src_type
, src
);
420 * Tries to find a suitable destination for the given source and cargo.
421 * @param cid Subsidized cargo.
422 * @param src_type Type of \a src.
423 * @param src Index of source.
424 * @return True iff the subsidy was created.
426 bool FindSubsidyCargoDestination(CargoID cid
, SourceType src_type
, SourceID src
)
428 /* Choose a random destination. */
429 SourceType dst_type
= Chance16(1, 2) ? SourceType::Town
: SourceType::Industry
;
433 case SourceType::Town
: {
434 /* Select a random town. */
435 const Town
*dst_town
= Town::GetRandom();
437 /* Calculate cargo acceptance of houses around town center. */
438 CargoArray town_cargo_accepted
{};
439 TileArea ta
= TileArea(dst_town
->xy
, 1, 1).Expand(SUBSIDY_TOWN_CARGO_RADIUS
);
440 for (TileIndex tile
: ta
) {
441 if (IsTileType(tile
, MP_HOUSE
)) {
442 AddAcceptedCargo(tile
, town_cargo_accepted
, nullptr);
446 /* Check if the town can accept this cargo. */
447 if (town_cargo_accepted
[cid
] < 8) return false;
449 dst
= dst_town
->index
;
453 case SourceType::Industry
: {
454 /* Select a random industry. */
455 const Industry
*dst_ind
= Industry::GetRandom();
456 if (dst_ind
== nullptr) return false;
458 /* The industry must accept the cargo */
459 if (!dst_ind
->IsCargoAccepted(cid
)) return false;
461 dst
= dst_ind
->index
;
465 default: NOT_REACHED();
468 /* Check that the source and the destination are not the same. */
469 if (src_type
== dst_type
&& src
== dst
) return false;
471 /* Check distance between source and destination. */
472 if (!CheckSubsidyDistance(src_type
, src
, dst_type
, dst
)) return false;
474 /* Avoid duplicate subsidies. */
475 if (CheckSubsidyDuplicate(cid
, src_type
, src
, dst_type
, dst
)) return false;
477 CreateSubsidy(cid
, src_type
, src
, dst_type
, dst
);
482 /** Perform the economy monthly update of open subsidies, and try to create a new one. */
483 static IntervalTimer
<TimerGameEconomy
> _economy_subsidies_monthly({TimerGameEconomy::MONTH
, TimerGameEconomy::Priority::SUBSIDY
}, [](auto)
485 bool modified
= false;
487 for (Subsidy
*s
: Subsidy::Iterate()) {
488 if (--s
->remaining
== 0) {
489 if (!s
->IsAwarded()) {
490 std::pair
<NewsReferenceType
, NewsReferenceType
> reftype
= SetupSubsidyDecodeParam(s
, SubsidyDecodeParamType::NewsWithdrawn
);
491 AddNewsItem(STR_NEWS_OFFER_OF_SUBSIDY_EXPIRED
, NT_SUBSIDIES
, NF_NORMAL
, reftype
.first
, s
->src
, reftype
.second
, s
->dst
);
492 AI::BroadcastNewEvent(new ScriptEventSubsidyOfferExpired(s
->index
));
493 Game::NewEvent(new ScriptEventSubsidyOfferExpired(s
->index
));
495 if (s
->awarded
== _local_company
) {
496 std::pair
<NewsReferenceType
, NewsReferenceType
> reftype
= SetupSubsidyDecodeParam(s
, SubsidyDecodeParamType::NewsWithdrawn
);
497 AddNewsItem(STR_NEWS_SUBSIDY_WITHDRAWN_SERVICE
, NT_SUBSIDIES
, NF_NORMAL
, reftype
.first
, s
->src
, reftype
.second
, s
->dst
);
499 AI::BroadcastNewEvent(new ScriptEventSubsidyExpired(s
->index
));
500 Game::NewEvent(new ScriptEventSubsidyExpired(s
->index
));
508 RebuildSubsidisedSourceAndDestinationCache();
509 } else if (_settings_game
.difficulty
.subsidy_duration
== 0) {
510 /* If subsidy duration is set to 0, subsidies are disabled, so bail out. */
512 } else if (_settings_game
.linkgraph
.distribution_pax
!= DT_MANUAL
&&
513 _settings_game
.linkgraph
.distribution_mail
!= DT_MANUAL
&&
514 _settings_game
.linkgraph
.distribution_armoured
!= DT_MANUAL
&&
515 _settings_game
.linkgraph
.distribution_default
!= DT_MANUAL
) {
516 /* Return early if there are no manually distributed cargoes and if we
517 * don't need to invalidate the subsidies window. */
521 bool passenger_subsidy
= false;
522 bool town_subsidy
= false;
523 bool industry_subsidy
= false;
525 int random_chance
= RandomRange(16);
527 if (random_chance
< 2 && _settings_game
.linkgraph
.distribution_pax
== DT_MANUAL
) {
528 /* There is a 1/8 chance each month of generating a passenger subsidy. */
532 passenger_subsidy
= FindSubsidyPassengerRoute();
533 } while (!passenger_subsidy
&& n
--);
534 } else if (random_chance
== 2) {
535 /* Cargo subsidies with a town as a source have a 1/16 chance. */
539 town_subsidy
= FindSubsidyTownCargoRoute();
540 } while (!town_subsidy
&& n
--);
541 } else if (random_chance
== 3) {
542 /* Cargo subsidies with an industry as a source have a 1/16 chance. */
546 industry_subsidy
= FindSubsidyIndustryCargoRoute();
547 } while (!industry_subsidy
&& n
--);
550 modified
|= passenger_subsidy
|| town_subsidy
|| industry_subsidy
;
552 if (modified
) InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
556 * Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company
557 * @param cargo_type type of cargo
558 * @param company company delivering the cargo
559 * @param src_type type of \a src
560 * @param src index of source
561 * @param st station where the cargo is delivered to
562 * @return is the delivery subsidised?
564 bool CheckSubsidised(CargoID cargo_type
, CompanyID company
, SourceType src_type
, SourceID src
, const Station
*st
)
566 /* If the source isn't subsidised, don't continue */
567 if (src
== INVALID_SOURCE
) return false;
569 case SourceType::Industry
:
570 if (!(Industry::Get(src
)->part_of_subsidy
& POS_SRC
)) return false;
572 case SourceType::Town
:
573 if (!(Town::Get(src
)->cache
.part_of_subsidy
& POS_SRC
)) return false;
575 default: return false;
578 /* Remember all towns near this station (at least one house in its catchment radius)
579 * which are destination of subsidised path. Do that only if needed */
580 std::vector
<const Town
*> towns_near
;
581 if (!st
->rect
.IsEmpty()) {
582 for (const Subsidy
*s
: Subsidy::Iterate()) {
583 /* Don't create the cache if there is no applicable subsidy with town as destination */
584 if (s
->dst_type
!= SourceType::Town
) continue;
585 if (s
->cargo_type
!= cargo_type
|| s
->src_type
!= src_type
|| s
->src
!= src
) continue;
586 if (s
->IsAwarded() && s
->awarded
!= company
) continue;
588 BitmapTileIterator
it(st
->catchment_tiles
);
589 for (TileIndex tile
= it
; tile
!= INVALID_TILE
; tile
= ++it
) {
590 if (!IsTileType(tile
, MP_HOUSE
)) continue;
591 const Town
*t
= Town::GetByTile(tile
);
592 if (t
->cache
.part_of_subsidy
& POS_DST
) include(towns_near
, t
);
598 bool subsidised
= false;
600 /* Check if there's a (new) subsidy that applies. There can be more subsidies triggered by this delivery!
601 * Think about the case that subsidies are A->B and A->C and station has both B and C in its catchment area */
602 for (Subsidy
*s
: Subsidy::Iterate()) {
603 if (s
->cargo_type
== cargo_type
&& s
->src_type
== src_type
&& s
->src
== src
&& (!s
->IsAwarded() || s
->awarded
== company
)) {
604 switch (s
->dst_type
) {
605 case SourceType::Industry
:
606 for (const auto &i
: st
->industries_near
) {
607 if (s
->dst
== i
.industry
->index
) {
608 assert(i
.industry
->part_of_subsidy
& POS_DST
);
610 if (!s
->IsAwarded()) s
->AwardTo(company
);
614 case SourceType::Town
:
615 for (const Town
*tp
: towns_near
) {
616 if (s
->dst
== tp
->index
) {
617 assert(tp
->cache
.part_of_subsidy
& POS_DST
);
619 if (!s
->IsAwarded()) s
->AwardTo(company
);