Codechange: [Win32] simplify when/where GdiFlush() is called
[openttd-github.git] / src / tree_cmd.cpp
blobdee79e1b7228555a7178c6d51c9e86241c088fd5
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file tree_cmd.cpp Handling of tree tiles. */
10 #include "stdafx.h"
11 #include "clear_map.h"
12 #include "landscape.h"
13 #include "tree_map.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
16 #include "town.h"
17 #include "genworld.h"
18 #include "clear_func.h"
19 #include "company_func.h"
20 #include "sound_func.h"
21 #include "water.h"
22 #include "company_base.h"
23 #include "core/random_func.hpp"
24 #include "newgrf_generic.h"
26 #include "table/strings.h"
27 #include "table/tree_land.h"
28 #include "table/clear_land.h"
30 #include "safeguards.h"
32 /**
33 * List of tree placer algorithm.
35 * This enumeration defines all possible tree placer algorithm in the game.
37 enum TreePlacer {
38 TP_NONE, ///< No tree placer algorithm
39 TP_ORIGINAL, ///< The original algorithm
40 TP_IMPROVED, ///< A 'improved' algorithm
43 /** Where to place trees while in-game? */
44 enum ExtraTreePlacement {
45 ETP_NO_SPREAD, ///< Grow trees on tiles that have them but don't spread to new ones
46 ETP_SPREAD_RAINFOREST, ///< Grow trees on tiles that have them, only spread to new ones in rainforests
47 ETP_SPREAD_ALL, ///< Grow trees and spread them without restrictions
48 ETP_NO_GROWTH_NO_SPREAD, ///< Don't grow trees and don't spread them at all
51 /** Determines when to consider building more trees. */
52 byte _trees_tick_ctr;
54 static const uint16 DEFAULT_TREE_STEPS = 1000; ///< Default number of attempts for placing trees.
55 static const uint16 DEFAULT_RAINFOREST_TREE_STEPS = 15000; ///< Default number of attempts for placing extra trees at rainforest in tropic.
56 static const uint16 EDITOR_TREE_DIV = 5; ///< Game editor tree generation divisor factor.
58 /**
59 * Tests if a tile can be converted to MP_TREES
60 * This is true for clear ground without farms or rocks.
62 * @param tile the tile of interest
63 * @param allow_desert Allow planting trees on CLEAR_DESERT?
64 * @return true if trees can be built.
66 static bool CanPlantTreesOnTile(TileIndex tile, bool allow_desert)
68 switch (GetTileType(tile)) {
69 case MP_WATER:
70 return !IsBridgeAbove(tile) && IsCoast(tile) && !IsSlopeWithOneCornerRaised(GetTileSlope(tile));
72 case MP_CLEAR:
73 return !IsBridgeAbove(tile) && !IsClearGround(tile, CLEAR_FIELDS) && GetRawClearGround(tile) != CLEAR_ROCKS &&
74 (allow_desert || !IsClearGround(tile, CLEAR_DESERT));
76 default: return false;
80 /**
81 * Creates a tree tile
82 * Ground type and density is preserved.
84 * @pre the tile must be suitable for trees.
86 * @param tile where to plant the trees.
87 * @param treetype The type of the tree
88 * @param count the number of trees (minus 1)
89 * @param growth the growth status
91 static void PlantTreesOnTile(TileIndex tile, TreeType treetype, uint count, uint growth)
93 assert(treetype != TREE_INVALID);
94 assert(CanPlantTreesOnTile(tile, true));
96 TreeGround ground;
97 uint density = 3;
99 switch (GetTileType(tile)) {
100 case MP_WATER:
101 ground = TREE_GROUND_SHORE;
102 break;
104 case MP_CLEAR:
105 switch (GetClearGround(tile)) {
106 case CLEAR_GRASS: ground = TREE_GROUND_GRASS; break;
107 case CLEAR_ROUGH: ground = TREE_GROUND_ROUGH; break;
108 case CLEAR_SNOW: ground = GetRawClearGround(tile) == CLEAR_ROUGH ? TREE_GROUND_ROUGH_SNOW : TREE_GROUND_SNOW_DESERT; break;
109 default: ground = TREE_GROUND_SNOW_DESERT; break;
111 if (GetClearGround(tile) != CLEAR_ROUGH) density = GetClearDensity(tile);
112 break;
114 default: NOT_REACHED();
117 MakeTree(tile, treetype, count, growth, ground, density);
121 * Get a random TreeType for the given tile based on a given seed
123 * This function returns a random TreeType which can be placed on the given tile.
124 * The seed for randomness must be less or equal 256, use #GB on the value of Random()
125 * to get such a value.
127 * @param tile The tile to get a random TreeType from
128 * @param seed The seed for randomness, must be less or equal 256
129 * @return The random tree type
131 static TreeType GetRandomTreeType(TileIndex tile, uint seed)
133 switch (_settings_game.game_creation.landscape) {
134 case LT_TEMPERATE:
135 return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
137 case LT_ARCTIC:
138 return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
140 case LT_TROPIC:
141 switch (GetTropicZone(tile)) {
142 case TROPICZONE_NORMAL: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL);
143 case TROPICZONE_DESERT: return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS);
144 default: return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST);
147 default:
148 return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND);
153 * Make a random tree tile of the given tile
155 * Create a new tree-tile for the given tile. The second parameter is used for
156 * randomness like type and number of trees.
158 * @param tile The tile to make a tree-tile from
159 * @param r The randomness value from a Random() value
161 static void PlaceTree(TileIndex tile, uint32 r)
163 TreeType tree = GetRandomTreeType(tile, GB(r, 24, 8));
165 if (tree != TREE_INVALID) {
166 PlantTreesOnTile(tile, tree, GB(r, 22, 2), std::min<byte>(GB(r, 16, 3), 6));
168 /* Rerandomize ground, if neither snow nor shore */
169 TreeGround ground = GetTreeGround(tile);
170 if (ground != TREE_GROUND_SNOW_DESERT && ground != TREE_GROUND_ROUGH_SNOW && ground != TREE_GROUND_SHORE) {
171 SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 3);
174 /* Set the counter to a random start value */
175 SetTreeCounter(tile, (TreeGround)GB(r, 24, 4));
180 * Creates a number of tree groups.
181 * The number of trees in each group depends on how many trees are actually placed around the given tile.
183 * @param num_groups Number of tree groups to place.
185 static void PlaceTreeGroups(uint num_groups)
187 do {
188 TileIndex center_tile = RandomTile();
190 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
191 uint32 r = Random();
192 int x = GB(r, 0, 5) - 16;
193 int y = GB(r, 8, 5) - 16;
194 uint dist = abs(x) + abs(y);
195 TileIndex cur_tile = TileAddWrap(center_tile, x, y);
197 IncreaseGeneratingWorldProgress(GWP_TREE);
199 if (cur_tile != INVALID_TILE && dist <= 13 && CanPlantTreesOnTile(cur_tile, true)) {
200 PlaceTree(cur_tile, r);
204 } while (--num_groups);
208 * Place a tree at the same height as an existing tree.
210 * Add a new tree around the given tile which is at the same
211 * height or at some offset (2 units) of it.
213 * @param tile The base tile to add a new tree somewhere around
214 * @param height The height (like the one from the tile)
216 static void PlaceTreeAtSameHeight(TileIndex tile, int height)
218 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
219 uint32 r = Random();
220 int x = GB(r, 0, 5) - 16;
221 int y = GB(r, 8, 5) - 16;
222 TileIndex cur_tile = TileAddWrap(tile, x, y);
223 if (cur_tile == INVALID_TILE) continue;
225 /* Keep in range of the existing tree */
226 if (abs(x) + abs(y) > 16) continue;
228 /* Clear tile, no farm-tiles or rocks */
229 if (!CanPlantTreesOnTile(cur_tile, true)) continue;
231 /* Not too much height difference */
232 if (Delta(GetTileZ(cur_tile), height) > 2) continue;
234 /* Place one tree and quit */
235 PlaceTree(cur_tile, r);
236 break;
241 * Place some trees randomly
243 * This function just place some trees randomly on the map.
245 void PlaceTreesRandomly()
247 int i, j, ht;
249 i = ScaleByMapSize(DEFAULT_TREE_STEPS);
250 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
251 do {
252 uint32 r = Random();
253 TileIndex tile = RandomTileSeed(r);
255 IncreaseGeneratingWorldProgress(GWP_TREE);
257 if (CanPlantTreesOnTile(tile, true)) {
258 PlaceTree(tile, r);
259 if (_settings_game.game_creation.tree_placer != TP_IMPROVED) continue;
261 /* Place a number of trees based on the tile height.
262 * This gives a cool effect of multiple trees close together.
263 * It is almost real life ;) */
264 ht = GetTileZ(tile);
265 /* The higher we get, the more trees we plant */
266 j = GetTileZ(tile) * 2;
267 /* Above snowline more trees! */
268 if (_settings_game.game_creation.landscape == LT_ARCTIC && ht > GetSnowLine()) j *= 3;
269 while (j--) {
270 PlaceTreeAtSameHeight(tile, ht);
273 } while (--i);
275 /* place extra trees at rainforest area */
276 if (_settings_game.game_creation.landscape == LT_TROPIC) {
277 i = ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
278 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
280 do {
281 uint32 r = Random();
282 TileIndex tile = RandomTileSeed(r);
284 IncreaseGeneratingWorldProgress(GWP_TREE);
286 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST && CanPlantTreesOnTile(tile, false)) {
287 PlaceTree(tile, r);
289 } while (--i);
294 * Place some trees in a radius around a tile.
295 * The trees are placed in an quasi-normal distribution around the indicated tile, meaning that while
296 * the radius does define a square, the distribution inside the square will be roughly circular.
297 * @note This function the interactive RNG and must only be used in editor and map generation.
298 * @param tile Tile to place trees around.
299 * @param treetype Type of trees to place. Must be a valid tree type for the climate.
300 * @param radius Maximum distance (on each axis) from tile to place trees.
301 * @param count Maximum number of trees to place.
302 * @return Number of trees actually placed.
304 uint PlaceTreeGroupAroundTile(TileIndex tile, TreeType treetype, uint radius, uint count)
306 assert(treetype < TREE_TOYLAND + TREE_COUNT_TOYLAND);
307 const bool allow_desert = treetype == TREE_CACTUS;
308 uint planted = 0;
310 for (; count > 0; count--) {
311 /* Simple quasi-normal distribution with range [-radius; radius) */
312 auto mkcoord = [&]() -> int32 {
313 const uint32 rand = InteractiveRandom();
314 const int32 dist = GB<int32>(rand, 0, 8) + GB<int32>(rand, 8, 8) + GB<int32>(rand, 16, 8) + GB<int32>(rand, 24, 8);
315 const int32 scu = dist * radius / 512;
316 return scu - radius;
318 const int32 xofs = mkcoord();
319 const int32 yofs = mkcoord();
320 const TileIndex tile_to_plant = TileAddWrap(tile, xofs, yofs);
321 if (tile_to_plant != INVALID_TILE) {
322 if (IsTileType(tile_to_plant, MP_TREES) && GetTreeCount(tile_to_plant) < 4) {
323 AddTreeCount(tile_to_plant, 1);
324 SetTreeGrowth(tile_to_plant, 0);
325 MarkTileDirtyByTile(tile_to_plant, 0);
326 planted++;
327 } else if (CanPlantTreesOnTile(tile_to_plant, allow_desert)) {
328 PlantTreesOnTile(tile_to_plant, treetype, 0, 3);
329 MarkTileDirtyByTile(tile_to_plant, 0);
330 planted++;
335 return planted;
339 * Place new trees.
341 * This function takes care of the selected tree placer algorithm and
342 * place randomly the trees for a new game.
344 void GenerateTrees()
346 uint i, total;
348 if (_settings_game.game_creation.tree_placer == TP_NONE) return;
350 switch (_settings_game.game_creation.tree_placer) {
351 case TP_ORIGINAL: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 15 : 6; break;
352 case TP_IMPROVED: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 4 : 2; break;
353 default: NOT_REACHED();
356 total = ScaleByMapSize(DEFAULT_TREE_STEPS);
357 if (_settings_game.game_creation.landscape == LT_TROPIC) total += ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
358 total *= i;
359 uint num_groups = (_settings_game.game_creation.landscape != LT_TOYLAND) ? ScaleByMapSize(GB(Random(), 0, 5) + 25) : 0;
360 total += num_groups * DEFAULT_TREE_STEPS;
361 SetGeneratingWorldProgress(GWP_TREE, total);
363 if (num_groups != 0) PlaceTreeGroups(num_groups);
365 for (; i != 0; i--) {
366 PlaceTreesRandomly();
371 * Plant a tree.
372 * @param tile end tile of area-drag
373 * @param flags type of operation
374 * @param p1 tree type, TREE_INVALID means random.
375 * @param p2 start tile of area-drag of tree plantation
376 * @param text unused
377 * @return the cost of this operation or an error
379 CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
381 StringID msg = INVALID_STRING_ID;
382 CommandCost cost(EXPENSES_OTHER);
383 const byte tree_to_plant = GB(p1, 0, 8); // We cannot use Extract as min and max are climate specific.
385 if (p2 >= MapSize()) return CMD_ERROR;
386 /* Check the tree type within the current climate */
387 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;
389 Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : nullptr;
390 int limit = (c == nullptr ? INT32_MAX : GB(c->tree_limit, 16, 16));
392 TileArea ta(tile, p2);
393 TILE_AREA_LOOP(tile, ta) {
394 switch (GetTileType(tile)) {
395 case MP_TREES:
396 /* no more space for trees? */
397 if (GetTreeCount(tile) == 4) {
398 msg = STR_ERROR_TREE_ALREADY_HERE;
399 continue;
402 /* Test tree limit. */
403 if (--limit < 1) {
404 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
405 break;
408 if (flags & DC_EXEC) {
409 AddTreeCount(tile, 1);
410 MarkTileDirtyByTile(tile);
411 if (c != nullptr) c->tree_limit -= 1 << 16;
413 /* 2x as expensive to add more trees to an existing tile */
414 cost.AddCost(_price[PR_BUILD_TREES] * 2);
415 break;
417 case MP_WATER:
418 if (!IsCoast(tile) || IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
419 msg = STR_ERROR_CAN_T_BUILD_ON_WATER;
420 continue;
422 FALLTHROUGH;
424 case MP_CLEAR: {
425 if (IsBridgeAbove(tile)) {
426 msg = STR_ERROR_SITE_UNSUITABLE;
427 continue;
430 TreeType treetype = (TreeType)tree_to_plant;
431 /* Be a bit picky about which trees go where. */
432 if (_settings_game.game_creation.landscape == LT_TROPIC && treetype != TREE_INVALID && (
433 /* No cacti outside the desert */
434 (treetype == TREE_CACTUS && GetTropicZone(tile) != TROPICZONE_DESERT) ||
435 /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
436 (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) ||
437 /* And no subtropical trees in the desert/rain forest */
438 (IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(tile) != TROPICZONE_NORMAL))) {
439 msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE;
440 continue;
443 /* Test tree limit. */
444 if (--limit < 1) {
445 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
446 break;
449 if (IsTileType(tile, MP_CLEAR)) {
450 /* Remove fields or rocks. Note that the ground will get barrened */
451 switch (GetRawClearGround(tile)) {
452 case CLEAR_FIELDS:
453 case CLEAR_ROCKS: {
454 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
455 if (ret.Failed()) return ret;
456 cost.AddCost(ret);
457 break;
460 default: break;
464 if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
465 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
466 if (t != nullptr) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
469 if (flags & DC_EXEC) {
470 if (treetype == TREE_INVALID) {
471 treetype = GetRandomTreeType(tile, GB(Random(), 24, 8));
472 if (treetype == TREE_INVALID) treetype = TREE_CACTUS;
475 /* Plant full grown trees in scenario editor */
476 PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
477 MarkTileDirtyByTile(tile);
478 if (c != nullptr) c->tree_limit -= 1 << 16;
480 /* When planting rainforest-trees, set tropiczone to rainforest in editor. */
481 if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
482 SetTropicZone(tile, TROPICZONE_RAINFOREST);
485 cost.AddCost(_price[PR_BUILD_TREES]);
486 break;
489 default:
490 msg = STR_ERROR_SITE_UNSUITABLE;
491 break;
494 /* Tree limit used up? No need to check more. */
495 if (limit < 0) break;
498 if (cost.GetCost() == 0) {
499 return_cmd_error(msg);
500 } else {
501 return cost;
505 struct TreeListEnt : PalSpriteID {
506 byte x, y;
509 static void DrawTile_Trees(TileInfo *ti)
511 switch (GetTreeGround(ti->tile)) {
512 case TREE_GROUND_SHORE: DrawShoreTile(ti->tileh); break;
513 case TREE_GROUND_GRASS: DrawClearLandTile(ti, GetTreeDensity(ti->tile)); break;
514 case TREE_GROUND_ROUGH: DrawHillyLandTile(ti); break;
515 default: DrawGroundSprite(_clear_land_sprites_snow_desert[GetTreeDensity(ti->tile)] + SlopeToSpriteOffset(ti->tileh), PAL_NONE); break;
518 /* Do not draw trees when the invisible trees setting is set */
519 if (IsInvisibilitySet(TO_TREES)) return;
521 uint tmp = CountBits(ti->tile + ti->x + ti->y);
522 uint index = GB(tmp, 0, 2) + (GetTreeType(ti->tile) << 2);
524 /* different tree styles above one of the grounds */
525 if ((GetTreeGround(ti->tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(ti->tile) == TREE_GROUND_ROUGH_SNOW) &&
526 GetTreeDensity(ti->tile) >= 2 &&
527 IsInsideMM(index, TREE_SUB_ARCTIC << 2, TREE_RAINFOREST << 2)) {
528 index += 164 - (TREE_SUB_ARCTIC << 2);
531 assert(index < lengthof(_tree_layout_sprite));
533 const PalSpriteID *s = _tree_layout_sprite[index];
534 const TreePos *d = _tree_layout_xy[GB(tmp, 2, 2)];
536 /* combine trees into one sprite object */
537 StartSpriteCombine();
539 TreeListEnt te[4];
541 /* put the trees to draw in a list */
542 uint trees = GetTreeCount(ti->tile);
544 for (uint i = 0; i < trees; i++) {
545 SpriteID sprite = s[0].sprite + (i == trees - 1 ? GetTreeGrowth(ti->tile) : 3);
546 PaletteID pal = s[0].pal;
548 te[i].sprite = sprite;
549 te[i].pal = pal;
550 te[i].x = d->x;
551 te[i].y = d->y;
552 s++;
553 d++;
556 /* draw them in a sorted way */
557 int z = ti->z + GetSlopeMaxPixelZ(ti->tileh) / 2;
559 for (; trees > 0; trees--) {
560 uint min = te[0].x + te[0].y;
561 uint mi = 0;
563 for (uint i = 1; i < trees; i++) {
564 if ((uint)(te[i].x + te[i].y) < min) {
565 min = te[i].x + te[i].y;
566 mi = i;
570 AddSortableSpriteToDraw(te[mi].sprite, te[mi].pal, ti->x + te[mi].x, ti->y + te[mi].y, 16 - te[mi].x, 16 - te[mi].y, 0x30, z, IsTransparencySet(TO_TREES), -te[mi].x, -te[mi].y);
572 /* replace the removed one with the last one */
573 te[mi] = te[trees - 1];
576 EndSpriteCombine();
580 static int GetSlopePixelZ_Trees(TileIndex tile, uint x, uint y)
582 int z;
583 Slope tileh = GetTilePixelSlope(tile, &z);
585 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
588 static Foundation GetFoundation_Trees(TileIndex tile, Slope tileh)
590 return FOUNDATION_NONE;
593 static CommandCost ClearTile_Trees(TileIndex tile, DoCommandFlag flags)
595 uint num;
597 if (Company::IsValidID(_current_company)) {
598 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
599 if (t != nullptr) ChangeTownRating(t, RATING_TREE_DOWN_STEP, RATING_TREE_MINIMUM, flags);
602 num = GetTreeCount(tile);
603 if (IsInsideMM(GetTreeType(tile), TREE_RAINFOREST, TREE_CACTUS)) num *= 4;
605 if (flags & DC_EXEC) DoClearSquare(tile);
607 return CommandCost(EXPENSES_CONSTRUCTION, num * _price[PR_CLEAR_TREES]);
610 static void GetTileDesc_Trees(TileIndex tile, TileDesc *td)
612 TreeType tt = GetTreeType(tile);
614 if (IsInsideMM(tt, TREE_RAINFOREST, TREE_CACTUS)) {
615 td->str = STR_LAI_TREE_NAME_RAINFOREST;
616 } else {
617 td->str = tt == TREE_CACTUS ? STR_LAI_TREE_NAME_CACTUS_PLANTS : STR_LAI_TREE_NAME_TREES;
620 td->owner[0] = GetTileOwner(tile);
623 static void TileLoopTreesDesert(TileIndex tile)
625 switch (GetTropicZone(tile)) {
626 case TROPICZONE_DESERT:
627 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT) {
628 SetTreeGroundDensity(tile, TREE_GROUND_SNOW_DESERT, 3);
629 MarkTileDirtyByTile(tile);
631 break;
633 case TROPICZONE_RAINFOREST: {
634 static const SoundFx forest_sounds[] = {
635 SND_42_LOON_BIRD,
636 SND_43_LION,
637 SND_44_MONKEYS,
638 SND_48_DISTANT_BIRD
640 uint32 r = Random();
642 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) SndPlayTileFx(forest_sounds[GB(r, 16, 2)], tile);
643 break;
646 default: break;
650 static void TileLoopTreesAlps(TileIndex tile)
652 int k = GetTileZ(tile) - GetSnowLine() + 1;
654 if (k < 0) {
655 switch (GetTreeGround(tile)) {
656 case TREE_GROUND_SNOW_DESERT: SetTreeGroundDensity(tile, TREE_GROUND_GRASS, 3); break;
657 case TREE_GROUND_ROUGH_SNOW: SetTreeGroundDensity(tile, TREE_GROUND_ROUGH, 3); break;
658 default: return;
660 } else {
661 uint density = std::min<uint>(k, 3);
663 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT && GetTreeGround(tile) != TREE_GROUND_ROUGH_SNOW) {
664 TreeGround tg = GetTreeGround(tile) == TREE_GROUND_ROUGH ? TREE_GROUND_ROUGH_SNOW : TREE_GROUND_SNOW_DESERT;
665 SetTreeGroundDensity(tile, tg, density);
666 } else if (GetTreeDensity(tile) != density) {
667 SetTreeGroundDensity(tile, GetTreeGround(tile), density);
668 } else {
669 if (GetTreeDensity(tile) == 3) {
670 uint32 r = Random();
671 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) {
672 SndPlayTileFx((r & 0x80000000) ? SND_39_HEAVY_WIND : SND_34_WIND, tile);
675 return;
678 MarkTileDirtyByTile(tile);
681 static bool CanPlantExtraTrees(TileIndex tile)
683 return ((_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) == TROPICZONE_RAINFOREST) ?
684 (_settings_game.construction.extra_tree_placement == ETP_SPREAD_ALL || _settings_game.construction.extra_tree_placement == ETP_SPREAD_RAINFOREST) :
685 _settings_game.construction.extra_tree_placement == ETP_SPREAD_ALL);
688 static void TileLoop_Trees(TileIndex tile)
690 if (GetTreeGround(tile) == TREE_GROUND_SHORE) {
691 TileLoop_Water(tile);
692 } else {
693 switch (_settings_game.game_creation.landscape) {
694 case LT_TROPIC: TileLoopTreesDesert(tile); break;
695 case LT_ARCTIC: TileLoopTreesAlps(tile); break;
699 AmbientSoundEffect(tile);
701 uint treeCounter = GetTreeCounter(tile);
703 /* Handle growth of grass (under trees/on MP_TREES tiles) at every 8th processings, like it's done for grass on MP_CLEAR tiles. */
704 if ((treeCounter & 7) == 7 && GetTreeGround(tile) == TREE_GROUND_GRASS) {
705 uint density = GetTreeDensity(tile);
706 if (density < 3) {
707 SetTreeGroundDensity(tile, TREE_GROUND_GRASS, density + 1);
708 MarkTileDirtyByTile(tile);
712 if (_settings_game.construction.extra_tree_placement == ETP_NO_GROWTH_NO_SPREAD) return;
714 if (GetTreeCounter(tile) < 15) {
715 AddTreeCounter(tile, 1);
716 return;
718 SetTreeCounter(tile, 0);
720 switch (GetTreeGrowth(tile)) {
721 case 3: // regular sized tree
722 if (_settings_game.game_creation.landscape == LT_TROPIC &&
723 GetTreeType(tile) != TREE_CACTUS &&
724 GetTropicZone(tile) == TROPICZONE_DESERT) {
725 AddTreeGrowth(tile, 1);
726 } else {
727 switch (GB(Random(), 0, 3)) {
728 case 0: // start destructing
729 AddTreeGrowth(tile, 1);
730 break;
732 case 1: // add a tree
733 if (GetTreeCount(tile) < 4 && CanPlantExtraTrees(tile)) {
734 AddTreeCount(tile, 1);
735 SetTreeGrowth(tile, 0);
736 break;
738 FALLTHROUGH;
740 case 2: { // add a neighbouring tree
741 if (!CanPlantExtraTrees(tile)) break;
743 TreeType treetype = GetTreeType(tile);
745 tile += TileOffsByDir((Direction)(Random() & 7));
747 /* Cacti don't spread */
748 if (!CanPlantTreesOnTile(tile, false)) return;
750 /* Don't plant trees, if ground was freshly cleared */
751 if (IsTileType(tile, MP_CLEAR) && GetClearGround(tile) == CLEAR_GRASS && GetClearDensity(tile) != 3) return;
753 PlantTreesOnTile(tile, treetype, 0, 0);
755 break;
758 default:
759 return;
762 break;
764 case 6: // final stage of tree destruction
765 if (!CanPlantExtraTrees(tile)) {
766 /* if trees can't spread just plant a new one to prevent deforestation */
767 SetTreeGrowth(tile, 0);
768 } else if (GetTreeCount(tile) > 1) {
769 /* more than one tree, delete it */
770 AddTreeCount(tile, -1);
771 SetTreeGrowth(tile, 3);
772 } else {
773 /* just one tree, change type into MP_CLEAR */
774 switch (GetTreeGround(tile)) {
775 case TREE_GROUND_SHORE: MakeShore(tile); break;
776 case TREE_GROUND_GRASS: MakeClear(tile, CLEAR_GRASS, GetTreeDensity(tile)); break;
777 case TREE_GROUND_ROUGH: MakeClear(tile, CLEAR_ROUGH, 3); break;
778 case TREE_GROUND_ROUGH_SNOW: {
779 uint density = GetTreeDensity(tile);
780 MakeClear(tile, CLEAR_ROUGH, 3);
781 MakeSnow(tile, density);
782 break;
784 default: // snow or desert
785 if (_settings_game.game_creation.landscape == LT_TROPIC) {
786 MakeClear(tile, CLEAR_DESERT, GetTreeDensity(tile));
787 } else {
788 uint density = GetTreeDensity(tile);
789 MakeClear(tile, CLEAR_GRASS, 3);
790 MakeSnow(tile, density);
792 break;
795 break;
797 default:
798 AddTreeGrowth(tile, 1);
799 break;
802 MarkTileDirtyByTile(tile);
805 void OnTick_Trees()
807 /* Don't spread trees if that's not allowed */
808 if (_settings_game.construction.extra_tree_placement == ETP_NO_SPREAD || _settings_game.construction.extra_tree_placement == ETP_NO_GROWTH_NO_SPREAD) return;
810 uint32 r;
811 TileIndex tile;
812 TreeType tree;
814 /* place a tree at a random rainforest spot */
815 if (_settings_game.game_creation.landscape == LT_TROPIC &&
816 (r = Random(), tile = RandomTileSeed(r), GetTropicZone(tile) == TROPICZONE_RAINFOREST) &&
817 CanPlantTreesOnTile(tile, false) &&
818 (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
819 PlantTreesOnTile(tile, tree, 0, 0);
822 /* byte underflow */
823 if (--_trees_tick_ctr != 0 || _settings_game.construction.extra_tree_placement == ETP_SPREAD_RAINFOREST) return;
825 /* place a tree at a random spot */
826 r = Random();
827 tile = RandomTileSeed(r);
828 if (CanPlantTreesOnTile(tile, false) && (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
829 PlantTreesOnTile(tile, tree, 0, 0);
833 static TrackStatus GetTileTrackStatus_Trees(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
835 return 0;
838 static void ChangeTileOwner_Trees(TileIndex tile, Owner old_owner, Owner new_owner)
840 /* not used */
843 void InitializeTrees()
845 _trees_tick_ctr = 0;
848 static CommandCost TerraformTile_Trees(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
850 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
854 extern const TileTypeProcs _tile_type_trees_procs = {
855 DrawTile_Trees, // draw_tile_proc
856 GetSlopePixelZ_Trees, // get_slope_z_proc
857 ClearTile_Trees, // clear_tile_proc
858 nullptr, // add_accepted_cargo_proc
859 GetTileDesc_Trees, // get_tile_desc_proc
860 GetTileTrackStatus_Trees, // get_tile_track_status_proc
861 nullptr, // click_tile_proc
862 nullptr, // animate_tile_proc
863 TileLoop_Trees, // tile_loop_proc
864 ChangeTileOwner_Trees, // change_tile_owner_proc
865 nullptr, // add_produced_cargo_proc
866 nullptr, // vehicle_enter_tile_proc
867 GetFoundation_Trees, // get_foundation_proc
868 TerraformTile_Trees, // terraform_tile_proc