Rework ChoosePylonPosition to simplify the loop
[openttd/fttd.git] / src / tree_cmd.cpp
blob7223722b210cfb902789f0dda1daf090f874d26f
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file tree_cmd.cpp Handling of tree tiles. */
12 #include "stdafx.h"
13 #include "map/ground.h"
14 #include "map/slope.h"
15 #include "map/bridge.h"
16 #include "landscape.h"
17 #include "viewport_func.h"
18 #include "command_func.h"
19 #include "town.h"
20 #include "genworld.h"
21 #include "clear_func.h"
22 #include "company_func.h"
23 #include "water.h"
24 #include "company_base.h"
25 #include "core/random_func.hpp"
26 #include "newgrf_generic.h"
28 #include "table/strings.h"
29 #include "table/tree_land.h"
31 /**
32 * List of tree placer algorithm.
34 * This enumeration defines all possible tree placer algorithm in the game.
36 enum TreePlacer {
37 TP_NONE, ///< No tree placer algorithm
38 TP_ORIGINAL, ///< The original algorithm
39 TP_IMPROVED, ///< A 'improved' algorithm
42 /** Where to place trees while in-game? */
43 enum ExtraTreePlacement {
44 ETP_NONE, ///< Place trees on no tiles
45 ETP_RAINFOREST, ///< Place trees only on rainforest tiles
46 ETP_ALL, ///< Place trees on all tiles
49 /** Determines when to consider building more trees. */
50 byte _trees_tick_ctr;
52 static const uint16 DEFAULT_TREE_STEPS = 1000; ///< Default number of attempts for placing trees.
53 static const uint16 DEFAULT_RAINFOREST_TREE_STEPS = 15000; ///< Default number of attempts for placing extra trees at rainforest in tropic.
54 static const uint16 EDITOR_TREE_DIV = 5; ///< Game editor tree generation divisor factor.
56 /**
57 * Tests if a tile can be converted to have trees
58 * This is true for clear ground without farms or rocks.
60 * @param tile the tile of interest
61 * @param allow_desert Allow planting trees on GROUND_DESERT?
62 * @return true if trees can be built.
64 static bool CanPlantTreesOnTile(TileIndex tile, bool allow_desert)
66 switch (GetTileType(tile)) {
67 case TT_WATER:
68 return !HasBridgeAbove(tile) && IsCoast(tile) && !IsSlopeWithOneCornerRaised(GetTileSlope(tile));
70 case TT_GROUND:
71 return IsTileSubtype(tile, TT_GROUND_CLEAR) && !HasBridgeAbove(tile) && GetRawClearGround(tile) != GROUND_ROCKS &&
72 (allow_desert || !IsClearGround(tile, GROUND_DESERT));
74 default: return false;
78 /**
79 * Creates a tree tile
80 * Ground type and density is preserved.
82 * @pre the tile must be suitable for trees.
84 * @param tile where to plant the trees.
85 * @param treetype The type of the tree
86 * @param count the number of trees (minus 1)
87 * @param growth the growth status
89 static void PlantTreesOnTile(TileIndex tile, TreeType treetype, uint count, uint growth)
91 assert(treetype != TREE_INVALID);
92 assert(CanPlantTreesOnTile(tile, true));
94 Ground ground;
95 uint density;
97 switch (GetTileType(tile)) {
98 case TT_WATER:
99 ground = GROUND_SHORE;
100 density = 3;
101 break;
103 case TT_GROUND:
104 assert(IsTileSubtype(tile, TT_GROUND_CLEAR));
105 ground = GetFullClearGround(tile);
106 density = GetClearDensity(tile);
107 break;
109 default: NOT_REACHED();
112 MakeTree(tile, treetype, count, growth, ground, density);
115 void AddNeighbouringTree(TileIndex tile)
117 /* Don't plant extra trees if that's not allowed. */
118 if ((_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) == TROPICZONE_RAINFOREST) ?
119 _settings_game.construction.extra_tree_placement == ETP_NONE :
120 _settings_game.construction.extra_tree_placement != ETP_ALL) {
121 return;
124 TreeType treetype = GetTreeType(tile);
126 tile += TileOffsByDir((Direction)(Random() & 7));
128 /* Cacti don't spread */
129 if (!CanPlantTreesOnTile(tile, false)) return;
131 /* Don't plant trees, if ground was freshly cleared */
132 if (IsClearTile(tile) && GetClearGround(tile) == GROUND_GRASS && GetClearDensity(tile) != 3) return;
134 PlantTreesOnTile(tile, treetype, 0, 0);
138 * Get a random TreeType for the given tile based on a given seed
140 * This function returns a random TreeType which can be placed on the given tile.
141 * The seed for randomness must be less or equal 256, use #GB on the value of Random()
142 * to get such a value.
144 * @param tile The tile to get a random TreeType from
145 * @param seed The seed for randomness, must be less or equal 256
146 * @return The random tree type
148 static TreeType GetRandomTreeType(TileIndex tile, uint seed)
150 switch (_settings_game.game_creation.landscape) {
151 case LT_TEMPERATE:
152 return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
154 case LT_ARCTIC:
155 return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
157 case LT_TROPIC:
158 switch (GetTropicZone(tile)) {
159 case TROPICZONE_NORMAL: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL);
160 case TROPICZONE_DESERT: return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS);
161 default: return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST);
164 default:
165 return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND);
170 * Make a random tree tile of the given tile
172 * Create a new tree-tile for the given tile. The second parameter is used for
173 * randomness like type and number of trees.
175 * @param tile The tile to make a tree-tile from
176 * @param r The randomness value from a Random() value
178 static void PlaceTree(TileIndex tile, uint32 r)
180 TreeType tree = GetRandomTreeType(tile, GB(r, 24, 8));
182 if (tree != TREE_INVALID) {
183 PlantTreesOnTile(tile, tree, GB(r, 22, 2), min(GB(r, 16, 3), 6));
185 /* Rerandomize ground, if neither snow nor shore */
186 Ground ground = GetClearGround(tile);
187 if (ground == GROUND_GRASS || ground == GROUND_ROUGH ) {
188 SetClearGroundDensity(tile, GB(r, 28, 1) ? GROUND_ROUGH : GROUND_GRASS, 3);
191 /* Set the counter to a random start value */
192 SetClearCounter(tile, (Ground)GB(r, 24, 4));
197 * Creates a number of tree groups.
198 * The number of trees in each group depends on how many trees are actually placed around the given tile.
200 * @param num_groups Number of tree groups to place.
202 static void PlaceTreeGroups(uint num_groups)
204 do {
205 TileIndex center_tile = RandomTile();
207 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
208 uint32 r = Random();
209 int x = GB(r, 0, 5) - 16;
210 int y = GB(r, 8, 5) - 16;
211 uint dist = abs(x) + abs(y);
212 TileIndex cur_tile = TileAddWrap(center_tile, x, y);
214 IncreaseGeneratingWorldProgress(GWP_TREE);
216 if (cur_tile != INVALID_TILE && dist <= 13 && CanPlantTreesOnTile(cur_tile, true)) {
217 PlaceTree(cur_tile, r);
221 } while (--num_groups);
225 * Place a tree at the same height as an existing tree.
227 * Add a new tree around the given tile which is at the same
228 * height or at some offset (2 units) of it.
230 * @param tile The base tile to add a new tree somewhere around
231 * @param height The height (like the one from the tile)
233 static void PlaceTreeAtSameHeight(TileIndex tile, int height)
235 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
236 uint32 r = Random();
237 int x = GB(r, 0, 5) - 16;
238 int y = GB(r, 8, 5) - 16;
239 TileIndex cur_tile = TileAddWrap(tile, x, y);
240 if (cur_tile == INVALID_TILE) continue;
242 /* Keep in range of the existing tree */
243 if (abs(x) + abs(y) > 16) continue;
245 /* Clear tile, no farm-tiles or rocks */
246 if (!CanPlantTreesOnTile(cur_tile, true)) continue;
248 /* Not too much height difference */
249 if (Delta(GetTileZ(cur_tile), height) > 2) continue;
251 /* Place one tree and quit */
252 PlaceTree(cur_tile, r);
253 break;
258 * Place some trees randomly
260 * This function just place some trees randomly on the map.
262 void PlaceTreesRandomly()
264 int i, j, ht;
266 i = ScaleByMapSize(DEFAULT_TREE_STEPS);
267 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
268 do {
269 uint32 r = Random();
270 TileIndex tile = RandomTileSeed(r);
272 IncreaseGeneratingWorldProgress(GWP_TREE);
274 if (CanPlantTreesOnTile(tile, true)) {
275 PlaceTree(tile, r);
276 if (_settings_game.game_creation.tree_placer != TP_IMPROVED) continue;
278 /* Place a number of trees based on the tile height.
279 * This gives a cool effect of multiple trees close together.
280 * It is almost real life ;) */
281 ht = GetTileZ(tile);
282 /* The higher we get, the more trees we plant */
283 j = GetTileZ(tile) * 2;
284 /* Above snowline more trees! */
285 if (_settings_game.game_creation.landscape == LT_ARCTIC && ht > GetSnowLine()) j *= 3;
286 while (j--) {
287 PlaceTreeAtSameHeight(tile, ht);
290 } while (--i);
292 /* place extra trees at rainforest area */
293 if (_settings_game.game_creation.landscape == LT_TROPIC) {
294 i = ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
295 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
297 do {
298 uint32 r = Random();
299 TileIndex tile = RandomTileSeed(r);
301 IncreaseGeneratingWorldProgress(GWP_TREE);
303 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST && CanPlantTreesOnTile(tile, false)) {
304 PlaceTree(tile, r);
306 } while (--i);
311 * Place new trees.
313 * This function takes care of the selected tree placer algorithm and
314 * place randomly the trees for a new game.
316 void GenerateTrees()
318 uint i, total;
320 if (_settings_game.game_creation.tree_placer == TP_NONE) return;
322 switch (_settings_game.game_creation.tree_placer) {
323 case TP_ORIGINAL: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 15 : 6; break;
324 case TP_IMPROVED: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 4 : 2; break;
325 default: NOT_REACHED();
328 total = ScaleByMapSize(DEFAULT_TREE_STEPS);
329 if (_settings_game.game_creation.landscape == LT_TROPIC) total += ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
330 total *= i;
331 uint num_groups = (_settings_game.game_creation.landscape != LT_TOYLAND) ? ScaleByMapSize(GB(Random(), 0, 5) + 25) : 0;
332 total += num_groups * DEFAULT_TREE_STEPS;
333 SetGeneratingWorldProgress(GWP_TREE, total);
335 if (num_groups != 0) PlaceTreeGroups(num_groups);
337 for (; i != 0; i--) {
338 PlaceTreesRandomly();
343 * Plant a tree.
344 * @param tile end tile of area-drag
345 * @param flags type of operation
346 * @param p1 tree type, TREE_INVALID means random.
347 * @param p2 start tile of area-drag of tree plantation
348 * @param text unused
349 * @return the cost of this operation or an error
351 CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
353 StringID msg = INVALID_STRING_ID;
354 CommandCost cost(EXPENSES_OTHER);
355 const byte tree_to_plant = GB(p1, 0, 8); // We cannot use Extract as min and max are climate specific.
357 if (p2 >= MapSize()) return CMD_ERROR;
358 /* Check the tree type within the current climate */
359 if (tree_to_plant != TREE_INVALID && !IsInsideBS(tree_to_plant, _tree_base_by_landscape[_settings_game.game_creation.landscape], _tree_count_by_landscape[_settings_game.game_creation.landscape])) return CMD_ERROR;
361 Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : NULL;
362 int limit = (c == NULL ? INT32_MAX : GB(c->tree_limit, 16, 16));
364 TileArea ta(tile, p2);
365 TILE_AREA_LOOP(tile, ta) {
366 switch (GetTileType(tile)) {
367 case TT_GROUND:
368 if (!IsTreeTile(tile)) break;
370 /* no more space for trees? */
371 if (_game_mode != GM_EDITOR && GetTreeCount(tile) == 4) {
372 msg = STR_ERROR_TREE_ALREADY_HERE;
373 continue;
376 /* Test tree limit. */
377 if (--limit < 1) {
378 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
379 break;
382 if (flags & DC_EXEC) {
383 AddTreeCount(tile, 1);
384 MarkTileDirtyByTile(tile);
385 if (c != NULL) c->tree_limit -= 1 << 16;
387 /* 2x as expensive to add more trees to an existing tile */
388 cost.AddCost(_price[PR_BUILD_TREES] * 2);
389 continue;
391 case TT_WATER:
392 if (!IsCoast(tile) || IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
393 msg = STR_ERROR_CAN_T_BUILD_ON_WATER;
394 continue;
396 break;
398 default:
399 msg = STR_ERROR_SITE_UNSUITABLE;
400 continue;
403 if (HasBridgeAbove(tile)) {
404 msg = STR_ERROR_SITE_UNSUITABLE;
405 continue;
408 TreeType treetype = (TreeType)tree_to_plant;
409 /* Be a bit picky about which trees go where. */
410 if (_settings_game.game_creation.landscape == LT_TROPIC && treetype != TREE_INVALID && (
411 /* No cacti outside the desert */
412 (treetype == TREE_CACTUS && GetTropicZone(tile) != TROPICZONE_DESERT) ||
413 /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
414 (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) ||
415 /* And no subtropical trees in the desert/rain forest */
416 (IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(tile) != TROPICZONE_NORMAL))) {
417 msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE;
418 continue;
421 /* Test tree limit. */
422 if (--limit < 1) {
423 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
424 break;
427 if (IsTileType(tile, TT_GROUND)) {
428 /* Remove fields or rocks. Note that the ground will get barrened */
429 if (IsTileSubtype(tile, TT_GROUND_FIELDS) || GetRawClearGround(tile) == GROUND_ROCKS) {
430 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
431 if (ret.Failed()) return ret;
432 cost.AddCost(ret);
436 if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
437 Town *t = LocalAuthorityTownFromTile(tile);
438 if (t != NULL) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
441 if (flags & DC_EXEC) {
442 if (treetype == TREE_INVALID) {
443 treetype = GetRandomTreeType(tile, GB(Random(), 24, 8));
444 if (treetype == TREE_INVALID) treetype = TREE_CACTUS;
447 /* Plant full grown trees in scenario editor */
448 PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
449 MarkTileDirtyByTile(tile);
450 if (c != NULL) c->tree_limit -= 1 << 16;
452 /* When planting rainforest-trees, set tropiczone to rainforest in editor. */
453 if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
454 SetTropicZone(tile, TROPICZONE_RAINFOREST);
458 cost.AddCost(_price[PR_BUILD_TREES]);
460 /* Tree limit used up? No need to check more. */
461 if (limit < 0) break;
464 if (cost.GetCost() == 0) {
465 return_cmd_error(msg);
466 } else {
467 return cost;
471 void OnTick_Trees()
473 /* Don't place trees if that's not allowed */
474 if (_settings_game.construction.extra_tree_placement == ETP_NONE) return;
476 uint32 r;
477 TileIndex tile;
478 TreeType tree;
480 /* place a tree at a random rainforest spot */
481 if (_settings_game.game_creation.landscape == LT_TROPIC &&
482 (r = Random(), tile = RandomTileSeed(r), GetTropicZone(tile) == TROPICZONE_RAINFOREST) &&
483 CanPlantTreesOnTile(tile, false) &&
484 (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
485 PlantTreesOnTile(tile, tree, 0, 0);
488 /* byte underflow */
489 if (--_trees_tick_ctr != 0 || _settings_game.construction.extra_tree_placement != ETP_ALL) return;
491 /* place a tree at a random spot */
492 r = Random();
493 tile = RandomTileSeed(r);
494 if (CanPlantTreesOnTile(tile, false) && (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
495 PlantTreesOnTile(tile, tree, 0, 0);
499 void InitializeTrees()
501 _trees_tick_ctr = 0;