object_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: object_cmd.cpp 23795 2012-01-13 21:54:59Z rubidium $ */
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 "landscape.h"
00014 #include "command_func.h"
00015 #include "viewport_func.h"
00016 #include "company_base.h"
00017 #include "town.h"
00018 #include "bridge_map.h"
00019 #include "genworld.h"
00020 #include "autoslope.h"
00021 #include "clear_func.h"
00022 #include "water.h"
00023 #include "window_func.h"
00024 #include "company_gui.h"
00025 #include "cheat_type.h"
00026 #include "object.h"
00027 #include "cargopacket.h"
00028 #include "sprite.h"
00029 #include "core/random_func.hpp"
00030 #include "core/pool_func.hpp"
00031 #include "object_map.h"
00032 #include "object_base.h"
00033 #include "newgrf_config.h"
00034 #include "newgrf_object.h"
00035 #include "date_func.h"
00036 #include "newgrf_debug.h"
00037 #include "vehicle_func.h"
00038 
00039 #include "table/strings.h"
00040 #include "table/object_land.h"
00041 
00042 ObjectPool _object_pool("Object");
00043 INSTANTIATE_POOL_METHODS(Object)
00044 uint16 Object::counts[NUM_OBJECTS];
00045 
00051 /* static */ Object *Object::GetByTile(TileIndex tile)
00052 {
00053   return Object::Get(GetObjectIndex(tile));
00054 }
00055 
00057 void InitializeObjects()
00058 {
00059   _object_pool.CleanPool();
00060   Object::ResetTypeCounts();
00061 }
00062 
00073 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8 view)
00074 {
00075   const ObjectSpec *spec = ObjectSpec::Get(type);
00076 
00077   TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
00078   Object *o = new Object();
00079   o->location      = ta;
00080   o->town          = town == NULL ? CalcClosestTownFromTile(tile) : town;
00081   o->build_date    = _date;
00082   o->view          = view;
00083 
00084   /* If nothing owns the object, the colour will be random. Otherwise
00085    * get the colour from the company's livery settings. */
00086   if (owner == OWNER_NONE) {
00087     o->colour = Random();
00088   } else {
00089     const Livery *l = Company::Get(owner)->livery;
00090     o->colour = l->colour1 + l->colour2 * 16;
00091   }
00092 
00093   /* If the object wants only one colour, then give it that colour. */
00094   if ((spec->flags & OBJECT_FLAG_2CC_COLOUR) == 0) o->colour &= 0xF;
00095 
00096   if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) {
00097     uint16 res = GetObjectCallback(CBID_OBJECT_COLOUR, o->colour, 0, spec, o, tile);
00098     if (res != CALLBACK_FAILED) o->colour = GB(res, 0, 8);
00099   }
00100 
00101   assert(o->town != NULL);
00102 
00103   TILE_AREA_LOOP(t, ta) {
00104     WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
00105     MakeObject(t, type, owner, o->index, wc, Random());
00106     MarkTileDirtyByTile(t);
00107   }
00108 
00109   Object::IncTypeCount(type);
00110   if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
00111 }
00112 
00117 static void IncreaseAnimationStage(TileIndex tile)
00118 {
00119   TileArea ta = Object::GetByTile(tile)->location;
00120   TILE_AREA_LOOP(t, ta) {
00121     SetAnimationFrame(t, GetAnimationFrame(t) + 1);
00122     MarkTileDirtyByTile(t);
00123   }
00124 }
00125 
00127 #define GetCompanyHQSize GetAnimationFrame
00128 
00129 #define IncreaseCompanyHQSize IncreaseAnimationStage
00130 
00136 void UpdateCompanyHQ(TileIndex tile, uint score)
00137 {
00138   if (tile == INVALID_TILE) return;
00139 
00140   byte val;
00141   (val = 0, score < 170) ||
00142   (val++, score < 350) ||
00143   (val++, score < 520) ||
00144   (val++, score < 720) ||
00145   (val++, true);
00146 
00147   while (GetCompanyHQSize(tile) < val) {
00148     IncreaseCompanyHQSize(tile);
00149   }
00150 }
00151 
00156 void UpdateObjectColours(const Company *c)
00157 {
00158   Object *obj;
00159   FOR_ALL_OBJECTS(obj) {
00160     Owner owner = GetTileOwner(obj->location.tile);
00161     /* Not the current owner, so colour doesn't change. */
00162     if (owner != c->index) continue;
00163 
00164     const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
00165     /* Using the object colour callback, so not using company colour. */
00166     if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
00167 
00168     const Livery *l = c->livery;
00169     obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
00170   }
00171 }
00172 
00173 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool check_bridge);
00174 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
00175 
00185 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00186 {
00187   CommandCost cost(EXPENSES_PROPERTY);
00188 
00189   ObjectType type = (ObjectType)GB(p1, 0, 8);
00190   uint8 view = GB(p2, 0, 2);
00191   const ObjectSpec *spec = ObjectSpec::Get(type);
00192   if (!spec->IsAvailable()) return CMD_ERROR;
00193 
00194   if (spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT && (_game_mode != GM_EDITOR || _current_company != OWNER_NONE)) return CMD_ERROR;
00195   if (spec->flags & OBJECT_FLAG_ONLY_IN_GAME && (_game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
00196   if (view >= spec->views) return CMD_ERROR;
00197 
00198   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
00199   if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
00200 
00201   int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
00202   int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
00203   TileArea ta(tile, size_x, size_y);
00204 
00205   if (type == OBJECT_OWNED_LAND) {
00206     /* Owned land is special as it can be placed on any slope. */
00207     cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
00208   } else {
00209     /* Check the surface to build on. At this time we can't actually execute the
00210      * the CLEAR_TILE commands since the newgrf callback later on can check
00211      * some information about the tiles. */
00212     bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
00213     bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
00214     TILE_AREA_LOOP(t, ta) {
00215       if (HasTileWaterGround(t)) {
00216         if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00217         if (!IsWaterTile(t)) {
00218           /* Normal water tiles don't have to be cleared. For all other tile types clear
00219            * the tile but leave the water. */
00220           cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
00221         } else {
00222           /* Can't build on water owned by another company. */
00223           Owner o = GetTileOwner(t);
00224           if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
00225 
00226           /* However, the tile has to be clear of vehicles. */
00227           cost.AddCost(EnsureNoVehicleOnGround(t));
00228         }
00229       } else {
00230         if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
00231         /* For non-water tiles, we'll have to clear it before building. */
00232         cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
00233       }
00234     }
00235 
00236     /* So, now the surface is checked... check the slope of said surface. */
00237     int allowed_z;
00238     if (GetTileSlope(tile, (uint*)&allowed_z) != SLOPE_FLAT) allowed_z += TILE_HEIGHT;
00239 
00240     TILE_AREA_LOOP(t, ta) {
00241       uint16 callback = CALLBACK_FAILED;
00242       if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
00243         TileIndex diff = t - tile;
00244         callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t, NULL), TileY(diff) << 4 | TileX(diff), spec, NULL, t, view);
00245       }
00246 
00247       if (callback == CALLBACK_FAILED) {
00248         cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false));
00249       } else if (callback != 0) {
00250         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00251       }
00252     }
00253 
00254     if (flags & DC_EXEC) {
00255       /* This is basically a copy of the loop above with the exception that we now
00256        * execute the commands and don't check for errors, since that's already done. */
00257       TILE_AREA_LOOP(t, ta) {
00258         if (HasTileWaterGround(t)) {
00259           if (!IsWaterTile(t)) {
00260             DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
00261           }
00262         } else {
00263           DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
00264         }
00265       }
00266     }
00267   }
00268   if (cost.Failed()) return cost;
00269 
00270   /* Finally do a check for bridges. */
00271   TILE_AREA_LOOP(t, ta) {
00272     if (MayHaveBridgeAbove(t) && IsBridgeAbove(t) && (
00273         !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
00274         (GetTileMaxZ(t) + spec->height * TILE_HEIGHT >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
00275       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00276     }
00277   }
00278 
00279   int hq_score = 0;
00280   switch (type) {
00281     case OBJECT_TRANSMITTER:
00282     case OBJECT_LIGHTHOUSE:
00283       if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00284       break;
00285 
00286     case OBJECT_OWNED_LAND:
00287       if (IsTileType(tile, MP_OBJECT) &&
00288           IsTileOwner(tile, _current_company) &&
00289           IsOwnedLand(tile)) {
00290         return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
00291       }
00292       break;
00293 
00294     case OBJECT_HQ: {
00295       Company *c = Company::Get(_current_company);
00296       if (c->location_of_HQ != INVALID_TILE) {
00297         /* We need to persuade a bit harder to remove the old HQ. */
00298         _current_company = OWNER_WATER;
00299         cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
00300         _current_company = c->index;
00301       }
00302 
00303       if (flags & DC_EXEC) {
00304         hq_score = UpdateCompanyRatingAndValue(c, false);
00305         c->location_of_HQ = tile;
00306         SetWindowDirty(WC_COMPANY, c->index);
00307       }
00308       break;
00309     }
00310 
00311     case OBJECT_STATUE:
00312       /* This may never be constructed using this method. */
00313       return CMD_ERROR;
00314 
00315     default: // i.e. NewGRF provided.
00316       break;
00317   }
00318 
00319   if (flags & DC_EXEC) {
00320     BuildObject(type, tile, _current_company, NULL, view);
00321 
00322     /* Make sure the HQ starts at the right size. */
00323     if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
00324   }
00325 
00326   cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
00327   return cost;
00328 }
00329 
00330 
00331 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
00332 
00333 static void DrawTile_Object(TileInfo *ti)
00334 {
00335   ObjectType type = GetObjectType(ti->tile);
00336   const ObjectSpec *spec = ObjectSpec::Get(type);
00337 
00338   /* Fall back for when the object doesn't exist anymore. */
00339   if (!spec->enabled) type = OBJECT_TRANSMITTER;
00340 
00341   if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
00342 
00343   if (type < NEW_OBJECT_OFFSET) {
00344     const DrawTileSprites *dts = NULL;
00345     Owner to = GetTileOwner(ti->tile);
00346     PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
00347 
00348     if (type == OBJECT_HQ) {
00349       TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
00350       dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
00351     } else {
00352       dts = &_objects[type];
00353     }
00354 
00355     if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
00356       /* If an object has no foundation, but tries to draw a (flat) ground
00357        * type... we have to be nice and convert that for them. */
00358       switch (dts->ground.sprite) {
00359         case SPR_FLAT_BARE_LAND:          DrawClearLandTile(ti, 0); break;
00360         case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
00361         case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
00362         case SPR_FLAT_GRASS_TILE:         DrawClearLandTile(ti, 3); break;
00363         default: DrawGroundSprite(dts->ground.sprite, palette);     break;
00364       }
00365     } else {
00366       DrawGroundSprite(dts->ground.sprite, palette);
00367     }
00368 
00369     if (!IsInvisibilitySet(TO_STRUCTURES)) {
00370       const DrawTileSeqStruct *dtss;
00371       foreach_draw_tile_seq(dtss, dts->seq) {
00372         AddSortableSpriteToDraw(
00373           dtss->image.sprite, palette,
00374           ti->x + dtss->delta_x, ti->y + dtss->delta_y,
00375           dtss->size_x, dtss->size_y,
00376           dtss->size_z, ti->z + dtss->delta_z,
00377           IsTransparencySet(TO_STRUCTURES)
00378         );
00379       }
00380     }
00381   } else {
00382     DrawNewObjectTile(ti, spec);
00383   }
00384 
00385   if (spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) DrawBridgeMiddle(ti);
00386 }
00387 
00388 static uint GetSlopeZ_Object(TileIndex tile, uint x, uint y)
00389 {
00390   if (IsOwnedLand(tile)) {
00391     uint z;
00392     Slope tileh = GetTileSlope(tile, &z);
00393 
00394     return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
00395   } else {
00396     return GetTileMaxZ(tile);
00397   }
00398 }
00399 
00400 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
00401 {
00402   return IsOwnedLand(tile) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
00403 }
00404 
00409 static void ReallyClearObjectTile(Object *o)
00410 {
00411   Object::DecTypeCount(GetObjectType(o->location.tile));
00412   TILE_AREA_LOOP(tile_cur, o->location) {
00413     DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
00414 
00415     MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
00416   }
00417   delete o;
00418 }
00419 
00420 SmallVector<ClearedObjectArea, 4> _cleared_object_areas;
00421 
00427 ClearedObjectArea *FindClearedObject(TileIndex tile)
00428 {
00429   TileArea ta = TileArea(tile, 1, 1);
00430 
00431   const ClearedObjectArea *end = _cleared_object_areas.End();
00432   for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) {
00433     if (coa->area.Intersects(ta)) return coa;
00434   }
00435 
00436   return NULL;
00437 }
00438 
00439 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
00440 {
00441   ObjectType type = GetObjectType(tile);
00442   const ObjectSpec *spec = ObjectSpec::Get(type);
00443 
00444   /* Get to the northern most tile. */
00445   Object *o = Object::GetByTile(tile);
00446   TileArea ta = o->location;
00447 
00448   CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
00449   if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
00450 
00451   /* Water can remove everything! */
00452   if (_current_company != OWNER_WATER) {
00453     if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
00454       /* There is water under the object, treat it as water tile. */
00455       return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00456     } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
00457       /* No automatic removal by overbuilding stuff. */
00458       return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
00459     } else if (_game_mode == GM_EDITOR) {
00460       /* No further limitations for the editor. */
00461     } else if (GetTileOwner(tile) == OWNER_NONE) {
00462       /* Owned by nobody, so we can only remove it with brute force! */
00463       if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
00464     } else if (CheckTileOwnership(tile).Failed()) {
00465       /* We don't own it!. */
00466       return_cmd_error(STR_ERROR_OWNED_BY);
00467     } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
00468       /* In the game editor or with cheats we can remove, otherwise we can't. */
00469       if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
00470 
00471       /* Removing with the cheat costs more in TTDPatch / the specs. */
00472       cost.MultiplyCost(25);
00473     }
00474   } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
00475     /* Water can't remove objects that are buildable on water. */
00476     return CMD_ERROR;
00477   }
00478 
00479   switch (type) {
00480     case OBJECT_HQ: {
00481       Company *c = Company::Get(GetTileOwner(tile));
00482       if (flags & DC_EXEC) {
00483         c->location_of_HQ = INVALID_TILE; // reset HQ position
00484         SetWindowDirty(WC_COMPANY, c->index);
00485         CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
00486       }
00487 
00488       /* cost of relocating company is 1% of company value */
00489       cost = CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
00490       break;
00491     }
00492 
00493     case OBJECT_STATUE:
00494       if (flags & DC_EXEC) {
00495         Town *town = o->town;
00496         ClrBit(town->statues, GetTileOwner(tile));
00497         SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
00498       }
00499       break;
00500 
00501     default:
00502       break;
00503   }
00504 
00505   ClearedObjectArea *cleared_area = _cleared_object_areas.Append();
00506   cleared_area->first_tile = tile;
00507   cleared_area->area = ta;
00508 
00509   if (flags & DC_EXEC) ReallyClearObjectTile(o);
00510 
00511   return cost;
00512 }
00513 
00514 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00515 {
00516   if (!IsCompanyHQ(tile)) return;
00517 
00518   /* HQ accepts passenger and mail; but we have to divide the values
00519    * between 4 tiles it occupies! */
00520 
00521   /* HQ level (depends on company performance) in the range 1..5. */
00522   uint level = GetCompanyHQSize(tile) + 1;
00523 
00524   /* Top town building generates 10, so to make HQ interesting, the top
00525    * type makes 20. */
00526   acceptance[CT_PASSENGERS] += max(1U, level);
00527   SetBit(*always_accepted, CT_PASSENGERS);
00528 
00529   /* Top town building generates 4, HQ can make up to 8. The
00530    * proportion passengers:mail is different because such a huge
00531    * commercial building generates unusually high amount of mail
00532    * correspondence per physical visitor. */
00533   acceptance[CT_MAIL] += max(1U, level / 2);
00534   SetBit(*always_accepted, CT_MAIL);
00535 }
00536 
00537 
00538 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
00539 {
00540   const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00541   td->str = spec->name;
00542   td->owner[0] = GetTileOwner(tile);
00543   td->build_date = Object::GetByTile(tile)->build_date;
00544 
00545   if (spec->grf_prop.grffile != NULL) {
00546     td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
00547   }
00548 }
00549 
00550 static void TileLoop_Object(TileIndex tile)
00551 {
00552   const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00553   if (spec->flags & OBJECT_FLAG_ANIMATION) {
00554     const Object *o = Object::GetByTile(tile);
00555     TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
00556     if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
00557   }
00558 
00559   if (IsTileOnWater(tile)) TileLoop_Water(tile);
00560 
00561   if (!IsCompanyHQ(tile)) return;
00562 
00563   /* HQ accepts passenger and mail; but we have to divide the values
00564    * between 4 tiles it occupies! */
00565 
00566   /* HQ level (depends on company performance) in the range 1..5. */
00567   uint level = GetCompanyHQSize(tile) + 1;
00568   assert(level < 6);
00569 
00570   StationFinder stations(TileArea(tile, 2, 2));
00571 
00572   uint r = Random();
00573   /* Top town buildings generate 250, so the top HQ type makes 256. */
00574   if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
00575     uint amt = GB(r, 0, 8) / 8 / 4 + 1;
00576     if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00577     MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
00578   }
00579 
00580   /* Top town building generates 90, HQ can make up to 196. The
00581    * proportion passengers:mail is about the same as in the acceptance
00582    * equations. */
00583   if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
00584     uint amt = GB(r, 8, 8) / 8 / 4 + 1;
00585     if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00586     MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
00587   }
00588 }
00589 
00590 
00591 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00592 {
00593   return 0;
00594 }
00595 
00596 static bool ClickTile_Object(TileIndex tile)
00597 {
00598   if (!IsCompanyHQ(tile)) return false;
00599 
00600   ShowCompany(GetTileOwner(tile));
00601   return true;
00602 }
00603 
00604 static void AnimateTile_Object(TileIndex tile)
00605 {
00606   AnimateNewObjectTile(tile);
00607 }
00608 
00615 static bool HasTransmitter(TileIndex tile, void *user)
00616 {
00617   return IsTransmitterTile(tile);
00618 }
00619 
00620 void GenerateObjects()
00621 {
00622   if (_settings_game.game_creation.landscape == LT_TOYLAND) return;
00623 
00624   /* add radio tower */
00625   int radiotower_to_build = ScaleByMapSize(15); // maximum number of radio towers on the map
00626   int lighthouses_to_build = _settings_game.game_creation.landscape == LT_TROPIC ? 0 : ScaleByMapSize1D((Random() & 3) + 7);
00627 
00628   /* Scale the amount of lighthouses with the amount of land at the borders. */
00629   if (_settings_game.construction.freeform_edges && lighthouses_to_build != 0) {
00630     uint num_water_tiles = 0;
00631     for (uint x = 0; x < MapMaxX(); x++) {
00632       if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
00633       if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
00634     }
00635     for (uint y = 1; y < MapMaxY() - 1; y++) {
00636       if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
00637       if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
00638     }
00639     /* The -6 is because the top borders are MP_VOID (-2) and all corners
00640      * are counted twice (-4). */
00641     lighthouses_to_build = lighthouses_to_build * num_water_tiles / (2 * MapMaxY() + 2 * MapMaxX() - 6);
00642   }
00643 
00644   SetGeneratingWorldProgress(GWP_OBJECT, radiotower_to_build + lighthouses_to_build);
00645 
00646   for (uint i = ScaleByMapSize(1000); i != 0 && Object::CanAllocateItem(); i--) {
00647     TileIndex tile = RandomTile();
00648 
00649     uint h;
00650     if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h >= TILE_HEIGHT * 4 && !IsBridgeAbove(tile)) {
00651       TileIndex t = tile;
00652       if (CircularTileSearch(&t, 9, HasTransmitter, NULL)) continue;
00653 
00654       BuildObject(OBJECT_TRANSMITTER, tile);
00655       IncreaseGeneratingWorldProgress(GWP_OBJECT);
00656       if (--radiotower_to_build == 0) break;
00657     }
00658   }
00659 
00660   /* add lighthouses */
00661   uint maxx = MapMaxX();
00662   uint maxy = MapMaxY();
00663   for (int loop_count = 0; loop_count < 1000 && lighthouses_to_build != 0 && Object::CanAllocateItem(); loop_count++) {
00664     uint r = Random();
00665 
00666     /* Scatter the lighthouses more evenly around the perimeter */
00667     int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
00668     DiagDirection dir;
00669     for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
00670       perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
00671     }
00672 
00673     TileIndex tile;
00674     switch (dir) {
00675       default:
00676       case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
00677       case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
00678       case DIAGDIR_SW: tile = TileXY(1,        r % maxy); break;
00679       case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
00680     }
00681 
00682     /* Only build lighthouses at tiles where the border is sea. */
00683     if (!IsTileType(tile, MP_WATER)) continue;
00684 
00685     for (int j = 0; j < 19; j++) {
00686       uint h;
00687       if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h <= TILE_HEIGHT * 2 && !IsBridgeAbove(tile)) {
00688         BuildObject(OBJECT_LIGHTHOUSE, tile);
00689         IncreaseGeneratingWorldProgress(GWP_OBJECT);
00690         lighthouses_to_build--;
00691         assert(tile < MapSize());
00692         break;
00693       }
00694       tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir));
00695       if (tile == INVALID_TILE) break;
00696     }
00697   }
00698 }
00699 
00700 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
00701 {
00702   if (!IsTileOwner(tile, old_owner)) return;
00703 
00704   if (IsOwnedLand(tile) && new_owner != INVALID_OWNER) {
00705     SetTileOwner(tile, new_owner);
00706   } else if (IsStatueTile(tile)) {
00707     Town *t = Object::GetByTile(tile)->town;
00708     ClrBit(t->statues, old_owner);
00709     if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
00710       /* Transfer ownership to the new company */
00711       SetBit(t->statues, new_owner);
00712       SetTileOwner(tile, new_owner);
00713     } else {
00714       ReallyClearObjectTile(Object::GetByTile(tile));
00715     }
00716 
00717     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
00718   } else {
00719     ReallyClearObjectTile(Object::GetByTile(tile));
00720   }
00721 }
00722 
00723 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
00724 {
00725   ObjectType type = GetObjectType(tile);
00726 
00727   if (type == OBJECT_OWNED_LAND) {
00728     /* Owned land remains unsold */
00729     CommandCost ret = CheckTileOwnership(tile);
00730     if (ret.Succeeded()) return CommandCost();
00731   } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
00732     /* Behaviour:
00733      *  - Both new and old slope must not be steep.
00734      *  - TileMaxZ must not be changed.
00735      *  - Allow autoslope by default.
00736      *  - Disallow autoslope if callback succeeds and returns non-zero.
00737      */
00738     Slope tileh_old = GetTileSlope(tile, NULL);
00739     /* TileMaxZ must not be changed. Slopes must not be steep. */
00740     if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
00741       const ObjectSpec *spec = ObjectSpec::Get(type);
00742 
00743       /* Call callback 'disable autosloping for objects'. */
00744       if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
00745         /* If the callback fails, allow autoslope. */
00746         uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
00747         if ((res == 0) || (res == CALLBACK_FAILED)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00748       } else if (spec->enabled) {
00749         /* allow autoslope */
00750         return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00751       }
00752     }
00753   }
00754 
00755   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00756 }
00757 
00758 extern const TileTypeProcs _tile_type_object_procs = {
00759   DrawTile_Object,             // draw_tile_proc
00760   GetSlopeZ_Object,            // get_slope_z_proc
00761   ClearTile_Object,            // clear_tile_proc
00762   AddAcceptedCargo_Object,     // add_accepted_cargo_proc
00763   GetTileDesc_Object,          // get_tile_desc_proc
00764   GetTileTrackStatus_Object,   // get_tile_track_status_proc
00765   ClickTile_Object,            // click_tile_proc
00766   AnimateTile_Object,          // animate_tile_proc
00767   TileLoop_Object,             // tile_loop_clear
00768   ChangeTileOwner_Object,      // change_tile_owner_clear
00769   NULL,                        // add_produced_cargo_proc
00770   NULL,                        // vehicle_enter_tile_proc
00771   GetFoundation_Object,        // get_foundation_proc
00772   TerraformTile_Object,        // terraform_tile_proc
00773 };