4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
10 /** @file subsidy.cpp Handling of subsidies. */
13 #include "company_func.h"
16 #include "news_func.h"
18 #include "station_base.h"
19 #include "strings_func.h"
20 #include "window_func.h"
21 #include "subsidy_base.h"
22 #include "subsidy_func.h"
23 #include "core/pool_func.hpp"
24 #include "core/random_func.hpp"
25 #include "game/game.hpp"
26 #include "command_func.h"
28 #include "table/strings.h"
30 template<> Subsidy::Pool
Subsidy::PoolItem::pool ("Subsidy");
31 INSTANTIATE_POOL_METHODS(Subsidy
)
34 * Marks subsidy as awarded, creates news and AI event
35 * @param company awarded company
37 void Subsidy::AwardTo(CompanyID company
)
39 assert(!this->IsAwarded());
41 this->awarded
= company
;
42 this->remaining
= SUBSIDY_CONTRACT_MONTHS
;
44 char company_name
[MAX_LENGTH_COMPANY_NAME_CHARS
* MAX_CHAR_LENGTH
];
45 SetDParam(0, company
);
46 GetString(company_name
, STR_COMPANY_NAME
, lastof(company_name
));
48 char *cn
= strdup(company_name
);
51 Pair reftype
= SetupSubsidyDecodeParam(this, false);
56 STR_NEWS_SERVICE_SUBSIDY_AWARDED_HALF
+ _settings_game
.difficulty
.subsidy_multiplier
,
57 NT_SUBSIDIES
, NF_NORMAL
,
58 (NewsReferenceType
)reftype
.a
, this->src
, (NewsReferenceType
)reftype
.b
, this->dst
,
61 AI::BroadcastNewEvent(new ScriptEventSubsidyAwarded(this->index
));
62 Game::NewEvent(new ScriptEventSubsidyAwarded(this->index
));
64 InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
68 * Setup the string parameters for printing the subsidy at the screen, and compute the news reference for the subsidy.
69 * @param s %Subsidy being printed.
70 * @param mode Unit of cargo used, \c true means general name, \c false means singular form.
71 * @return Reference of the subsidy in the news system.
73 Pair
SetupSubsidyDecodeParam(const Subsidy
*s
, bool mode
)
75 NewsReferenceType reftype1
= NR_NONE
;
76 NewsReferenceType reftype2
= NR_NONE
;
78 /* if mode is false, use the singular form */
79 const CargoSpec
*cs
= CargoSpec::Get(s
->cargo_type
);
80 SetDParam(0, mode
? cs
->name
: cs
->name_single
);
82 switch (s
->src_type
) {
84 reftype1
= NR_INDUSTRY
;
85 SetDParam(1, STR_INDUSTRY_NAME
);
89 SetDParam(1, STR_TOWN_NAME
);
91 default: NOT_REACHED();
95 switch (s
->dst_type
) {
97 reftype2
= NR_INDUSTRY
;
98 SetDParam(4, STR_INDUSTRY_NAME
);
102 SetDParam(4, STR_TOWN_NAME
);
104 default: NOT_REACHED();
106 SetDParam(5, s
->dst
);
115 * Sets a flag indicating that given town/industry is part of subsidised route.
116 * @param type is it a town or an industry?
117 * @param index index of town/industry
118 * @param flag flag to set
120 static inline void SetPartOfSubsidyFlag(SourceType type
, SourceID index
, PartOfSubsidy flag
)
123 case ST_INDUSTRY
: Industry::Get(index
)->part_of_subsidy
|= flag
; return;
124 case ST_TOWN
: Town::Get(index
)->cache
.part_of_subsidy
|= flag
; return;
125 default: NOT_REACHED();
129 /** Perform a full rebuild of the subsidies cache. */
130 void RebuildSubsidisedSourceAndDestinationCache()
133 FOR_ALL_TOWNS(t
) t
->cache
.part_of_subsidy
= POS_NONE
;
136 FOR_ALL_INDUSTRIES(i
) i
->part_of_subsidy
= POS_NONE
;
139 FOR_ALL_SUBSIDIES(s
) {
140 SetPartOfSubsidyFlag(s
->src_type
, s
->src
, POS_SRC
);
141 SetPartOfSubsidyFlag(s
->dst_type
, s
->dst
, POS_DST
);
146 * Delete the subsidies associated with a given cargo source type and id.
147 * @param type Cargo source type of the id.
148 * @param index Id to remove.
150 void DeleteSubsidyWith(SourceType type
, SourceID index
)
155 FOR_ALL_SUBSIDIES(s
) {
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
)
180 FOR_ALL_SUBSIDIES(s
) {
181 if (s
->cargo_type
== cargo
&&
182 s
->src_type
== src_type
&& s
->src
== src
&&
183 s
->dst_type
== dst_type
&& s
->dst
== dst
) {
191 * Checks if the source and destination of a subsidy are inside the distance limit.
192 * @param src_type Type of \a src.
193 * @param src Index of source.
194 * @param dst_type Type of \a dst.
195 * @param dst Index of destination.
196 * @return True if they are inside the distance limit.
198 static bool CheckSubsidyDistance(SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
200 TileIndex tile_src
= (src_type
== ST_TOWN
) ? Town::Get(src
)->xy
: Industry::Get(src
)->location
.tile
;
201 TileIndex tile_dst
= (dst_type
== ST_TOWN
) ? Town::Get(dst
)->xy
: Industry::Get(dst
)->location
.tile
;
203 return (DistanceManhattan(tile_src
, tile_dst
) <= SUBSIDY_MAX_DISTANCE
);
207 * Creates a subsidy with the given parameters.
208 * @param cid Subsidised cargo.
209 * @param src_type Type of \a src.
210 * @param src Index of source.
211 * @param dst_type Type of \a dst.
212 * @param dst Index of destination.
214 void CreateSubsidy(CargoID cid
, SourceType src_type
, SourceID src
, SourceType dst_type
, SourceID dst
)
216 Subsidy
*s
= new Subsidy();
218 s
->src_type
= src_type
;
220 s
->dst_type
= dst_type
;
222 s
->remaining
= SUBSIDY_OFFER_MONTHS
;
223 s
->awarded
= INVALID_COMPANY
;
225 Pair reftype
= SetupSubsidyDecodeParam(s
, false);
226 AddNewsItem(STR_NEWS_SERVICE_SUBSIDY_OFFERED
, NT_SUBSIDIES
, NF_NORMAL
, (NewsReferenceType
)reftype
.a
, s
->src
, (NewsReferenceType
)reftype
.b
, s
->dst
);
227 SetPartOfSubsidyFlag(s
->src_type
, s
->src
, POS_SRC
);
228 SetPartOfSubsidyFlag(s
->dst_type
, s
->dst
, POS_DST
);
229 AI::BroadcastNewEvent(new ScriptEventSubsidyOffer(s
->index
));
230 Game::NewEvent(new ScriptEventSubsidyOffer(s
->index
));
232 InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
236 * Create a new subsidy.
237 * @param tile unused.
238 * @param flags type of operation
239 * @param p1 various bitstuffed elements
240 * - p1 = (bit 0 - 7) - SourceType of source.
241 * - p1 = (bit 8 - 23) - SourceID of source.
242 * - p1 = (bit 24 - 31) - CargoID of subsidy.
243 * @param p2 various bitstuffed elements
244 * - p2 = (bit 0 - 7) - SourceType of destination.
245 * - p2 = (bit 8 - 23) - SourceID of destination.
246 * @param text unused.
247 * @return the cost of this operation or an error
249 CommandCost
CmdCreateSubsidy(TileIndex tile
, DoCommandFlag flags
, uint32 p1
, uint32 p2
, const char *text
)
251 if (!Subsidy::CanAllocateItem()) return CMD_ERROR
;
253 CargoID cid
= GB(p1
, 24, 8);
254 SourceType src_type
= (SourceType
)GB(p1
, 0, 8);
255 SourceID src
= GB(p1
, 8, 16);
256 SourceType dst_type
= (SourceType
)GB(p2
, 0, 8);
257 SourceID dst
= GB(p2
, 8, 16);
259 if (_current_company
!= OWNER_DEITY
) return CMD_ERROR
;
261 if (cid
>= NUM_CARGO
|| !::CargoSpec::Get(cid
)->IsValid()) return CMD_ERROR
;
265 if (!Town::IsValidID(src
)) return CMD_ERROR
;
268 if (!Industry::IsValidID(src
)) return CMD_ERROR
;
275 if (!Town::IsValidID(dst
)) return CMD_ERROR
;
278 if (!Industry::IsValidID(dst
)) return CMD_ERROR
;
284 if (flags
& DC_EXEC
) {
285 CreateSubsidy(cid
, src_type
, src
, dst_type
, dst
);
288 return CommandCost();
292 * Tries to create a passenger subsidy between two towns.
293 * @return True iff the subsidy was created.
295 bool FindSubsidyPassengerRoute()
297 if (!Subsidy::CanAllocateItem()) return false;
299 const Town
*src
= Town::GetRandom();
300 if (src
->cache
.population
< SUBSIDY_PAX_MIN_POPULATION
||
301 src
->GetPercentTransported(CT_PASSENGERS
) > SUBSIDY_MAX_PCT_TRANSPORTED
) {
305 const Town
*dst
= Town::GetRandom();
306 if (dst
->cache
.population
< SUBSIDY_PAX_MIN_POPULATION
|| src
== dst
) {
310 if (DistanceManhattan(src
->xy
, dst
->xy
) > SUBSIDY_MAX_DISTANCE
) return false;
311 if (CheckSubsidyDuplicate(CT_PASSENGERS
, ST_TOWN
, src
->index
, ST_TOWN
, dst
->index
)) return false;
313 CreateSubsidy(CT_PASSENGERS
, ST_TOWN
, src
->index
, ST_TOWN
, dst
->index
);
318 bool FindSubsidyCargoDestination(CargoID cid
, SourceType src_type
, SourceID src
);
322 * Tries to create a cargo subsidy with a town as source.
323 * @return True iff the subsidy was created.
325 bool FindSubsidyTownCargoRoute()
327 if (!Subsidy::CanAllocateItem()) return false;
329 SourceType src_type
= ST_TOWN
;
331 /* Select a random town. */
332 const Town
*src_town
= Town::GetRandom();
334 uint32 town_cargo_produced
= src_town
->cargo_produced
;
336 /* Passenger subsidies are not handled here. */
337 ClrBit(town_cargo_produced
, CT_PASSENGERS
);
339 /* No cargo produced at all? */
340 if (town_cargo_produced
== 0) return false;
342 /* Choose a random cargo that is produced in the town. */
343 uint8 cargo_number
= RandomRange(CountBits(town_cargo_produced
));
345 FOR_EACH_SET_CARGO_ID(cid
, town_cargo_produced
) {
346 if (cargo_number
== 0) break;
350 /* Avoid using invalid NewGRF cargoes. */
351 if (!CargoSpec::Get(cid
)->IsValid() ||
352 _settings_game
.linkgraph
.GetDistributionType(cid
) != DT_MANUAL
) {
356 /* Quit if the percentage transported is large enough. */
357 if (src_town
->GetPercentTransported(cid
) > SUBSIDY_MAX_PCT_TRANSPORTED
) return false;
359 SourceID src
= src_town
->index
;
361 return FindSubsidyCargoDestination(cid
, src_type
, src
);
365 * Tries to create a cargo subsidy with an industry as source.
366 * @return True iff the subsidy was created.
368 bool FindSubsidyIndustryCargoRoute()
370 if (!Subsidy::CanAllocateItem()) return false;
372 SourceType src_type
= ST_INDUSTRY
;
374 /* Select a random industry. */
375 const Industry
*src_ind
= Industry::GetRandom();
376 if (src_ind
== NULL
) return false;
382 /* Randomize cargo type */
383 if (src_ind
->produced_cargo
[1] != CT_INVALID
&& HasBit(Random(), 0)) {
384 cid
= src_ind
->produced_cargo
[1];
385 trans
= src_ind
->last_month_pct_transported
[1];
386 total
= src_ind
->last_month_production
[1];
388 cid
= src_ind
->produced_cargo
[0];
389 trans
= src_ind
->last_month_pct_transported
[0];
390 total
= src_ind
->last_month_production
[0];
393 /* Quit if no production in this industry
394 * or if the pct transported is already large enough
395 * or if the cargo is automatically distributed */
396 if (total
== 0 || trans
> SUBSIDY_MAX_PCT_TRANSPORTED
||
398 _settings_game
.linkgraph
.GetDistributionType(cid
) != DT_MANUAL
) {
402 SourceID src
= src_ind
->index
;
404 return FindSubsidyCargoDestination(cid
, src_type
, src
);
408 * Tries to find a suitable destination for the given source and cargo.
409 * @param cid Subsidized cargo.
410 * @param src_type Type of \a src.
411 * @param src Index of source.
412 * @return True iff the subsidy was created.
414 bool FindSubsidyCargoDestination(CargoID cid
, SourceType src_type
, SourceID src
)
416 /* Choose a random destination. Only consider towns if they can accept the cargo. */
417 SourceType dst_type
= (HasBit(_town_cargoes_accepted
, cid
) && Chance16(1, 2)) ? ST_TOWN
: ST_INDUSTRY
;
422 /* Select a random town. */
423 const Town
*dst_town
= Town::GetRandom();
425 /* Check if the town can accept this cargo. */
426 if (!HasBit(dst_town
->cargo_accepted_total
, cid
)) return false;
428 dst
= dst_town
->index
;
433 /* Select a random industry. */
434 const Industry
*dst_ind
= Industry::GetRandom();
436 /* The industry must accept the cargo */
437 if (dst_ind
== NULL
||
438 (cid
!= dst_ind
->accepts_cargo
[0] &&
439 cid
!= dst_ind
->accepts_cargo
[1] &&
440 cid
!= dst_ind
->accepts_cargo
[2])) {
444 dst
= dst_ind
->index
;
448 default: NOT_REACHED();
451 /* Check that the source and the destination are not the same. */
452 if (src_type
== dst_type
&& src
== dst
) return false;
454 /* Check distance between source and destination. */
455 if (!CheckSubsidyDistance(src_type
, src
, dst_type
, dst
)) return false;
457 /* Avoid duplicate subsidies. */
458 if (CheckSubsidyDuplicate(cid
, src_type
, src
, dst_type
, dst
)) return false;
460 CreateSubsidy(cid
, src_type
, src
, dst_type
, dst
);
465 /** Perform the monthly update of open subsidies, and try to create a new one. */
466 void SubsidyMonthlyLoop()
468 bool modified
= false;
471 FOR_ALL_SUBSIDIES(s
) {
472 if (--s
->remaining
== 0) {
473 if (!s
->IsAwarded()) {
474 Pair reftype
= SetupSubsidyDecodeParam(s
, true);
475 AddNewsItem(STR_NEWS_OFFER_OF_SUBSIDY_EXPIRED
, NT_SUBSIDIES
, NF_NORMAL
, (NewsReferenceType
)reftype
.a
, s
->src
, (NewsReferenceType
)reftype
.b
, s
->dst
);
476 AI::BroadcastNewEvent(new ScriptEventSubsidyOfferExpired(s
->index
));
477 Game::NewEvent(new ScriptEventSubsidyOfferExpired(s
->index
));
479 if (s
->awarded
== _local_company
) {
480 Pair reftype
= SetupSubsidyDecodeParam(s
, true);
481 AddNewsItem(STR_NEWS_SUBSIDY_WITHDRAWN_SERVICE
, NT_SUBSIDIES
, NF_NORMAL
, (NewsReferenceType
)reftype
.a
, s
->src
, (NewsReferenceType
)reftype
.b
, s
->dst
);
483 AI::BroadcastNewEvent(new ScriptEventSubsidyExpired(s
->index
));
484 Game::NewEvent(new ScriptEventSubsidyExpired(s
->index
));
492 RebuildSubsidisedSourceAndDestinationCache();
493 } else if (_settings_game
.linkgraph
.distribution_pax
!= DT_MANUAL
&&
494 _settings_game
.linkgraph
.distribution_mail
!= DT_MANUAL
&&
495 _settings_game
.linkgraph
.distribution_armoured
!= DT_MANUAL
&&
496 _settings_game
.linkgraph
.distribution_default
!= DT_MANUAL
) {
497 /* Return early if there are no manually distributed cargoes and if we
498 * don't need to invalidate the subsidies window. */
502 bool passenger_subsidy
= false;
503 bool town_subsidy
= false;
504 bool industry_subsidy
= false;
506 int random_chance
= RandomRange(16);
508 if (random_chance
< 2 && _settings_game
.linkgraph
.distribution_pax
== DT_MANUAL
) {
509 /* There is a 1/8 chance each month of generating a passenger subsidy. */
513 passenger_subsidy
= FindSubsidyPassengerRoute();
514 } while (!passenger_subsidy
&& n
--);
515 } else if (random_chance
== 2) {
516 /* Cargo subsidies with a town as a source have a 1/16 chance. */
520 town_subsidy
= FindSubsidyTownCargoRoute();
521 } while (!town_subsidy
&& n
--);
522 } else if (random_chance
== 3) {
523 /* Cargo subsidies with an industry as a source have a 1/16 chance. */
527 industry_subsidy
= FindSubsidyIndustryCargoRoute();
528 } while (!industry_subsidy
&& n
--);
531 modified
|= passenger_subsidy
|| town_subsidy
|| industry_subsidy
;
533 if (modified
) InvalidateWindowData(WC_SUBSIDIES_LIST
, 0);
537 * Tests whether given delivery is subsidised and possibly awards the subsidy to delivering company
538 * @param cargo_type type of cargo
539 * @param company company delivering the cargo
540 * @param src_type type of \a src
541 * @param src index of source
542 * @param st station where the cargo is delivered to
543 * @return is the delivery subsidised?
545 bool CheckSubsidised(CargoID cargo_type
, CompanyID company
, SourceType src_type
, SourceID src
, const Station
*st
)
547 /* If the source isn't subsidised, don't continue */
548 if (src
== INVALID_SOURCE
) return false;
551 if (!(Industry::Get(src
)->part_of_subsidy
& POS_SRC
)) return false;
554 if (!(Town::Get(src
)->cache
.part_of_subsidy
& POS_SRC
)) return false;
556 default: return false;
559 /* Remember all towns near this station (at least one house in its catchment radius)
560 * which are destination of subsidised path. Do that only if needed */
561 SmallVector
<const Town
*, 2> towns_near
;
562 if (!st
->rect
.IsEmpty()) {
564 FOR_ALL_SUBSIDIES(s
) {
565 /* Don't create the cache if there is no applicable subsidy with town as destination */
566 if (s
->dst_type
!= ST_TOWN
) continue;
567 if (s
->cargo_type
!= cargo_type
|| s
->src_type
!= src_type
|| s
->src
!= src
) continue;
568 if (s
->IsAwarded() && s
->awarded
!= company
) continue;
570 Rect rect
= st
->GetCatchmentRect();
572 for (int y
= rect
.top
; y
<= rect
.bottom
; y
++) {
573 for (int x
= rect
.left
; x
<= rect
.right
; x
++) {
574 TileIndex tile
= TileXY(x
, y
);
575 if (!IsHouseTile(tile
)) continue;
576 const Town
*t
= Town::GetByTile(tile
);
577 if (t
->cache
.part_of_subsidy
& POS_DST
) towns_near
.Include(t
);
584 bool subsidised
= false;
586 /* Check if there's a (new) subsidy that applies. There can be more subsidies triggered by this delivery!
587 * Think about the case that subsidies are A->B and A->C and station has both B and C in its catchment area */
589 FOR_ALL_SUBSIDIES(s
) {
590 if (s
->cargo_type
== cargo_type
&& s
->src_type
== src_type
&& s
->src
== src
&& (!s
->IsAwarded() || s
->awarded
== company
)) {
591 switch (s
->dst_type
) {
593 for (const Industry
* const *ip
= st
->industries_near
.Begin(); ip
!= st
->industries_near
.End(); ip
++) {
594 if (s
->dst
== (*ip
)->index
) {
595 assert((*ip
)->part_of_subsidy
& POS_DST
);
597 if (!s
->IsAwarded()) s
->AwardTo(company
);
602 for (const Town
* const *tp
= towns_near
.Begin(); tp
!= towns_near
.End(); tp
++) {
603 if (s
->dst
== (*tp
)->index
) {
604 assert((*tp
)->cache
.part_of_subsidy
& POS_DST
);
606 if (!s
->IsAwarded()) s
->AwardTo(company
);