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