# industry_cmd.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "clear_map.h"
    00014 #include "industry.h"
    00015 #include "station_base.h"
    00016 #include "landscape.h"
    00017 #include "viewport_func.h"
    00018 #include "command_func.h"
    00019 #include "town.h"
    00020 #include "news_func.h"
    00021 #include "cheat_type.h"
    00022 #include "genworld.h"
    00023 #include "tree_map.h"
    00024 #include "newgrf_cargo.h"
    00025 #include "newgrf_debug.h"
    00026 #include "newgrf_industrytiles.h"
    00027 #include "autoslope.h"
    00028 #include "water.h"
    00029 #include "strings_func.h"
    00030 #include "window_func.h"
    00031 #include "date_func.h"
    00032 #include "vehicle_func.h"
    00033 #include "sound_func.h"
    00034 #include "animated_tile_func.h"
    00035 #include "effectvehicle_func.h"
    00036 #include "effectvehicle_base.h"
    00037 #include "ai/ai.hpp"
    00038 #include "core/pool_func.hpp"
    00039 #include "subsidy_func.h"
    00040 #include "core/backup_type.hpp"
    00041 #include "object_base.h"
    00042 #include "game/game.hpp"
    00043
    00044 #include "table/strings.h"
    00045 #include "table/industry_land.h"
    00046 #include "table/build_industry.h"
    00047
    00048 IndustryPool _industry_pool("Industry");
    00049 INSTANTIATE_POOL_METHODS(Industry)
    00050
    00051 void ShowIndustryViewWindow(int industry);
    00052 void BuildOilRig(TileIndex tile);
    00053
    00054 static byte _industry_sound_ctr;
    00055 static TileIndex _industry_sound_tile;
    00056
    00057 uint16 Industry::counts[NUM_INDUSTRYTYPES];
    00058
    00059 IndustrySpec _industry_specs[NUM_INDUSTRYTYPES];
    00060 IndustryTileSpec _industry_tile_specs[NUM_INDUSTRYTILES];
    00061 IndustryBuildData _industry_builder;
    00062
    00069 void ResetIndustries()
    00070 {
    00071   memset(&_industry_specs, 0, sizeof(_industry_specs));
    00072   memcpy(&_industry_specs, &_origin_industry_specs, sizeof(_origin_industry_specs));
    00073
    00074   /* once performed, enable only the current climate industries */
    00075   for (IndustryType i = 0; i < NUM_INDUSTRYTYPES; i++) {
    00076     _industry_specs[i].enabled = i < NEW_INDUSTRYOFFSET &&
    00077         HasBit(_origin_industry_specs[i].climate_availability, _settings_game.game_creation.landscape);
    00078   }
    00079
    00080   memset(&_industry_tile_specs, 0, sizeof(_industry_tile_specs));
    00081   memcpy(&_industry_tile_specs, &_origin_industry_tile_specs, sizeof(_origin_industry_tile_specs));
    00082
    00083   /* Reset any overrides that have been set. */
    00084   _industile_mngr.ResetOverride();
    00085   _industry_mngr.ResetOverride();
    00086 }
    00087
    00096 IndustryType GetIndustryType(TileIndex tile)
    00097 {
    00098   assert(IsTileType(tile, MP_INDUSTRY));
    00099
    00100   const Industry *ind = Industry::GetByTile(tile);
    00101   assert(ind != NULL);
    00102   return ind->type;
    00103 }
    00104
    00113 const IndustrySpec *GetIndustrySpec(IndustryType thistype)
    00114 {
    00115   assert(thistype < NUM_INDUSTRYTYPES);
    00116   return &_industry_specs[thistype];
    00117 }
    00118
    00127 const IndustryTileSpec *GetIndustryTileSpec(IndustryGfx gfx)
    00128 {
    00129   assert(gfx < INVALID_INDUSTRYTILE);
    00130   return &_industry_tile_specs[gfx];
    00131 }
    00132
    00133 Industry::~Industry()
    00134 {
    00135   if (CleaningPool()) return;
    00136
    00137   /* Industry can also be destroyed when not fully initialized.
    00138    * This means that we do not have to clear tiles either.
    00139    * Also we must not decrement industry counts in that case. */
    00140   if (this->location.w == 0) return;
    00141
    00142   TILE_AREA_LOOP(tile_cur, this->location) {
    00143     if (IsTileType(tile_cur, MP_INDUSTRY)) {
    00144       if (GetIndustryIndex(tile_cur) == this->index) {
    00145         DeleteNewGRFInspectWindow(GSF_INDUSTRYTILES, tile_cur);
    00146
    00147         /* MakeWaterKeepingClass() can also handle 'land' */
    00148         MakeWaterKeepingClass(tile_cur, OWNER_NONE);
    00149       }
    00150     } else if (IsTileType(tile_cur, MP_STATION) && IsOilRig(tile_cur)) {
    00151       DeleteOilRig(tile_cur);
    00152     }
    00153   }
    00154
    00155   if (GetIndustrySpec(this->type)->behaviour & INDUSTRYBEH_PLANT_FIELDS) {
    00156     TileArea ta(this->location.tile - TileDiffXY(min(TileX(this->location.tile), 21), min(TileY(this->location.tile), 21)), 42, 42);
    00157     ta.ClampToMap();
    00158
    00159     /* Remove the farmland and convert it to regular tiles over time. */
    00160     TILE_AREA_LOOP(tile_cur, ta) {
    00161       if (IsTileType(tile_cur, MP_CLEAR) && IsClearGround(tile_cur, CLEAR_FIELDS) &&
    00162           GetIndustryIndexOfField(tile_cur) == this->index) {
    00163         SetIndustryIndexOfField(tile_cur, INVALID_INDUSTRY);
    00164       }
    00165     }
    00166   }
    00167
    00168   /* don't let any disaster vehicle target invalid industry */
    00169   ReleaseDisastersTargetingIndustry(this->index);
    00170
    00171   /* Clear the persistent storage. */
    00172   delete this->psa;
    00173
    00174   DecIndustryTypeCount(this->type);
    00175
    00176   DeleteIndustryNews(this->index);
    00177   DeleteWindowById(WC_INDUSTRY_VIEW, this->index);
    00178   DeleteNewGRFInspectWindow(GSF_INDUSTRIES, this->index);
    00179
    00180   DeleteSubsidyWith(ST_INDUSTRY, this->index);
    00181   CargoPacket::InvalidateAllFrom(ST_INDUSTRY, this->index);
    00182 }
    00183
    00188 void Industry::PostDestructor(size_t index)
    00189 {
    00190   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 0);
    00191   Station::RecomputeIndustriesNearForAll();
    00192 }
    00193
    00194
    00199 /* static */ Industry *Industry::GetRandom()
    00200 {
    00201   if (Industry::GetNumItems() == 0) return NULL;
    00202   int num = RandomRange((uint16)Industry::GetNumItems());
    00203   size_t index = MAX_UVALUE(size_t);
    00204
    00205   while (num >= 0) {
    00206     num--;
    00207     index++;
    00208
    00209     /* Make sure we have a valid industry */
    00210     while (!Industry::IsValidID(index)) {
    00211       index++;
    00212       assert(index < Industry::GetPoolSize());
    00213     }
    00214   }
    00215
    00216   return Industry::Get(index);
    00217 }
    00218
    00219
    00220 static void IndustryDrawSugarMine(const TileInfo *ti)
    00221 {
    00222   if (!IsIndustryCompleted(ti->tile)) return;
    00223
    00224   const DrawIndustryAnimationStruct *d = &_draw_industry_spec1[GetAnimationFrame(ti->tile)];
    00225
    00226   AddChildSpriteScreen(SPR_IT_SUGAR_MINE_SIEVE + d->image_1, PAL_NONE, d->x, 0);
    00227
    00228   if (d->image_2 != 0) {
    00229     AddChildSpriteScreen(SPR_IT_SUGAR_MINE_CLOUDS + d->image_2 - 1, PAL_NONE, 8, 41);
    00230   }
    00231
    00232   if (d->image_3 != 0) {
    00233     AddChildSpriteScreen(SPR_IT_SUGAR_MINE_PILE + d->image_3 - 1, PAL_NONE,
    00234       _drawtile_proc1[d->image_3 - 1].x, _drawtile_proc1[d->image_3 - 1].y);
    00235   }
    00236 }
    00237
    00238 static void IndustryDrawToffeeQuarry(const TileInfo *ti)
    00239 {
    00240   uint8 x = 0;
    00241
    00242   if (IsIndustryCompleted(ti->tile)) {
    00243     x = _industry_anim_offs_toffee[GetAnimationFrame(ti->tile)];
    00244     if (x == 0xFF) {
    00245       x = 0;
    00246     }
    00247   }
    00248
    00249   AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_SHOVEL, PAL_NONE, 22 - x, 24 + x);
    00250   AddChildSpriteScreen(SPR_IT_TOFFEE_QUARRY_TOFFEE, PAL_NONE, 6, 14);
    00251 }
    00252
    00253 static void IndustryDrawBubbleGenerator( const TileInfo *ti)
    00254 {
    00255   if (IsIndustryCompleted(ti->tile)) {
    00256     AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_BUBBLE, PAL_NONE, 5, _industry_anim_offs_bubbles[GetAnimationFrame(ti->tile)]);
    00257   }
    00258   AddChildSpriteScreen(SPR_IT_BUBBLE_GENERATOR_SPRING, PAL_NONE, 3, 67);
    00259 }
    00260
    00261 static void IndustryDrawToyFactory(const TileInfo *ti)
    00262 {
    00263   const DrawIndustryAnimationStruct *d = &_industry_anim_offs_toys[GetAnimationFrame(ti->tile)];
    00264
    00265   if (d->image_1 != 0xFF) {
    00266     AddChildSpriteScreen(SPR_IT_TOY_FACTORY_CLAY, PAL_NONE, d->x, 96 + d->image_1);
    00267   }
    00268
    00269   if (d->image_2 != 0xFF) {
    00270     AddChildSpriteScreen(SPR_IT_TOY_FACTORY_ROBOT, PAL_NONE, 16 - d->image_2 * 2, 100 + d->image_2);
    00271   }
    00272
    00273   AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP, PAL_NONE, 7, d->image_3);
    00274   AddChildSpriteScreen(SPR_IT_TOY_FACTORY_STAMP_HOLDER, PAL_NONE, 0, 42);
    00275 }
    00276
    00277 static void IndustryDrawCoalPlantSparks(const TileInfo *ti)
    00278 {
    00279   if (IsIndustryCompleted(ti->tile)) {
    00280     uint8 image = GetAnimationFrame(ti->tile);
    00281
    00282     if (image != 0 && image < 7) {
    00283       AddChildSpriteScreen(image + SPR_IT_POWER_PLANT_TRANSFORMERS,
    00284         PAL_NONE,
    00285         _coal_plant_sparks[image - 1].x,
    00286         _coal_plant_sparks[image - 1].y
    00287       );
    00288     }
    00289   }
    00290 }
    00291
    00292 typedef void IndustryDrawTileProc(const TileInfo *ti);
    00293 static IndustryDrawTileProc * const _industry_draw_tile_procs[5] = {
    00294   IndustryDrawSugarMine,
    00295   IndustryDrawToffeeQuarry,
    00296   IndustryDrawBubbleGenerator,
    00297   IndustryDrawToyFactory,
    00298   IndustryDrawCoalPlantSparks,
    00299 };
    00300
    00301 static void DrawTile_Industry(TileInfo *ti)
    00302 {
    00303   IndustryGfx gfx = GetIndustryGfx(ti->tile);
    00304   Industry *ind = Industry::GetByTile(ti->tile);
    00305   const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
    00306
    00307   /* Retrieve pointer to the draw industry tile struct */
    00308   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
    00309     /* Draw the tile using the specialized method of newgrf industrytile.
    00310      * DrawNewIndustry will return false if ever the resolver could not
    00311      * find any sprite to display.  So in this case, we will jump on the
    00312      * substitute gfx instead. */
    00313     if (indts->grf_prop.spritegroup[0] != NULL && DrawNewIndustryTile(ti, ind, gfx, indts)) {
    00314       return;
    00315     } else {
    00316       /* No sprite group (or no valid one) found, meaning no graphics associated.
    00317        * Use the substitute one instead */
    00318       if (indts->grf_prop.subst_id != INVALID_INDUSTRYTILE) {
    00319         gfx = indts->grf_prop.subst_id;
    00320         /* And point the industrytile spec accordingly */
    00321         indts = GetIndustryTileSpec(gfx);
    00322       }
    00323     }
    00324   }
    00325
    00326   const DrawBuildingsTileStruct *dits = &_industry_draw_tile_data[gfx << 2 | (indts->anim_state ?
    00327       GetAnimationFrame(ti->tile) & INDUSTRY_COMPLETED :
    00328       GetIndustryConstructionStage(ti->tile))];
    00329
    00330   SpriteID image = dits->ground.sprite;
    00331
    00332   /* DrawFoundation() modifes ti->z and ti->tileh */
    00333   if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
    00334
    00335   /* If the ground sprite is the default flat water sprite, draw also canal/river borders.
    00336    * Do not do this if the tile's WaterClass is 'land'. */
    00337   if (image == SPR_FLAT_WATER_TILE && IsTileOnWater(ti->tile)) {
    00338     DrawWaterClassGround(ti);
    00339   } else {
    00340     DrawGroundSprite(image, GroundSpritePaletteTransform(image, dits->ground.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)));
    00341   }
    00342
    00343   /* If industries are transparent and invisible, do not draw the upper part */
    00344   if (IsInvisibilitySet(TO_INDUSTRIES)) return;
    00345
    00346   /* Add industry on top of the ground? */
    00347   image = dits->building.sprite;
    00348   if (image != 0) {
    00349     AddSortableSpriteToDraw(image, SpriteLayoutPaletteTransform(image, dits->building.pal, GENERAL_SPRITE_COLOUR(ind->random_colour)),
    00350       ti->x + dits->subtile_x,
    00351       ti->y + dits->subtile_y,
    00352       dits->width,
    00353       dits->height,
    00354       dits->dz,
    00355       ti->z,
    00356       IsTransparencySet(TO_INDUSTRIES));
    00357
    00358     if (IsTransparencySet(TO_INDUSTRIES)) return;
    00359   }
    00360
    00361   {
    00362     int proc = dits->draw_proc - 1;
    00363     if (proc >= 0) _industry_draw_tile_procs[proc](ti);
    00364   }
    00365 }
    00366
    00367 static int GetSlopePixelZ_Industry(TileIndex tile, uint x, uint y)
    00368 {
    00369   return GetTileMaxPixelZ(tile);
    00370 }
    00371
    00372 static Foundation GetFoundation_Industry(TileIndex tile, Slope tileh)
    00373 {
    00374   IndustryGfx gfx = GetIndustryGfx(tile);
    00375
    00376   /* For NewGRF industry tiles we might not be drawing a foundation. We need to
    00377    * account for this, as other structures should
    00378    * draw the wall of the foundation in this case.
    00379    */
    00380   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
    00381     const IndustryTileSpec *indts = GetIndustryTileSpec(gfx);
    00382     if (indts->grf_prop.spritegroup[0] != NULL && HasBit(indts->callback_mask, CBM_INDT_DRAW_FOUNDATIONS)) {
    00383       uint32 callback_res = GetIndustryTileCallback(CBID_INDTILE_DRAW_FOUNDATIONS, 0, 0, gfx, Industry::GetByTile(tile), tile);
    00384       if (callback_res != CALLBACK_FAILED && !ConvertBooleanCallback(indts->grf_prop.grffile, CBID_INDTILE_DRAW_FOUNDATIONS, callback_res)) return FOUNDATION_NONE;
    00385     }
    00386   }
    00387   return FlatteningFoundation(tileh);
    00388 }
    00389
    00390 static void AddAcceptedCargo_Industry(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
    00391 {
    00392   IndustryGfx gfx = GetIndustryGfx(tile);
    00393   const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
    00394
    00395   /* When we have to use a callback, we put our data in the next two variables */
    00396   CargoID raw_accepts_cargo[lengthof(itspec->accepts_cargo)];
    00397   uint8 raw_cargo_acceptance[lengthof(itspec->acceptance)];
    00398
    00399   /* And then these will always point to a same sized array with the required data */
    00400   const CargoID *accepts_cargo = itspec->accepts_cargo;
    00401   const uint8 *cargo_acceptance = itspec->acceptance;
    00402
    00403   if (HasBit(itspec->callback_mask, CBM_INDT_ACCEPT_CARGO)) {
    00404     uint16 res = GetIndustryTileCallback(CBID_INDTILE_ACCEPT_CARGO, 0, 0, gfx, Industry::GetByTile(tile), tile);
    00405     if (res != CALLBACK_FAILED) {
    00406       accepts_cargo = raw_accepts_cargo;
    00407       for (uint i = 0; i < lengthof(itspec->accepts_cargo); i++) raw_accepts_cargo[i] = GetCargoTranslation(GB(res, i * 5, 5), itspec->grf_prop.grffile);
    00408     }
    00409   }
    00410
    00411   if (HasBit(itspec->callback_mask, CBM_INDT_CARGO_ACCEPTANCE)) {
    00412     uint16 res = GetIndustryTileCallback(CBID_INDTILE_CARGO_ACCEPTANCE, 0, 0, gfx, Industry::GetByTile(tile), tile);
    00413     if (res != CALLBACK_FAILED) {
    00414       cargo_acceptance = raw_cargo_acceptance;
    00415       for (uint i = 0; i < lengthof(itspec->accepts_cargo); i++) raw_cargo_acceptance[i] = GB(res, i * 4, 4);
    00416     }
    00417   }
    00418
    00419   const Industry *ind = Industry::GetByTile(tile);
    00420   for (byte i = 0; i < lengthof(itspec->accepts_cargo); i++) {
    00421     CargoID a = accepts_cargo[i];
    00422     if (a == CT_INVALID || cargo_acceptance[i] == 0) continue; // work only with valid cargoes
    00423
    00424     /* Add accepted cargo */
    00425     acceptance[a] += cargo_acceptance[i];
    00426
    00427     /* Maybe set 'always accepted' bit (if it's not set already) */
    00428     if (HasBit(*always_accepted, a)) continue;
    00429
    00430     bool accepts = false;
    00431     for (uint cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) {
    00432       /* Test whether the industry itself accepts the cargo type */
    00433       if (ind->accepts_cargo[cargo_index] == a) {
    00434         accepts = true;
    00435         break;
    00436       }
    00437     }
    00438
    00439     if (accepts) continue;
    00440
    00441     /* If the industry itself doesn't accept this cargo, set 'always accepted' bit */
    00442     SetBit(*always_accepted, a);
    00443   }
    00444 }
    00445
    00446 static void GetTileDesc_Industry(TileIndex tile, TileDesc *td)
    00447 {
    00448   const Industry *i = Industry::GetByTile(tile);
    00449   const IndustrySpec *is = GetIndustrySpec(i->type);
    00450
    00451   td->owner[0] = i->owner;
    00452   td->str = is->name;
    00453   if (!IsIndustryCompleted(tile)) {
    00454     SetDParamX(td->dparam, 0, td->str);
    00455     td->str = STR_LAI_TOWN_INDUSTRY_DESCRIPTION_UNDER_CONSTRUCTION;
    00456   }
    00457
    00458   if (is->grf_prop.grffile != NULL) {
    00459     td->grf = GetGRFConfig(is->grf_prop.grffile->grfid)->GetName();
    00460   }
    00461 }
    00462
    00463 static CommandCost ClearTile_Industry(TileIndex tile, DoCommandFlag flags)
    00464 {
    00465   Industry *i = Industry::GetByTile(tile);
    00466   const IndustrySpec *indspec = GetIndustrySpec(i->type);
    00467
    00468   /* water can destroy industries
    00469    * in editor you can bulldoze industries
    00470    * with magic_bulldozer cheat you can destroy industries
    00471    * (area around OILRIG is water, so water shouldn't flood it
    00472    */
    00473   if ((_current_company != OWNER_WATER && _game_mode != GM_EDITOR &&
    00474       !_cheats.magic_bulldozer.value) ||
    00475       ((flags & DC_AUTO) != 0) ||
    00476       (_current_company == OWNER_WATER &&
    00477         ((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) ||
    00478         HasBit(GetIndustryTileSpec(GetIndustryGfx(tile))->slopes_refused, 5)))) {
    00479     SetDParam(1, indspec->name);
    00480     return_cmd_error(flags & DC_AUTO ? STR_ERROR_GENERIC_OBJECT_IN_THE_WAY : INVALID_STRING_ID);
    00481   }
    00482
    00483   if (flags & DC_EXEC) {
    00484     AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
    00485     Game::NewEvent(new ScriptEventIndustryClose(i->index));
    00486     delete i;
    00487   }
    00488   return CommandCost(EXPENSES_CONSTRUCTION, indspec->GetRemovalCost());
    00489 }
    00490
    00491 static void TransportIndustryGoods(TileIndex tile)
    00492 {
    00493   Industry *i = Industry::GetByTile(tile);
    00494   const IndustrySpec *indspec = GetIndustrySpec(i->type);
    00495   bool moved_cargo = false;
    00496
    00497   StationFinder stations(i->location);
    00498
    00499   for (uint j = 0; j < lengthof(i->produced_cargo_waiting); j++) {
    00500     uint cw = min(i->produced_cargo_waiting[j], 255);
    00501     if (cw > indspec->minimal_cargo && i->produced_cargo[j] != CT_INVALID) {
    00502       i->produced_cargo_waiting[j] -= cw;
    00503
    00504       /* fluctuating economy? */
    00505       if (EconomyIsInRecession()) cw = (cw + 1) / 2;
    00506
    00507       i->this_month_production[j] += cw;
    00508
    00509       uint am = MoveGoodsToStation(i->produced_cargo[j], cw, ST_INDUSTRY, i->index, stations.GetStations());
    00510       i->this_month_transported[j] += am;
    00511
    00512       moved_cargo |= (am != 0);
    00513     }
    00514   }
    00515
    00516   if (moved_cargo && !StartStopIndustryTileAnimation(i, IAT_INDUSTRY_DISTRIBUTES_CARGO)) {
    00517     uint newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_production;
    00518
    00519     if (newgfx != INDUSTRYTILE_NOANIM) {
    00520       ResetIndustryConstructionStage(tile);
    00521       SetIndustryCompleted(tile, true);
    00522       SetIndustryGfx(tile, newgfx);
    00523       MarkTileDirtyByTile(tile);
    00524     }
    00525   }
    00526 }
    00527
    00528
    00529 static void AnimateTile_Industry(TileIndex tile)
    00530 {
    00531   IndustryGfx gfx = GetIndustryGfx(tile);
    00532
    00533   if (GetIndustryTileSpec(gfx)->animation.status != ANIM_STATUS_NO_ANIMATION) {
    00534     AnimateNewIndustryTile(tile);
    00535     return;
    00536   }
    00537
    00538   switch (gfx) {
    00539   case GFX_SUGAR_MINE_SIEVE:
    00540     if ((_tick_counter & 1) == 0) {
    00541       byte m = GetAnimationFrame(tile) + 1;
    00542
    00543       switch (m & 7) {
    00544       case 2: SndPlayTileFx(SND_2D_RIP_2, tile); break;
    00545       case 6: SndPlayTileFx(SND_29_RIP, tile); break;
    00546       }
    00547
    00548       if (m >= 96) {
    00549         m = 0;
    00550         DeleteAnimatedTile(tile);
    00551       }
    00552       SetAnimationFrame(tile, m);
    00553
    00554       MarkTileDirtyByTile(tile);
    00555     }
    00556     break;
    00557
    00558   case GFX_TOFFEE_QUARY:
    00559     if ((_tick_counter & 3) == 0) {
    00560       byte m = GetAnimationFrame(tile);
    00561
    00562       if (_industry_anim_offs_toffee[m] == 0xFF) {
    00563         SndPlayTileFx(SND_30_CARTOON_SOUND, tile);
    00564       }
    00565
    00566       if (++m >= 70) {
    00567         m = 0;
    00568         DeleteAnimatedTile(tile);
    00569       }
    00570       SetAnimationFrame(tile, m);
    00571
    00572       MarkTileDirtyByTile(tile);
    00573     }
    00574     break;
    00575
    00576   case GFX_BUBBLE_CATCHER:
    00577     if ((_tick_counter & 1) == 0) {
    00578       byte m = GetAnimationFrame(tile);
    00579
    00580       if (++m >= 40) {
    00581         m = 0;
    00582         DeleteAnimatedTile(tile);
    00583       }
    00584       SetAnimationFrame(tile, m);
    00585
    00586       MarkTileDirtyByTile(tile);
    00587     }
    00588     break;
    00589
    00590   /* Sparks on a coal plant */
    00591   case GFX_POWERPLANT_SPARKS:
    00592     if ((_tick_counter & 3) == 0) {
    00593       byte m = GetAnimationFrame(tile);
    00594       if (m == 6) {
    00595         SetAnimationFrame(tile, 0);
    00596         DeleteAnimatedTile(tile);
    00597       } else {
    00598         SetAnimationFrame(tile, m + 1);
    00599         MarkTileDirtyByTile(tile);
    00600       }
    00601     }
    00602     break;
    00603
    00604   case GFX_TOY_FACTORY:
    00605     if ((_tick_counter & 1) == 0) {
    00606       byte m = GetAnimationFrame(tile) + 1;
    00607
    00608       switch (m) {
    00609         case  1: SndPlayTileFx(SND_2C_MACHINERY, tile); break;
    00610         case 23: SndPlayTileFx(SND_2B_COMEDY_HIT, tile); break;
    00611         case 28: SndPlayTileFx(SND_2A_EXTRACT_AND_POP, tile); break;
    00612         default:
    00613           if (m >= 50) {
    00614             int n = GetIndustryAnimationLoop(tile) + 1;
    00615             m = 0;
    00616             if (n >= 8) {
    00617               n = 0;
    00618               DeleteAnimatedTile(tile);
    00619             }
    00620             SetIndustryAnimationLoop(tile, n);
    00621           }
    00622       }
    00623
    00624       SetAnimationFrame(tile, m);
    00625       MarkTileDirtyByTile(tile);
    00626     }
    00627     break;
    00628
    00629   case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
    00630   case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
    00631   case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
    00632   case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
    00633     if ((_tick_counter & 3) == 0) {
    00634       IndustryGfx gfx = GetIndustryGfx(tile);
    00635
    00636       gfx = (gfx < 155) ? gfx + 1 : 148;
    00637       SetIndustryGfx(tile, gfx);
    00638       MarkTileDirtyByTile(tile);
    00639     }
    00640     break;
    00641
    00642   case GFX_OILWELL_ANIMATED_1:
    00643   case GFX_OILWELL_ANIMATED_2:
    00644   case GFX_OILWELL_ANIMATED_3:
    00645     if ((_tick_counter & 7) == 0) {
    00646       bool b = Chance16(1, 7);
    00647       IndustryGfx gfx = GetIndustryGfx(tile);
    00648
    00649       byte m = GetAnimationFrame(tile) + 1;
    00650       if (m == 4 && (m = 0, ++gfx) == GFX_OILWELL_ANIMATED_3 + 1 && (gfx = GFX_OILWELL_ANIMATED_1, b)) {
    00651         SetIndustryGfx(tile, GFX_OILWELL_NOT_ANIMATED);
    00652         SetIndustryConstructionStage(tile, 3);
    00653         DeleteAnimatedTile(tile);
    00654       } else {
    00655         SetAnimationFrame(tile, m);
    00656         SetIndustryGfx(tile, gfx);
    00657         MarkTileDirtyByTile(tile);
    00658       }
    00659     }
    00660     break;
    00661
    00662   case GFX_COAL_MINE_TOWER_ANIMATED:
    00663   case GFX_COPPER_MINE_TOWER_ANIMATED:
    00664   case GFX_GOLD_MINE_TOWER_ANIMATED: {
    00665       int state = _tick_counter & 0x7FF;
    00666
    00667       if ((state -= 0x400) < 0) return;
    00668
    00669       if (state < 0x1A0) {
    00670         if (state < 0x20 || state >= 0x180) {
    00671           byte m = GetAnimationFrame(tile);
    00672           if (!(m & 0x40)) {
    00673             SetAnimationFrame(tile, m | 0x40);
    00674             SndPlayTileFx(SND_0B_MINING_MACHINERY, tile);
    00675           }
    00676           if (state & 7) return;
    00677         } else {
    00678           if (state & 3) return;
    00679         }
    00680         byte m = (GetAnimationFrame(tile) + 1) | 0x40;
    00681         if (m > 0xC2) m = 0xC0;
    00682         SetAnimationFrame(tile, m);
    00683         MarkTileDirtyByTile(tile);
    00684       } else if (state >= 0x200 && state < 0x3A0) {
    00685         int i = (state < 0x220 || state >= 0x380) ? 7 : 3;
    00686         if (state & i) return;
    00687
    00688         byte m = (GetAnimationFrame(tile) & 0xBF) - 1;
    00689         if (m < 0x80) m = 0x82;
    00690         SetAnimationFrame(tile, m);
    00691         MarkTileDirtyByTile(tile);
    00692       }
    00693       break;
    00694     }
    00695   }
    00696 }
    00697
    00698 static void CreateChimneySmoke(TileIndex tile)
    00699 {
    00700   uint x = TileX(tile) * TILE_SIZE;
    00701   uint y = TileY(tile) * TILE_SIZE;
    00702   int z = GetTileMaxPixelZ(tile);
    00703
    00704   CreateEffectVehicle(x + 15, y + 14, z + 59, EV_CHIMNEY_SMOKE);
    00705 }
    00706
    00707 static void MakeIndustryTileBigger(TileIndex tile)
    00708 {
    00709   byte cnt = GetIndustryConstructionCounter(tile) + 1;
    00710   if (cnt != 4) {
    00711     SetIndustryConstructionCounter(tile, cnt);
    00712     return;
    00713   }
    00714
    00715   byte stage = GetIndustryConstructionStage(tile) + 1;
    00716   SetIndustryConstructionCounter(tile, 0);
    00717   SetIndustryConstructionStage(tile, stage);
    00718   StartStopIndustryTileAnimation(tile, IAT_CONSTRUCTION_STATE_CHANGE);
    00719   if (stage == INDUSTRY_COMPLETED) SetIndustryCompleted(tile, true);
    00720
    00721   MarkTileDirtyByTile(tile);
    00722
    00723   if (!IsIndustryCompleted(tile)) return;
    00724
    00725   IndustryGfx gfx = GetIndustryGfx(tile);
    00726   if (gfx >= NEW_INDUSTRYTILEOFFSET) {
    00727     /* New industries are already animated on construction. */
    00728     return;
    00729   }
    00730
    00731   switch (gfx) {
    00732   case GFX_POWERPLANT_CHIMNEY:
    00733     CreateChimneySmoke(tile);
    00734     break;
    00735
    00736   case GFX_OILRIG_1: {
    00737     /* Do not require an industry tile to be after the first two GFX_OILRIG_1
    00738      * tiles (like the default oil rig). Do a proper check to ensure the
    00739      * tiles belong to the same industry and based on that build the oil rig's
    00740      * station. */
    00741     TileIndex other = tile + TileDiffXY(0, 1);
    00742
    00743     if (IsTileType(other, MP_INDUSTRY) &&
    00744         GetIndustryGfx(other) == GFX_OILRIG_1 &&
    00745         GetIndustryIndex(tile) == GetIndustryIndex(other)) {
    00746       BuildOilRig(tile);
    00747     }
    00748     break;
    00749   }
    00750
    00751   case GFX_TOY_FACTORY:
    00752   case GFX_BUBBLE_CATCHER:
    00753   case GFX_TOFFEE_QUARY:
    00754     SetAnimationFrame(tile, 0);
    00755     SetIndustryAnimationLoop(tile, 0);
    00756     break;
    00757
    00758   case GFX_PLASTIC_FOUNTAIN_ANIMATED_1: case GFX_PLASTIC_FOUNTAIN_ANIMATED_2:
    00759   case GFX_PLASTIC_FOUNTAIN_ANIMATED_3: case GFX_PLASTIC_FOUNTAIN_ANIMATED_4:
    00760   case GFX_PLASTIC_FOUNTAIN_ANIMATED_5: case GFX_PLASTIC_FOUNTAIN_ANIMATED_6:
    00761   case GFX_PLASTIC_FOUNTAIN_ANIMATED_7: case GFX_PLASTIC_FOUNTAIN_ANIMATED_8:
    00762     AddAnimatedTile(tile);
    00763     break;
    00764   }
    00765 }
    00766
    00767 static void TileLoopIndustry_BubbleGenerator(TileIndex tile)
    00768 {
    00769   static const int8 _bubble_spawn_location[3][4] = {
    00770     { 11,   0, -4, -14 },
    00771     { -4, -10, -4,   1 },
    00772     { 49,  59, 60,  65 },
    00773   };
    00774
    00775   SndPlayTileFx(SND_2E_EXTRACT_AND_POP, tile);
    00776
    00777   int dir = Random() & 3;
    00778
    00779   EffectVehicle *v = CreateEffectVehicleAbove(
    00780     TileX(tile) * TILE_SIZE + _bubble_spawn_location[0][dir],
    00781     TileY(tile) * TILE_SIZE + _bubble_spawn_location[1][dir],
    00782     _bubble_spawn_location[2][dir],
    00783     EV_BUBBLE
    00784   );
    00785
    00786   if (v != NULL) v->animation_substate = dir;
    00787 }
    00788
    00789 static void TileLoop_Industry(TileIndex tile)
    00790 {
    00791   if (IsTileOnWater(tile)) TileLoop_Water(tile);
    00792
    00793   /* Normally this doesn't happen, but if an industry NewGRF is removed
    00794    * an industry that was previously build on water can now be flooded.
    00795    * If this happens the tile is no longer an industry tile after
    00796    * returning from TileLoop_Water. */
    00797   if (!IsTileType(tile, MP_INDUSTRY)) return;
    00798
    00799   TriggerIndustryTile(tile, INDTILE_TRIGGER_TILE_LOOP);
    00800
    00801   if (!IsIndustryCompleted(tile)) {
    00802     MakeIndustryTileBigger(tile);
    00803     return;
    00804   }
    00805
    00806   if (_game_mode == GM_EDITOR) return;
    00807
    00808   TransportIndustryGoods(tile);
    00809
    00810   if (StartStopIndustryTileAnimation(tile, IAT_TILELOOP)) return;
    00811
    00812   IndustryGfx newgfx = GetIndustryTileSpec(GetIndustryGfx(tile))->anim_next;
    00813   if (newgfx != INDUSTRYTILE_NOANIM) {
    00814     ResetIndustryConstructionStage(tile);
    00815     SetIndustryGfx(tile, newgfx);
    00816     MarkTileDirtyByTile(tile);
    00817     return;
    00818   }
    00819
    00820   IndustryGfx gfx = GetIndustryGfx(tile);
    00821   switch (gfx) {
    00822   case GFX_COAL_MINE_TOWER_NOT_ANIMATED:
    00823   case GFX_COPPER_MINE_TOWER_NOT_ANIMATED:
    00824   case GFX_GOLD_MINE_TOWER_NOT_ANIMATED:
    00825     if (!(_tick_counter & 0x400) && Chance16(1, 2)) {
    00826       switch (gfx) {
    00827         case GFX_COAL_MINE_TOWER_NOT_ANIMATED:   gfx = GFX_COAL_MINE_TOWER_ANIMATED;   break;
    00828         case GFX_COPPER_MINE_TOWER_NOT_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_ANIMATED; break;
    00829         case GFX_GOLD_MINE_TOWER_NOT_ANIMATED:   gfx = GFX_GOLD_MINE_TOWER_ANIMATED;   break;
    00830       }
    00831       SetIndustryGfx(tile, gfx);
    00832       SetAnimationFrame(tile, 0x80);
    00833       AddAnimatedTile(tile);
    00834     }
    00835     break;
    00836
    00837   case GFX_OILWELL_NOT_ANIMATED:
    00838     if (Chance16(1, 6)) {
    00839       SetIndustryGfx(tile, GFX_OILWELL_ANIMATED_1);
    00840       SetAnimationFrame(tile, 0);
    00841       AddAnimatedTile(tile);
    00842     }
    00843     break;
    00844
    00845   case GFX_COAL_MINE_TOWER_ANIMATED:
    00846   case GFX_COPPER_MINE_TOWER_ANIMATED:
    00847   case GFX_GOLD_MINE_TOWER_ANIMATED:
    00848     if (!(_tick_counter & 0x400)) {
    00849       switch (gfx) {
    00850         case GFX_COAL_MINE_TOWER_ANIMATED:   gfx = GFX_COAL_MINE_TOWER_NOT_ANIMATED;   break;
    00851         case GFX_COPPER_MINE_TOWER_ANIMATED: gfx = GFX_COPPER_MINE_TOWER_NOT_ANIMATED; break;
    00852         case GFX_GOLD_MINE_TOWER_ANIMATED:   gfx = GFX_GOLD_MINE_TOWER_NOT_ANIMATED;   break;
    00853       }
    00854       SetIndustryGfx(tile, gfx);
    00855       SetIndustryCompleted(tile, true);
    00856       SetIndustryConstructionStage(tile, 3);
    00857       DeleteAnimatedTile(tile);
    00858     }
    00859     break;
    00860
    00861   case GFX_POWERPLANT_SPARKS:
    00862     if (Chance16(1, 3)) {
    00863       SndPlayTileFx(SND_0C_ELECTRIC_SPARK, tile);
    00864       AddAnimatedTile(tile);
    00865     }
    00866     break;
    00867
    00868   case GFX_COPPER_MINE_CHIMNEY:
    00869     CreateEffectVehicleAbove(TileX(tile) * TILE_SIZE + 6, TileY(tile) * TILE_SIZE + 6, 43, EV_COPPER_MINE_SMOKE);
    00870     break;
    00871
    00872
    00873   case GFX_TOY_FACTORY: {
    00874       Industry *i = Industry::GetByTile(tile);
    00875       if (i->was_cargo_delivered) {
    00876         i->was_cargo_delivered = false;
    00877         SetIndustryAnimationLoop(tile, 0);
    00878         AddAnimatedTile(tile);
    00879       }
    00880     }
    00881     break;
    00882
    00883   case GFX_BUBBLE_GENERATOR:
    00884     TileLoopIndustry_BubbleGenerator(tile);
    00885     break;
    00886
    00887   case GFX_TOFFEE_QUARY:
    00888     AddAnimatedTile(tile);
    00889     break;
    00890
    00891   case GFX_SUGAR_MINE_SIEVE:
    00892     if (Chance16(1, 3)) AddAnimatedTile(tile);
    00893     break;
    00894   }
    00895 }
    00896
    00897 static bool ClickTile_Industry(TileIndex tile)
    00898 {
    00899   ShowIndustryViewWindow(GetIndustryIndex(tile));
    00900   return true;
    00901 }
    00902
    00903 static TrackStatus GetTileTrackStatus_Industry(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
    00904 {
    00905   return 0;
    00906 }
    00907
    00908 static void ChangeTileOwner_Industry(TileIndex tile, Owner old_owner, Owner new_owner)
    00909 {
    00910   /* If the founder merges, the industry was created by the merged company */
    00911   Industry *i = Industry::GetByTile(tile);
    00912   if (i->founder == old_owner) i->founder = (new_owner == INVALID_OWNER) ? OWNER_NONE : new_owner;
    00913 }
    00914
    00920 bool IsTileForestIndustry(TileIndex tile)
    00921 {
    00922   /* Check for industry tile */
    00923   if (!IsTileType(tile, MP_INDUSTRY)) return false;
    00924
    00925   const Industry *ind = Industry::GetByTile(tile);
    00926
    00927   /* Check for organic industry (i.e. not processing or extractive) */
    00928   if ((GetIndustrySpec(ind->type)->life_type & INDUSTRYLIFE_ORGANIC) == 0) return false;
    00929
    00930   /* Check for wood production */
    00931   for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
    00932     /* The industry produces wood. */
    00933     if (ind->produced_cargo[i] != CT_INVALID && CargoSpec::Get(ind->produced_cargo[i])->label == 'WOOD') return true;
    00934   }
    00935
    00936   return false;
    00937 }
    00938
    00939 static const byte _plantfarmfield_type[] = {1, 1, 1, 1, 1, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6};
    00940
    00941 static bool IsBadFarmFieldTile(TileIndex tile)
    00942 {
    00943   switch (GetTileType(tile)) {
    00944     case MP_CLEAR: return IsClearGround(tile, CLEAR_FIELDS) || IsClearGround(tile, CLEAR_SNOW) || IsClearGround(tile, CLEAR_DESERT);
    00945     case MP_TREES: return (GetTreeGround(tile) == TREE_GROUND_SHORE);
    00946     default:       return true;
    00947   }
    00948 }
    00949
    00950 static bool IsBadFarmFieldTile2(TileIndex tile)
    00951 {
    00952   switch (GetTileType(tile)) {
    00953     case MP_CLEAR: return IsClearGround(tile, CLEAR_SNOW) || IsClearGround(tile, CLEAR_DESERT);
    00954     case MP_TREES: return (GetTreeGround(tile) == TREE_GROUND_SHORE);
    00955     default:       return true;
    00956   }
    00957 }
    00958
    00959 static void SetupFarmFieldFence(TileIndex tile, int size, byte type, Axis direction, bool north)
    00960 {
    00961   do {
    00962     tile = TILE_MASK(tile);
    00963
    00964     if (IsTileType(tile, MP_CLEAR) && IsClearGround(tile, CLEAR_FIELDS)) {
    00965       byte or_ = type;
    00966
    00967       if (or_ == 1 && Chance16(1, 7)) or_ = 2;
    00968
    00969       if (direction == AXIS_X) {
    00970         if (north) {
    00971           SetFenceNW(tile, or_);
    00972         } else {
    00973           SetFenceSE(tile, or_);
    00974         }
    00975       } else {
    00976         if (north) {
    00977           SetFenceNE(tile, or_);
    00978         } else {
    00979           SetFenceSW(tile, or_);
    00980         }
    00981       }
    00982     }
    00983
    00984     tile += (direction == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1));
    00985   } while (--size);
    00986 }
    00987
    00988 static void PlantFarmField(TileIndex tile, IndustryID industry)
    00989 {
    00990   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
    00991     if (GetTileZ(tile) + 2 >= GetSnowLine()) return;
    00992   }
    00993
    00994   /* determine field size */
    00995   uint32 r = (Random() & 0x303) + 0x404;
    00996   if (_settings_game.game_creation.landscape == LT_ARCTIC) r += 0x404;
    00997   uint size_x = GB(r, 0, 8);
    00998   uint size_y = GB(r, 8, 8);
    00999
    01000   TileArea ta(tile - TileDiffXY(min(TileX(tile), size_x / 2), min(TileY(tile), size_y / 2)), size_x, size_y);
    01001   ta.ClampToMap();
    01002
    01003   if (ta.w == 0 || ta.h == 0) return;
    01004
    01005   /* check the amount of bad tiles */
    01006   int count = 0;
    01007   TILE_AREA_LOOP(cur_tile, ta) {
    01008     assert(cur_tile < MapSize());
    01009     count += IsBadFarmFieldTile(cur_tile);
    01010   }
    01011   if (count * 2 >= ta.w * ta.h) return;
    01012
    01013   /* determine type of field */
    01014   r = Random();
    01015   uint counter = GB(r, 5, 3);
    01016   uint field_type = GB(r, 8, 8) * 9 >> 8;
    01017
    01018   /* make field */
    01019   TILE_AREA_LOOP(cur_tile, ta) {
    01020     assert(cur_tile < MapSize());
    01021     if (!IsBadFarmFieldTile2(cur_tile)) {
    01022       MakeField(cur_tile, field_type, industry);
    01023       SetClearCounter(cur_tile, counter);
    01024       MarkTileDirtyByTile(cur_tile);
    01025     }
    01026   }
    01027
    01028   int type = 3;
    01029   if (_settings_game.game_creation.landscape != LT_ARCTIC && _settings_game.game_creation.landscape != LT_TROPIC) {
    01030     type = _plantfarmfield_type[Random() & 0xF];
    01031   }
    01032
    01033   SetupFarmFieldFence(ta.tile, ta.h, type, AXIS_Y, true);
    01034   SetupFarmFieldFence(ta.tile, ta.w, type, AXIS_X, true);
    01035   SetupFarmFieldFence(ta.tile + TileDiffXY(ta.w - 1, 0), ta.h, type, AXIS_Y, false);
    01036   SetupFarmFieldFence(ta.tile + TileDiffXY(0, ta.h - 1), ta.w, type, AXIS_X, false);
    01037 }
    01038
    01039 void PlantRandomFarmField(const Industry *i)
    01040 {
    01041   int x = i->location.w / 2 + Random() % 31 - 16;
    01042   int y = i->location.h / 2 + Random() % 31 - 16;
    01043
    01044   TileIndex tile = TileAddWrap(i->location.tile, x, y);
    01045
    01046   if (tile != INVALID_TILE) PlantFarmField(tile, i->index);
    01047 }
    01048
    01055 static bool SearchLumberMillTrees(TileIndex tile, void *user_data)
    01056 {
    01057   if (IsTileType(tile, MP_TREES) && GetTreeGrowth(tile) > 2) {
    01058     /* found a tree */
    01059
    01060     Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
    01061
    01062     _industry_sound_ctr = 1;
    01063     _industry_sound_tile = tile;
    01064     SndPlayTileFx(SND_38_CHAINSAW, tile);
    01065
    01066     DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
    01067
    01068     cur_company.Restore();
    01069     return true;
    01070   }
    01071   return false;
    01072 }
    01073
    01078 static void ChopLumberMillTrees(Industry *i)
    01079 {
    01080   /* We only want to cut trees if all tiles are completed. */
    01081   TILE_AREA_LOOP(tile_cur, i->location) {
    01082     if (i->TileBelongsToIndustry(tile_cur)) {
    01083       if (!IsIndustryCompleted(tile_cur)) return;
    01084     }
    01085   }
    01086
    01087   TileIndex tile = i->location.tile;
    01088   if (CircularTileSearch(&tile, 40, SearchLumberMillTrees, NULL)) { // 40x40 tiles  to search.
    01089     i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + 45); // Found a tree, add according value to waiting cargo.
    01090   }
    01091 }
    01092
    01093 static void ProduceIndustryGoods(Industry *i)
    01094 {
    01095   const IndustrySpec *indsp = GetIndustrySpec(i->type);
    01096
    01097   /* play a sound? */
    01098   if ((i->counter & 0x3F) == 0) {
    01099     uint32 r;
    01100     uint num;
    01101     if (Chance16R(1, 14, r) && (num = indsp->number_of_sounds) != 0) {
    01102       SndPlayTileFx(
    01103         (SoundFx)(indsp->random_sounds[((r >> 16) * num) >> 16]),
    01104         i->location.tile);
    01105     }
    01106   }
    01107
    01108   i->counter--;
    01109
    01110   /* produce some cargo */
    01111   if ((i->counter % INDUSTRY_PRODUCE_TICKS) == 0) {
    01112     if (HasBit(indsp->callback_mask, CBM_IND_PRODUCTION_256_TICKS)) IndustryProductionCallback(i, 1);
    01113
    01114     IndustryBehaviour indbehav = indsp->behaviour;
    01115     i->produced_cargo_waiting[0] = min(0xffff, i->produced_cargo_waiting[0] + i->production_rate[0]);
    01116     i->produced_cargo_waiting[1] = min(0xffff, i->produced_cargo_waiting[1] + i->production_rate[1]);
    01117
    01118     if ((indbehav & INDUSTRYBEH_PLANT_FIELDS) != 0) {
    01119       uint16 cb_res = CALLBACK_FAILED;
    01120       if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
    01121         cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 0, i, i->type, i->location.tile);
    01122       }
    01123
    01124       bool plant;
    01125       if (cb_res != CALLBACK_FAILED) {
    01126         plant = ConvertBooleanCallback(indsp->grf_prop.grffile, CBID_INDUSTRY_SPECIAL_EFFECT, cb_res);
    01127       } else {
    01128         plant = Chance16(1, 8);
    01129       }
    01130
    01131       if (plant) PlantRandomFarmField(i);
    01132     }
    01133     if ((indbehav & INDUSTRYBEH_CUT_TREES) != 0) {
    01134       uint16 cb_res = CALLBACK_FAILED;
    01135       if (HasBit(indsp->callback_mask, CBM_IND_SPECIAL_EFFECT)) {
    01136         cb_res = GetIndustryCallback(CBID_INDUSTRY_SPECIAL_EFFECT, Random(), 1, i, i->type, i->location.tile);
    01137       }
    01138
    01139       bool cut;
    01140       if (cb_res != CALLBACK_FAILED) {
    01141         cut = ConvertBooleanCallback(indsp->grf_prop.grffile, CBID_INDUSTRY_SPECIAL_EFFECT, cb_res);
    01142       } else {
    01143         cut = ((i->counter % INDUSTRY_CUT_TREE_TICKS) == 0);
    01144       }
    01145
    01146       if (cut) ChopLumberMillTrees(i);
    01147     }
    01148
    01149     TriggerIndustry(i, INDUSTRY_TRIGGER_INDUSTRY_TICK);
    01150     StartStopIndustryTileAnimation(i, IAT_INDUSTRY_TICK);
    01151   }
    01152 }
    01153
    01154 void OnTick_Industry()
    01155 {
    01156   if (_industry_sound_ctr != 0) {
    01157     _industry_sound_ctr++;
    01158
    01159     if (_industry_sound_ctr == 75) {
    01160       SndPlayTileFx(SND_37_BALLOON_SQUEAK, _industry_sound_tile);
    01161     } else if (_industry_sound_ctr == 160) {
    01162       _industry_sound_ctr = 0;
    01163       SndPlayTileFx(SND_36_CARTOON_CRASH, _industry_sound_tile);
    01164     }
    01165   }
    01166
    01167   if (_game_mode == GM_EDITOR) return;
    01168
    01169   Industry *i;
    01170   FOR_ALL_INDUSTRIES(i) {
    01171     ProduceIndustryGoods(i);
    01172   }
    01173 }
    01174
    01180 static CommandCost CheckNewIndustry_NULL(TileIndex tile)
    01181 {
    01182   return CommandCost();
    01183 }
    01184
    01190 static CommandCost CheckNewIndustry_Forest(TileIndex tile)
    01191 {
    01192   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
    01193     if (GetTileZ(tile) < HighestSnowLine() + 2) {
    01194       return_cmd_error(STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED);
    01195     }
    01196   }
    01197   return CommandCost();
    01198 }
    01199
    01205 static CommandCost CheckNewIndustry_OilRefinery(TileIndex tile)
    01206 {
    01207   if (_game_mode == GM_EDITOR) return CommandCost();
    01208   if (DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
    01209
    01210   return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
    01211 }
    01212
    01213 extern bool _ignore_restrictions;
    01214
    01220 static CommandCost CheckNewIndustry_OilRig(TileIndex tile)
    01221 {
    01222   if (_game_mode == GM_EDITOR && _ignore_restrictions) return CommandCost();
    01223   if (TileHeight(tile) == 0 &&
    01224       DistanceFromEdge(TILE_ADDXY(tile, 1, 1)) < _settings_game.game_creation.oil_refinery_limit) return CommandCost();
    01225
    01226   return_cmd_error(STR_ERROR_CAN_ONLY_BE_POSITIONED);
    01227 }
    01228
    01234 static CommandCost CheckNewIndustry_Farm(TileIndex tile)
    01235 {
    01236   if (_settings_game.game_creation.landscape == LT_ARCTIC) {
    01237     if (GetTileZ(tile) + 2 >= HighestSnowLine()) {
    01238       return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01239     }
    01240   }
    01241   return CommandCost();
    01242 }
    01243
    01249 static CommandCost CheckNewIndustry_Plantation(TileIndex tile)
    01250 {
    01251   if (GetTropicZone(tile) == TROPICZONE_DESERT) {
    01252     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01253   }
    01254   return CommandCost();
    01255 }
    01256
    01262 static CommandCost CheckNewIndustry_Water(TileIndex tile)
    01263 {
    01264   if (GetTropicZone(tile) != TROPICZONE_DESERT) {
    01265     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_DESERT);
    01266   }
    01267   return CommandCost();
    01268 }
    01269
    01275 static CommandCost CheckNewIndustry_Lumbermill(TileIndex tile)
    01276 {
    01277   if (GetTropicZone(tile) != TROPICZONE_RAINFOREST) {
    01278     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_RAINFOREST);
    01279   }
    01280   return CommandCost();
    01281 }
    01282
    01288 static CommandCost CheckNewIndustry_BubbleGen(TileIndex tile)
    01289 {
    01290   if (GetTileZ(tile) > 4) {
    01291     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_LOW_AREAS);
    01292   }
    01293   return CommandCost();
    01294 }
    01295
    01301 typedef CommandCost CheckNewIndustryProc(TileIndex tile);
    01302
    01304 static CheckNewIndustryProc * const _check_new_industry_procs[CHECK_END] = {
    01305   CheckNewIndustry_NULL,
    01306   CheckNewIndustry_Forest,
    01307   CheckNewIndustry_OilRefinery,
    01308   CheckNewIndustry_Farm,
    01309   CheckNewIndustry_Plantation,
    01310   CheckNewIndustry_Water,
    01311   CheckNewIndustry_Lumbermill,
    01312   CheckNewIndustry_BubbleGen,
    01313   CheckNewIndustry_OilRig,
    01314 };
    01315
    01326 static CommandCost FindTownForIndustry(TileIndex tile, int type, Town **t)
    01327 {
    01328   *t = ClosestTownFromTile(tile, UINT_MAX);
    01329
    01330   if (_settings_game.economy.multiple_industry_per_town) return CommandCost();
    01331
    01332   const Industry *i;
    01333   FOR_ALL_INDUSTRIES(i) {
    01334     if (i->type == (byte)type && i->town == *t) {
    01335       *t = NULL;
    01336       return_cmd_error(STR_ERROR_ONLY_ONE_ALLOWED_PER_TOWN);
    01337     }
    01338   }
    01339
    01340   return CommandCost();
    01341 }
    01342
    01343 bool IsSlopeRefused(Slope current, Slope refused)
    01344 {
    01345   if (IsSteepSlope(current)) return true;
    01346   if (current != SLOPE_FLAT) {
    01347     if (IsSteepSlope(refused)) return true;
    01348
    01349     Slope t = ComplementSlope(current);
    01350
    01351     if ((refused & SLOPE_W) && (t & SLOPE_NW)) return true;
    01352     if ((refused & SLOPE_S) && (t & SLOPE_NE)) return true;
    01353     if ((refused & SLOPE_E) && (t & SLOPE_SW)) return true;
    01354     if ((refused & SLOPE_N) && (t & SLOPE_SE)) return true;
    01355   }
    01356
    01357   return false;
    01358 }
    01359
    01372 static CommandCost CheckIfIndustryTilesAreFree(TileIndex tile, const IndustryTileTable *it, uint itspec_index, int type, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type, bool *custom_shape_check = NULL)
    01373 {
    01374   bool refused_slope = false;
    01375   bool custom_shape = false;
    01376
    01377   do {
    01378     IndustryGfx gfx = GetTranslatedIndustryTileID(it->gfx);
    01379     TileIndex cur_tile = TileAddWrap(tile, it->ti.x, it->ti.y);
    01380
    01381     if (!IsValidTile(cur_tile)) {
    01382       return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01383     }
    01384
    01385     if (gfx == GFX_WATERTILE_SPECIALCHECK) {
    01386       if (!IsTileType(cur_tile, MP_WATER) ||
    01387           GetTileSlope(cur_tile) != SLOPE_FLAT) {
    01388         return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01389       }
    01390     } else {
    01391       CommandCost ret = EnsureNoVehicleOnGround(cur_tile);
    01392       if (ret.Failed()) return ret;
    01393       if (MayHaveBridgeAbove(cur_tile) && IsBridgeAbove(cur_tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01394
    01395       const IndustryTileSpec *its = GetIndustryTileSpec(gfx);
    01396
    01397       IndustryBehaviour ind_behav = GetIndustrySpec(type)->behaviour;
    01398
    01399       /* Perform land/water check if not disabled */
    01400       if (!HasBit(its->slopes_refused, 5) && ((HasTileWaterClass(cur_tile) && IsTileOnWater(cur_tile)) == !(ind_behav & INDUSTRYBEH_BUILT_ONWATER))) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01401
    01402       if (HasBit(its->callback_mask, CBM_INDT_SHAPE_CHECK)) {
    01403         custom_shape = true;
    01404         CommandCost ret = PerformIndustryTileSlopeCheck(tile, cur_tile, its, type, gfx, itspec_index, initial_random_bits, founder, creation_type);
    01405         if (ret.Failed()) return ret;
    01406       } else {
    01407         Slope tileh = GetTileSlope(cur_tile);
    01408         refused_slope |= IsSlopeRefused(tileh, its->slopes_refused);
    01409       }
    01410
    01411       if ((ind_behav & (INDUSTRYBEH_ONLY_INTOWN | INDUSTRYBEH_TOWN1200_MORE)) || // Tile must be a house
    01412           ((ind_behav & INDUSTRYBEH_ONLY_NEARTOWN) && IsTileType(cur_tile, MP_HOUSE))) { // Tile is allowed to be a house (and it is a house)
    01413         if (!IsTileType(cur_tile, MP_HOUSE)) {
    01414           return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS);
    01415         }
    01416
    01417         /* Clear the tiles as OWNER_TOWN to not affect town rating, and to not clear protected buildings */
    01418         Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
    01419         CommandCost ret = DoCommand(cur_tile, 0, 0, DC_NONE, CMD_LANDSCAPE_CLEAR);
    01420         cur_company.Restore();
    01421
    01422         if (ret.Failed()) return ret;
    01423       } else {
    01424         /* Clear the tiles, but do not affect town ratings */
    01425         CommandCost ret = DoCommand(cur_tile, 0, 0, DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
    01426
    01427         if (ret.Failed()) return ret;
    01428       }
    01429     }
    01430   } while ((++it)->ti.x != -0x80);
    01431
    01432   if (custom_shape_check != NULL) *custom_shape_check = custom_shape;
    01433
    01434   /* It is almost impossible to have a fully flat land in TG, so what we
    01435    *  do is that we check if we can make the land flat later on. See
    01436    *  CheckIfCanLevelIndustryPlatform(). */
    01437   if (!refused_slope || (_settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world && !custom_shape && !_ignore_restrictions)) {
    01438     return CommandCost();
    01439   }
    01440   return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01441 }
    01442
    01450 static CommandCost CheckIfIndustryIsAllowed(TileIndex tile, int type, const Town *t)
    01451 {
    01452   if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_TOWN1200_MORE) && t->population < 1200) {
    01453     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_IN_TOWNS_WITH_POPULATION_OF_1200);
    01454   }
    01455
    01456   if ((GetIndustrySpec(type)->behaviour & INDUSTRYBEH_ONLY_NEARTOWN) && DistanceMax(t->xy, tile) > 9) {
    01457     return_cmd_error(STR_ERROR_CAN_ONLY_BE_BUILT_NEAR_TOWN_CENTER);
    01458   }
    01459
    01460   return CommandCost();
    01461 }
    01462
    01463 static bool CheckCanTerraformSurroundingTiles(TileIndex tile, uint height, int internal)
    01464 {
    01465   /* Check if we don't leave the map */
    01466   if (TileX(tile) == 0 || TileY(tile) == 0 || GetTileType(tile) == MP_VOID) return false;
    01467
    01468   TileArea ta(tile - TileDiffXY(1, 1), 2, 2);
    01469   TILE_AREA_LOOP(tile_walk, ta) {
    01470     uint curh = TileHeight(tile_walk);
    01471     /* Is the tile clear? */
    01472     if ((GetTileType(tile_walk) != MP_CLEAR) && (GetTileType(tile_walk) != MP_TREES)) return false;
    01473
    01474     /* Don't allow too big of a change if this is the sub-tile check */
    01475     if (internal != 0 && Delta(curh, height) > 1) return false;
    01476
    01477     /* Different height, so the surrounding tiles of this tile
    01478      *  has to be correct too (in level, or almost in level)
    01479      *  else you get a chain-reaction of terraforming. */
    01480     if (internal == 0 && curh != height) {
    01481       if (TileX(tile_walk) == 0 || TileY(tile_walk) == 0 || !CheckCanTerraformSurroundingTiles(tile_walk + TileDiffXY(-1, -1), height, internal + 1)) {
    01482         return false;
    01483       }
    01484     }
    01485   }
    01486
    01487   return true;
    01488 }
    01489
    01494 static bool CheckIfCanLevelIndustryPlatform(TileIndex tile, DoCommandFlag flags, const IndustryTileTable *it, int type)
    01495 {
    01496   const int MKEND = -0x80;   // used for last element in an IndustryTileTable (see build_industry.h)
    01497   int max_x = 0;
    01498   int max_y = 0;
    01499
    01500   /* Finds dimensions of largest variant of this industry */
    01501   do {
    01502     if (it->gfx == 0xFF) continue;  //  FF been a marquer for a check on clear water, skip it
    01503     if (it->ti.x > max_x) max_x = it->ti.x;
    01504     if (it->ti.y > max_y) max_y = it->ti.y;
    01505   } while ((++it)->ti.x != MKEND);
    01506
    01507   /* Remember level height */
    01508   uint h = TileHeight(tile);
    01509
    01510   if (TileX(tile) <= _settings_game.construction.industry_platform + 1U || TileY(tile) <= _settings_game.construction.industry_platform + 1U) return false;
    01511   /* Check that all tiles in area and surrounding are clear
    01512    * this determines that there are no obstructing items */
    01513
    01514   TileArea ta(tile + TileDiffXY(-_settings_game.construction.industry_platform, -_settings_game.construction.industry_platform),
    01515       max_x + 2 + 2 * _settings_game.construction.industry_platform, max_y + 2 + 2 * _settings_game.construction.industry_platform);
    01516
    01517   if (TileX(ta.tile) + ta.w >= MapMaxX() || TileY(ta.tile) + ta.h >= MapMaxY()) return false;
    01518
    01519   /* _current_company is OWNER_NONE for randomly generated industries and in editor, or the company who funded or prospected the industry.
    01520    * Perform terraforming as OWNER_TOWN to disable autoslope and town ratings. */
    01521   Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
    01522
    01523   TILE_AREA_LOOP(tile_walk, ta) {
    01524     uint curh = TileHeight(tile_walk);
    01525     if (curh != h) {
    01526       /* This tile needs terraforming. Check if we can do that without
    01527        *  damaging the surroundings too much. */
    01528       if (!CheckCanTerraformSurroundingTiles(tile_walk, h, 0)) {
    01529         cur_company.Restore();
    01530         return false;
    01531       }
    01532       /* This is not 100% correct check, but the best we can do without modifying the map.
    01533        *  What is missing, is if the difference in height is more than 1.. */
    01534       if (DoCommand(tile_walk, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND).Failed()) {
    01535         cur_company.Restore();
    01536         return false;
    01537       }
    01538     }
    01539   }
    01540
    01541   if (flags & DC_EXEC) {
    01542     /* Terraform the land under the industry */
    01543     TILE_AREA_LOOP(tile_walk, ta) {
    01544       uint curh = TileHeight(tile_walk);
    01545       while (curh != h) {
    01546         /* We give the terraforming for free here, because we can't calculate
    01547          *  exact cost in the test-round, and as we all know, that will cause
    01548          *  a nice assert if they don't match ;) */
    01549         DoCommand(tile_walk, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
    01550         curh += (curh > h) ? -1 : 1;
    01551       }
    01552     }
    01553   }
    01554
    01555   cur_company.Restore();
    01556   return true;
    01557 }
    01558
    01559
    01566 static CommandCost CheckIfFarEnoughFromConflictingIndustry(TileIndex tile, int type)
    01567 {
    01568   const IndustrySpec *indspec = GetIndustrySpec(type);
    01569   const Industry *i;
    01570   FOR_ALL_INDUSTRIES(i) {
    01571     /* Within 14 tiles from another industry is considered close */
    01572     if (DistanceMax(tile, i->location.tile) > 14) continue;
    01573
    01574     /* check if there are any conflicting industry types around */
    01575     if (i->type == indspec->conflicting[0] ||
    01576         i->type == indspec->conflicting[1] ||
    01577         i->type == indspec->conflicting[2]) {
    01578       return_cmd_error(STR_ERROR_INDUSTRY_TOO_CLOSE);
    01579     }
    01580   }
    01581   return CommandCost();
    01582 }
    01583
    01595 static void DoCreateNewIndustry(Industry *i, TileIndex tile, IndustryType type, const IndustryTileTable *it, byte layout, Town *t, Owner founder, uint16 initial_random_bits)
    01596 {
    01597   const IndustrySpec *indspec = GetIndustrySpec(type);
    01598
    01599   i->location = TileArea(tile, 1, 1);
    01600   i->type = type;
    01601   Industry::IncIndustryTypeCount(type);
    01602
    01603   i->produced_cargo[0] = indspec->produced_cargo[0];
    01604   i->produced_cargo[1] = indspec->produced_cargo[1];
    01605   i->accepts_cargo[0] = indspec->accepts_cargo[0];
    01606   i->accepts_cargo[1] = indspec->accepts_cargo[1];
    01607   i->accepts_cargo[2] = indspec->accepts_cargo[2];
    01608   i->production_rate[0] = indspec->production_rate[0];
    01609   i->production_rate[1] = indspec->production_rate[1];
    01610
    01611   /* don't use smooth economy for industries using production related callbacks */
    01612   if (indspec->UsesSmoothEconomy()) {
    01613     i->production_rate[0] = min((RandomRange(256) + 128) * i->production_rate[0] >> 8, 255);
    01614     i->production_rate[1] = min((RandomRange(256) + 128) * i->production_rate[1] >> 8, 255);
    01615   }
    01616
    01617   i->town = t;
    01618   i->owner = OWNER_NONE;
    01619
    01620   uint16 r = Random();
    01621   i->random_colour = GB(r, 0, 4);
    01622   i->counter = GB(r, 4, 12);
    01623   i->random = initial_random_bits;
    01624   i->produced_cargo_waiting[0] = 0;
    01625   i->produced_cargo_waiting[1] = 0;
    01626   i->incoming_cargo_waiting[0] = 0;
    01627   i->incoming_cargo_waiting[1] = 0;
    01628   i->incoming_cargo_waiting[2] = 0;
    01629   i->this_month_production[0] = 0;
    01630   i->this_month_production[1] = 0;
    01631   i->this_month_transported[0] = 0;
    01632   i->this_month_transported[1] = 0;
    01633   i->last_month_pct_transported[0] = 0;
    01634   i->last_month_pct_transported[1] = 0;
    01635   i->last_month_transported[0] = 0;
    01636   i->last_month_transported[1] = 0;
    01637   i->was_cargo_delivered = false;
    01638   i->last_prod_year = _cur_year;
    01639   i->last_month_production[0] = i->production_rate[0] * 8;
    01640   i->last_month_production[1] = i->production_rate[1] * 8;
    01641   i->founder = founder;
    01642
    01643   i->construction_date = _date;
    01644   i->construction_type = (_game_mode == GM_EDITOR) ? ICT_SCENARIO_EDITOR :
    01645       (_generating_world ? ICT_MAP_GENERATION : ICT_NORMAL_GAMEPLAY);
    01646
    01647   /* Adding 1 here makes it conform to specs of var44 of varaction2 for industries
    01648    * 0 = created prior of newindustries
    01649    * else, chosen layout + 1 */
    01650   i->selected_layout = layout + 1;
    01651
    01652   if (!_generating_world) i->last_month_production[0] = i->last_month_production[1] = 0;
    01653
    01654   i->prod_level = PRODLEVEL_DEFAULT;
    01655
    01656   /* Call callbacks after the regular fields got initialised. */
    01657
    01658   if (HasBit(indspec->callback_mask, CBM_IND_DECIDE_COLOUR)) {
    01659     uint16 res = GetIndustryCallback(CBID_INDUSTRY_DECIDE_COLOUR, 0, 0, i, type, INVALID_TILE);
    01660     if (res != CALLBACK_FAILED) {
    01661       if (GB(res, 4, 11) != 0) ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_DECIDE_COLOUR, res);
    01662       i->random_colour = GB(res, 0, 4);
    01663     }
    01664   }
    01665
    01666   if (HasBit(indspec->callback_mask, CBM_IND_INPUT_CARGO_TYPES)) {
    01667     for (uint j = 0; j < lengthof(i->accepts_cargo); j++) i->accepts_cargo[j] = CT_INVALID;
    01668     for (uint j = 0; j < lengthof(i->accepts_cargo); j++) {
    01669       uint16 res = GetIndustryCallback(CBID_INDUSTRY_INPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
    01670       if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
    01671       if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
    01672         ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_INPUT_CARGO_TYPES, res);
    01673         break;
    01674       }
    01675       i->accepts_cargo[j] = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
    01676     }
    01677   }
    01678
    01679   if (HasBit(indspec->callback_mask, CBM_IND_OUTPUT_CARGO_TYPES)) {
    01680     for (uint j = 0; j < lengthof(i->produced_cargo); j++) i->produced_cargo[j] = CT_INVALID;
    01681     for (uint j = 0; j < lengthof(i->produced_cargo); j++) {
    01682       uint16 res = GetIndustryCallback(CBID_INDUSTRY_OUTPUT_CARGO_TYPES, j, 0, i, type, INVALID_TILE);
    01683       if (res == CALLBACK_FAILED || GB(res, 0, 8) == CT_INVALID) break;
    01684       if (indspec->grf_prop.grffile->grf_version >= 8 && res >= 0x100) {
    01685         ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_OUTPUT_CARGO_TYPES, res);
    01686         break;
    01687       }
    01688       i->produced_cargo[j] = GetCargoTranslation(GB(res, 0, 8), indspec->grf_prop.grffile);
    01689     }
    01690   }
    01691
    01692   /* Plant the tiles */
    01693
    01694   do {
    01695     TileIndex cur_tile = tile + ToTileIndexDiff(it->ti);
    01696
    01697     if (it->gfx != GFX_WATERTILE_SPECIALCHECK) {
    01698       i->location.Add(cur_tile);
    01699
    01700       WaterClass wc = (IsWaterTile(cur_tile) ? GetWaterClass(cur_tile) : WATER_CLASS_INVALID);
    01701
    01702       DoCommand(cur_tile, 0, 0, DC_EXEC | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
    01703
    01704       MakeIndustry(cur_tile, i->index, it->gfx, Random(), wc);
    01705
    01706       if (_generating_world) {
    01707         SetIndustryConstructionCounter(cur_tile, 3);
    01708         SetIndustryConstructionStage(cur_tile, 2);
    01709       }
    01710
    01711       /* it->gfx is stored in the map. But the translated ID cur_gfx is the interesting one */
    01712       IndustryGfx cur_gfx = GetTranslatedIndustryTileID(it->gfx);
    01713       const IndustryTileSpec *its = GetIndustryTileSpec(cur_gfx);
    01714       if (its->animation.status != ANIM_STATUS_NO_ANIMATION) AddAnimatedTile(cur_tile);
    01715     }
    01716   } while ((++it)->ti.x != -0x80);
    01717
    01718   if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
    01719     for (uint j = 0; j != 50; j++) PlantRandomFarmField(i);
    01720   }
    01721   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 0);
    01722
    01723   Station::RecomputeIndustriesNearForAll();
    01724 }
    01725
    01742 static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, DoCommandFlag flags, const IndustrySpec *indspec, uint itspec_index, uint32 random_var8f, uint16 random_initial_bits, Owner founder, IndustryAvailabilityCallType creation_type, Industry **ip)
    01743 {
    01744   assert(itspec_index < indspec->num_table);
    01745   const IndustryTileTable *it = indspec->table[itspec_index];
    01746   bool custom_shape_check = false;
    01747
    01748   *ip = NULL;
    01749
    01750   SmallVector<ClearedObjectArea, 1> object_areas(_cleared_object_areas);
    01751   CommandCost ret = CheckIfIndustryTilesAreFree(tile, it, itspec_index, type, random_initial_bits, founder, creation_type, &custom_shape_check);
    01752   _cleared_object_areas = object_areas;
    01753   if (ret.Failed()) return ret;
    01754
    01755   if (HasBit(GetIndustrySpec(type)->callback_mask, CBM_IND_LOCATION)) {
    01756     ret = CheckIfCallBackAllowsCreation(tile, type, itspec_index, random_var8f, random_initial_bits, founder, creation_type);
    01757   } else {
    01758     ret = _check_new_industry_procs[indspec->check_proc](tile);
    01759   }
    01760   if (ret.Failed()) return ret;
    01761
    01762   if (!custom_shape_check && _settings_game.game_creation.land_generator == LG_TERRAGENESIS && _generating_world &&
    01763       !_ignore_restrictions && !CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER, it, type)) {
    01764     return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
    01765   }
    01766
    01767   ret = CheckIfFarEnoughFromConflictingIndustry(tile, type);
    01768   if (ret.Failed()) return ret;
    01769
    01770   Town *t = NULL;
    01771   ret = FindTownForIndustry(tile, type, &t);
    01772   if (ret.Failed()) return ret;
    01773   assert(t != NULL);
    01774
    01775   ret = CheckIfIndustryIsAllowed(tile, type, t);
    01776   if (ret.Failed()) return ret;
    01777
    01778   if (!Industry::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_INDUSTRIES);
    01779
    01780   if (flags & DC_EXEC) {
    01781     *ip = new Industry(tile);
    01782     if (!custom_shape_check) CheckIfCanLevelIndustryPlatform(tile, DC_NO_WATER | DC_EXEC, it, type);
    01783     DoCreateNewIndustry(*ip, tile, type, it, itspec_index, t, founder, random_initial_bits);
    01784   }
    01785
    01786   return CommandCost();
    01787 }
    01788
    01800 CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
    01801 {
    01802   IndustryType it = GB(p1, 0, 8);
    01803   if (it >= NUM_INDUSTRYTYPES) return CMD_ERROR;
    01804
    01805   const IndustrySpec *indspec = GetIndustrySpec(it);
    01806
    01807   /* Check if the to-be built/founded industry is available for this climate. */
    01808   if (!indspec->enabled || indspec->num_table == 0) return CMD_ERROR;
    01809
    01810   /* If the setting for raw-material industries is not on, you cannot build raw-material industries.
    01811    * Raw material industries are industries that do not accept cargo (at least for now) */
    01812   if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 0 && indspec->IsRawIndustry()) {
    01813     return CMD_ERROR;
    01814   }
    01815
    01816   if (_game_mode != GM_EDITOR && GetIndustryProbabilityCallback(it, IACT_USERCREATION, 1) == 0) {
    01817     return CMD_ERROR;
    01818   }
    01819
    01820   Randomizer randomizer;
    01821   randomizer.SetSeed(p2);
    01822   uint16 random_initial_bits = GB(p2, 0, 16);
    01823   uint32 random_var8f = randomizer.Next();
    01824   int num_layouts = indspec->num_table;
    01825   CommandCost ret = CommandCost(STR_ERROR_SITE_UNSUITABLE);
    01826
    01827   Industry *ind = NULL;
    01828   if (_game_mode != GM_EDITOR && _settings_game.construction.raw_industry_construction == 2 && indspec->IsRawIndustry()) {
    01829     if (flags & DC_EXEC) {
    01830       /* Prospected industries are build as OWNER_TOWN to not e.g. be build on owned land of the founder */
    01831       Backup<CompanyByte> cur_company(_current_company, OWNER_TOWN, FILE_LINE);
    01832       /* Prospecting has a chance to fail, however we cannot guarantee that something can
    01833        * be built on the map, so the chance gets lower when the map is fuller, but there
    01834        * is nothing we can really do about that. */
    01835       if (Random() <= indspec->prospecting_chance) {
    01836         for (int i = 0; i < 5000; i++) {
    01837           /* We should not have more than one Random() in a function call
    01838            * because parameter evaluation order is not guaranteed in the c++ standard
    01839            */
    01840           tile = RandomTile();
    01841           /* Start with a random layout */
    01842           int layout = RandomRange(num_layouts);
    01843           /* Check now each layout, starting with the random one */
    01844           for (int j = 0; j < num_layouts; j++) {
    01845             layout = (layout + 1) % num_layouts;
    01846             ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, cur_company.GetOriginalValue(), IACT_PROSPECTCREATION, &ind);
    01847             if (ret.Succeeded()) break;
    01848           }
    01849           if (ret.Succeeded()) break;
    01850         }
    01851       }
    01852       cur_company.Restore();
    01853     }
    01854   } else {
    01855     int layout = GB(p1, 8, 8);
    01856     if (layout >= num_layouts) return CMD_ERROR;
    01857
    01858     /* Check subsequently each layout, starting with the given layout in p1 */
    01859     for (int i = 0; i < num_layouts; i++) {
    01860       layout = (layout + 1) % num_layouts;
    01861       ret = CreateNewIndustryHelper(tile, it, flags, indspec, layout, random_var8f, random_initial_bits, _current_company, IACT_USERCREATION, &ind);
    01862       if (ret.Succeeded()) break;
    01863     }
    01864
    01865     /* If it still failed, there's no suitable layout to build here, return the error */
    01866     if (ret.Failed()) return ret;
    01867   }
    01868
    01869   if ((flags & DC_EXEC) && ind != NULL && _game_mode != GM_EDITOR) {
    01870     /* Created a new industry in-game, advertise the event. */
    01871     SetDParam(0, indspec->name);
    01872     if (indspec->new_industry_text > STR_LAST_STRINGID) {
    01873       SetDParam(1, STR_TOWN_NAME);
    01874       SetDParam(2, ind->town->index);
    01875     } else {
    01876       SetDParam(1, ind->town->index);
    01877     }
    01878     AddIndustryNewsItem(indspec->new_industry_text, NS_INDUSTRY_OPEN, ind->index);
    01879     AI::BroadcastNewEvent(new ScriptEventIndustryOpen(ind->index));
    01880     Game::NewEvent(new ScriptEventIndustryOpen(ind->index));
    01881   }
    01882
    01883   return CommandCost(EXPENSES_OTHER, indspec->GetConstructionCost());
    01884 }
    01885
    01886
    01894 static Industry *CreateNewIndustry(TileIndex tile, IndustryType type, IndustryAvailabilityCallType creation_type)
    01895 {
    01896   const IndustrySpec *indspec = GetIndustrySpec(type);
    01897
    01898   uint32 seed = Random();
    01899   uint32 seed2 = Random();
    01900   Industry *i = NULL;
    01901   CommandCost ret = CreateNewIndustryHelper(tile, type, DC_EXEC, indspec, RandomRange(indspec->num_table), seed, GB(seed2, 0, 16), OWNER_NONE, creation_type, &i);
    01902   assert(i != NULL || ret.Failed());
    01903   return i;
    01904 }
    01905
    01912 static uint32 GetScaledIndustryGenerationProbability(IndustryType it, bool *force_at_least_one)
    01913 {
    01914   const IndustrySpec *ind_spc = GetIndustrySpec(it);
    01915   uint32 chance = ind_spc->appear_creation[_settings_game.game_creation.landscape] * 16; // * 16 to increase precision
    01916   if (!ind_spc->enabled || ind_spc->num_table == 0 ||
    01917       (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) ||
    01918       (chance = GetIndustryProbabilityCallback(it, IACT_MAPGENERATION, chance)) == 0) {
    01919     *force_at_least_one = false;
    01920     return 0;
    01921   } else {
    01922     /* We want industries appearing at coast to appear less often on bigger maps, as length of coast increases slower than map area.
    01923      * For simplicity we scale in both cases, though scaling the probabilities of all industries has no effect. */
    01924     chance = (ind_spc->check_proc == CHECK_REFINERY || ind_spc->check_proc == CHECK_OIL_RIG) ? ScaleByMapSize1D(chance) : ScaleByMapSize(chance);
    01925
    01926     *force_at_least_one = (chance > 0) && !(ind_spc->behaviour & INDUSTRYBEH_NOBUILT_MAPCREATION) && (_game_mode != GM_EDITOR);
    01927     return chance;
    01928   }
    01929 }
    01930
    01937 static uint16 GetIndustryGamePlayProbability(IndustryType it, byte *min_number)
    01938 {
    01939   if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) {
    01940     *min_number = 0;
    01941     return 0;
    01942   }
    01943
    01944   const IndustrySpec *ind_spc = GetIndustrySpec(it);
    01945   byte chance = ind_spc->appear_ingame[_settings_game.game_creation.landscape];
    01946   if (!ind_spc->enabled || ind_spc->num_table == 0 ||
    01947       ((ind_spc->behaviour & INDUSTRYBEH_BEFORE_1950) && _cur_year > 1950) ||
    01948       ((ind_spc->behaviour & INDUSTRYBEH_AFTER_1960) && _cur_year < 1960) ||
    01949       (chance = GetIndustryProbabilityCallback(it, IACT_RANDOMCREATION, chance)) == 0) {
    01950     *min_number = 0;
    01951     return 0;
    01952   }
    01953   *min_number = (ind_spc->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) ? 1 : 0;
    01954   return chance;
    01955 }
    01956
    01961 static uint GetNumberOfIndustries()
    01962 {
    01963   /* Number of industries on a 256x256 map. */
    01964   static const uint16 numof_industry_table[] = {
    01965     0,    // none
    01966     0,    // minimal
    01967     10,   // very low
    01968     25,   // low
    01969     55,   // normal
    01970     80,   // high
    01971   };
    01972
    01973   assert(lengthof(numof_industry_table) == ID_END);
    01974   uint difficulty = (_game_mode != GM_EDITOR) ? _settings_game.difficulty.industry_density : (uint)ID_VERY_LOW;
    01975   return ScaleByMapSize(numof_industry_table[difficulty]);
    01976 }
    01977
    01982 static void AdvertiseIndustryOpening(const Industry *ind)
    01983 {
    01984   const IndustrySpec *ind_spc = GetIndustrySpec(ind->type);
    01985   SetDParam(0, ind_spc->name);
    01986   if (ind_spc->new_industry_text > STR_LAST_STRINGID) {
    01987     SetDParam(1, STR_TOWN_NAME);
    01988     SetDParam(2, ind->town->index);
    01989   } else {
    01990     SetDParam(1, ind->town->index);
    01991   }
    01992   AddIndustryNewsItem(ind_spc->new_industry_text, NS_INDUSTRY_OPEN, ind->index);
    01993   AI::BroadcastNewEvent(new ScriptEventIndustryOpen(ind->index));
    01994   Game::NewEvent(new ScriptEventIndustryOpen(ind->index));
    01995 }
    01996
    02005 static Industry *PlaceIndustry(IndustryType type, IndustryAvailabilityCallType creation_type, bool try_hard)
    02006 {
    02007   uint tries = try_hard ? 10000u : 2000u;
    02008   for (; tries > 0; tries--) {
    02009     Industry *ind = CreateNewIndustry(RandomTile(), type, creation_type);
    02010     if (ind != NULL) return ind;
    02011   }
    02012   return NULL;
    02013 }
    02014
    02020 static void PlaceInitialIndustry(IndustryType type, bool try_hard)
    02021 {
    02022   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
    02023
    02024   IncreaseGeneratingWorldProgress(GWP_INDUSTRY);
    02025   PlaceIndustry(type, IACT_MAPGENERATION, try_hard);
    02026
    02027   cur_company.Restore();
    02028 }
    02029
    02034 static uint GetCurrentTotalNumberOfIndustries()
    02035 {
    02036   int total = 0;
    02037   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) total += Industry::GetIndustryTypeCount(it);
    02038   return total;
    02039 }
    02040
    02041
    02043 void IndustryTypeBuildData::Reset()
    02044 {
    02045   this->probability  = 0;
    02046   this->min_number   = 0;
    02047   this->target_count = 0;
    02048   this->max_wait     = 1;
    02049   this->wait_count   = 0;
    02050 }
    02051
    02053 void IndustryBuildData::Reset()
    02054 {
    02055   this->wanted_inds = GetCurrentTotalNumberOfIndustries() << 16;
    02056
    02057   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02058     this->builddata[it].Reset();
    02059   }
    02060 }
    02061
    02063 void IndustryBuildData::MonthlyLoop()
    02064 {
    02065   static const int NEWINDS_PER_MONTH = 0x38000 / (10 * 12); // lower 16 bits is a float fraction, 3.5 industries per decade, divided by 10 * 12 months.
    02066   if (_settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // 'no industries' setting.
    02067
    02068   /* To prevent running out of unused industries for the player to connect,
    02069    * add a fraction of new industries each month, but only if the manager can keep up. */
    02070   uint max_behind = 1 + min(99u, ScaleByMapSize(3)); // At most 2 industries for small maps, and 100 at the biggest map (about 6 months industry build attempts).
    02071   if (GetCurrentTotalNumberOfIndustries() + max_behind >= (this->wanted_inds >> 16)) {
    02072     this->wanted_inds += ScaleByMapSize(NEWINDS_PER_MONTH);
    02073   }
    02074 }
    02075
    02080 void GenerateIndustries()
    02081 {
    02082   if (_game_mode != GM_EDITOR && _settings_game.difficulty.industry_density == ID_FUND_ONLY) return; // No industries in the game.
    02083
    02084   uint32 industry_probs[NUM_INDUSTRYTYPES];
    02085   bool force_at_least_one[NUM_INDUSTRYTYPES];
    02086   uint32 total_prob = 0;
    02087   uint num_forced = 0;
    02088
    02089   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02090     industry_probs[it] = GetScaledIndustryGenerationProbability(it, force_at_least_one + it);
    02091     total_prob += industry_probs[it];
    02092     if (force_at_least_one[it]) num_forced++;
    02093   }
    02094
    02095   uint total_amount = GetNumberOfIndustries();
    02096   if (total_prob == 0 || total_amount < num_forced) {
    02097     /* Only place the forced ones */
    02098     total_amount = num_forced;
    02099   }
    02100
    02101   SetGeneratingWorldProgress(GWP_INDUSTRY, total_amount);
    02102
    02103   /* Try to build one industry per type independent of any probabilities */
    02104   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02105     if (force_at_least_one[it]) {
    02106       assert(total_amount > 0);
    02107       total_amount--;
    02108       PlaceInitialIndustry(it, true);
    02109     }
    02110   }
    02111
    02112   /* Add the remaining industries according to their probabilities */
    02113   for (uint i = 0; i < total_amount; i++) {
    02114     uint32 r = RandomRange(total_prob);
    02115     IndustryType it = 0;
    02116     while (r >= industry_probs[it]) {
    02117       r -= industry_probs[it];
    02118       it++;
    02119       assert(it < NUM_INDUSTRYTYPES);
    02120     }
    02121     assert(industry_probs[it] > 0);
    02122     PlaceInitialIndustry(it, false);
    02123   }
    02124   _industry_builder.Reset();
    02125 }
    02126
    02131 static void UpdateIndustryStatistics(Industry *i)
    02132 {
    02133   for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
    02134     if (i->produced_cargo[j] != CT_INVALID) {
    02135       byte pct = 0;
    02136       if (i->this_month_production[j] != 0) {
    02137         i->last_prod_year = _cur_year;
    02138         pct = min(i->this_month_transported[j] * 256 / i->this_month_production[j], 255);
    02139       }
    02140       i->last_month_pct_transported[j] = pct;
    02141
    02142       i->last_month_production[j] = i->this_month_production[j];
    02143       i->this_month_production[j] = 0;
    02144
    02145       i->last_month_transported[j] = i->this_month_transported[j];
    02146       i->this_month_transported[j] = 0;
    02147     }
    02148   }
    02149 }
    02150
    02155 void Industry::RecomputeProductionMultipliers()
    02156 {
    02157   const IndustrySpec *indspec = GetIndustrySpec(this->type);
    02158   assert(!indspec->UsesSmoothEconomy());
    02159
    02160   /* Rates are rounded up, so e.g. oilrig always produces some passengers */
    02161   this->production_rate[0] = min(CeilDiv(indspec->production_rate[0] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
    02162   this->production_rate[1] = min(CeilDiv(indspec->production_rate[1] * this->prod_level, PRODLEVEL_DEFAULT), 0xFF);
    02163 }
    02164
    02165
    02171 bool IndustryTypeBuildData::GetIndustryTypeData(IndustryType it)
    02172 {
    02173   byte min_number;
    02174   uint32 probability = GetIndustryGamePlayProbability(it, &min_number);
    02175   bool changed = min_number != this->min_number || probability != this->probability;
    02176   this->min_number = min_number;
    02177   this->probability = probability;
    02178   return changed;
    02179 }
    02180
    02182 void IndustryBuildData::SetupTargetCount()
    02183 {
    02184   bool changed = false;
    02185   uint num_planned = 0; // Number of industries planned in the industry build data.
    02186   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02187     changed |= this->builddata[it].GetIndustryTypeData(it);
    02188     num_planned += this->builddata[it].target_count;
    02189   }
    02190   uint total_amount = this->wanted_inds >> 16; // Desired total number of industries.
    02191   changed |= num_planned != total_amount;
    02192   if (!changed) return; // All industries are still the same, no need to re-randomize.
    02193
    02194   /* Initialize the target counts. */
    02195   uint force_build = 0;  // Number of industries that should always be available.
    02196   uint32 total_prob = 0; // Sum of probabilities.
    02197   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02198     IndustryTypeBuildData *ibd = this->builddata + it;
    02199     force_build += ibd->min_number;
    02200     ibd->target_count = ibd->min_number;
    02201     total_prob += ibd->probability;
    02202   }
    02203
    02204   if (total_prob == 0) return; // No buildable industries.
    02205
    02206   /* Subtract forced industries from the number of industries available for construction. */
    02207   total_amount = (total_amount <= force_build) ? 0 : total_amount - force_build;
    02208
    02209   /* Assign number of industries that should be aimed for, by using the probability as a weight. */
    02210   while (total_amount > 0) {
    02211     uint32 r = RandomRange(total_prob);
    02212     IndustryType it = 0;
    02213     while (r >= this->builddata[it].probability) {
    02214       r -= this->builddata[it].probability;
    02215       it++;
    02216       assert(it < NUM_INDUSTRYTYPES);
    02217     }
    02218     assert(this->builddata[it].probability > 0);
    02219     this->builddata[it].target_count++;
    02220     total_amount--;
    02221   }
    02222 }
    02223
    02227 void IndustryBuildData::TryBuildNewIndustry()
    02228 {
    02229   this->SetupTargetCount();
    02230
    02231   int missing = 0;       // Number of industries that need to be build.
    02232   uint count = 0;        // Number of industry types eligible for build.
    02233   uint32 total_prob = 0; // Sum of probabilities.
    02234   IndustryType forced_build = NUM_INDUSTRYTYPES; // Industry type that should be forcibly build.
    02235   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02236     int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
    02237     missing += difference;
    02238     if (this->builddata[it].wait_count > 0) continue; // This type may not be built now.
    02239     if (difference > 0) {
    02240       if (Industry::GetIndustryTypeCount(it) == 0 && this->builddata[it].min_number > 0) {
    02241         /* An industry that should exist at least once, is not available. Force it, trying the most needed one first. */
    02242         if (forced_build == NUM_INDUSTRYTYPES ||
    02243             difference > this->builddata[forced_build].target_count - Industry::GetIndustryTypeCount(forced_build)) {
    02244           forced_build = it;
    02245         }
    02246       }
    02247       total_prob += difference;
    02248       count++;
    02249     }
    02250   }
    02251
    02252   if (EconomyIsInRecession() || (forced_build == NUM_INDUSTRYTYPES && (missing <= 0 || total_prob == 0))) count = 0; // Skip creation of an industry.
    02253
    02254   if (count >= 1) {
    02255     /* If not forced, pick a weighted random industry to build.
    02256      * For the case that count == 1, there is no need to draw a random number. */
    02257     IndustryType it;
    02258     if (forced_build != NUM_INDUSTRYTYPES) {
    02259       it = forced_build;
    02260     } else {
    02261       /* Non-forced, select an industry type to build (weighted random). */
    02262       uint32 r = 0; // Initialized to silence the compiler.
    02263       if (count > 1) r = RandomRange(total_prob);
    02264       for (it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02265         if (this->builddata[it].wait_count > 0) continue; // Type may not be built now.
    02266         int difference = this->builddata[it].target_count - Industry::GetIndustryTypeCount(it);
    02267         if (difference <= 0) continue; // Too many of this kind.
    02268         if (count == 1) break;
    02269         if (r < (uint)difference) break;
    02270         r -= difference;
    02271       }
    02272       assert(it < NUM_INDUSTRYTYPES && this->builddata[it].target_count > Industry::GetIndustryTypeCount(it));
    02273     }
    02274
    02275     /* Try to create the industry. */
    02276     const Industry *ind = PlaceIndustry(it, IACT_RANDOMCREATION, false);
    02277     if (ind == NULL) {
    02278       this->builddata[it].wait_count = this->builddata[it].max_wait + 1; // Compensate for decrementing below.
    02279       this->builddata[it].max_wait = min(1000, this->builddata[it].max_wait + 2);
    02280     } else {
    02281       AdvertiseIndustryOpening(ind);
    02282       this->builddata[it].max_wait = max(this->builddata[it].max_wait / 2, 1); // Reduce waiting time of the industry type.
    02283     }
    02284   }
    02285
    02286   /* Decrement wait counters. */
    02287   for (IndustryType it = 0; it < NUM_INDUSTRYTYPES; it++) {
    02288     if (this->builddata[it].wait_count > 0) this->builddata[it].wait_count--;
    02289   }
    02290 }
    02291
    02300 static bool CheckIndustryCloseDownProtection(IndustryType type)
    02301 {
    02302   const IndustrySpec *indspec = GetIndustrySpec(type);
    02303
    02304   /* oil wells (or the industries with that flag set) are always allowed to closedown */
    02305   if ((indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE) return false;
    02306   return (indspec->behaviour & INDUSTRYBEH_CANCLOSE_LASTINSTANCE) == 0 && Industry::GetIndustryTypeCount(type) <= 1;
    02307 }
    02308
    02318 static void CanCargoServiceIndustry(CargoID cargo, Industry *ind, bool *c_accepts, bool *c_produces)
    02319 {
    02320   if (cargo == CT_INVALID) return;
    02321
    02322   /* Check for acceptance of cargo */
    02323   for (byte j = 0; j < lengthof(ind->accepts_cargo); j++) {
    02324     if (cargo == ind->accepts_cargo[j] && !IndustryTemporarilyRefusesCargo(ind, cargo)) {
    02325       *c_accepts = true;
    02326       break;
    02327     }
    02328   }
    02329
    02330   /* Check for produced cargo */
    02331   for (byte j = 0; j < lengthof(ind->produced_cargo); j++) {
    02332     if (cargo == ind->produced_cargo[j]) {
    02333       *c_produces = true;
    02334       break;
    02335     }
    02336   }
    02337 }
    02338
    02352 static int WhoCanServiceIndustry(Industry *ind)
    02353 {
    02354   /* Find all stations within reach of the industry */
    02355   StationList stations;
    02356   FindStationsAroundTiles(ind->location, &stations);
    02357
    02358   if (stations.Length() == 0) return 0; // No stations found at all => nobody services
    02359
    02360   const Vehicle *v;
    02361   int result = 0;
    02362   FOR_ALL_VEHICLES(v) {
    02363     /* Is it worthwhile to try this vehicle? */
    02364     if (v->owner != _local_company && result != 0) continue;
    02365
    02366     /* Check whether it accepts the right kind of cargo */
    02367     bool c_accepts = false;
    02368     bool c_produces = false;
    02369     if (v->type == VEH_TRAIN && v->IsFrontEngine()) {
    02370       for (const Vehicle *u = v; u != NULL; u = u->Next()) {
    02371         CanCargoServiceIndustry(u->cargo_type, ind, &c_accepts, &c_produces);
    02372       }
    02373     } else if (v->type == VEH_ROAD || v->type == VEH_SHIP || v->type == VEH_AIRCRAFT) {
    02374       CanCargoServiceIndustry(v->cargo_type, ind, &c_accepts, &c_produces);
    02375     } else {
    02376       continue;
    02377     }
    02378     if (!c_accepts && !c_produces) continue; // Wrong cargo
    02379
    02380     /* Check orders of the vehicle.
    02381      * We cannot check the first of shared orders only, since the first vehicle in such a chain
    02382      * may have a different cargo type.
    02383      */
    02384     const Order *o;
    02385     FOR_VEHICLE_ORDERS(v, o) {
    02386       if (o->IsType(OT_GOTO_STATION) && !(o->GetUnloadType() & OUFB_TRANSFER)) {
    02387         /* Vehicle visits a station to load or unload */
    02388         Station *st = Station::Get(o->GetDestination());
    02389         assert(st != NULL);
    02390
    02391         /* Same cargo produced by industry is dropped here => not serviced by vehicle v */
    02392         if ((o->GetUnloadType() & OUFB_UNLOAD) && !c_accepts) break;
    02393
    02394         if (stations.Contains(st)) {
    02395           if (v->owner == _local_company) return 2; // Company services industry
    02396           result = 1; // Competitor services industry
    02397         }
    02398       }
    02399     }
    02400   }
    02401   return result;
    02402 }
    02403
    02411 static void ReportNewsProductionChangeIndustry(Industry *ind, CargoID type, int percent)
    02412 {
    02413   NewsSubtype ns;
    02414
    02415   switch (WhoCanServiceIndustry(ind)) {
    02416     case 0: ns = NS_INDUSTRY_NOBODY;  break;
    02417     case 1: ns = NS_INDUSTRY_OTHER;   break;
    02418     case 2: ns = NS_INDUSTRY_COMPANY; break;
    02419     default: NOT_REACHED();
    02420   }
    02421   SetDParam(2, abs(percent));
    02422   SetDParam(0, CargoSpec::Get(type)->name);
    02423   SetDParam(1, ind->index);
    02424   AddIndustryNewsItem(
    02425     percent >= 0 ? STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_SMOOTH : STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_SMOOTH,
    02426     ns,
    02427     ind->index
    02428   );
    02429 }
    02430
    02431 static const uint PERCENT_TRANSPORTED_60 = 153;
    02432 static const uint PERCENT_TRANSPORTED_80 = 204;
    02433
    02439 static void ChangeIndustryProduction(Industry *i, bool monthly)
    02440 {
    02441   StringID str = STR_NULL;
    02442   bool closeit = false;
    02443   const IndustrySpec *indspec = GetIndustrySpec(i->type);
    02444   bool standard = false;
    02445   bool suppress_message = false;
    02446   bool recalculate_multipliers = false;
    02447   /* don't use smooth economy for industries using production related callbacks */
    02448   bool smooth_economy = indspec->UsesSmoothEconomy();
    02449   byte div = 0;
    02450   byte mul = 0;
    02451   int8 increment = 0;
    02452
    02453   bool callback_enabled = HasBit(indspec->callback_mask, monthly ? CBM_IND_MONTHLYPROD_CHANGE : CBM_IND_PRODUCTION_CHANGE);
    02454   if (callback_enabled) {
    02455     uint16 res = GetIndustryCallback(monthly ? CBID_INDUSTRY_MONTHLYPROD_CHANGE : CBID_INDUSTRY_PRODUCTION_CHANGE, 0, Random(), i, i->type, i->location.tile);
    02456     if (res != CALLBACK_FAILED) { // failed callback means "do nothing"
    02457       suppress_message = HasBit(res, 7);
    02458       /* Get the custom message if any */
    02459       if (HasBit(res, 8)) str = MapGRFStringID(indspec->grf_prop.grffile->grfid, GB(GetRegister(0x100), 0, 16));
    02460       res = GB(res, 0, 4);
    02461       switch (res) {
    02462         default: NOT_REACHED();
    02463         case 0x0: break;                  // Do nothing, but show the custom message if any
    02464         case 0x1: div = 1; break;         // Halve industry production. If production reaches the quarter of the default, the industry is closed instead.
    02465         case 0x2: mul = 1; break;         // Double industry production if it hasn't reached eight times of the original yet.
    02466         case 0x3: closeit = true; break;  // The industry announces imminent closure, and is physically removed from the map next month.
    02467         case 0x4: standard = true; break; // Do the standard random production change as if this industry was a primary one.
    02468         case 0x5: case 0x6: case 0x7:     // Divide production by 4, 8, 16
    02469         case 0x8: div = res - 0x3; break; // Divide production by 32
    02470         case 0x9: case 0xA: case 0xB:     // Multiply production by 4, 8, 16
    02471         case 0xC: mul = res - 0x7; break; // Multiply production by 32
    02472         case 0xD:                         // decrement production
    02473         case 0xE:                         // increment production
    02474           increment = res == 0x0D ? -1 : 1;
    02475           break;
    02476         case 0xF:                         // Set production to third byte of register 0x100
    02477           i->prod_level = Clamp(GB(GetRegister(0x100), 16, 8), PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
    02478           recalculate_multipliers = true;
    02479           break;
    02480       }
    02481     }
    02482   } else {
    02483     if (monthly != smooth_economy) return;
    02484     if (indspec->life_type == INDUSTRYLIFE_BLACK_HOLE) return;
    02485   }
    02486
    02487   if (standard || (!callback_enabled && (indspec->life_type & (INDUSTRYLIFE_ORGANIC | INDUSTRYLIFE_EXTRACTIVE)) != 0)) {
    02488     /* decrease or increase */
    02489     bool only_decrease = (indspec->behaviour & INDUSTRYBEH_DONT_INCR_PROD) && _settings_game.game_creation.landscape == LT_TEMPERATE;
    02490
    02491     if (smooth_economy) {
    02492       closeit = true;
    02493       for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
    02494         if (i->produced_cargo[j] == CT_INVALID) continue;
    02495         uint32 r = Random();
    02496         int old_prod, new_prod, percent;
    02497         /* If over 60% is transported, mult is 1, else mult is -1. */
    02498         int mult = (i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_60) ? 1 : -1;
    02499
    02500         new_prod = old_prod = i->production_rate[j];
    02501
    02502         /* For industries with only_decrease flags (temperate terrain Oil Wells),
    02503          * the multiplier will always be -1 so they will only decrease. */
    02504         if (only_decrease) {
    02505           mult = -1;
    02506         /* For normal industries, if over 60% is transported, 33% chance for decrease.
    02507          * Bonus for very high station ratings (over 80%): 16% chance for decrease. */
    02508         } else if (Chance16I(1, ((i->last_month_pct_transported[j] > PERCENT_TRANSPORTED_80) ? 6 : 3), r)) {
    02509           mult *= -1;
    02510         }
    02511
    02512         /* 4.5% chance for 3-23% (or 1 unit for very low productions) production change,
    02513          * determined by mult value. If mult = 1 prod. increases, else (-1) it decreases. */
    02514         if (Chance16I(1, 22, r >> 16)) {
    02515           new_prod += mult * (max(((RandomRange(50) + 10) * old_prod) >> 8, 1U));
    02516         }
    02517
    02518         /* Prevent production to overflow or Oil Rig passengers to be over-"produced" */
    02519         new_prod = Clamp(new_prod, 1, 255);
    02520
    02521         if (((indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) && j == 1) {
    02522           new_prod = Clamp(new_prod, 0, 16);
    02523         }
    02524
    02525         /* Do not stop closing the industry when it has the lowest possible production rate */
    02526         if (new_prod == old_prod && old_prod > 1) {
    02527           closeit = false;
    02528           continue;
    02529         }
    02530
    02531         percent = (old_prod == 0) ? 100 : (new_prod * 100 / old_prod - 100);
    02532         i->production_rate[j] = new_prod;
    02533
    02534         /* Close the industry when it has the lowest possible production rate */
    02535         if (new_prod > 1) closeit = false;
    02536
    02537         if (abs(percent) >= 10) {
    02538           ReportNewsProductionChangeIndustry(i, i->produced_cargo[j], percent);
    02539         }
    02540       }
    02541     } else {
    02542       if (only_decrease || Chance16(1, 3)) {
    02543         /* If more than 60% transported, 66% chance of increase, else 33% chance of increase */
    02544         if (!only_decrease && (i->last_month_pct_transported[0] > PERCENT_TRANSPORTED_60) != Chance16(1, 3)) {
    02545           mul = 1; // Increase production
    02546         } else {
    02547           div = 1; // Decrease production
    02548         }
    02549       }
    02550     }
    02551   }
    02552
    02553   if (!callback_enabled && (indspec->life_type & INDUSTRYLIFE_PROCESSING)) {
    02554     if ( (byte)(_cur_year - i->last_prod_year) >= 5 && Chance16(1, smooth_economy ? 180 : 2)) {
    02555       closeit = true;
    02556     }
    02557   }
    02558
    02559   /* Increase if needed */
    02560   while (mul-- != 0 && i->prod_level < PRODLEVEL_MAXIMUM) {
    02561     i->prod_level = min(i->prod_level * 2, PRODLEVEL_MAXIMUM);
    02562     recalculate_multipliers = true;
    02563     if (str == STR_NULL) str = indspec->production_up_text;
    02564   }
    02565
    02566   /* Decrease if needed */
    02567   while (div-- != 0 && !closeit) {
    02568     if (i->prod_level == PRODLEVEL_MINIMUM) {
    02569       closeit = true;
    02570     } else {
    02571       i->prod_level = max(i->prod_level / 2, (int)PRODLEVEL_MINIMUM); // typecast to int required to please MSVC
    02572       recalculate_multipliers = true;
    02573       if (str == STR_NULL) str = indspec->production_down_text;
    02574     }
    02575   }
    02576
    02577   /* Increase or Decreasing the production level if needed */
    02578   if (increment != 0) {
    02579     if (increment < 0 && i->prod_level == PRODLEVEL_MINIMUM) {
    02580       closeit = true;
    02581     } else {
    02582       i->prod_level = ClampU(i->prod_level + increment, PRODLEVEL_MINIMUM, PRODLEVEL_MAXIMUM);
    02583       recalculate_multipliers = true;
    02584     }
    02585   }
    02586
    02587   /* Recalculate production_rate
    02588    * For non-smooth economy these should always be synchronized with prod_level */
    02589   if (recalculate_multipliers) i->RecomputeProductionMultipliers();
    02590
    02591   /* Close if needed and allowed */
    02592   if (closeit && !CheckIndustryCloseDownProtection(i->type)) {
    02593     i->prod_level = PRODLEVEL_CLOSURE;
    02594     str = indspec->closure_text;
    02595   }
    02596
    02597   if (!suppress_message && str != STR_NULL) {
    02598     NewsSubtype ns;
    02599     /* Compute news category */
    02600     if (closeit) {
    02601       ns = NS_INDUSTRY_CLOSE;
    02602       AI::BroadcastNewEvent(new ScriptEventIndustryClose(i->index));
    02603       Game::NewEvent(new ScriptEventIndustryClose(i->index));
    02604     } else {
    02605       switch (WhoCanServiceIndustry(i)) {
    02606         case 0: ns = NS_INDUSTRY_NOBODY;  break;
    02607         case 1: ns = NS_INDUSTRY_OTHER;   break;
    02608         case 2: ns = NS_INDUSTRY_COMPANY; break;
    02609         default: NOT_REACHED();
    02610       }
    02611     }
    02612     /* Set parameters of news string */
    02613     if (str > STR_LAST_STRINGID) {
    02614       SetDParam(0, STR_TOWN_NAME);
    02615       SetDParam(1, i->town->index);
    02616       SetDParam(2, indspec->name);
    02617     } else if (closeit) {
    02618       SetDParam(0, STR_FORMAT_INDUSTRY_NAME);
    02619       SetDParam(1, i->town->index);
    02620       SetDParam(2, indspec->name);
    02621     } else {
    02622       SetDParam(0, i->index);
    02623     }
    02624     /* and report the news to the user */
    02625     AddNewsItem(str,
    02626       ns,
    02627       closeit ? NR_TILE : NR_INDUSTRY,
    02628       closeit ? i->location.tile + TileDiffXY(1, 1) : i->index);
    02629   }
    02630 }
    02631
    02639 void IndustryDailyLoop()
    02640 {
    02641   _economy.industry_daily_change_counter += _economy.industry_daily_increment;
    02642
    02643   /* Bits 16-31 of industry_construction_counter contain the number of industries to change/create today,
    02644    * the lower 16 bit are a fractional part that might accumulate over several days until it
    02645    * is sufficient for an industry. */
    02646   uint16 change_loop = _economy.industry_daily_change_counter >> 16;
    02647
    02648   /* Reset the active part of the counter, just keeping the "factional part" */
    02649   _economy.industry_daily_change_counter &= 0xFFFF;
    02650
    02651   if (change_loop == 0) {
    02652     return;  // Nothing to do? get out
    02653   }
    02654
    02655   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
    02656
    02657   /* perform the required industry changes for the day */
    02658
    02659   uint perc = 3; // Between 3% and 9% chance of creating a new industry.
    02660   if ((_industry_builder.wanted_inds >> 16) > GetCurrentTotalNumberOfIndustries()) {
    02661     perc = min(9u, perc + (_industry_builder.wanted_inds >> 16) - GetCurrentTotalNumberOfIndustries());
    02662   }
    02663   for (uint16 j = 0; j < change_loop; j++) {
    02664     if (Chance16(perc, 100)) {
    02665       _industry_builder.TryBuildNewIndustry();
    02666     } else {
    02667       Industry *i = Industry::GetRandom();
    02668       if (i != NULL) {
    02669         ChangeIndustryProduction(i, false);
    02670         SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
    02671       }
    02672     }
    02673   }
    02674
    02675   cur_company.Restore();
    02676
    02677   /* production-change */
    02678   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 1);
    02679 }
    02680
    02681 void IndustryMonthlyLoop()
    02682 {
    02683   Backup<CompanyByte> cur_company(_current_company, OWNER_NONE, FILE_LINE);
    02684
    02685   _industry_builder.MonthlyLoop();
    02686
    02687   Industry *i;
    02688   FOR_ALL_INDUSTRIES(i) {
    02689     UpdateIndustryStatistics(i);
    02690     if (i->prod_level == PRODLEVEL_CLOSURE) {
    02691       delete i;
    02692     } else {
    02693       ChangeIndustryProduction(i, true);
    02694       SetWindowDirty(WC_INDUSTRY_VIEW, i->index);
    02695     }
    02696   }
    02697
    02698   cur_company.Restore();
    02699
    02700   /* production-change */
    02701   InvalidateWindowData(WC_INDUSTRY_DIRECTORY, 0, 1);
    02702 }
    02703
    02704
    02705 void InitializeIndustries()
    02706 {
    02707   Industry::ResetIndustryCounts();
    02708   _industry_sound_tile = 0;
    02709
    02710   _industry_builder.Reset();
    02711 }
    02712
    02717 bool IndustrySpec::IsRawIndustry() const
    02718 {
    02719   /* Lumber mills are extractive/organic, but can always be built like a non-raw industry */
    02720   return (this->life_type & (INDUSTRYLIFE_EXTRACTIVE | INDUSTRYLIFE_ORGANIC)) != 0 &&
    02721       (this->behaviour & INDUSTRYBEH_CUT_TREES) == 0;
    02722 }
    02723
    02728 Money IndustrySpec::GetConstructionCost() const
    02729 {
    02730   /* Building raw industries like secondary uses different price base */
    02731   return (_price[(_settings_game.construction.raw_industry_construction == 1 && this->IsRawIndustry()) ?
    02732       PR_BUILD_INDUSTRY_RAW : PR_BUILD_INDUSTRY] * this->cost_multiplier) >> 8;
    02733 }
    02734
    02741 Money IndustrySpec::GetRemovalCost() const
    02742 {
    02743   return (_price[PR_CLEAR_INDUSTRY] * this->removal_cost_multiplier) >> 8;
    02744 }
    02745
    02750 bool IndustrySpec::UsesSmoothEconomy() const
    02751 {
    02752   return _settings_game.economy.smooth_economy &&
    02753     !(HasBit(this->callback_mask, CBM_IND_PRODUCTION_256_TICKS) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) && // production callbacks
    02754     !(HasBit(this->callback_mask, CBM_IND_MONTHLYPROD_CHANGE) || HasBit(this->callback_mask, CBM_IND_PRODUCTION_CHANGE));            // production change callbacks
    02755 }
    02756
    02757 static CommandCost TerraformTile_Industry(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
    02758 {
    02759   if (AutoslopeEnabled()) {
    02760     /* We imitate here TTDP's behaviour:
    02761      *  - Both new and old slope must not be steep.
    02762      *  - TileMaxZ must not be changed.
    02763      *  - Allow autoslope by default.
    02764      *  - Disallow autoslope if callback succeeds and returns non-zero.
    02765      */
    02766     Slope tileh_old = GetTileSlope(tile);
    02767     /* TileMaxZ must not be changed. Slopes must not be steep. */
    02768     if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
    02769       const IndustryGfx gfx = GetIndustryGfx(tile);
    02770       const IndustryTileSpec *itspec = GetIndustryTileSpec(gfx);
    02771
    02772       /* Call callback 3C 'disable autosloping for industry tiles'. */
    02773       if (HasBit(itspec->callback_mask, CBM_INDT_AUTOSLOPE)) {
    02774         /* If the callback fails, allow autoslope. */
    02775         uint16 res = GetIndustryTileCallback(CBID_INDTILE_AUTOSLOPE, 0, 0, gfx, Industry::GetByTile(tile), tile);
    02776         if (res == CALLBACK_FAILED || !ConvertBooleanCallback(itspec->grf_prop.grffile, CBID_INDTILE_AUTOSLOPE, res)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    02777       } else {
    02778         /* allow autoslope */
    02779         return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
    02780       }
    02781     }
    02782   }
    02783   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
    02784 }
    02785
    02786 extern const TileTypeProcs _tile_type_industry_procs = {
    02787   DrawTile_Industry,           // draw_tile_proc
    02788   GetSlopePixelZ_Industry,     // get_slope_z_proc
    02789   ClearTile_Industry,          // clear_tile_proc
    02790   AddAcceptedCargo_Industry,   // add_accepted_cargo_proc
    02791   GetTileDesc_Industry,        // get_tile_desc_proc
    02792   GetTileTrackStatus_Industry, // get_tile_track_status_proc
    02793   ClickTile_Industry,          // click_tile_proc
    02794   AnimateTile_Industry,        // animate_tile_proc
    02795   TileLoop_Industry,           // tile_loop_proc
    02796   ChangeTileOwner_Industry,    // change_tile_owner_proc
    02797   NULL,                        // add_produced_cargo_proc
    02798   NULL,                        // vehicle_enter_tile_proc
    02799   GetFoundation_Industry,      // get_foundation_proc
    02800   TerraformTile_Industry,      // terraform_tile_proc
    02801 };