Feature: Ctrl-click to remove fully autoreplaced vehicles from list (#9639)
[openttd-github.git] / src / newgrf_industries.cpp
blob01731fbc93d04be6040727462c14d656c46d04c8
1 /*
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/>.
6 */
8 /** @file newgrf_industries.cpp Handling of NewGRF industries. */
10 #include "stdafx.h"
11 #include "debug.h"
12 #include "industry.h"
13 #include "newgrf_industries.h"
14 #include "newgrf_town.h"
15 #include "newgrf_cargo.h"
16 #include "window_func.h"
17 #include "town.h"
18 #include "company_base.h"
19 #include "error.h"
20 #include "strings_func.h"
21 #include "core/random_func.hpp"
23 #include "table/strings.h"
25 #include "safeguards.h"
27 /* Since the industry IDs defined by the GRF file don't necessarily correlate
28 * to those used by the game, the IDs used for overriding old industries must be
29 * translated when the idustry spec is set. */
30 IndustryOverrideManager _industry_mngr(NEW_INDUSTRYOFFSET, NUM_INDUSTRYTYPES, INVALID_INDUSTRYTYPE);
31 IndustryTileOverrideManager _industile_mngr(NEW_INDUSTRYTILEOFFSET, NUM_INDUSTRYTILES, INVALID_INDUSTRYTILE);
33 /**
34 * Map the GRF local type to an industry type.
35 * @param grf_type The GRF local type.
36 * @param grf_id The GRF of the local type.
37 * @return The industry type in the global scope.
39 IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
41 if (grf_type == IT_INVALID) return IT_INVALID;
42 if (!HasBit(grf_type, 7)) return GB(grf_type, 0, 7);
44 return _industry_mngr.GetID(GB(grf_type, 0, 7), grf_id);
47 /**
48 * Make an analysis of a tile and check for its belonging to the same
49 * industry, and/or the same grf file
50 * @param tile TileIndex of the tile to query
51 * @param i Industry to which to compare the tile to
52 * @param cur_grfid GRFID of the current callback chain
53 * @return value encoded as per NFO specs
55 uint32 GetIndustryIDAtOffset(TileIndex tile, const Industry *i, uint32 cur_grfid)
57 if (!i->TileBelongsToIndustry(tile)) {
58 /* No industry and/or the tile does not have the same industry as the one we match it with */
59 return 0xFFFF;
62 IndustryGfx gfx = GetCleanIndustryGfx(tile);
63 const IndustryTileSpec *indtsp = GetIndustryTileSpec(gfx);
65 if (gfx < NEW_INDUSTRYTILEOFFSET) { // Does it belongs to an old type?
66 /* It is an old tile. We have to see if it's been overridden */
67 if (indtsp->grf_prop.override == INVALID_INDUSTRYTILE) { // has it been overridden?
68 return 0xFF << 8 | gfx; // no. Tag FF + the gfx id of that tile
70 /* Overridden */
71 const IndustryTileSpec *tile_ovr = GetIndustryTileSpec(indtsp->grf_prop.override);
73 if (tile_ovr->grf_prop.grffile->grfid == cur_grfid) {
74 return tile_ovr->grf_prop.local_id; // same grf file
75 } else {
76 return 0xFFFE; // not the same grf file
79 /* Not an 'old type' tile */
80 if (indtsp->grf_prop.spritegroup[0] != nullptr) { // tile has a spritegroup ?
81 if (indtsp->grf_prop.grffile->grfid == cur_grfid) { // same industry, same grf ?
82 return indtsp->grf_prop.local_id;
83 } else {
84 return 0xFFFE; // Defined in another grf file
87 /* The tile has no spritegroup */
88 return 0xFF << 8 | indtsp->grf_prop.subst_id; // so just give it the substitute
91 static uint32 GetClosestIndustry(TileIndex tile, IndustryType type, const Industry *current)
93 uint32 best_dist = UINT32_MAX;
94 for (const Industry *i : Industry::Iterate()) {
95 if (i->type != type || i == current) continue;
97 best_dist = std::min(best_dist, DistanceManhattan(tile, i->location.tile));
100 return best_dist;
104 * Implementation of both var 67 and 68
105 * since the mechanism is almost the same, it is easier to regroup them on the same
106 * function.
107 * @param param_setID parameter given to the callback, which is the set id, or the local id, in our terminology
108 * @param layout_filter on what layout do we filter?
109 * @param town_filter Do we filter on the same town as the current industry?
110 * @param current Industry for which the inquiry is made
111 * @return the formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
113 static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout_filter, bool town_filter, const Industry *current)
115 uint32 GrfID = GetRegister(0x100); ///< Get the GRFID of the definition to look for in register 100h
116 IndustryType ind_index;
117 uint32 closest_dist = UINT32_MAX;
118 byte count = 0;
120 /* Determine what will be the industry type to look for */
121 switch (GrfID) {
122 case 0: // this is a default industry type
123 ind_index = param_setID;
124 break;
126 case 0xFFFFFFFF: // current grf
127 GrfID = GetIndustrySpec(current->type)->grf_prop.grffile->grfid;
128 FALLTHROUGH;
130 default: // use the grfid specified in register 100h
131 SetBit(param_setID, 7); // bit 7 means it is not an old type
132 ind_index = MapNewGRFIndustryType(param_setID, GrfID);
133 break;
136 /* If the industry type is invalid, there is none and the closest is far away. */
137 if (ind_index >= NUM_INDUSTRYTYPES) return 0 | 0xFFFF;
139 if (layout_filter == 0 && !town_filter) {
140 /* If the filter is 0, it could be because none was specified as well as being really a 0.
141 * In either case, just do the regular var67 */
142 closest_dist = GetClosestIndustry(current->location.tile, ind_index, current);
143 count = std::min<uint>(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
144 } else {
145 /* Count only those who match the same industry type and layout filter
146 * Unfortunately, we have to do it manually */
147 for (const Industry *i : Industry::Iterate()) {
148 if (i->type == ind_index && i != current && (i->selected_layout == layout_filter || layout_filter == 0) && (!town_filter || i->town == current->town)) {
149 closest_dist = std::min(closest_dist, DistanceManhattan(current->location.tile, i->location.tile));
150 count++;
155 return count << 16 | GB(closest_dist, 0, 16);
158 /* virtual */ uint32 IndustriesScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
160 if (this->ro.callback == CBID_INDUSTRY_LOCATION) {
161 /* Variables available during construction check. */
163 switch (variable) {
164 case 0x80: return this->tile;
165 case 0x81: return GB(this->tile, 8, 8);
167 /* Pointer to the town the industry is associated with */
168 case 0x82: return this->industry->town->index;
169 case 0x83:
170 case 0x84:
171 case 0x85: Debug(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
173 /* Number of the layout */
174 case 0x86: return this->industry->selected_layout;
176 /* Ground type */
177 case 0x87: return GetTerrainType(this->tile);
179 /* Town zone */
180 case 0x88: return GetTownRadiusGroup(this->industry->town, this->tile);
182 /* Manhattan distance of the closest town */
183 case 0x89: return std::min(DistanceManhattan(this->industry->town->xy, this->tile), 255u);
185 /* Lowest height of the tile */
186 case 0x8A: return Clamp(GetTileZ(this->tile) * (this->ro.grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFF);
188 /* Distance to the nearest water/land tile */
189 case 0x8B: return GetClosestWaterDistance(this->tile, (GetIndustrySpec(this->industry->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
191 /* Square of Euclidian distance from town */
192 case 0x8D: return std::min(DistanceSquare(this->industry->town->xy, this->tile), 65535u);
194 /* 32 random bits */
195 case 0x8F: return this->random_bits;
199 const IndustrySpec *indspec = GetIndustrySpec(this->type);
201 if (this->industry == nullptr) {
202 Debug(grf, 1, "Unhandled variable 0x{:X} (no available industry) in callback 0x{:x}", variable, this->ro.callback);
204 *available = false;
205 return UINT_MAX;
208 switch (variable) {
209 case 0x40:
210 case 0x41:
211 case 0x42: { // waiting cargo, but only if those two callback flags are set
212 uint16 callback = indspec->callback_mask;
213 if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
214 if ((indspec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) {
215 if (this->industry->prod_level == 0) return 0;
216 return std::min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, 0xFFFFu);
217 } else {
218 return std::min<uint16>(this->industry->incoming_cargo_waiting[variable - 0x40], 0xFFFFu);
220 } else {
221 return 0;
225 /* Manhattan distance of closes dry/water tile */
226 case 0x43:
227 if (this->tile == INVALID_TILE) break;
228 return GetClosestWaterDistance(this->tile, (indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
230 /* Layout number */
231 case 0x44: return this->industry->selected_layout;
233 /* Company info */
234 case 0x45: {
235 byte colours = 0;
236 bool is_ai = false;
238 const Company *c = Company::GetIfValid(this->industry->founder);
239 if (c != nullptr) {
240 const Livery *l = &c->livery[LS_DEFAULT];
242 is_ai = c->is_ai;
243 colours = l->colour1 + l->colour2 * 16;
246 return this->industry->founder | (is_ai ? 0x10000 : 0) | (colours << 24);
249 case 0x46: return this->industry->construction_date; // Date when built - long format - (in days)
251 /* Override flags from GS */
252 case 0x47: return this->industry->ctlflags;
254 /* Get industry ID at offset param */
255 case 0x60: return GetIndustryIDAtOffset(GetNearbyTile(parameter, this->industry->location.tile, false), this->industry, this->ro.grffile->grfid);
257 /* Get random tile bits at offset param */
258 case 0x61: {
259 if (this->tile == INVALID_TILE) break;
260 TileIndex tile = GetNearbyTile(parameter, this->tile, false);
261 return this->industry->TileBelongsToIndustry(tile) ? GetIndustryRandomBits(tile) : 0;
264 /* Land info of nearby tiles */
265 case 0x62:
266 if (this->tile == INVALID_TILE) break;
267 return GetNearbyIndustryTileInformation(parameter, this->tile, INVALID_INDUSTRY, false, this->ro.grffile->grf_version >= 8);
269 /* Animation stage of nearby tiles */
270 case 0x63: {
271 if (this->tile == INVALID_TILE) break;
272 TileIndex tile = GetNearbyTile(parameter, this->tile, false);
273 if (this->industry->TileBelongsToIndustry(tile)) {
274 return GetAnimationFrame(tile);
276 return 0xFFFFFFFF;
279 /* Distance of nearest industry of given type */
280 case 0x64:
281 if (this->tile == INVALID_TILE) break;
282 return GetClosestIndustry(this->tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), this->industry);
283 /* Get town zone and Manhattan distance of closest town */
284 case 0x65: {
285 if (this->tile == INVALID_TILE) break;
286 TileIndex tile = GetNearbyTile(parameter, this->tile, true);
287 return GetTownRadiusGroup(this->industry->town, tile) << 16 | std::min(DistanceManhattan(tile, this->industry->town->xy), 0xFFFFu);
289 /* Get square of Euclidian distance of closest town */
290 case 0x66: {
291 if (this->tile == INVALID_TILE) break;
292 TileIndex tile = GetNearbyTile(parameter, this->tile, true);
293 return DistanceSquare(tile, this->industry->town->xy);
296 /* Count of industry, distance of closest instance
297 * 68 is the same as 67, but with a filtering on selected layout */
298 case 0x67:
299 case 0x68: {
300 byte layout_filter = 0;
301 bool town_filter = false;
302 if (variable == 0x68) {
303 uint32 reg = GetRegister(0x101);
304 layout_filter = GB(reg, 0, 8);
305 town_filter = HasBit(reg, 8);
307 return GetCountAndDistanceOfClosestInstance(parameter, layout_filter, town_filter, this->industry);
310 case 0x69:
311 case 0x6A:
312 case 0x6B:
313 case 0x6C:
314 case 0x6D:
315 case 0x70:
316 case 0x71: {
317 CargoID cargo = GetCargoTranslation(parameter, this->ro.grffile);
318 if (cargo == CT_INVALID) return 0;
319 int index = this->industry->GetCargoProducedIndex(cargo);
320 if (index < 0) return 0; // invalid cargo
321 switch (variable) {
322 case 0x69: return this->industry->produced_cargo_waiting[index];
323 case 0x6A: return this->industry->this_month_production[index];
324 case 0x6B: return this->industry->this_month_transported[index];
325 case 0x6C: return this->industry->last_month_production[index];
326 case 0x6D: return this->industry->last_month_transported[index];
327 case 0x70: return this->industry->production_rate[index];
328 case 0x71: return this->industry->last_month_pct_transported[index];
329 default: NOT_REACHED();
334 case 0x6E:
335 case 0x6F: {
336 CargoID cargo = GetCargoTranslation(parameter, this->ro.grffile);
337 if (cargo == CT_INVALID) return 0;
338 int index = this->industry->GetCargoAcceptedIndex(cargo);
339 if (index < 0) return 0; // invalid cargo
340 if (variable == 0x6E) return this->industry->last_cargo_accepted_at[index];
341 if (variable == 0x6F) return this->industry->incoming_cargo_waiting[index];
342 NOT_REACHED();
345 /* Get a variable from the persistent storage */
346 case 0x7C: return (this->industry->psa != nullptr) ? this->industry->psa->GetValue(parameter) : 0;
348 /* Industry structure access*/
349 case 0x80: return this->industry->location.tile;
350 case 0x81: return GB(this->industry->location.tile, 8, 8);
351 /* Pointer to the town the industry is associated with */
352 case 0x82: return this->industry->town->index;
353 case 0x83:
354 case 0x84:
355 case 0x85: Debug(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
356 case 0x86: return this->industry->location.w;
357 case 0x87: return this->industry->location.h;// xy dimensions
359 case 0x88:
360 case 0x89: return this->industry->produced_cargo[variable - 0x88];
361 case 0x8A: return this->industry->produced_cargo_waiting[0];
362 case 0x8B: return GB(this->industry->produced_cargo_waiting[0], 8, 8);
363 case 0x8C: return this->industry->produced_cargo_waiting[1];
364 case 0x8D: return GB(this->industry->produced_cargo_waiting[1], 8, 8);
365 case 0x8E:
366 case 0x8F: return this->industry->production_rate[variable - 0x8E];
367 case 0x90:
368 case 0x91:
369 case 0x92: return this->industry->accepts_cargo[variable - 0x90];
370 case 0x93: return this->industry->prod_level;
371 /* amount of cargo produced so far THIS month. */
372 case 0x94: return this->industry->this_month_production[0];
373 case 0x95: return GB(this->industry->this_month_production[0], 8, 8);
374 case 0x96: return this->industry->this_month_production[1];
375 case 0x97: return GB(this->industry->this_month_production[1], 8, 8);
376 /* amount of cargo transported so far THIS month. */
377 case 0x98: return this->industry->this_month_transported[0];
378 case 0x99: return GB(this->industry->this_month_transported[0], 8, 8);
379 case 0x9A: return this->industry->this_month_transported[1];
380 case 0x9B: return GB(this->industry->this_month_transported[1], 8, 8);
381 /* fraction of cargo transported LAST month. */
382 case 0x9C:
383 case 0x9D: return this->industry->last_month_pct_transported[variable - 0x9C];
384 /* amount of cargo produced LAST month. */
385 case 0x9E: return this->industry->last_month_production[0];
386 case 0x9F: return GB(this->industry->last_month_production[0], 8, 8);
387 case 0xA0: return this->industry->last_month_production[1];
388 case 0xA1: return GB(this->industry->last_month_production[1], 8, 8);
389 /* amount of cargo transported last month. */
390 case 0xA2: return this->industry->last_month_transported[0];
391 case 0xA3: return GB(this->industry->last_month_transported[0], 8, 8);
392 case 0xA4: return this->industry->last_month_transported[1];
393 case 0xA5: return GB(this->industry->last_month_transported[1], 8, 8);
395 case 0xA6: return indspec->grf_prop.local_id;
396 case 0xA7: return this->industry->founder;
397 case 0xA8: return this->industry->random_colour;
398 case 0xA9: return Clamp(this->industry->last_prod_year - ORIGINAL_BASE_YEAR, 0, 255);
399 case 0xAA: return this->industry->counter;
400 case 0xAB: return GB(this->industry->counter, 8, 8);
401 case 0xAC: return this->industry->was_cargo_delivered;
403 case 0xB0: return Clamp(this->industry->construction_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date when built since 1920 (in days)
404 case 0xB3: return this->industry->construction_type; // Construction type
405 case 0xB4: {
406 Date *latest = std::max_element(this->industry->last_cargo_accepted_at, endof(this->industry->last_cargo_accepted_at));
407 return Clamp((*latest) - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date last cargo accepted since 1920 (in days)
411 Debug(grf, 1, "Unhandled industry variable 0x{:X}", variable);
413 *available = false;
414 return UINT_MAX;
417 /* virtual */ uint32 IndustriesScopeResolver::GetRandomBits() const
419 return this->industry != nullptr ? this->industry->random : 0;
422 /* virtual */ uint32 IndustriesScopeResolver::GetTriggers() const
424 return 0;
427 /* virtual */ void IndustriesScopeResolver::StorePSA(uint pos, int32 value)
429 if (this->industry->index == INVALID_INDUSTRY) return;
431 if (this->industry->psa == nullptr) {
432 /* There is no need to create a storage if the value is zero. */
433 if (value == 0) return;
435 /* Create storage on first modification. */
436 const IndustrySpec *indsp = GetIndustrySpec(this->industry->type);
437 uint32 grfid = (indsp->grf_prop.grffile != nullptr) ? indsp->grf_prop.grffile->grfid : 0;
438 assert(PersistentStorage::CanAllocateItem());
439 this->industry->psa = new PersistentStorage(grfid, GSF_INDUSTRIES, this->industry->location.tile);
442 this->industry->psa->StoreValue(pos, value);
446 * Get the grf file associated with the given industry type.
447 * @param type Industry type to query.
448 * @return The associated GRF file, if any.
450 static const GRFFile *GetGrffile(IndustryType type)
452 const IndustrySpec *indspec = GetIndustrySpec(type);
453 return (indspec != nullptr) ? indspec->grf_prop.grffile : nullptr;
457 * Constructor of the industries resolver.
458 * @param tile %Tile owned by the industry.
459 * @param indus %Industry being resolved.
460 * @param type Type of the industry.
461 * @param random_bits Random bits of the new industry.
462 * @param callback Callback ID.
463 * @param callback_param1 First parameter (var 10) of the callback.
464 * @param callback_param2 Second parameter (var 18) of the callback.
466 IndustriesResolverObject::IndustriesResolverObject(TileIndex tile, Industry *indus, IndustryType type, uint32 random_bits,
467 CallbackID callback, uint32 callback_param1, uint32 callback_param2)
468 : ResolverObject(GetGrffile(type), callback, callback_param1, callback_param2),
469 industries_scope(*this, tile, indus, type, random_bits),
470 town_scope(nullptr)
472 this->root_spritegroup = GetIndustrySpec(type)->grf_prop.spritegroup[0];
475 IndustriesResolverObject::~IndustriesResolverObject()
477 delete this->town_scope;
481 * Get or create the town scope object associated with the industry.
482 * @return The associated town scope, if it exists.
484 TownScopeResolver *IndustriesResolverObject::GetTown()
486 if (this->town_scope == nullptr) {
487 Town *t = nullptr;
488 bool readonly = true;
489 if (this->industries_scope.industry != nullptr) {
490 t = this->industries_scope.industry->town;
491 readonly = this->industries_scope.industry->index == INVALID_INDUSTRY;
492 } else if (this->industries_scope.tile != INVALID_TILE) {
493 t = ClosestTownFromTile(this->industries_scope.tile, UINT_MAX);
495 if (t == nullptr) return nullptr;
496 this->town_scope = new TownScopeResolver(*this, t, readonly);
498 return this->town_scope;
501 GrfSpecFeature IndustriesResolverObject::GetFeature() const
503 return GSF_INDUSTRIES;
506 uint32 IndustriesResolverObject::GetDebugID() const
508 return GetIndustrySpec(this->industries_scope.type)->grf_prop.local_id;
512 * Perform an industry callback.
513 * @param callback The callback to perform.
514 * @param param1 The first parameter.
515 * @param param2 The second parameter.
516 * @param industry The industry to do the callback for.
517 * @param type The type of industry to do the callback for.
518 * @param tile The tile associated with the callback.
519 * @return The callback result.
521 uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
523 IndustriesResolverObject object(tile, industry, type, 0, callback, param1, param2);
524 return object.ResolveCallback();
528 * Check that the industry callback allows creation of the industry.
529 * @param tile %Tile to build the industry.
530 * @param type Type of industry to build.
531 * @param layout Layout number.
532 * @param seed Seed for the random generator.
533 * @param initial_random_bits The random bits the industry is going to have after construction.
534 * @param founder Industry founder
535 * @param creation_type The circumstances the industry is created under.
536 * @return Succeeded or failed command.
538 CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, size_t layout, uint32 seed, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
540 const IndustrySpec *indspec = GetIndustrySpec(type);
542 Industry ind;
543 ind.index = INVALID_INDUSTRY;
544 ind.location.tile = tile;
545 ind.location.w = 0; // important to mark the industry invalid
546 ind.type = type;
547 ind.selected_layout = (byte)layout;
548 ind.town = ClosestTownFromTile(tile, UINT_MAX);
549 ind.random = initial_random_bits;
550 ind.founder = founder;
551 ind.psa = nullptr;
553 IndustriesResolverObject object(tile, &ind, type, seed, CBID_INDUSTRY_LOCATION, 0, creation_type);
554 uint16 result = object.ResolveCallback();
556 /* Unlike the "normal" cases, not having a valid result means we allow
557 * the building of the industry, as that's how it's done in TTDP. */
558 if (result == CALLBACK_FAILED) return CommandCost();
560 return GetErrorMessageFromLocationCallbackResult(result, indspec->grf_prop.grffile, STR_ERROR_SITE_UNSUITABLE);
564 * Check with callback #CBID_INDUSTRY_PROBABILITY whether the industry can be built.
565 * @param type Industry type to check.
566 * @param creation_type Reason to construct a new industry.
567 * @return If the industry has no callback or allows building, \c true is returned. Otherwise, \c false is returned.
569 uint32 GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCallType creation_type, uint32 default_prob)
571 const IndustrySpec *indspec = GetIndustrySpec(type);
573 if (HasBit(indspec->callback_mask, CBM_IND_PROBABILITY)) {
574 uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROBABILITY, 0, creation_type, nullptr, type, INVALID_TILE);
575 if (res != CALLBACK_FAILED) {
576 if (indspec->grf_prop.grffile->grf_version < 8) {
577 /* Disallow if result != 0 */
578 if (res != 0) default_prob = 0;
579 } else {
580 /* Use returned probability. 0x100 to use default */
581 if (res < 0x100) {
582 default_prob = res;
583 } else if (res > 0x100) {
584 ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_PROBABILITY, res);
589 return default_prob;
592 static int32 DerefIndProd(int field, bool use_register)
594 return use_register ? (int32)GetRegister(field) : field;
598 * Get the industry production callback and apply it to the industry.
599 * @param ind the industry this callback has to be called for
600 * @param reason the reason it is called (0 = incoming cargo, 1 = periodic tick callback)
602 void IndustryProductionCallback(Industry *ind, int reason)
604 const IndustrySpec *spec = GetIndustrySpec(ind->type);
605 IndustriesResolverObject object(ind->location.tile, ind, ind->type);
606 if ((spec->behaviour & INDUSTRYBEH_PRODCALLBACK_RANDOM) != 0) object.callback_param1 = Random();
607 int multiplier = 1;
608 if ((spec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) multiplier = ind->prod_level;
609 object.callback_param2 = reason;
611 for (uint loop = 0;; loop++) {
612 /* limit the number of calls to break infinite loops.
613 * 'loop' is provided as 16 bits to the newgrf, so abort when those are exceeded. */
614 if (loop >= 0x10000) {
615 /* display error message */
616 SetDParamStr(0, spec->grf_prop.grffile->filename);
617 SetDParam(1, spec->name);
618 ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_ENDLESS_PRODUCTION_CALLBACK, WL_WARNING);
620 /* abort the function early, this error isn't critical and will allow the game to continue to run */
621 break;
624 SB(object.callback_param2, 8, 16, loop);
625 const SpriteGroup *tgroup = object.Resolve();
626 if (tgroup == nullptr || tgroup->type != SGT_INDUSTRY_PRODUCTION) break;
627 const IndustryProductionSpriteGroup *group = (const IndustryProductionSpriteGroup *)tgroup;
629 if (group->version == 0xFF) {
630 /* Result was marked invalid on load, display error message */
631 SetDParamStr(0, spec->grf_prop.grffile->filename);
632 SetDParam(1, spec->name);
633 SetDParam(2, ind->location.tile);
634 ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_INVALID_CARGO_PRODUCTION_CALLBACK, WL_WARNING);
636 /* abort the function early, this error isn't critical and will allow the game to continue to run */
637 break;
640 bool deref = (group->version >= 1);
642 if (group->version < 2) {
643 /* Callback parameters map directly to industry cargo slot indices */
644 for (uint i = 0; i < group->num_input; i++) {
645 ind->incoming_cargo_waiting[i] = Clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->subtract_input[i], deref) * multiplier, 0, 0xFFFF);
647 for (uint i = 0; i < group->num_output; i++) {
648 ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + std::max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
650 } else {
651 /* Callback receives list of cargos to apply for, which need to have their cargo slots in industry looked up */
652 for (uint i = 0; i < group->num_input; i++) {
653 int cargo_index = ind->GetCargoAcceptedIndex(group->cargo_input[i]);
654 if (cargo_index < 0) continue;
655 ind->incoming_cargo_waiting[cargo_index] = Clamp(ind->incoming_cargo_waiting[cargo_index] - DerefIndProd(group->subtract_input[i], deref) * multiplier, 0, 0xFFFF);
657 for (uint i = 0; i < group->num_output; i++) {
658 int cargo_index = ind->GetCargoProducedIndex(group->cargo_output[i]);
659 if (cargo_index < 0) continue;
660 ind->produced_cargo_waiting[cargo_index] = Clamp(ind->produced_cargo_waiting[cargo_index] + std::max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
664 int32 again = DerefIndProd(group->again, deref);
665 if (again == 0) break;
667 SB(object.callback_param2, 24, 8, again);
670 SetWindowDirty(WC_INDUSTRY_VIEW, ind->index);
674 * Check whether an industry temporarily refuses to accept a certain cargo.
675 * @param ind The industry to query.
676 * @param cargo_type The cargo to get information about.
677 * @pre cargo_type is in ind->accepts_cargo.
678 * @return Whether the given industry refuses to accept this cargo type.
680 bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
682 assert(std::find(ind->accepts_cargo, endof(ind->accepts_cargo), cargo_type) != endof(ind->accepts_cargo));
684 const IndustrySpec *indspec = GetIndustrySpec(ind->type);
685 if (HasBit(indspec->callback_mask, CBM_IND_REFUSE_CARGO)) {
686 uint16 res = GetIndustryCallback(CBID_INDUSTRY_REFUSE_CARGO,
687 0, indspec->grf_prop.grffile->cargo_map[cargo_type],
688 ind, ind->type, ind->location.tile);
689 if (res != CALLBACK_FAILED) return !ConvertBooleanCallback(indspec->grf_prop.grffile, CBID_INDUSTRY_REFUSE_CARGO, res);
691 return false;