diff --git a/.gitignore b/.gitignore index 8cdabf2eb4..b2f7e881fd 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ opencode.json /S2 /build +/build-xcode /external/boost* /win32/*.aps /data/RTTR/languages/*.mo diff --git a/libs/s25main/ingameWindows/iwMapGenerator.cpp b/libs/s25main/ingameWindows/iwMapGenerator.cpp index 760aadd3d4..4026135dc5 100644 --- a/libs/s25main/ingameWindows/iwMapGenerator.cpp +++ b/libs/s25main/ingameWindows/iwMapGenerator.cpp @@ -4,6 +4,7 @@ #include "iwMapGenerator.h" #include "Loader.h" +#include "controls/ctrlCheck.h" #include "controls/ctrlComboBox.h" #include "controls/ctrlProgress.h" #include "helpers/containerUtils.h" @@ -19,7 +20,7 @@ using namespace rttr::mapGenerator; iwMapGenerator::iwMapGenerator(MapSettings& settings) - : IngameWindow(CGI_MAP_GENERATOR, IngameWindow::posLastOrCenter, Extent(270, 520), _("Map Generator"), + : IngameWindow(CGI_MAP_GENERATOR, IngameWindow::posLastOrCenter, Extent(270, 645), _("Map Generator"), LOADER.getImageN("resource", 41), true, CloseBehavior::Custom), mapSettings(settings) { @@ -109,10 +110,22 @@ iwMapGenerator::iwMapGenerator(MapSettings& settings) addText(ID_txtTrees, curPos, _("Trees:"), COLOR_YELLOW, FontStyle{}, NormalFont); addProgress(ID_pgTrees, DrawPoint(pgrOffset, curPos.y - 5), progressSize, TextureColor::Grey, 139, 138, 100); curPos.y += 30; + addText(ID_txtMountains, curPos, _("Mountains:"), COLOR_YELLOW, FontStyle{}, NormalFont); + addProgress(ID_pgMountains, DrawPoint(pgrOffset, curPos.y - 5), progressSize, TextureColor::Grey, 139, 138, 100); + curPos.y += 30; + addText(ID_txtDesert, curPos, _("Desert:"), COLOR_YELLOW, FontStyle{}, NormalFont); + addProgress(ID_pgDesert, DrawPoint(pgrOffset, curPos.y - 5), progressSize, TextureColor::Grey, 139, 138, 100); + curPos.y += 30; + addText(ID_txtSwamp, curPos, _("Swamp:"), COLOR_YELLOW, FontStyle{}, NormalFont); + addProgress(ID_pgSwamp, DrawPoint(pgrOffset, curPos.y - 5), progressSize, TextureColor::Grey, 139, 138, 100); + curPos.y += 30; addText(ID_txtStonePiles, curPos, _("Stone piles:"), COLOR_YELLOW, FontStyle{}, NormalFont); addProgress(ID_pgStonePiles, DrawPoint(pgrOffset, curPos.y - 5), progressSize, TextureColor::Grey, 139, 138, 100); curPos.y += 25; + addCheckBox(ID_cbSpecialObjects, curPos, comboSize, TextureColor::Grey, _("Special Objects"), NormalFont, false); + + curPos.y += 35; addTextButton(ID_btBack, curPos, buttonSize, TextureColor::Red1, _("Back"), NormalFont); addTextButton(ID_btApply, DrawPoint(130, curPos.y), buttonSize, TextureColor::Green2, _("Apply"), NormalFont); @@ -140,7 +153,11 @@ void iwMapGenerator::apply() mapSettings.ratioGranite = getCtrl(ID_pgGraniteRatio)->getPosition(); mapSettings.rivers = getCtrl(ID_pgRivers)->getPosition(); mapSettings.trees = getCtrl(ID_pgTrees)->getPosition(); + mapSettings.mountains = getCtrl(ID_pgMountains)->getPosition(); + mapSettings.desert = getCtrl(ID_pgDesert)->getPosition(); + mapSettings.swamp = getCtrl(ID_pgSwamp)->getPosition(); mapSettings.stonePiles = getCtrl(ID_pgStonePiles)->getPosition(); + mapSettings.specialObjects = getCtrl(ID_cbSpecialObjects)->isChecked(); switch(getCtrl(ID_cbMountainDist)->getSelection().value()) { @@ -181,7 +198,11 @@ void iwMapGenerator::reset() getCtrl(ID_pgGraniteRatio)->setPosition(mapSettings.ratioGranite); getCtrl(ID_pgRivers)->setPosition(mapSettings.rivers); getCtrl(ID_pgTrees)->setPosition(mapSettings.trees); + getCtrl(ID_pgMountains)->setPosition(mapSettings.mountains); + getCtrl(ID_pgDesert)->setPosition(mapSettings.desert); + getCtrl(ID_pgSwamp)->setPosition(mapSettings.swamp); getCtrl(ID_pgStonePiles)->setPosition(mapSettings.stonePiles); + getCtrl(ID_cbSpecialObjects)->setChecked(mapSettings.specialObjects); auto* combo = getCtrl(ID_cbMountainDist); switch(mapSettings.mountainDistance) diff --git a/libs/s25main/ingameWindows/iwMapGenerator.h b/libs/s25main/ingameWindows/iwMapGenerator.h index 7298b389be..982026859c 100644 --- a/libs/s25main/ingameWindows/iwMapGenerator.h +++ b/libs/s25main/ingameWindows/iwMapGenerator.h @@ -23,6 +23,9 @@ class iwMapGenerator : public IngameWindow ID_txtRivers, ID_txtMountainDist, ID_txtTrees, + ID_txtMountains, + ID_txtDesert, + ID_txtSwamp, ID_txtStonePiles, ID_txtIslands, ID_cbNumPlayers, @@ -40,8 +43,12 @@ class iwMapGenerator : public IngameWindow ID_pgRivers, ID_cbMountainDist, ID_pgTrees, + ID_pgMountains, + ID_pgDesert, + ID_pgSwamp, ID_pgStonePiles, - ID_cbIslands + ID_cbIslands, + ID_cbSpecialObjects }; /** diff --git a/libs/s25main/mapGenerator/FreeLand.cpp b/libs/s25main/mapGenerator/FreeLand.cpp new file mode 100644 index 0000000000..1af8ad07cb --- /dev/null +++ b/libs/s25main/mapGenerator/FreeLand.cpp @@ -0,0 +1,294 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "mapGenerator/FreeLand.h" +#include "helpers/EnumRange.h" +#include "helpers/containerUtils.h" +#include "mapGenerator/Algorithms.h" +#include "mapGenerator/TextureHelper.h" +#include "libsiedler2/enumTypes.h" +#include +#include +#include +#include + +namespace rttr::mapGenerator { + +namespace { + /// Maximum elevation of the center of a desert hill + constexpr unsigned maxDesertElevation = 4; + /// Number of rings of transition textures around the desert + constexpr unsigned desertTransitions = 2; + /// Chance in percentage for bones on a node around the center of a desert hill + constexpr unsigned boneChance = 12; + /// Chance in percentage for a dead tree on a node next to a swamp + constexpr unsigned deadTreeChance = 33; + /// Number of passes to close gaps of an area + constexpr unsigned gapIterations = 2; + /// Number of neighbors within an area required for a node to be considered a gap of the area + constexpr unsigned minGapNeighbors = 4; + + void placeDecoration(Map& map, const MapPoint& pt, uint8_t index) + { + map.objectTypes[pt] = OT_Decoration; + map.objectInfos[pt] = index; + } +} // namespace + +Mountain closeGaps(const MapExtent& size, const Mountain& area) +{ + NodeMapBase neighbors; + neighbors.resize(size); + Mountain closedArea = area; + + for(unsigned i = 0; i < gapIterations; i++) + { + std::set candidates; + for(const MapPoint& pt : closedArea) + { + for(const MapPoint& neighbor : neighbors.getNeighbours(pt)) + { + if(!helpers::contains(closedArea, neighbor)) + candidates.insert(neighbor); + } + } + + std::vector gaps; + for(const MapPoint& candidate : candidates) + { + const auto inArea = [&closedArea](const MapPoint& pt) { return helpers::contains(closedArea, pt); }; + if(helpers::countIf(neighbors.getNeighbours(candidate), inArea) >= minGapNeighbors) + gaps.push_back(candidate); + } + + if(gaps.empty()) + break; + closedArea.insert(gaps.begin(), gaps.end()); + } + + return closedArea; +} + +LandFill selectLandFill(RandomUtility& rnd, const LandFillAmounts& amounts, const LandFillAmounts& assigned) +{ + const uint64_t totalAmount = std::accumulate(amounts.begin(), amounts.end(), uint64_t(0)); + const uint64_t totalAssigned = std::accumulate(assigned.begin(), assigned.end(), uint64_t(0)); + + if(totalAmount == 0 || (totalAssigned == 0 && amounts[LandFill::Mountain] > 0)) + return LandFill::Mountain; + + // A type is behind if its share of assigned nodes doesn't exceed its share of the amounts. + // This always applies to at least one of the types. + std::vector candidates; + unsigned candidateAmount = 0; + for(const LandFill type : helpers::EnumRange()) + { + if(amounts[type] > 0 && assigned[type] * totalAmount <= totalAssigned * amounts[type]) + { + candidates.push_back(type); + candidateAmount += amounts[type]; + } + } + + if(candidates.size() == 1) + return candidates.front(); + + unsigned value = rnd.randomValue(1u, candidateAmount); + for(const LandFill candidate : candidates) + { + if(value <= amounts[candidate]) + return candidate; + value -= amounts[candidate]; + } + + return candidates.back(); +} + +void raiseDesertHill(Map& map, RandomUtility& rnd, const Mountain& area) +{ + if(area.empty()) + return; + + const auto footDistance = getFootDistances(map.size, area); + const unsigned maxDistance = getMaximum(footDistance, area); + // Small hills get less transitions to still contain some desert + const unsigned transitions = std::min(desertTransitions, maxDistance); + + const auto desert = map.textureMap.find(isCoastTerrain); + auto transitionTextures = map.textureMap.findAll(isBuildableCoast); + map.textureMap.sort(transitionTextures, byHumidity); + + // Neighboring nodes share triangles. Texturing from the foot to the center lets the inner texture win which results + // in one row of triangles per transition and nodes of the desert which are entirely covered by desert. + std::vector nodes(area.begin(), area.end()); + std::stable_sort(nodes.begin(), nodes.end(), [&footDistance](const MapPoint& lhs, const MapPoint& rhs) { + return footDistance[lhs] < footDistance[rhs]; + }); + + for(const MapPoint& pt : nodes) + { + const unsigned distance = footDistance[pt]; + const unsigned elevation = std::min((distance + 1) / 2, maxDesertElevation); + map.z[pt] = static_cast(std::min(map.z[pt] + elevation, map.height.maximum)); + + if(distance >= transitions) + { + map.textureMap.set(pt, desert); + map.barren.insert(pt); + } else + { + // The driest texture is next to the desert + const auto maxIndex = static_cast(transitionTextures.size() - 1); + const unsigned index = std::min(transitions - 1 - distance, maxIndex); + map.textureMap.set(pt, transitionTextures[index]); + } + } + + bool hasBones = false; + for(const MapPoint& pt : area) + { + const unsigned distance = footDistance[pt]; + const bool isCenter = distance == maxDistance; + const bool isAroundCenter = distance >= transitions && distance * 3 >= maxDistance * 2; + + if((isCenter && !hasBones) || (isAroundCenter && rnd.byChance(boneChance))) + { + placeDecoration(map, pt, rnd.byChance(50) ? OI_Bone1 : OI_Bone2); + hasBones = true; + } + } +} + +void createSwamp(Map& map, RandomUtility& rnd, const Mountain& area) +{ + if(area.empty()) + return; + + const auto swamp = map.textureMap.find(isImpassable); + const uint8_t level = map.z[*std::min_element( + area.begin(), area.end(), [&map](const MapPoint& lhs, const MapPoint& rhs) { return map.z[lhs] < map.z[rhs]; })]; + + // Other landscapes (rivers, mountains, deserts, water) are textured already or located at sea level. Rivers follow + // the height of the land. Lowering their banks would leave the water on top of a ridge. + const auto obstacleDistances = distancesTo(map.size, [&map](const MapPoint& pt) { + if(map.z[pt] == map.height.minimum) + return true; + const auto triangles = getTriangles(pt, map.size); + return helpers::containsIf(triangles, + [&map](const Triangle& t) { return static_cast(map.textureMap.get(t)); }); + }); + + for(const MapPoint& pt : area) + { + map.z[pt] = level; + map.textureMap.set(pt, swamp); + map.barren.insert(pt); + } + + const auto distances = distancesTo(area, map.size); + + RTTR_FOREACH_PT(MapPoint, map.size) + { + const unsigned distance = distances[pt]; + if(distance == 0) + continue; + + // The land descends to the swamp by one level per node at most. Other landscapes and the land next to them + // keep their height. From there the land may be lowered by one more level with each node. + const unsigned maxLowering = obstacleDistances[pt] > 0 ? obstacleDistances[pt] - 1 : 0; + const unsigned target = std::min(map.z[pt], level + distance); + map.z[pt] = static_cast(std::max(target, map.z[pt] > maxLowering ? map.z[pt] - maxLowering : 0u)); + + if(distance == 1 && map.objectTypes[pt] == libsiedler2::OT_Empty && rnd.byChance(deadTreeChance)) + { + placeDecoration(map, pt, rnd.byChance(50) ? OI_DeadTree : OI_DeadTreeTrunk); + } + } +} + +void smoothDesertTransitions(Map& map) +{ + auto& textures = map.textureMap; + const auto desert = textures.find(isCoastTerrain); + std::vector desertNodes; + for(const MapPoint& pt : map.barren) + { + if(textures.all(pt, isCoastTerrain)) + desertNodes.push_back(pt); + } + if(desertNodes.empty()) + return; + + // Land from dry to lush: each ring around the desert may be one step more lush than the previous one + auto ramp = textures.findAll(isBuildableLand); + textures.sort(ramp, [](const TerrainDesc& terrain) { return std::make_pair(terrain.humidity, terrain.s2Id); }); + const auto exceeds = [&textures, &ramp](const MapPoint& pt, unsigned limit) { + for(const Triangle& triangle : getTriangles(pt, textures.textures_.getSize())) + { + const auto it = std::find(ramp.begin(), ramp.end(), textures.get(triangle)); + if(it != ramp.end() && static_cast(it - ramp.begin()) > limit) + return true; + } + return false; + }; + const auto isWalkableLand = [](const TerrainDesc& terrain) { + return terrain.kind == TerrainKind::Land && terrain.is(ETerrain::Walkable); + }; + + const auto distances = distancesTo(desertNodes, map.size); + const unsigned rings = std::min(3, static_cast(ramp.size())); + + // Neighboring nodes share triangles: painting from the outside to the inside keeps one row for each transition + for(unsigned ring = rings; ring > 0; ring--) + { + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(distances[pt] == ring && !helpers::contains(map.barren, pt) && textures.all(pt, isWalkableLand) + && exceeds(pt, ring - 1)) + textures.set(pt, ramp[ring - 1]); + } + } + for(const MapPoint& pt : desertNodes) + textures.set(pt, desert); +} + +std::vector fillFreeLand(Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings, const LandFillAmounts& amounts) +{ + std::vector types; + LandFillAmounts assigned{}; + + // The type is required before the area is known as it has an impact on the size + const auto getSize = [&](unsigned index) { + const LandFill type = selectLandFill(rnd, amounts, assigned); + unsigned size = getMountainSize(settings, index); + if(type == LandFill::Swamp) + size = std::max(size / 2, std::min(size, settings.minSize)); + + types.push_back(type); + assigned[type] += size; + return size; + }; + + const auto areas = findMountains(map, rnd, mountainLevel, settings.minFreeLand, getSize); + + std::vector filledAreas; + for(unsigned i = 0; i < areas.size(); i++) + { + // Gaps would end up as pits within desert hills and as tiny islands within swamps + const Mountain area = types[i] == LandFill::Mountain ? areas[i] : closeGaps(map.size, areas[i]); + + switch(types[i]) + { + case LandFill::Mountain: raiseMountain(map, rnd, area); break; + case LandFill::Desert: raiseDesertHill(map, rnd, area); break; + case LandFill::Swamp: createSwamp(map, rnd, area); break; + } + filledAreas.push_back(FilledArea{types[i], area}); + } + + return filledAreas; +} + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/FreeLand.h b/libs/s25main/mapGenerator/FreeLand.h new file mode 100644 index 0000000000..e5df92f698 --- /dev/null +++ b/libs/s25main/mapGenerator/FreeLand.h @@ -0,0 +1,75 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "helpers/EnumArray.h" +#include "mapGenerator/Map.h" +#include "mapGenerator/Mountains.h" +#include "mapGenerator/RandomUtility.h" +#include + +namespace rttr::mapGenerator { + +/// Types of landscape used to fill up large areas of free land +enum class LandFill +{ + Mountain, + Desert, + Swamp +}; +constexpr auto maxEnumValue(LandFill) +{ + return LandFill::Swamp; +} + +/// Desired amount of each type of landscape. Only the proportions matter. +using LandFillAmounts = helpers::EnumArray; + +struct FilledArea +{ + LandFill type; + Mountain nodes; +}; + +/// Object type of decorative objects +constexpr uint8_t OT_Decoration = 0xC8; +/// Object indices of the decorative objects used for deserts and swamps +constexpr uint8_t OI_DeadTreeTrunk = 0x05; +constexpr uint8_t OI_DeadTree = 0x06; +constexpr uint8_t OI_Bone1 = 0x07; +constexpr uint8_t OI_Bone2 = 0x08; + +/// Returns the area extended by all nodes which are mostly surrounded by it. +Mountain closeGaps(const MapExtent& size, const Mountain& area); + +/** + * Selects the type of landscape for the next area from the types which are below their desired share. + * The first area is always a mountain (if desired at all) since mountains are required for mining. + * + * @param assigned number of nodes assigned to each type so far + */ +LandFill selectLandFill(RandomUtility& rnd, const LandFillAmounts& amounts, const LandFillAmounts& assigned); + +/// Turns the area into a desert hill with buildable transition textures at its foot and some bones around its center. +void raiseDesertHill(Map& map, RandomUtility& rnd, const Mountain& area); + +/// Turns the area into a flat swamp surrounded by gently descending land and some dead trees. +void createSwamp(Map& map, RandomUtility& rnd, const Mountain& area); + +/// Surrounds deserts by rings of increasingly lush land. Must be called once all textures are in place. +void smoothDesertTransitions(Map& map); + +/** + * Fills large areas of free land with mountains, desert hills and swamps. + * + * @param mountainLevel minimum z-value of mountains + * @param settings size of the new areas - swamps only get half the size as they are impassable + * + * @returns the type and the nodes of each new area. + */ +std::vector fillFreeLand(Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings, const LandFillAmounts& amounts); + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/Harbors.cpp b/libs/s25main/mapGenerator/Harbors.cpp index 439a27aa0b..a0a7e309e1 100644 --- a/libs/s25main/mapGenerator/Harbors.cpp +++ b/libs/s25main/mapGenerator/Harbors.cpp @@ -41,7 +41,10 @@ std::vector> findCoastlines(const Map& map, const std::vec std::set visited; const auto isCoast = [&map](const MapPoint& pt) { - const auto allWater = [&map](const MapPoint& p) { return map.textureMap.all(p, isWater); }; + // Swamps may consist of water textures but can't be used by ships + const auto allWater = [&map](const MapPoint& p) { + return map.textureMap.all(p, isWater) && !helpers::contains(map.barren, p); + }; return map.textureMap.any(pt, isLand) && map.textureMap.any(pt, isWater) && helpers::containsIf(map.getTextures().getNeighbours(pt), allWater); }; diff --git a/libs/s25main/mapGenerator/Map.h b/libs/s25main/mapGenerator/Map.h index bfe24a1c4f..6cb04f80c1 100644 --- a/libs/s25main/mapGenerator/Map.h +++ b/libs/s25main/mapGenerator/Map.h @@ -12,6 +12,7 @@ #include "libsiedler2/archives.h" #include +#include #include namespace rttr::mapGenerator { @@ -29,6 +30,10 @@ class Map NodeMapBase animals; std::vector harbors; std::vector hqPositions; + /// Nodes of deserts and swamps which get neither trees, stone piles, animals nor fish + std::set barren; + /// Nodes of special scenes which get neither trees nor stone piles + std::set reserved; TextureMap textureMap; const std::string name; diff --git a/libs/s25main/mapGenerator/MapSettings.h b/libs/s25main/mapGenerator/MapSettings.h index 1a5d6413e7..5993639b1c 100644 --- a/libs/s25main/mapGenerator/MapSettings.h +++ b/libs/s25main/mapGenerator/MapSettings.h @@ -48,9 +48,13 @@ struct MapSettings unsigned short ratioIron = 36; unsigned short ratioCoal = 40; unsigned short ratioGranite = 15; - unsigned short rivers = 15; + unsigned short rivers = 21; unsigned short trees = 40; + unsigned short mountains = 25; + unsigned short desert = 22; + unsigned short swamp = 18; unsigned short stonePiles = 5; + bool specialObjects = true; IslandAmount islands = IslandAmount::Few; MountainDistance mountainDistance = MountainDistance::Normal; DescIdx type = DescIdx(0); diff --git a/libs/s25main/mapGenerator/Mountains.cpp b/libs/s25main/mapGenerator/Mountains.cpp new file mode 100644 index 0000000000..9446d08cfb --- /dev/null +++ b/libs/s25main/mapGenerator/Mountains.cpp @@ -0,0 +1,169 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "mapGenerator/Mountains.h" +#include "helpers/containerUtils.h" +#include "mapGenerator/Algorithms.h" +#include "mapGenerator/TextureHelper.h" +#include +#include +#include +#include + +namespace rttr::mapGenerator { + +namespace { + /// Size of each mountain relative to the previous one + constexpr double sizeDecay = 0.9; + /// Radius of the brush collecting nodes around a node of a growing mountain + constexpr unsigned brushRadius = 2; + /// Chance of the brush to collect a node - values below 100 create irregular shapes + constexpr unsigned brushDensity = 75; + + /// Updates the distances after the specified nodes stopped being free land + void markAsOccupied(NodeMapBase& freeLand, const Mountain& mountain) + { + std::queue queue; + for(const MapPoint& pt : mountain) + { + freeLand[pt] = 0; + queue.push(pt); + } + + // UpdateDistances only fills unset values so it can't be used to lower existing distances + while(!queue.empty()) + { + const MapPoint current = queue.front(); + queue.pop(); + + const unsigned distance = freeLand[current] + 1; + for(const MapPoint& neighbor : freeLand.getNeighbours(current)) + { + if(distance < freeLand[neighbor]) + { + freeLand[neighbor] = distance; + queue.push(neighbor); + } + } + } + } +} // namespace + +unsigned getMountainSize(const MountainSettings& settings, unsigned index) +{ + const auto size = static_cast(settings.maxSize * std::pow(sizeDecay, index)); + return std::max(size, settings.minSize); +} + +NodeMapBase getFreeLandDistances(const Map& map, unsigned mountainLevel) +{ + const auto& textures = map.getTextures(); + return distancesTo(map.size, [&map, &textures, mountainLevel](const MapPoint& pt) { + return map.z[pt] == map.height.minimum || map.z[pt] >= mountainLevel || textures[pt].rsu || textures[pt].lsd; + }); +} + +Mountain growMountain(const NodeMapBase& freeLand, RandomUtility& rnd, const MapPoint& center, unsigned size, + unsigned margin) +{ + const auto priority = [&freeLand, ¢er](const MapPoint& pt) { + return static_cast(freeLand[pt]) - freeLand.calcDistance(center, pt); + }; + const auto compare = [&priority](const MapPoint& lhs, const MapPoint& rhs) { + return priority(lhs) < priority(rhs); + }; + + std::priority_queue, decltype(compare)> queue(compare); + Mountain mountain{center}; + queue.push(center); + + while(!queue.empty() && mountain.size() < size) + { + const MapPoint current = queue.top(); + queue.pop(); + + for(const MapPoint& pt : freeLand.getPointsInRadius(current, brushRadius)) + { + if(mountain.size() < size && freeLand[pt] > margin && rnd.byChance(brushDensity) + && mountain.insert(pt).second) + { + queue.push(pt); + } + } + } + + return mountain; +} + +std::vector findMountains(const Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings) +{ + return findMountains(map, rnd, mountainLevel, settings.minFreeLand, + [&settings](unsigned index) { return getMountainSize(settings, index); }); +} + +std::vector findMountains(const Map& map, RandomUtility& rnd, unsigned mountainLevel, unsigned minFreeLand, + const std::function& getSize) +{ + std::vector mountains; + auto freeLand = getFreeLandDistances(map, mountainLevel); + const auto maxDistance = [&freeLand] { return *std::max_element(freeLand.begin(), freeLand.end()); }; + + for(unsigned distance = maxDistance(); distance > minFreeLand; distance = maxDistance()) + { + const auto isFreest = [&freeLand, distance](const MapPoint& pt) { return freeLand[pt] == distance; }; + const MapPoint center = rnd.randomItem(selectPoints(isFreest, map.size)); + + // A larger margin than required varies the gaps. It must stay below the distance to include the center. + const unsigned maxMargin = std::min(minFreeLand + minFreeLand / 2, distance - 1); + const unsigned margin = rnd.randomValue(minFreeLand, maxMargin); + const unsigned size = getSize(static_cast(mountains.size())); + + mountains.push_back(growMountain(freeLand, rnd, center, size, margin)); + markAsOccupied(freeLand, mountains.back()); + } + + return mountains; +} + +NodeMapBase getFootDistances(const MapExtent& size, const Mountain& mountain) +{ + NodeMapBase neighbors; + neighbors.resize(size); + + const auto isFoot = [&neighbors, &mountain](const MapPoint& pt) { + return helpers::containsIf(neighbors.getNeighbours(pt), + [&mountain](const MapPoint& pt) { return !helpers::contains(mountain, pt); }); + }; + return distances(size, mountain, 0, isFoot); +} + +void raiseMountain(Map& map, RandomUtility& rnd, const Mountain& mountain) +{ + const auto footDistance = getFootDistances(map.size, mountain); + const ValueRange range(0u, getMaximum(footDistance, mountain)); + const auto textures = map.textureMap.findAll(isMinableMountain); + + for(const MapPoint& pt : mountain) + { + const unsigned elevation = rnd.randomValue(footDistance[pt], footDistance[pt] + 1u); + map.z[pt] = static_cast(std::min(map.z[pt] + elevation, map.height.maximum)); + map.textureMap.set(pt, textures[mapValueToIndex(footDistance[pt], range, textures.size())]); + } +} + +std::vector createMountains(Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings) +{ + auto mountains = findMountains(map, rnd, mountainLevel, settings); + + for(const Mountain& mountain : mountains) + { + raiseMountain(map, rnd, mountain); + } + + return mountains; +} + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/Mountains.h b/libs/s25main/mapGenerator/Mountains.h new file mode 100644 index 0000000000..ee814846a6 --- /dev/null +++ b/libs/s25main/mapGenerator/Mountains.h @@ -0,0 +1,66 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "mapGenerator/Map.h" +#include "mapGenerator/RandomUtility.h" +#include +#include +#include + +namespace rttr::mapGenerator { + +using Mountain = std::set; + +struct MountainSettings +{ + /// Land up to this distance to water or mountains stays free. Larger areas are filled up with mountains. + unsigned minFreeLand; + /// Number of nodes of the first mountain. Each following mountain is smaller than the previous one. + unsigned maxSize; + /// Lower limit for the number of nodes of a mountain (unless there isn't sufficient free land). + unsigned minSize; +}; + +/// Desired number of nodes of the mountain with the given index (0 = first). Decreases with the index down to minSize. +unsigned getMountainSize(const MountainSettings& settings, unsigned index); + +/// Distance of each node to the closest node which isn't free land, i.e. water, mountain or already textured. +NodeMapBase getFreeLandDistances(const Map& map, unsigned mountainLevel); + +/** + * Grows an irregular mountain around the center preferring nodes far away from obstacles. + * + * @param freeLand distances to the closest node which isn't free land + * @param size maximum number of nodes + * @param margin only nodes with a larger distance to obstacles become part of the mountain + */ +Mountain growMountain(const NodeMapBase& freeLand, RandomUtility& rnd, const MapPoint& center, unsigned size, + unsigned margin); + +/** + * Selects the nodes of new mountains until no node is further away from obstacles than settings.minFreeLand. + * Nodes close to obstacles are never selected so passages stay open. Does not modify the map. + * + * @returns the nodes of each mountain. all mountains are disjoint. + */ +std::vector findMountains(const Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings); + +/// Same as above but queries the size of each mountain (by its index) right before growing it. +std::vector findMountains(const Map& map, RandomUtility& rnd, unsigned mountainLevel, unsigned minFreeLand, + const std::function& getSize); + +/// Distance of each node of the mountain to its foot (its outermost nodes). Zero for nodes outside the mountain. +NodeMapBase getFootDistances(const MapExtent& size, const Mountain& mountain); + +/// Elevates the nodes of the mountain and applies mountain textures to them. +void raiseMountain(Map& map, RandomUtility& rnd, const Mountain& mountain); + +/// Fills large areas of free land with mountains and returns their nodes. +std::vector createMountains(Map& map, RandomUtility& rnd, unsigned mountainLevel, + const MountainSettings& settings); + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/RandomMap.cpp b/libs/s25main/mapGenerator/RandomMap.cpp index 6e12de91bb..4e6a1c6982 100644 --- a/libs/s25main/mapGenerator/RandomMap.cpp +++ b/libs/s25main/mapGenerator/RandomMap.cpp @@ -3,10 +3,13 @@ // SPDX-License-Identifier: GPL-2.0-or-later #include "mapGenerator/RandomMap.h" +#include "mapGenerator/FreeLand.h" #include "mapGenerator/Harbors.h" #include "mapGenerator/HeadQuarters.h" #include "mapGenerator/Islands.h" +#include "mapGenerator/Mountains.h" #include "mapGenerator/Resources.h" +#include "mapGenerator/SpecialObjects.h" #include "mapGenerator/Terrain.h" #include "mapGenerator/TextureHelper.h" #include "mapGenerator/Textures.h" @@ -14,6 +17,7 @@ #include "lua/GameDataLoader.h" #include "libsiedler2/libsiedler2.h" +#include #include namespace rttr::mapGenerator { @@ -78,6 +82,28 @@ unsigned getIslandSize(const MapExtent& size) return 1200; } +unsigned getMaxMountainSize(const MapExtent& size) +{ + const unsigned combinedSize = size.x * size.y; + if(combinedSize <= 64 * 64) + return 150; + else if(combinedSize <= 128 * 128) + return 300; + else if(combinedSize <= 256 * 256) + return 600; + else if(combinedSize <= 512 * 512) + return 1000; + else + return 1500; +} + +unsigned getMinFreeLand(unsigned mountainDistance, unsigned mountains) +{ + constexpr unsigned minFreeLand = 4; // Headquarters and the transition textures around mountains need space + const unsigned freeLandPercentage = 2 * (100 - std::min(mountains, 100u)); + return std::max(minFreeLand, mountainDistance * freeLandPercentage / 100); +} + unsigned getSmoothRadius(const MapExtent& size) { const unsigned combinedSize = size.x * size.y; @@ -139,6 +165,9 @@ void RandomMap::create(const MapSettings& settings) case MapStyle::Land: createLandMap(); break; } + if(settings_.specialObjects) + addSpecialScenes(map_, rnd_); + addObjects(map_, rnd_, settings_); addResources(map_, rnd_, settings_); addAnimals(map_, rnd_); @@ -179,6 +208,40 @@ void RandomMap::createFreeIslands(unsigned waterNodes) } } +void RandomMap::fillFreeLand(unsigned mountainLevel) +{ + const LandFillAmounts amounts{settings_.mountains, settings_.desert, settings_.swamp}; + const unsigned totalAmount = settings_.mountains + settings_.desert + settings_.swamp; + if(totalAmount == 0) + return; + + const auto freeLand = getMinFreeLand(static_cast(settings_.mountainDistance), totalAmount); + const auto minFreeLand = rnd_.randomValue(freeLand, freeLand + 5u); + const auto maxMountainSize = getMaxMountainSize(map_.size); + const auto maxSize = rnd_.randomValue(maxMountainSize / 2, maxMountainSize); + + rttr::mapGenerator::fillFreeLand(map_, rnd_, mountainLevel, + MountainSettings{minFreeLand, maxSize, maxMountainSize / 4}, amounts); +} + +void RandomMap::addTextures(unsigned mountainLevel) +{ + const NodeMapBase textures = map_.getTextures(); + + texturizer_.addTextures(mountainLevel, getCoastline(map_.size)); + + for(const MapPoint& pt : map_.barren) + { + for(const Triangle& triangle : getTriangles(pt, map_.size)) + { + const TexturePair& pair = textures[triangle.position]; + map_.textureMap.set(triangle, triangle.rsu ? pair.rsu : pair.lsd); + } + } + + smoothDesertTransitions(map_); +} + void RandomMap::createMixedMap() { const auto center = rnd_.Point(map_.size); @@ -203,7 +266,9 @@ void RandomMap::createMixedMap() createFreeIslands(waterNodes); - texturizer_.addTextures(mountainLevel, getCoastline(map_.size)); + fillFreeLand(mountainLevel); + + addTextures(mountainLevel); placeHarbors(map_, rivers); placeHeadquarters(map_, rnd_, map_.players, settings_.mountainDistance); @@ -247,7 +312,9 @@ void RandomMap::createWaterMap() const auto rivers = createRivers(center); - texturizer_.addTextures(mountainLevel, getCoastline(map_.size)); + fillFreeLand(mountainLevel); + + addTextures(mountainLevel); placeHarbors(map_, rivers); @@ -271,7 +338,9 @@ void RandomMap::createLandMap() const auto mountainLevel = limitFor(map_.z, land, static_cast(1)) + 1; createRivers(); - texturizer_.addTextures(mountainLevel, getCoastline(map_.size)); + fillFreeLand(mountainLevel); + + addTextures(mountainLevel); placeHeadquarters(map_, rnd_, map_.players, settings_.mountainDistance); } diff --git a/libs/s25main/mapGenerator/RandomMap.h b/libs/s25main/mapGenerator/RandomMap.h index c5b6e50625..5568c8dcd9 100644 --- a/libs/s25main/mapGenerator/RandomMap.h +++ b/libs/s25main/mapGenerator/RandomMap.h @@ -17,6 +17,16 @@ unsigned getMaximumHeight(const MapExtent& size); unsigned getCoastline(const MapExtent& size); unsigned getIslandRadius(const MapExtent& size); unsigned getIslandSize(const MapExtent& size); +unsigned getMaxMountainSize(const MapExtent& size); + +/** + * Computes the distance to water and mountains up to which land stays free. + * + * @param mountains desired amount of mountains, deserts and swamps in percent. 50 keeps the mountain distance while + * higher values reduce it down to the space required by headquarters. + */ +unsigned getMinFreeLand(unsigned mountainDistance, unsigned mountains); + unsigned getSmoothRadius(const MapExtent& size); unsigned getSmoothIterations(const MapExtent& size); @@ -32,6 +42,8 @@ class RandomMap std::vector createRivers(MapPoint source = MapPoint::invalid()); void createFreeIslands(unsigned waterNodes); + void fillFreeLand(unsigned mountainLevel); + void addTextures(unsigned mountainLevel); void createMixedMap(); void createLandMap(); void createWaterMap(); diff --git a/libs/s25main/mapGenerator/Resources.cpp b/libs/s25main/mapGenerator/Resources.cpp index 34cebd0778..bccb6ea7dd 100644 --- a/libs/s25main/mapGenerator/Resources.cpp +++ b/libs/s25main/mapGenerator/Resources.cpp @@ -66,12 +66,22 @@ void addObjects(Map& map, RandomUtility& rnd, const MapSettings& settings) { auto suroundingArea = map.getTextures().getPointsInRadiusWithCenter(pt, 5); excludedArea.insert(suroundingArea.begin(), suroundingArea.end()); + // Remove the decoration of deserts and swamps as well + for(const MapPoint& excluded : suroundingArea) + { + map.objectTypes[excluded] = libsiedler2::OT_Empty; + map.objectInfos[excluded] = libsiedler2::OI_Empty; + } } else if(map.textureMap.any(pt, isSnowOrLava)) { excludedArea.insert(pt); } } + // Deserts and swamps come with their own objects + excludedArea.insert(map.barren.begin(), map.barren.end()); + excludedArea.insert(map.reserved.begin(), map.reserved.end()); + const auto distanceToExcludedArea = distancesTo(excludedArea, map.size); // 1) compute maximum water distance until mountain area @@ -140,6 +150,10 @@ void addObjects(Map& map, RandomUtility& rnd, const MapSettings& settings) RTTR_FOREACH_PT(MapPoint, map.size) { + // Keep objects which are already part of the landscape + if(map.objectTypes[pt] != libsiedler2::OT_Empty) + continue; + const bool canPlaceStonePile = waterDistance[pt] > 0 && distanceToExcludedArea[pt] > 0; if(canPlaceStonePile && rnd.byChance(settings.stonePiles)) { @@ -233,7 +247,7 @@ void addResources(Map& map, RandomUtility& rnd, const MapSettings& settings) } } } - } else if(textures.all(pt, isWater)) + } else if(textures.all(pt, isWater) && !helpers::contains(map.barren, pt)) { resources[pt] = libsiedler2::R_Fish; } else @@ -251,7 +265,7 @@ void addAnimals(Map& map, RandomUtility& rnd) const auto& textures = map.textureMap; RTTR_FOREACH_PT(MapPoint, map.size) { - if(rnd.byChance(3)) + if(rnd.byChance(3) && !helpers::contains(map.barren, pt)) { if(textures.all(pt, isWater)) { diff --git a/libs/s25main/mapGenerator/SpecialObjects.cpp b/libs/s25main/mapGenerator/SpecialObjects.cpp new file mode 100644 index 0000000000..a0d02c70ed --- /dev/null +++ b/libs/s25main/mapGenerator/SpecialObjects.cpp @@ -0,0 +1,892 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "mapGenerator/SpecialObjects.h" +#include "helpers/EnumRange.h" +#include "helpers/containerUtils.h" +#include "helpers/mathFuncs.h" +#include "mapGenerator/Algorithms.h" +#include "mapGenerator/FreeLand.h" +#include "mapGenerator/Resources.h" +#include "mapGenerator/TextureHelper.h" +#include "gameTypes/Direction.h" +#include "libsiedler2/enumTypes.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rttr::mapGenerator { + +namespace { + /// Minimum distance of the center of a scene to headquarters and harbors. Objects close to them are removed. + constexpr unsigned minPlayerDistance = sceneRadius + 6; + /// Radius of the ground in the middle of a scene which is leveled before hills are added + constexpr unsigned levelRadius = 3; + constexpr double pi = 3.14159265358979323846; + /// Texture indices which are the same for all landscapes + constexpr uint8_t flowerTextureId = 0x0F; // meadow covered by flowers + constexpr uint8_t rockTextureId = 0x22; // flat rock + + using Objects = std::vector; + const Objects mushrooms{0x00, 0x01, 0x22}; + const Objects stones{0x02, 0x03, 0x04}; + const Objects pebbles{0x25, 0x26, 0x27}; + const Objects deadTrees{OI_DeadTreeTrunk, OI_DeadTree, 0x1F, 0x20}; + const Objects bones{OI_Bone1, OI_Bone2}; + const Objects flowers{0x09}; + const Objects bushes{0x0A, 0x10, 0x11, 0x12, 0x28, 0x29, 0x2A}; + const Objects shrubs{0x0E, 0x0F, 0x13, 0x14}; + const Objects standingStones{0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E}; + const Objects cacti{0x0C, 0x0D}; + /// Bushes and shrubs of all kinds for hedges and thickets + const Objects undergrowth{0x0A, 0x10, 0x11, 0x12, 0x28, 0x29, 0x2A, 0x0E, 0x0F, 0x13, 0x14}; + /// Mostly flowers mixed with small plants and mushrooms for colorful beds and drifts + const Objects plants{0x09, 0x09, 0x09, 0x09, 0x09, 0x2A, 0x29, 0x0E, 0x13, 0x14, 0x00, 0x01, 0x22}; + /// Landscape index of the winter world which has no cacti + constexpr uint8_t winterLandscapeId = 2; + + /// Ground of a patch - either blended into the surrounding land or painted on top of it + enum class Ground + { + None, + /// Driest land which looks like trampled ground + Dry, + /// Meadow covered by flowers + Lush, + /// Flat rock with a rim of mountain meadow + Rock + }; + + /// Textures painted on top of the land in ascending priority + enum class Overlay : uint8_t + { + None, + RockRim, + Rock, + Sand, + Water + }; + + /// Objects and ground making up the character of a type of scene + struct Theme + { + /// Special object in the center + Objects main; + /// Larger objects used for clusters and along paths + Objects props; + /// Small objects scattered on the ground + Objects litter; + /// Ground right around the special object + Ground core; + /// Ground of the wider surroundings + Ground surround; + bool hill; + bool flowers; + bool granite; + bool deadVegetation; + }; + + Objects join(Objects lhs, const Objects& rhs) + { + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; + } + + Theme makeTheme(SceneType type, bool isWinter) + { + // Dry ground gets cacti unless it's frozen + const Objects dryPlants = isWinter ? pebbles : join(pebbles, cacti); + + switch(type) + { + case SceneType::CastleRuin: + return {{OI_CastleRuin}, stones, pebbles, Ground::Rock, Ground::Lush, true, true, true, false}; + case SceneType::RuinGrove: + return {{OI_TowerRuin, OI_GuardhouseRuin}, + stones, + mushrooms, + Ground::Lush, + Ground::Lush, + true, + true, + false, + false}; + case SceneType::Graveyard: + return {{OI_Cross}, {OI_Cross}, join(bones, mushrooms), Ground::Dry, Ground::Dry, false, false, + false, true}; + case SceneType::Camp: + return {{OI_Tent}, dryPlants, dryPlants, Ground::Dry, Ground::None, false, true, false, false}; + case SceneType::StoneCircle: + return {{OI_Gate, OI_OpenGate}, + standingStones, + mushrooms, + Ground::Rock, + Ground::Lush, + true, + true, + false, + false}; + } + throw std::invalid_argument("invalid type of scene"); + } + + /// Area of irregular shape around a node + struct Blob + { + MapPoint center; + double radius; + /// Phases of the waves deforming the outline - a circle if amplitude is zero + double amplitude, phase1, phase2; + }; + + /// Helper which collects the ground, the hills and the objects of a scene + class SceneBuilder + { + Map& map_; + RandomUtility& rnd_; + const MapPoint center_; + const Theme theme_; + /// Two kinds of trees - the first one dominates + const Tree tree_, otherTree_; + /// Buildable land textures from dry to lush used for smooth transitions + std::vector> ramp_; + /// Nodes with a desired index into the ramp in the order they were requested + std::vector> ground_; + /// Requests for the ground around the special object which take precedence over all others + std::vector> coreGround_; + NodeMapBase overlay_; + /// Nodes which have to stay free from objects + std::set blocked_; + /// Nodes of the scene which may be changed: buildable land without objects. Only the middle of a scene is + /// known to be free. Water, mountains and other landscapes further out are left untouched and cut the scene. + std::set free_; + + static unsigned mod6(int dir) { return static_cast((dir % 6 + 6) % 6); } + + std::pair planar(const MapPoint& from, const MapPoint& to) const + { + const auto delta = [](int value, int size) { + if(value > size / 2) + return value - size; + return value < -size / 2 ? value + size : value; + }; + const int dx = delta(static_cast(to.x) - from.x, map_.size.x); + const int dy = delta(static_cast(to.y) - from.y, map_.size.y); + // Odd rows are shifted to the right by half a node + return {dx + 0.5 * ((to.y & 1) - (from.y & 1)), dy * 0.866}; + } + + /// Index into the ramp of the land texture of the node + int rampIndex(const MapPoint& pt) const + { + const auto it = std::find(ramp_.begin(), ramp_.end(), map_.getTextures()[pt].rsu); + return it != ramp_.end() ? static_cast(it - ramp_.begin()) : static_cast(ramp_.size() / 2); + } + + int target(Ground ground) const { return ground == Ground::Dry ? 0 : static_cast(ramp_.size()) - 1; } + + DescIdx overlayTexture(Overlay overlay) const + { + const auto isRock = [](const TerrainDesc& t) { + return t.is(ETerrain::Buildable) && t.s2Id == rockTextureId; + }; + switch(overlay) + { + case Overlay::RockRim: return map_.textureMap.find(isBuildableMountain); + case Overlay::Rock: return map_.textureMap.find(isRock); + case Overlay::Sand: return map_.textureMap.find(isCoastTerrain); + default: return map_.textureMap.find(isShipableWater); + } + } + + public: + SceneBuilder(Map& map, RandomUtility& rnd, const MapPoint& center, SceneType type) + : map_(map), rnd_(rnd), center_(center), + theme_(makeTheme(type, map.textureMap.getLandscapeId() == winterLandscapeId)), + tree_(rnd.randomItem(createTrees(map.textureMap))), + otherTree_(rnd.randomItem(createTrees(map.textureMap))) + { + const auto sceneArea = map.z.getPointsInRadiusWithCenter(center, sceneRadius); + for(const MapPoint& pt : sceneArea) + { + if(map.textureMap.all(pt, isBuildableLand) && map.objectTypes[pt] == libsiedler2::OT_Empty + && !helpers::contains(map.barren, pt)) + free_.insert(pt); + } + map.reserved.insert(sceneArea.begin(), sceneArea.end()); + overlay_.resize(map.size, Overlay::None); + + // Flowers are the most lush texture. The index makes the order independent from the sort algorithm. + ramp_ = map.textureMap.findAll(isBuildableLand); + map.textureMap.sort(ramp_, [](const TerrainDesc& terrain) { + return std::make_tuple(terrain.humidity, terrain.s2Id == flowerTextureId, terrain.s2Id); + }); + + // Level the middle of the scene and reduce the slopes towards the surrounding land + const int level = map.z[center]; + for(const MapPoint& pt : free_) + { + const int tolerance = std::max(0, static_cast(distance(pt)) - static_cast(levelRadius)); + map.z[pt] = + static_cast(helpers::clamp(map.z[pt], std::max(level - tolerance, minZ()), + std::min(level + tolerance, map.height.maximum))); + } + } + + const MapPoint& center() const { return center_; } + const Theme& getTheme() const { return theme_; } + RandomUtility& rnd() { return rnd_; } + int minZ() const { return map_.height.minimum + 1; } + unsigned distance(const MapPoint& pt) const { return map_.z.calcDistance(center_, pt); } + unsigned distance(const MapPoint& from, const MapPoint& to) const { return map_.z.calcDistance(from, to); } + bool isPond(const MapPoint& pt) const { return overlay_[pt] == Overlay::Water; } + bool isFree(const MapPoint& pt) const { return helpers::contains(free_, pt); } + + /// Moves from the node into the direction which is counted clockwise starting in the west + MapPoint step(MapPoint pt, int dir, unsigned steps = 1) const + { + for(unsigned i = 0; i < steps; i++) + pt = map_.z.getNeighbour(pt, Direction(mod6(dir))); + return pt; + } + + /// All nodes with exactly the specified distance to the center in circular order starting in the west + std::vector ring(unsigned radius) const + { + std::vector result; + MapPoint pt = step(center_, 0, radius); + for(int dir = 2; dir < 8; dir++) + { + for(unsigned i = 0; i < radius; i++) + { + result.push_back(pt); + pt = step(pt, dir); + } + } + return result; + } + + std::vector area(const MapPoint& pt, unsigned radius) const + { + auto result = map_.z.getPointsInRadiusWithCenter(pt, radius); + helpers::eraseIf(result, [this](const MapPoint& p) { return !isFree(p); }); + return result; + } + + double angle(const MapPoint& from, const MapPoint& to) const + { + const auto [x, y] = planar(from, to); + return std::atan2(y, x); + } + + double randomAngle() { return rnd_.randomDouble(-pi, pi); } + + Blob makeBlob(const MapPoint& center, double radius, bool irregular = true) + { + return Blob{center, radius, irregular ? 1. : 0., randomAngle(), randomAngle()}; + } + + /// Relative position within a blob: 0 at the center, 1 at the outline and above 1 outside + double eval(const Blob& blob, const MapPoint& pt) const + { + const double theta = angle(blob.center, pt); + const double deformation = + 0.22 * std::sin(2 * theta + blob.phase1) + 0.13 * std::sin(3 * theta + blob.phase2); + return distance(blob.center, pt) / (blob.radius * (1. + blob.amplitude * deformation)); + } + + std::vector nodes(const Blob& blob, double limit = 1.) const + { + auto result = area(blob.center, static_cast(blob.radius * 1.4) + 1); + helpers::eraseIf(result, [this, &blob, limit](const MapPoint& pt) { return eval(blob, pt) >= limit; }); + return result; + } + + /// Requests the ground for the blob. Later requests take precedence where grounds meet - except for the + /// ground around the special object which always wins. + void blend(const Blob& blob, Ground ground, bool isCore = false) + { + if(ground == Ground::None) + return; + if(ground == Ground::Rock) + { + // Rock never touches the land directly but is enclosed by a rim + // Only the ground of the special object itself reaches the middle of the scene + const auto isAllowed = [this, isCore](const MapPoint& pt) { return isCore || distance(pt) > 1; }; + for(const MapPoint& pt : nodes(blob, 0.75)) + { + if(!isAllowed(pt)) + continue; + setOverlay(pt, Overlay::Rock); + for(const MapPoint& neighbor : area(pt, 1)) + { + if(isAllowed(neighbor)) + setOverlay(neighbor, Overlay::RockRim); + } + } + return; + } + + // Only the inner part gets the ground - the transition to the surrounding land is added in the end + for(const MapPoint& pt : nodes(blob, 0.75)) + (isCore ? coreGround_ : ground_).emplace_back(pt, target(ground)); + } + + void setOverlay(const MapPoint& pt, Overlay overlay) + { + if(isFree(pt) && distance(pt) < sceneRadius - 1 && overlay > overlay_[pt]) + overlay_[pt] = overlay; + } + + /// Raises (or lowers) a smooth hill around the node + void bump(const MapPoint& top, int height, double radius) + { + for(const MapPoint& pt : area(top, static_cast(radius))) + { + const double position = distance(top, pt) / radius; + if(position >= 1.) + continue; + const int elevation = static_cast(std::lround(height * 0.5 * (1. + std::cos(pi * position)))); + map_.z[pt] = static_cast(std::clamp(map_.z[pt] + elevation, minZ(), map_.height.maximum)); + } + } + + void block(const MapPoint& pt) { blocked_.insert(pt); } + + bool canPlace(const MapPoint& pt) const + { + return isFree(pt) && map_.objectTypes[pt] == libsiedler2::OT_Empty && !helpers::contains(blocked_, pt) + && !isPond(pt); + } + + bool chance(unsigned percentage) { return percentage >= 100 || rnd_.byChance(percentage); } + + void place(const MapPoint& pt, const Objects& objects) + { + if(!canPlace(pt)) + return; + map_.objectTypes[pt] = OT_Decoration; + map_.objectInfos[pt] = rnd_.randomItem(objects); + } + + void placeTree(const MapPoint& pt) + { + if(!canPlace(pt)) + return; + const Tree& tree = rnd_.byChance(75) ? tree_ : otherTree_; + map_.objectTypes[pt] = tree.type; + map_.objectInfos[pt] = tree.index + rnd_.randomValue(0, 7); + } + + void placeGranite(const MapPoint& pt) + { + if(!canPlace(pt)) + return; + map_.objectTypes[pt] = rnd_.byChance(50) ? libsiedler2::OT_Stone1 : libsiedler2::OT_Stone2; + map_.objectInfos[pt] = static_cast(rnd_.randomValue(2, 6)); + } + + /// Trees mixed with some undergrowth or dead trees for gloomy themes + void placeVegetation(const MapPoint& pt) + { + if(theme_.deadVegetation) + place(pt, rnd_.byChance(80) ? deadTrees : mushrooms); + else if(rnd_.byChance(85)) + placeTree(pt); + else + place(pt, undergrowth); + } + + /// Trees of a single kind for rows or dead trees for gloomy themes + void placeRowTree(const MapPoint& pt) + { + if(theme_.deadVegetation) + place(pt, deadTrees); + else if(canPlace(pt)) + { + map_.objectTypes[pt] = tree_.type; + map_.objectInfos[pt] = tree_.index + rnd_.randomValue(0, 7); + } + } + + /// Large rocks or the props of the theme + void placeRock(const MapPoint& pt) + { + if(theme_.granite && rnd_.byChance(60)) + placeGranite(pt); + else + place(pt, theme_.granite ? stones : theme_.props); + } + + /// Flowers mixed with other small plants or the litter of the theme + void placeGroundCover(const MapPoint& pt) { place(pt, theme_.flowers ? plants : theme_.litter); } + + /// Calls the function by chance for the nodes of a sector around the center + template + void forSector(double direction, double halfWidth, unsigned minDistance, unsigned maxDistance, + unsigned percentage, T_Place&& action) + { + for(const MapPoint& pt : area(center_, maxDistance)) + { + if(distance(pt) < minDistance) + continue; + double difference = std::fabs(angle(center_, pt) - direction); + difference = std::min(difference, 2 * pi - difference); + if(difference <= halfWidth && chance(percentage)) + action(pt); + } + } + + /// Calls the function by chance for the nodes of a blob + template + void forBlob(const Blob& blob, double limit, unsigned percentage, T_Place&& action) + { + for(const MapPoint& pt : nodes(blob, limit)) + { + if(chance(percentage)) + action(pt); + } + } + + /// Places the special object and the objects which make the type of scene recognizable in any style + void placeCore(SceneType type) + { + map_.objectTypes[center_] = OT_Decoration; + map_.objectInfos[center_] = rnd_.randomItem(theme_.main); + block(center_); + const auto innerRing = ring(1); + const auto outerRing = ring(2); + + switch(type) + { + case SceneType::CastleRuin: + // The ruin covers some of its neighbors + for(const int dir : {0, 1, 2}) + block(step(center_, dir)); + break; + case SceneType::Graveyard: + // Three rows of graves + for(const unsigned index : {0u, 3u}) + place(innerRing[index], theme_.main); + for(const unsigned index : {2u, 3u, 4u, 8u, 9u, 10u}) + place(outerRing[index], theme_.main); + break; + case SceneType::Camp: place(innerRing[rnd_.index(innerRing.size())], {OI_PileOfWood}); break; + case SceneType::StoneCircle: + for(unsigned i = 0; i < outerRing.size(); i += 2) + place(outerRing[i], standingStones); + break; + default: break; + } + } + + /// Applies the collected ground to the map and makes sure the special object stands on even ground + void finish() + { + flattenForCastleBuilding(map_.z, center_); + + // Ponds are flat + const auto sceneArea = map_.z.getPointsInRadiusWithCenter(center_, sceneRadius); + int waterLevel = map_.height.maximum; + for(const MapPoint& pt : sceneArea) + { + if(isPond(pt)) + waterLevel = std::min(waterLevel, map_.z[pt]); + } + for(const MapPoint& pt : sceneArea) + { + if(isPond(pt)) + map_.z[pt] = static_cast(waterLevel); + } + + ground_.insert(ground_.end(), coreGround_.begin(), coreGround_.end()); + paintGround(sceneArea); + for(const Overlay overlay : {Overlay::RockRim, Overlay::Rock, Overlay::Sand, Overlay::Water}) + { + for(const MapPoint& pt : sceneArea) + { + if(overlay_[pt] == overlay) + map_.textureMap.set(pt, overlayTexture(overlay)); + } + } + } + + private: + /// Paints the requested grounds with transitions: neighboring nodes differ by at most one step of the ramp. + /// Sand counts as one step below the driest land. On conflicts the surrounding land, shores and later requests + /// win. + void paintGround(const std::vector& sceneArea) + { + struct Anchor + { + MapPoint pt; + int index; + bool isBorder = false; + }; + std::vector anchors; + // All kinds of meadow look alike next to dry land: the land around the scene only asks for the + // transitions up to the first of them. Otherwise shores close to the border would get none at all. + const int firstMeadow = std::min(2, static_cast(ramp_.size()) - 1); + const auto limit = [this, &anchors, firstMeadow](const MapPoint& pt, int index) { + int lower = -100; + int upper = 100; + for(const Anchor& anchor : anchors) + { + const int dist = static_cast(distance(anchor.pt, pt)); + lower = + std::max(lower, (anchor.isBorder ? std::min(anchor.index, firstMeadow) : anchor.index) - dist); + upper = std::min(upper, anchor.index + dist); + } + // Anchors may contradict each other if the land around the scene has no transitions itself + return lower > upper ? (lower + upper) / 2 : std::clamp(index, lower, upper); + }; + + std::set visited; + std::vector painted; + const auto addAnchor = [&](const MapPoint& pt, int index, bool paint) { + if(!visited.insert(pt).second) + return; + const Anchor anchor{pt, limit(pt, index)}; + if(paint && anchor.index != rampIndex(pt)) + painted.push_back(anchor); + anchors.push_back(anchor); + }; + + // The land right outside the scene is not painted + for(const MapPoint& pt : ring(sceneRadius + 1)) + { + visited.insert(pt); + anchors.push_back(Anchor{pt, rampIndex(pt), true}); + } + for(const MapPoint& pt : sceneArea) + { + if(overlay_[pt] == Overlay::Sand || overlay_[pt] == Overlay::Water) + addAnchor(pt, -1, false); + } + for(auto it = ground_.rbegin(); it != ground_.rend(); ++it) + { + if(isFree(it->first)) + addAnchor(it->first, it->second, true); + } + // All other nodes keep their texture unless a transition is required + for(const MapPoint& pt : sceneArea) + { + if(visited.count(pt) || !isFree(pt)) + continue; + const int index = limit(pt, rampIndex(pt)); + if(index != rampIndex(pt)) + painted.push_back(Anchor{pt, index}); + } + + // Neighboring nodes share triangles: the texture which differs most from the land is painted last. Thus + // patches keep their size and each transition gets a row of triangles. + const auto change = [this](const Anchor& anchor) { return std::abs(anchor.index - rampIndex(anchor.pt)); }; + std::stable_sort(painted.begin(), painted.end(), + [&change](const Anchor& lhs, const Anchor& rhs) { return change(lhs) < change(rhs); }); + for(const Anchor& anchor : painted) + { + const int index = std::clamp(anchor.index, 0, static_cast(ramp_.size()) - 1); + map_.textureMap.set(anchor.pt, ramp_[index]); + } + } + }; + + /// Irregular patch with a cluster of rocks, a clump of trees and a drift of flowers in different directions + void createOvergrown(SceneBuilder& scene) + { + const Theme& theme = scene.getTheme(); + const MapPoint center = scene.center(); + + scene.blend(scene.makeBlob(center, 5.2), theme.surround); + scene.blend(scene.makeBlob(center, theme.core == Ground::Rock ? 2.0 : 2.8), theme.core, true); + if(theme.hill) + scene.bump(center, 2, 5.); + + // A path leads through the gap between the rocks and the trees + const int pathDir = static_cast(scene.rnd().randomValue(0, 5)); + for(unsigned i = 1; i < sceneRadius; i++) + { + const MapPoint pt = scene.step(scene.step(center, pathDir, i), pathDir + 1, i / 3); + scene.block(pt); + if(theme.surround != Ground::Dry && i > 1) + scene.blend(scene.makeBlob(pt, 1.7, false), Ground::Dry); + } + + const double pathAngle = scene.angle(center, scene.step(center, pathDir, 3)); + const double rockAngle = pathAngle + scene.rnd().randomDouble(1.2, 1.9); + const double treeAngle = pathAngle - scene.rnd().randomDouble(1.2, 1.9); + const auto wrap = [](double angle) { return std::atan2(std::sin(angle), std::cos(angle)); }; + + scene.forSector(wrap(rockAngle), 0.65, 2, 5, 55, [&scene](const MapPoint& pt) { scene.placeRock(pt); }); + scene.forSector(wrap(treeAngle), 0.8, 3, sceneRadius, 70, + [&scene](const MapPoint& pt) { scene.placeVegetation(pt); }); + scene.forSector(wrap(pathAngle + pi), 0.9, 2, 5, 50, + [&scene](const MapPoint& pt) { scene.placeGroundCover(pt); }); + scene.forSector(0., pi, 2, 6, 7, [&scene](const MapPoint& pt) { scene.place(pt, undergrowth); }); + scene.forSector(0., pi, 1, 4, 10, [&scene, &theme](const MapPoint& pt) { scene.place(pt, theme.litter); }); + } + + /// Straight road between two rows of trees leading to a court which is enclosed by a hedge + void createAvenue(SceneBuilder& scene) + { + const Theme& theme = scene.getTheme(); + const MapPoint center = scene.center(); + const int dir = static_cast(scene.rnd().randomValue(0, 5)); + const Ground paving = theme.core == Ground::Lush ? Ground::Dry : theme.core; + + scene.blend(scene.makeBlob(center, 4.6), theme.surround); + scene.blend(scene.makeBlob(center, paving == Ground::Rock ? 2.9 : 3.1, false), paving, true); + scene.bump(center, theme.hill ? 2 : 1, 5.); + + std::vector road; + for(unsigned i = 1; i <= sceneRadius; i++) + { + road.push_back(scene.step(center, dir, i)); + scene.block(road.back()); + if(paving == Ground::Rock) + scene.setOverlay(road.back(), Overlay::RockRim); + else + scene.blend(scene.makeBlob(road.back(), 1.1, false), Ground::Dry); + } + const auto nearRoad = [&scene, &road](const MapPoint& pt) { + return helpers::containsIf(road, [&](const MapPoint& node) { return scene.distance(node, pt) <= 1; }); + }; + + // Trees on both sides of the road outside the court + for(unsigned i = 3; i < road.size(); i++) + { + scene.placeRowTree(scene.step(road[i], dir + 2)); + scene.placeRowTree(scene.step(road[i], dir + 4)); + } + + // Beds within the court and a hedge around it + for(const MapPoint& pt : scene.ring(2)) + { + if(!nearRoad(pt)) + scene.placeGroundCover(pt); + } + const auto hedge = scene.ring(3); + for(unsigned i = 0; i < hedge.size(); i++) + { + if(nearRoad(hedge[i])) + continue; + if(theme.deadVegetation) + { + if(i % 2 == 0) + scene.place(hedge[i], deadTrees); + } else + scene.place(hedge[i], undergrowth); + } + // Rocks or props mark the corners + const auto outerRing = scene.ring(4); + for(unsigned i = 0; i < outerRing.size(); i += 4) + { + if(!nearRoad(outerRing[i])) + scene.placeRock(outerRing[i]); + } + } + + /// Rocky hill behind the special object, a pond in front of it and flowers and trees on its sides + void createCrag(SceneBuilder& scene) + { + const Theme& theme = scene.getTheme(); + const MapPoint center = scene.center(); + const int dir = static_cast(scene.rnd().randomValue(0, 5)); + const int side = scene.rnd().byChance(50) ? 2 : 4; + const MapPoint crag = scene.step(center, dir, 3); + const MapPoint pond = scene.step(center, dir + 3, 3); + + scene.blend(scene.makeBlob(center, 3.2), theme.surround); + scene.blend(scene.makeBlob(center, theme.core == Ground::Rock ? 1.6 : 2.2), theme.core, true); + + const Blob cragBlob = scene.makeBlob(crag, 2.9); + scene.blend(cragBlob, Ground::Rock); + scene.bump(crag, 4, 4.4); + scene.forBlob(cragBlob, 0.95, 55, [&scene](const MapPoint& pt) { + if(scene.rnd().byChance(65)) + scene.placeGranite(pt); + else + scene.place(pt, stones); + }); + scene.forBlob(scene.makeBlob(scene.step(center, dir, 6), 2.2), 1., 60, + [&scene](const MapPoint& pt) { scene.placeVegetation(pt); }); + + // Pond with a sandy shore and reed at its far side. It stays close to the middle of the scene to leave space + // for the transition from sand to the surrounding land. + scene.bump(pond, -1, 3.); + std::vector water{pond, scene.step(pond, dir + 3)}; + for(const MapPoint& pt : scene.area(pond, 1)) + { + if(scene.distance(pt) >= 3 && scene.rnd().byChance(60) && !helpers::contains(water, pt)) + water.push_back(pt); + } + for(const MapPoint& pt : water) + { + scene.setOverlay(pt, Overlay::Water); + scene.block(pt); + } + for(const MapPoint& pt : water) + { + for(const MapPoint& neighbor : scene.area(pt, 1)) + { + if(scene.isPond(neighbor)) + continue; + scene.setOverlay(neighbor, Overlay::Sand); + if(scene.distance(neighbor) > scene.distance(pond) && scene.rnd().byChance(50)) + scene.place(neighbor, shrubs); + } + } + + const Blob drift = scene.makeBlob(scene.step(center, dir + side, 4), 2.5); + scene.blend(drift, Ground::Lush); + scene.forBlob(drift, 0.85, 55, [&scene, &theme](const MapPoint& pt) { + if(theme.flowers) + scene.place(pt, plants); + else + scene.place(pt, theme.props); + }); + scene.forBlob(scene.makeBlob(scene.step(center, dir - side, 5), 2.1), 1., 65, + [&scene](const MapPoint& pt) { scene.placeVegetation(pt); }); + scene.forSector(0., pi, 1, 3, 12, [&scene, &theme](const MapPoint& pt) { scene.place(pt, theme.litter); }); + } + + /// Curved trail lined by remains which leads to the special object + void createTrail(SceneBuilder& scene) + { + const Theme& theme = scene.getTheme(); + const MapPoint center = scene.center(); + const int dir = static_cast(scene.rnd().randomValue(0, 5)); + const int turn = scene.rnd().byChance(50) ? 1 : -1; + + scene.blend(scene.makeBlob(center, 3.4), theme.surround); + scene.blend(scene.makeBlob(center, theme.core == Ground::Rock ? 1.9 : 2.6), theme.core, true); + if(theme.hill) + scene.bump(center, 2, 4.5); + + MapPoint pt = center; + std::vector> trail; + for(const int bend : {0, 0, 1, 1, 1, 2, 2}) + { + pt = scene.step(pt, dir + turn * bend); + trail.emplace_back(pt, dir + turn * bend); + scene.block(pt); + } + for(const auto& node : trail) + scene.blend(scene.makeBlob(node.first, 1.7, false), Ground::Dry); + + // Remains alternate on both sides of the trail + for(unsigned i = 1; i < trail.size(); i++) + { + const int left = trail[i].second + 2; + const int right = trail[i].second + 4; + scene.place(scene.step(trail[i].first, i % 2 ? left : right), theme.props); + if(scene.rnd().byChance(45)) + scene.place(scene.step(trail[i].first, i % 2 ? right : left), theme.litter); + } + scene.placeRock(scene.step(trail.back().first, trail.back().second + 1)); + + // Clumps of trees behind the special object and inside of the bend + scene.forBlob(scene.makeBlob(scene.step(center, dir + 3, 4), 2.4), 1., 65, + [&scene](const MapPoint& p) { scene.placeVegetation(p); }); + scene.forBlob(scene.makeBlob(scene.step(trail[3].first, trail[3].second + turn * 2, 3), 1.9), 1., 60, + [&scene](const MapPoint& p) { scene.placeVegetation(p); }); + scene.forSector(0., pi, 1, 3, 30, [&scene](const MapPoint& p) { scene.placeGroundCover(p); }); + scene.forSector(0., pi, 2, 6, 8, [&scene](const MapPoint& p) { scene.place(p, undergrowth); }); + } +} // namespace + +bool isSpecialObject(uint8_t objectType, uint8_t objectInfo) +{ + if(objectType != OT_Decoration) + return false; + return objectInfo == OI_Gate || objectInfo == OI_OpenGate || objectInfo == OI_Tent + || objectInfo == OI_GuardhouseRuin || objectInfo == OI_TowerRuin || objectInfo == OI_CastleRuin + || objectInfo == OI_Cross; +} + +unsigned getNumSpecialScenes(const MapExtent& size) +{ + return helpers::clamp((size.x + size.y) / 96u, 1u, 6u); +} + +std::vector findSceneSites(const Map& map, RandomUtility& rnd, unsigned number) +{ + const auto isUnsuitable = [&map](const MapPoint& pt) { + return !map.textureMap.all(pt, isBuildableLand) || map.objectTypes[pt] != libsiedler2::OT_Empty + || helpers::contains(map.barren, pt) || helpers::contains(map.reserved, pt); + }; + const auto obstacleDistance = distancesTo(map.size, isUnsuitable); + + std::vector players = map.hqPositions; + for(const Triangle& harbor : map.harbors) + players.push_back(harbor.position); + const auto playerDistance = distancesTo(players, map.size); + + // Only the middle of a scene requires free land - one node more leaves a gap to the surroundings. Obstacles + // further out cut the scene which allows scenes on maps with little free land. + auto candidates = selectPoints( + [&](const MapPoint& pt) { + return obstacleDistance[pt] > sceneCoreRadius + 1 && playerDistance[pt] >= minPlayerDistance; + }, + map.size); + + const unsigned minSceneDistance = std::max(4 * sceneRadius, (map.size.x + map.size.y) / 16u); + std::vector sites; + + while(sites.size() < number && !candidates.empty()) + { + const MapPoint site = rnd.randomItem(candidates); + sites.push_back(site); + helpers::eraseIf(candidates, [&map, &site, minSceneDistance](const MapPoint& pt) { + return map.z.calcDistance(site, pt) < minSceneDistance; + }); + } + + return sites; +} + +void createScene(Map& map, RandomUtility& rnd, const MapPoint& center, SceneType type, SceneStyle style) +{ + SceneBuilder scene(map, rnd, center, type); + scene.placeCore(type); + + switch(style) + { + case SceneStyle::Overgrown: createOvergrown(scene); break; + case SceneStyle::Avenue: createAvenue(scene); break; + case SceneStyle::Crag: createCrag(scene); break; + case SceneStyle::Trail: createTrail(scene); break; + } + + scene.finish(); +} + +std::vector addSpecialScenes(Map& map, RandomUtility& rnd) +{ + // Each type is used once before any type is repeated + std::vector types; + for(const SceneType type : helpers::EnumRange()) + types.push_back(type); + for(size_t i = types.size(); i > 1; i--) + std::swap(types[i - 1], types[rnd.index(i)]); + + std::vector scenes; + for(const MapPoint& site : findSceneSites(map, rnd, getNumSpecialScenes(map.size))) + { + const SceneType type = types[scenes.size() % types.size()]; + const auto style = + static_cast(rnd.randomValue(0u, static_cast(maxEnumValue(SceneStyle{})))); + createScene(map, rnd, site, type, style); + scenes.push_back(Scene{type, style, site}); + } + + return scenes; +} + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/SpecialObjects.h b/libs/s25main/mapGenerator/SpecialObjects.h new file mode 100644 index 0000000000..a7ba919827 --- /dev/null +++ b/libs/s25main/mapGenerator/SpecialObjects.h @@ -0,0 +1,96 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#pragma once + +#include "mapGenerator/Map.h" +#include "mapGenerator/RandomUtility.h" +#include + +namespace rttr::mapGenerator { + +/// Themes of sceneries built around a special object +enum class SceneType +{ + /// Castle ruin on rocky ground between flowers and rocks + CastleRuin, + /// Ruin of a tower or guardhouse between flowers and trees + RuinGrove, + /// Rows of crosses on barren ground between dead trees and bones + Graveyard, + /// Single tent with a pile of wood on trampled ground + Camp, + /// Gate within a circle of standing stones + StoneCircle +}; +constexpr auto maxEnumValue(SceneType) +{ + return SceneType::StoneCircle; +} + +/// Layouts arranging the surroundings of a special object +enum class SceneStyle +{ + /// Irregular patch with a cluster of rocks, a clump of trees and a drift of flowers in different directions + Overgrown, + /// Straight road between two rows of trees leading to a court which is enclosed by a hedge + Avenue, + /// Rocky hill behind the special object, a pond in front of it and flowers and trees on its sides + Crag, + /// Curved trail lined by remains which leads to the special object + Trail +}; +constexpr auto maxEnumValue(SceneStyle) +{ + return SceneStyle::Trail; +} + +struct Scene +{ + SceneType type; + SceneStyle style; + MapPoint center; +}; + +/// Radius around the center of a scene which is covered by the scene +constexpr unsigned sceneRadius = 7; +/// Radius around the center of a scene which has to be buildable land without any objects +constexpr unsigned sceneCoreRadius = 4; + +/// Indices of special objects (object type OT_Decoration) +constexpr uint8_t OI_Gate = 0x16; +constexpr uint8_t OI_OpenGate = 0x17; +constexpr uint8_t OI_Tent = 0x2C; +constexpr uint8_t OI_GuardhouseRuin = 0x2D; +constexpr uint8_t OI_TowerRuin = 0x2E; +constexpr uint8_t OI_CastleRuin = 0x2F; +constexpr uint8_t OI_Cross = 0x30; +constexpr uint8_t OI_PileOfWood = 0x32; + +/// Checks whether the object is the centerpiece of a scene +bool isSpecialObject(uint8_t objectType, uint8_t objectInfo); + +/// Desired number of scenes for the map size. Only a few are placed to keep them special. +unsigned getNumSpecialScenes(const MapExtent& size); + +/** + * Searches for up to `number` centers of scenes. The middle of a scene needs buildable land without objects and keeps + * a distance to headquarters, harbors and other scenes. Does not modify the map. + */ +std::vector findSceneSites(const Map& map, RandomUtility& rnd, unsigned number); + +/** + * Creates a scene around the center: the type defines the objects and the ground, the style their arrangement. + * Only buildable land without objects is changed. The nodes of the scene are reserved to keep them free from trees and + * stone piles. + */ +void createScene(Map& map, RandomUtility& rnd, const MapPoint& center, SceneType type, SceneStyle style); + +/** + * Places a few scenes of mixed types and random styles on the map. + * Must be called once textures, headquarters and harbors are in place but before any other objects are added. + */ +std::vector addSpecialScenes(Map& map, RandomUtility& rnd); + +} // namespace rttr::mapGenerator diff --git a/libs/s25main/mapGenerator/TextureHelper.cpp b/libs/s25main/mapGenerator/TextureHelper.cpp index 1678f1efe7..6060958a06 100644 --- a/libs/s25main/mapGenerator/TextureHelper.cpp +++ b/libs/s25main/mapGenerator/TextureHelper.cpp @@ -21,6 +21,11 @@ bool isSwamp(const TerrainDesc& terrain) return !terrain.is(ETerrain::Walkable) && terrain.humidity > 0; } +bool isImpassable(const TerrainDesc& terrain) +{ + return terrain.flags == ETerrain::Unwalkable; +} + bool isLand(const TerrainDesc& terrain) { return terrain.kind == TerrainKind::Land; diff --git a/libs/s25main/mapGenerator/TextureHelper.h b/libs/s25main/mapGenerator/TextureHelper.h index bc0581a8b8..5cdbfc9fbd 100644 --- a/libs/s25main/mapGenerator/TextureHelper.h +++ b/libs/s25main/mapGenerator/TextureHelper.h @@ -14,6 +14,9 @@ bool isWater(const TerrainDesc& terrain); bool isSwamp(const TerrainDesc& terrain); +/// Terrain which can neither be entered by settlers nor by ships, e.g. swamp +bool isImpassable(const TerrainDesc& terrain); + bool isLand(const TerrainDesc& terrain); bool isShipableWater(const TerrainDesc& terrain); diff --git a/tests/s25Main/UI/testIngameWindow.cpp b/tests/s25Main/UI/testIngameWindow.cpp index 48229a7dbe..fe3c6707cf 100644 --- a/tests/s25Main/UI/testIngameWindow.cpp +++ b/tests/s25Main/UI/testIngameWindow.cpp @@ -9,6 +9,7 @@ #include "Settings.h" #include "WindowManager.h" #include "controls/ctrlButton.h" +#include "controls/ctrlCheck.h" #include "controls/ctrlComboBox.h" #include "controls/ctrlEdit.h" #include "controls/ctrlOptionGroup.h" @@ -81,7 +82,11 @@ BOOST_AUTO_TEST_CASE(IwMapGenerator) const auto expectedGraniteRatio = rttr::test::randomValue(0u, 100u); const auto expectedRivers = rttr::test::randomValue(0u, 100u); const auto expectedTrees = rttr::test::randomValue(0u, 100u); + const auto expectedMountains = rttr::test::randomValue(0u, 100u); + const auto expectedDesert = rttr::test::randomValue(0u, 100u); + const auto expectedSwamp = rttr::test::randomValue(0u, 100u); const auto expectedStonePiles = rttr::test::randomValue(0u, 100u); + const bool expectedSpecialObjects = rttr::test::randomValue(0u, 1u) == 1u; rttr::mapGenerator::MapSettings settings; iwMapGenerator wnd(settings); @@ -116,8 +121,16 @@ BOOST_AUTO_TEST_CASE(IwMapGenerator) wnd.getCtrl(iwMapGenerator::ID_pgRivers)->setPosition(expectedRivers); BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_pgTrees)->getPosition() == settings.trees); wnd.getCtrl(iwMapGenerator::ID_pgTrees)->setPosition(expectedTrees); + BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_pgMountains)->getPosition() == settings.mountains); + wnd.getCtrl(iwMapGenerator::ID_pgMountains)->setPosition(expectedMountains); + BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_pgDesert)->getPosition() == settings.desert); + wnd.getCtrl(iwMapGenerator::ID_pgDesert)->setPosition(expectedDesert); + BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_pgSwamp)->getPosition() == settings.swamp); + wnd.getCtrl(iwMapGenerator::ID_pgSwamp)->setPosition(expectedSwamp); BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_pgStonePiles)->getPosition() == settings.stonePiles); wnd.getCtrl(iwMapGenerator::ID_pgStonePiles)->setPosition(expectedStonePiles); + BOOST_TEST(wnd.getCtrl(iwMapGenerator::ID_cbSpecialObjects)->isChecked() == settings.specialObjects); + wnd.getCtrl(iwMapGenerator::ID_cbSpecialObjects)->setChecked(expectedSpecialObjects); wnd.msgButtonClick(iwMapGenerator::ID_btApply); BOOST_TEST(wnd.shouldBeClosed()); @@ -133,7 +146,11 @@ BOOST_AUTO_TEST_CASE(IwMapGenerator) BOOST_TEST(settings.ratioGranite == expectedGraniteRatio); BOOST_TEST(settings.rivers == expectedRivers); BOOST_TEST(settings.trees == expectedTrees); + BOOST_TEST(settings.mountains == expectedMountains); + BOOST_TEST(settings.desert == expectedDesert); + BOOST_TEST(settings.swamp == expectedSwamp); BOOST_TEST(settings.stonePiles == expectedStonePiles); + BOOST_TEST(settings.specialObjects == expectedSpecialObjects); } BOOST_AUTO_TEST_CASE(ConnectWindow) diff --git a/tests/s25Main/mapGenerator/testFreeLand.cpp b/tests/s25Main/mapGenerator/testFreeLand.cpp new file mode 100644 index 0000000000..aec87d940b --- /dev/null +++ b/tests/s25Main/mapGenerator/testFreeLand.cpp @@ -0,0 +1,717 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "PointOutput.h" +#include "helpers/EnumRange.h" +#include "mapGenFixtures.h" +#include "mapGenerator/Algorithms.h" +#include "mapGenerator/FreeLand.h" +#include "mapGenerator/Resources.h" +#include "mapGenerator/TextureHelper.h" +#include "libsiedler2/enumTypes.h" +#include +#include +#include + +using namespace rttr::mapGenerator; + +namespace { +constexpr uint8_t landHeight = 10; +constexpr unsigned mountainLevel = 30; +constexpr MountainSettings settings{3, 100, 25}; +constexpr unsigned numLandscapes = 3; + +struct FreeLandFixture : MapGenFixture +{ + /// Creates a map covered by land except for a single row of water + Map createLandMap(const MapExtent size) const + { + Map map = createMap(size); + map.z.resize(size, landHeight); + RTTR_FOREACH_PT(MapPoint, size) + { + if(pt.y == 0) + map.z[pt] = map.height.minimum; + } + return map; + } + + /// Creates a map with a slope from the west to the center of the map + Map createSlopedMap(const MapExtent size) const + { + Map map = createMap(size); + map.z.resize(size, landHeight); + RTTR_FOREACH_PT(MapPoint, size) + { + map.z[pt] = static_cast(landHeight + std::min(pt.x, size.x - pt.x)); + } + return map; + } + + static Mountain createArea(const Map& map, const MapPoint& center, unsigned radius) + { + const auto points = map.z.getPointsInRadiusWithCenter(center, radius); + return Mountain(points.begin(), points.end()); + } +}; + +template +unsigned countObjects(const Map& map, T_Predicate&& predicate) +{ + unsigned count = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] != libsiedler2::OT_Empty && predicate(pt)) + count++; + } + return count; +} +} // namespace + +BOOST_FIXTURE_TEST_SUITE(FreeLandTests, FreeLandFixture) + +BOOST_AUTO_TEST_CASE(selectLandFill_returns_mountain_without_any_amounts) +{ + RandomUtility rnd(0); + + BOOST_TEST((selectLandFill(rnd, {0, 0, 0}, {0, 0, 0}) == LandFill::Mountain)); +} + +BOOST_AUTO_TEST_CASE(selectLandFill_starts_with_mountain_if_desired) +{ + for(unsigned seed = 0; seed < 20; seed++) + { + RandomUtility rnd(seed); + BOOST_TEST_REQUIRE((selectLandFill(rnd, {1, 100, 100}, {0, 0, 0}) == LandFill::Mountain)); + } +} + +BOOST_AUTO_TEST_CASE(selectLandFill_returns_only_desired_types) +{ + RandomUtility rnd(0); + LandFillAmounts assigned{}; + + for(unsigned i = 0; i < 50; i++) + { + const LandFill type = selectLandFill(rnd, {0, 30, 0}, assigned); + BOOST_TEST_REQUIRE((type == LandFill::Desert)); + assigned[type] += 10; + } +} + +BOOST_AUTO_TEST_CASE(selectLandFill_keeps_proportions_of_amounts) +{ + const LandFillAmounts amounts{50, 30, 20}; + + for(unsigned seed = 0; seed < 10; seed++) + { + RandomUtility rnd(seed); + LandFillAmounts assigned{}; + + // Even a low number of areas of decreasing size has to match the proportions roughly + unsigned total = 0; + for(unsigned size = 100; size > 40; size -= 5) + { + assigned[selectLandFill(rnd, amounts, assigned)] += size; + total += size; + } + + for(const LandFill type : helpers::EnumRange()) + { + const int share = static_cast(assigned[type] * 100 / total); + BOOST_TEST_REQUIRE(std::abs(share - static_cast(amounts[type])) <= 15, + "Type " << rttr::enumCast(type) << ": " << share); + } + } +} + +BOOST_AUTO_TEST_CASE(selectLandFill_varies_with_seed) +{ + const LandFillAmounts amounts{0, 50, 50}; + unsigned deserts = 0; + + for(unsigned seed = 0; seed < 50; seed++) + { + RandomUtility rnd(seed); + if(selectLandFill(rnd, amounts, {0, 0, 0}) == LandFill::Desert) + deserts++; + } + + BOOST_TEST(deserts > 0u); + BOOST_TEST(deserts < 50u); +} + +BOOST_AUTO_TEST_CASE(Swamp_and_desert_textures_exist_for_all_landscapes) +{ + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + const Map map = createMap(MapExtent(8, 8)); + + const auto swamp = map.textureMap.find(isImpassable); + const auto desert = map.textureMap.find(isCoastTerrain); + + // The swamp and its equivalents share the same index in all landscapes + BOOST_TEST(map.textureMap.getTextureId(swamp) == 3u); + BOOST_TEST(!worldDesc.get(swamp).is(ETerrain::Walkable)); + BOOST_TEST(!worldDesc.get(swamp).is(ETerrain::Shippable)); + BOOST_TEST(worldDesc.get(desert).is(ETerrain::Walkable)); + BOOST_TEST(!worldDesc.get(desert).is(ETerrain::Buildable)); + BOOST_TEST(map.textureMap.findAll(isBuildableCoast).size() >= 2u); + } +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_is_lower_than_mountain_and_keeps_surroundings) +{ + Map hill = createLandMap(MapExtent(48, 48)); + Map mountain = createLandMap(MapExtent(48, 48)); + const MapPoint center(24, 24); + const Mountain area = createArea(hill, center, 10); + RandomUtility rnd(0); + + raiseDesertHill(hill, rnd, area); + raiseMountain(mountain, rnd, area); + + BOOST_TEST(hill.z[center] > landHeight); + BOOST_TEST(hill.z[center] < mountain.z[center]); + RTTR_FOREACH_PT(MapPoint, hill.size) + { + if(!helpers::contains(area, pt)) + BOOST_TEST_REQUIRE(hill.z[pt] == (pt.y == 0 ? hill.height.minimum : landHeight), "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_rises_smoothly) +{ + Map map = createLandMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(24, 24), 10); + RandomUtility rnd(0); + + raiseDesertHill(map, rnd, area); + + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(pt.y <= 1 || pt.y + 1 >= map.size.y) // skip the water + continue; + for(const MapPoint& neighbor : map.z.getNeighbours(pt)) + { + const int difference = static_cast(map.z[pt]) - static_cast(map.z[neighbor]); + BOOST_TEST_REQUIRE(std::abs(difference) <= 1, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_applies_transitions_from_buildable_land_to_desert) +{ + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + Map map = createLandMap(MapExtent(48, 48)); + const MapPoint center(24, 24); + const Mountain area = createArea(map, center, 8); + const auto footDistance = getFootDistances(map.size, area); + RandomUtility rnd(0); + + raiseDesertHill(map, rnd, area); + + auto transitions = map.textureMap.findAll(isBuildableCoast); + map.textureMap.sort(transitions, byHumidity); + const auto count = [&map](DescIdx texture) { + return helpers::countIf(map.getTextures(), [texture](const TexturePair& pair) { + return pair.rsu == texture || pair.lsd == texture; + }); + }; + + for(const MapPoint& pt : area) + { + if(footDistance[pt] < 2) + { + BOOST_TEST_REQUIRE(map.textureMap.any(pt, isBuildableLand), "At point " << pt); + BOOST_TEST_REQUIRE(!helpers::contains(map.barren, pt), "At point " << pt); + } else + { + BOOST_TEST_REQUIRE(map.textureMap.all(pt, isCoastTerrain), "At point " << pt); + BOOST_TEST_REQUIRE(helpers::contains(map.barren, pt), "At point " << pt); + } + } + // The two driest buildable textures surround the desert + BOOST_TEST(count(transitions[0]) > 0); + BOOST_TEST(count(transitions[1]) > 0); + BOOST_TEST(count(transitions[2]) == 0); + BOOST_TEST(map.textureMap.all(center, isCoastTerrain)); + } +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_places_bones_around_center_only) +{ + for(unsigned seed = 0; seed < 10; seed++) + { + Map map = createLandMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(24, 24), 9); + const auto footDistance = getFootDistances(map.size, area); + const unsigned maxDistance = getMaximum(footDistance, area); + RandomUtility rnd(seed); + + raiseDesertHill(map, rnd, area); + + BOOST_TEST_REQUIRE(countObjects(map, [](const MapPoint&) { return true; }) > 0u); + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] == libsiedler2::OT_Empty) + continue; + BOOST_TEST_REQUIRE(map.objectTypes[pt] == OT_Decoration, "At point " << pt); + BOOST_TEST_REQUIRE((map.objectInfos[pt] == OI_Bone1 || map.objectInfos[pt] == OI_Bone2), "At point " << pt); + BOOST_TEST_REQUIRE(helpers::contains(area, pt), "At point " << pt); + BOOST_TEST_REQUIRE(footDistance[pt] * 3 >= maxDistance * 2, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_supports_tiny_areas) +{ + Map map = createLandMap(MapExtent(16, 16)); + const MapPoint center(8, 8); + RandomUtility rnd(0); + + raiseDesertHill(map, rnd, Mountain{center}); + raiseDesertHill(map, rnd, Mountain{}); + + BOOST_TEST(map.textureMap.all(center, isCoastTerrain)); + BOOST_TEST(map.objectTypes[center] == OT_Decoration); +} + +BOOST_AUTO_TEST_CASE(raiseDesertHill_does_not_exceed_maximum_height) +{ + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, map.height.maximum - 1); + RandomUtility rnd(0); + + raiseDesertHill(map, rnd, createArea(map, MapPoint(16, 16), 8)); + + RTTR_FOREACH_PT(MapPoint, map.size) + { + BOOST_TEST_REQUIRE(map.z[pt] <= map.height.maximum, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(createSwamp_is_entirely_flat_and_impassable) +{ + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + Map map = createSlopedMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(18, 24), 6); + const uint8_t lowest = map.z[MapPoint(12, 24)]; + RandomUtility rnd(0); + + createSwamp(map, rnd, area); + + for(const MapPoint& pt : area) + { + BOOST_TEST_REQUIRE(map.z[pt] == lowest, "At point " << pt); + BOOST_TEST_REQUIRE(map.textureMap.all(pt, isImpassable), "At point " << pt); + BOOST_TEST_REQUIRE(helpers::contains(map.barren, pt), "At point " << pt); + } + BOOST_TEST(map.barren.size() == area.size()); + } +} + +BOOST_AUTO_TEST_CASE(createSwamp_lowers_shore_towards_swamp) +{ + Map map = createSlopedMap(MapExtent(48, 48)); + const Map original = createSlopedMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(18, 24), 6); + const uint8_t level = original.z[MapPoint(12, 24)]; + const auto distances = distancesTo(area, map.size); + RandomUtility rnd(0); + + createSwamp(map, rnd, area); + + unsigned lowered = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(distances[pt] == 0) + continue; + // The land never rises by more than one level per node - no matter how far away from the swamp + BOOST_TEST_REQUIRE(map.z[pt] == std::min(original.z[pt], level + distances[pt]), "At point " << pt); + if(map.z[pt] < original.z[pt]) + lowered++; + } + BOOST_TEST(lowered > 0u); +} + +BOOST_AUTO_TEST_CASE(createSwamp_avoids_steep_slopes_on_steep_land) +{ + Map map = createMap(MapExtent(48, 48)); + map.z.resize(map.size, landHeight); + RTTR_FOREACH_PT(MapPoint, map.size) + { + // Ridge in the middle of the map which is three times as steep as the shore of a swamp + map.z[pt] = static_cast(landHeight + 3 * std::min(pt.x, map.size.x - pt.x)); + } + const Mountain area = createArea(map, MapPoint(16, 24), 5); + RandomUtility rnd(0); + + createSwamp(map, rnd, area); + + for(const MapPoint& pt : map.z.getPointsInRadiusWithCenter(MapPoint(16, 24), 10)) + { + // The land above the swamp is lowered while the land below keeps its slope + if(pt.x < 16) + continue; + for(const MapPoint& neighbor : map.z.getNeighbours(pt)) + { + if(neighbor.x <= pt.x) // look uphill only + continue; + const int difference = static_cast(map.z[neighbor]) - static_cast(map.z[pt]); + BOOST_TEST_REQUIRE(difference <= 1, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(createSwamp_never_lowers_banks_below_rivers) +{ + // Rivers follow the height of the land instead of the sea level + Map map = createSlopedMap(MapExtent(48, 48)); + const auto water = map.textureMap.find(isWater); + std::vector river; + for(unsigned y = 0; y < map.size.y; y++) + { + river.push_back(MapPoint(27, y)); + map.textureMap.set(river.back(), water); + } + const Map original = map; + const auto riverDistances = distancesTo(river, map.size); + RandomUtility rnd(0); + + // The river passes the upper side of the swamp at a distance of three nodes + const Mountain area = createArea(map, MapPoint(18, 24), 6); + createSwamp(map, rnd, area); + + unsigned lowered = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(helpers::contains(area, pt)) + continue; + if(riverDistances[pt] <= 1) + BOOST_TEST_REQUIRE(map.z[pt] == original.z[pt], "At point " << pt); + else + { + // The land is lowered by one more level with each node further away from the river + BOOST_TEST_REQUIRE(original.z[pt] - map.z[pt] < static_cast(riverDistances[pt]), "At point " << pt); + if(map.z[pt] < original.z[pt]) + lowered++; + } + } + BOOST_TEST(lowered > 0u); +} + +BOOST_AUTO_TEST_CASE(createSwamp_keeps_shape_of_other_landscapes) +{ + Map map = createSlopedMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(18, 24), 6); + const MapPoint mountain(26, 24); + const uint8_t height = map.z[mountain]; + map.textureMap.set(mountain, map.textureMap.find(isMinableMountain)); + RandomUtility rnd(0); + + createSwamp(map, rnd, area); + + BOOST_TEST(map.z[mountain] == height); +} + +BOOST_AUTO_TEST_CASE(smoothDesertTransitions_separates_desert_from_lush_land) +{ + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + Map map = createLandMap(MapExtent(48, 48)); + auto ramp = map.textureMap.findAll(isBuildableLand); + map.textureMap.sort(ramp, byHumidity); + const auto lush = ramp.back(); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, lush); + } + const MapPoint center(24, 24); + const Mountain area = createArea(map, center, 6); + RandomUtility rnd(0); + raiseDesertHill(map, rnd, area); + // Texturing coasts may replace the transitions of the hill + for(const MapPoint& pt : area) + { + if(!helpers::contains(map.barren, pt)) + map.textureMap.set(pt, lush); + } + for(const MapPoint& pt : map.barren) + map.textureMap.set(pt, map.textureMap.find(isCoastTerrain)); + + smoothDesertTransitions(map); + + const auto humidityOf = [this, &map](const Triangle& triangle) { + return worldDesc.get(map.textureMap.get(triangle)).humidity; + }; + RTTR_FOREACH_PT(MapPoint, map.size) + { + uint8_t driest = 100; + uint8_t wettest = 0; + for(const Triangle& triangle : getTriangles(pt, map.size)) + { + driest = std::min(driest, humidityOf(triangle)); + wettest = std::max(wettest, humidityOf(triangle)); + } + // Desert (0) meets steppe (30) only, steppe meets savannah (60) and savannah meets meadow (95) + BOOST_TEST_REQUIRE((driest > 0 || wettest <= 30), "At point " << pt); + BOOST_TEST_REQUIRE((driest > 30 || wettest <= 60), "At point " << pt); + BOOST_TEST_REQUIRE((driest > 60 || wettest <= 95), "At point " << pt); + } + BOOST_TEST(map.textureMap.all(center, isCoastTerrain)); + for(const MapPoint& pt : map.barren) + BOOST_TEST_REQUIRE(map.textureMap.all(pt, isCoastTerrain), "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(smoothDesertTransitions_keeps_maps_without_deserts) +{ + Map map = createLandMap(MapExtent(32, 32)); + const auto land = map.textureMap.find(isBuildableLand); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, land); + } + RandomUtility rnd(0); + createSwamp(map, rnd, createArea(map, MapPoint(16, 16), 4)); + const auto before = map.getTextures(); + + smoothDesertTransitions(map); + + RTTR_FOREACH_PT(MapPoint, map.size) + { + BOOST_TEST_REQUIRE((map.getTextures()[pt].rsu == before[pt].rsu), "At point " << pt); + BOOST_TEST_REQUIRE((map.getTextures()[pt].lsd == before[pt].lsd), "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(createSwamp_places_dead_trees_on_border_to_free_land_only) +{ + Map map = createLandMap(MapExtent(48, 48)); + const Mountain area = createArea(map, MapPoint(24, 24), 6); + const auto distances = distancesTo(area, map.size); + RandomUtility rnd(0); + + createSwamp(map, rnd, area); + + BOOST_TEST_REQUIRE(countObjects(map, [](const MapPoint&) { return true; }) > 0u); + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] == libsiedler2::OT_Empty) + continue; + BOOST_TEST_REQUIRE(map.objectTypes[pt] == OT_Decoration, "At point " << pt); + BOOST_TEST_REQUIRE((map.objectInfos[pt] == OI_DeadTree || map.objectInfos[pt] == OI_DeadTreeTrunk), + "At point " << pt); + BOOST_TEST_REQUIRE(distances[pt] == 1u, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(closeGaps_adds_enclosed_nodes_only) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const MapPoint center(16, 16); + const Mountain closed = createArea(map, center, 5); + Mountain area = closed; + area.erase(center); + area.erase(MapPoint(13, 15)); + + BOOST_TEST((closeGaps(map.size, area) == closed)); + BOOST_TEST((closeGaps(map.size, closed) == closed)); +} + +BOOST_AUTO_TEST_CASE(fillFreeLand_creates_all_desired_types_on_disjoint_areas) +{ + Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + const auto areas = fillFreeLand(map, rnd, mountainLevel, settings, {50, 50, 50}); + + BOOST_TEST_REQUIRE(areas.size() >= 3u); + BOOST_TEST((areas.front().type == LandFill::Mountain)); + + Mountain visited; + helpers::EnumArray count{}; + for(const FilledArea& area : areas) + { + count[area.type]++; + for(const MapPoint& pt : area.nodes) + { + BOOST_TEST_REQUIRE(visited.insert(pt).second, "At point " << pt); + } + } + BOOST_TEST(count[LandFill::Mountain] > 0u); + BOOST_TEST(count[LandFill::Desert] > 0u); + BOOST_TEST(count[LandFill::Swamp] > 0u); +} + +BOOST_AUTO_TEST_CASE(fillFreeLand_applies_textures_matching_the_type) +{ + Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + for(const FilledArea& area : fillFreeLand(map, rnd, mountainLevel, settings, {50, 50, 50})) + { + const auto all = [&map, &area](bool (*predicate)(const TerrainDesc&)) { + return std::all_of(area.nodes.begin(), area.nodes.end(), + [&](const MapPoint& pt) { return map.textureMap.all(pt, predicate); }); + }; + const auto any = [&map, &area](bool (*predicate)(const TerrainDesc&)) { + return std::any_of(area.nodes.begin(), area.nodes.end(), + [&](const MapPoint& pt) { return map.textureMap.all(pt, predicate); }); + }; + + switch(area.type) + { + case LandFill::Mountain: BOOST_TEST(all(isMinableMountain)); break; + case LandFill::Desert: BOOST_TEST(any(isCoastTerrain)); break; + case LandFill::Swamp: BOOST_TEST(all(isImpassable)); break; + } + } +} + +BOOST_AUTO_TEST_CASE(fillFreeLand_creates_only_mountains_by_default) +{ + Map map = createLandMap(MapExtent(64, 64)); + Map expected = createLandMap(MapExtent(64, 64)); + RandomUtility rnd1(7); + RandomUtility rnd2(7); + + const auto areas = fillFreeLand(map, rnd1, mountainLevel, settings, {50, 0, 0}); + const auto mountains = createMountains(expected, rnd2, mountainLevel, settings); + + BOOST_TEST_REQUIRE(areas.size() == mountains.size()); + for(unsigned i = 0; i < areas.size(); i++) + { + BOOST_TEST_REQUIRE((areas[i].type == LandFill::Mountain)); + BOOST_TEST_REQUIRE((areas[i].nodes == mountains[i]), "Area " << i); + } + RTTR_FOREACH_PT(MapPoint, map.size) + { + BOOST_TEST_REQUIRE(map.z[pt] == expected.z[pt], "At point " << pt); + } + BOOST_TEST(map.barren.empty()); +} + +BOOST_AUTO_TEST_CASE(fillFreeLand_limits_swamps_to_half_the_size) +{ + Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + const auto areas = fillFreeLand(map, rnd, mountainLevel, settings, {0, 0, 50}); + + BOOST_TEST_REQUIRE(!areas.empty()); + for(const FilledArea& area : areas) + { + BOOST_TEST_REQUIRE((area.type == LandFill::Swamp)); + } + // Closing gaps adds a few nodes to the desired size + BOOST_TEST(areas.front().nodes.size() >= settings.maxSize / 2); + BOOST_TEST(areas.front().nodes.size() < settings.maxSize * 3 / 4); +} + +BOOST_AUTO_TEST_CASE(fillFreeLand_leaves_no_free_land_beyond_limit) +{ + Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + fillFreeLand(map, rnd, mountainLevel, settings, {20, 40, 40}); + + const auto distances = getFreeLandDistances(map, mountainLevel); + BOOST_TEST(*std::max_element(distances.begin(), distances.end()) <= settings.minFreeLand); +} + +BOOST_AUTO_TEST_CASE(AddObjects_keeps_decoration_and_places_nothing_on_barren_nodes) +{ + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, landHeight); + const auto land = map.textureMap.find(isBuildableLand); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, land); + } + const Mountain swamp = createArea(map, MapPoint(8, 16), 4); + const Mountain hill = createArea(map, MapPoint(22, 16), 5); + RandomUtility rnd(0); + createSwamp(map, rnd, swamp); + raiseDesertHill(map, rnd, hill); + const auto typesBefore = map.objectTypes; + const auto infosBefore = map.objectInfos; + + MapSettings mapSettings; + mapSettings.trees = 100; + mapSettings.stonePiles = 20; + addObjects(map, rnd, mapSettings); + + BOOST_TEST_REQUIRE(countObjects(map, [](const MapPoint&) { return true; }) > 100u); + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(typesBefore[pt] != libsiedler2::OT_Empty) + { + BOOST_TEST_REQUIRE(map.objectTypes[pt] == typesBefore[pt], "At point " << pt); + BOOST_TEST_REQUIRE(map.objectInfos[pt] == infosBefore[pt], "At point " << pt); + } else if(helpers::contains(map.barren, pt)) + { + BOOST_TEST_REQUIRE(map.objectTypes[pt] == libsiedler2::OT_Empty, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(AddObjects_removes_decoration_around_headquarters) +{ + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, landHeight); + const auto land = map.textureMap.find(isBuildableLand); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, land); + } + const MapPoint hq(16, 16); + RandomUtility rnd(0); + createSwamp(map, rnd, createArea(map, MapPoint(9, 16), 4)); + map.hqPositions.push_back(hq); + + addObjects(map, rnd, MapSettings()); + + for(const MapPoint& pt : map.z.getPointsInRadius(hq, 5)) + { + BOOST_TEST_REQUIRE(map.objectTypes[pt] == libsiedler2::OT_Empty, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(AddResources_and_AddAnimals_skip_swamps_made_of_water) +{ + // Winter world uses ice floes (water) as equivalent for swamps + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, landHeight); + const auto land = map.textureMap.find(isBuildableLand); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, land); + } + const Mountain swamp = createArea(map, MapPoint(16, 16), 8); + RandomUtility rnd(0); + createSwamp(map, rnd, swamp); + + addResources(map, rnd, MapSettings()); + addAnimals(map, rnd); + + for(const MapPoint& pt : swamp) + { + BOOST_TEST_REQUIRE(map.resources[pt] != libsiedler2::R_Fish, "At point " << pt); + BOOST_TEST_REQUIRE((map.animals[pt] == libsiedler2::Animal::None), "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/s25Main/mapGenerator/testHarbors.cpp b/tests/s25Main/mapGenerator/testHarbors.cpp index a4b499802c..0e7ea20f44 100644 --- a/tests/s25Main/mapGenerator/testHarbors.cpp +++ b/tests/s25Main/mapGenerator/testHarbors.cpp @@ -66,6 +66,34 @@ BOOST_AUTO_TEST_CASE(PlaceHarborPosition_applies_buildable_terrain_around_positi } } +BOOST_AUTO_TEST_CASE(FindCoastlines_ignores_swamps_made_of_water) +{ + // Some landscapes use water textures for swamps which can't be used by ships + Map map = createMap(MapExtent(32, 32)); + map.getTextures().resize(map.size, TexturePair(map.textureMap.find(isBuildableLand))); + const auto water = map.textureMap.find(isWater); + const MapPoint lake(8, 16); + const MapPoint swamp(24, 16); + const unsigned radius = 4; + + for(const MapPoint& center : {lake, swamp}) + { + for(const MapPoint& pt : map.z.getPointsInRadiusWithCenter(center, radius)) + map.textureMap.set(pt, water); + } + const auto swampNodes = map.z.getPointsInRadiusWithCenter(swamp, radius); + map.barren.insert(swampNodes.begin(), swampNodes.end()); + + const auto coasts = findCoastlines(map, {}); + + BOOST_TEST_REQUIRE(coasts.size() == 1u); + BOOST_TEST_REQUIRE(!coasts.front().empty()); + for(const MapPoint& pt : coasts.front()) + { + BOOST_TEST(map.z.calcDistance(pt, lake) == radius + 1); + } +} + BOOST_AUTO_TEST_CASE(PlaceHarbors_places_no_harbors_on_coast_below_minimum_size) { Map map = createMap(MapExtent(6, 8)); diff --git a/tests/s25Main/mapGenerator/testMountains.cpp b/tests/s25Main/mapGenerator/testMountains.cpp new file mode 100644 index 0000000000..505cbfbf11 --- /dev/null +++ b/tests/s25Main/mapGenerator/testMountains.cpp @@ -0,0 +1,304 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "PointOutput.h" +#include "mapGenFixtures.h" +#include "mapGenerator/Algorithms.h" +#include "mapGenerator/Mountains.h" +#include "mapGenerator/TextureHelper.h" +#include +#include + +using namespace rttr::mapGenerator; + +namespace { +constexpr uint8_t landHeight = 10; +constexpr unsigned mountainLevel = 30; +constexpr MountainSettings settings{3, 100, 25}; + +struct MountainFixture : MapGenFixture +{ + /// Creates a map covered by land except for a single row of water + Map createLandMap(const MapExtent size) const + { + Map map = createMap(size); + map.z.resize(size, landHeight); + RTTR_FOREACH_PT(MapPoint, size) + { + if(pt.y == 0) + map.z[pt] = map.height.minimum; + } + return map; + } +}; + +unsigned maxDistance(const NodeMapBase& distances) +{ + return *std::max_element(distances.begin(), distances.end()); +} +} // namespace + +BOOST_FIXTURE_TEST_SUITE(MountainsTests, MountainFixture) + +BOOST_AUTO_TEST_CASE(getMountainSize_starts_with_maximum_size) +{ + BOOST_TEST(getMountainSize(settings, 0) == settings.maxSize); +} + +BOOST_AUTO_TEST_CASE(getMountainSize_decreases_with_index) +{ + BOOST_TEST(getMountainSize(settings, 1) < getMountainSize(settings, 0)); + BOOST_TEST(getMountainSize(settings, 2) < getMountainSize(settings, 1)); +} + +BOOST_AUTO_TEST_CASE(getMountainSize_never_drops_below_minimum_size) +{ + BOOST_TEST(getMountainSize(settings, 1000) == settings.minSize); +} + +BOOST_AUTO_TEST_CASE(getFreeLandDistances_is_zero_for_water) +{ + const Map map = createLandMap(MapExtent(16, 16)); + const auto distances = getFreeLandDistances(map, mountainLevel); + + BOOST_TEST(distances[MapPoint(5, 0)] == 0u); + BOOST_TEST(distances[MapPoint(5, 1)] == 1u); + BOOST_TEST(distances[MapPoint(5, 8)] == 8u); +} + +BOOST_AUTO_TEST_CASE(getFreeLandDistances_is_zero_for_nodes_at_mountain_level) +{ + Map map = createLandMap(MapExtent(16, 16)); + const MapPoint mountain(8, 8); + map.z[mountain] = mountainLevel; + + const auto distances = getFreeLandDistances(map, mountainLevel); + + BOOST_TEST(distances[mountain] == 0u); + BOOST_TEST(distances[MapPoint(9, 8)] == 1u); +} + +BOOST_AUTO_TEST_CASE(getFreeLandDistances_is_zero_for_textured_nodes) +{ + Map map = createLandMap(MapExtent(16, 16)); + const MapPoint river(8, 8); + map.textureMap.set(river, map.textureMap.find(isWater)); + + const auto distances = getFreeLandDistances(map, mountainLevel); + + BOOST_TEST(distances[river] == 0u); +} + +BOOST_AUTO_TEST_CASE(growMountain_contains_center_even_if_size_is_one) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const auto distances = getFreeLandDistances(map, mountainLevel); + const MapPoint center(16, 16); + RandomUtility rnd(0); + + const auto mountain = growMountain(distances, rnd, center, 1, 3); + + BOOST_TEST(mountain.size() == 1u); + BOOST_TEST(mountain.count(center) == 1u); +} + +BOOST_AUTO_TEST_CASE(growMountain_reaches_requested_size_on_sufficient_land) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const auto distances = getFreeLandDistances(map, mountainLevel); + RandomUtility rnd(0); + + const auto mountain = growMountain(distances, rnd, MapPoint(16, 16), 50, 3); + + BOOST_TEST(mountain.size() == 50u); +} + +BOOST_AUTO_TEST_CASE(growMountain_keeps_margin_to_obstacles) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const auto distances = getFreeLandDistances(map, mountainLevel); + const unsigned margin = 6; + RandomUtility rnd(0); + + const auto mountain = growMountain(distances, rnd, MapPoint(16, 16), 1000, margin); + + BOOST_TEST_REQUIRE(mountain.size() > 1u); + for(const MapPoint& pt : mountain) + { + BOOST_TEST_REQUIRE(distances[pt] > margin, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(findMountains_does_not_change_map) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const auto heightsBefore = map.z; + RandomUtility rnd(0); + + const auto mountains = findMountains(map, rnd, mountainLevel, settings); + + BOOST_TEST_REQUIRE(!mountains.empty()); + RTTR_FOREACH_PT(MapPoint, map.size) + { + BOOST_TEST_REQUIRE(map.z[pt] == heightsBefore[pt], "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(findMountains_finds_nothing_without_enough_free_land) +{ + const Map map = createLandMap(MapExtent(32, 32)); + const auto freeLand = maxDistance(getFreeLandDistances(map, mountainLevel)); + RandomUtility rnd(0); + + const MountainSettings limit{freeLand, settings.maxSize, settings.minSize}; + + BOOST_TEST(findMountains(map, rnd, mountainLevel, limit).empty()); +} + +BOOST_AUTO_TEST_CASE(findMountains_finds_nothing_on_water_only) +{ + Map map = createMap(MapExtent(16, 16)); + map.z.resize(map.size, map.height.minimum); + RandomUtility rnd(0); + + BOOST_TEST(findMountains(map, rnd, mountainLevel, settings).empty()); +} + +BOOST_AUTO_TEST_CASE(findMountains_covers_map_without_any_obstacles) +{ + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, landHeight); + RandomUtility rnd(0); + + BOOST_TEST(!findMountains(map, rnd, mountainLevel, settings).empty()); +} + +BOOST_AUTO_TEST_CASE(findMountains_returns_disjoint_mountains) +{ + const Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + const auto mountains = findMountains(map, rnd, mountainLevel, settings); + + BOOST_TEST_REQUIRE(mountains.size() > 1u); + Mountain visited; + for(const Mountain& mountain : mountains) + { + for(const MapPoint& pt : mountain) + { + BOOST_TEST_REQUIRE(visited.insert(pt).second, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(findMountains_respects_size_of_each_mountain) +{ + const Map map = createLandMap(MapExtent(64, 64)); + RandomUtility rnd(0); + + const auto mountains = findMountains(map, rnd, mountainLevel, settings); + + BOOST_TEST_REQUIRE(mountains.size() > 1u); + for(unsigned index = 0; index < mountains.size(); index++) + { + BOOST_TEST_REQUIRE(mountains[index].size() <= getMountainSize(settings, index), "Mountain " << index); + } +} + +BOOST_AUTO_TEST_CASE(findMountains_keeps_free_land_around_obstacles) +{ + const Map map = createLandMap(MapExtent(64, 64)); + const auto distances = getFreeLandDistances(map, mountainLevel); + RandomUtility rnd(0); + + for(const Mountain& mountain : findMountains(map, rnd, mountainLevel, settings)) + { + for(const MapPoint& pt : mountain) + { + BOOST_TEST_REQUIRE(distances[pt] > settings.minFreeLand, "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(raiseMountain_elevates_center_above_foot_and_keeps_surroundings) +{ + Map map = createLandMap(MapExtent(32, 32)); + const MapPoint center(16, 16); + const auto points = map.z.getPointsInRadiusWithCenter(center, 4); + const Mountain mountain(points.begin(), points.end()); + const MapPoint outside(16, 26); + RandomUtility rnd(0); + + raiseMountain(map, rnd, mountain); + + BOOST_TEST(map.z[center] > landHeight + 1); + BOOST_TEST(map.z[outside] == landHeight); + for(const MapPoint& pt : mountain) + { + BOOST_TEST_REQUIRE(map.z[pt] >= landHeight, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(raiseMountain_applies_minable_textures_to_all_nodes) +{ + Map map = createLandMap(MapExtent(32, 32)); + const auto points = map.z.getPointsInRadiusWithCenter(MapPoint(16, 16), 4); + const Mountain mountain(points.begin(), points.end()); + const auto minable = map.textureMap.findAll(isMinableMountain); + RandomUtility rnd(0); + + raiseMountain(map, rnd, mountain); + + for(const MapPoint& pt : mountain) + { + const auto& textures = map.getTextures()[pt]; + BOOST_TEST_REQUIRE(helpers::contains(minable, textures.rsu), "At point " << pt); + BOOST_TEST_REQUIRE(helpers::contains(minable, textures.lsd), "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(raiseMountain_does_not_exceed_maximum_height) +{ + Map map = createMap(MapExtent(32, 32)); + map.z.resize(map.size, map.height.maximum - 1); + const auto points = map.z.getPointsInRadiusWithCenter(MapPoint(16, 16), 6); + RandomUtility rnd(0); + + raiseMountain(map, rnd, Mountain(points.begin(), points.end())); + + RTTR_FOREACH_PT(MapPoint, map.size) + { + BOOST_TEST_REQUIRE(map.z[pt] <= map.height.maximum, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(createMountains_leaves_no_free_land_beyond_limit) +{ + Map map = createLandMap(MapExtent(64, 64)); + BOOST_TEST_REQUIRE(maxDistance(getFreeLandDistances(map, mountainLevel)) > settings.minFreeLand); + RandomUtility rnd(0); + + const auto mountains = createMountains(map, rnd, mountainLevel, settings); + + BOOST_TEST_REQUIRE(!mountains.empty()); + BOOST_TEST(maxDistance(getFreeLandDistances(map, mountainLevel)) <= settings.minFreeLand); +} + +BOOST_AUTO_TEST_CASE(findMountains_is_deterministic_for_same_seed) +{ + const Map map = createLandMap(MapExtent(48, 48)); + RandomUtility rnd1(42); + RandomUtility rnd2(42); + + const auto mountains1 = findMountains(map, rnd1, mountainLevel, settings); + const auto mountains2 = findMountains(map, rnd2, mountainLevel, settings); + + BOOST_TEST_REQUIRE(mountains1.size() == mountains2.size()); + for(unsigned index = 0; index < mountains1.size(); index++) + { + BOOST_TEST_REQUIRE((mountains1[index] == mountains2[index]), "Mountain " << index); + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/tests/s25Main/mapGenerator/testRandomMap.cpp b/tests/s25Main/mapGenerator/testRandomMap.cpp index 6112e5ff22..79270ca521 100644 --- a/tests/s25Main/mapGenerator/testRandomMap.cpp +++ b/tests/s25Main/mapGenerator/testRandomMap.cpp @@ -5,7 +5,10 @@ #include "PointOutput.h" #include "commonDefines.h" #include "lua/GameDataLoader.h" +#include "mapGenerator/Algorithms.h" #include "mapGenerator/RandomMap.h" +#include "mapGenerator/SpecialObjects.h" +#include "mapGenerator/TextureHelper.h" #include "gameData/MaxPlayers.h" #include "libsiedler2/ArchivItem_Map.h" #include "libsiedler2/ArchivItem_Map_Header.h" @@ -144,6 +147,290 @@ BOOST_AUTO_TEST_CASE(GenerateRandomMap_returns_valid_map_with_max_players) validateMap(map, settings.size, settings.numPlayers); } +BOOST_AUTO_TEST_CASE(getMaxMountainSize_grows_with_map_size) +{ + BOOST_TEST(getMaxMountainSize(MapExtent(64, 64)) < getMaxMountainSize(MapExtent(128, 128))); + BOOST_TEST(getMaxMountainSize(MapExtent(128, 128)) < getMaxMountainSize(MapExtent(256, 256))); + BOOST_TEST(getMaxMountainSize(MapExtent(256, 256)) < getMaxMountainSize(MapExtent(512, 512))); + BOOST_TEST(getMaxMountainSize(MapExtent(512, 512)) < getMaxMountainSize(MapExtent(1024, 1024))); +} + +BOOST_AUTO_TEST_CASE(getMinFreeLand_keeps_mountain_distance_for_medium_amount) +{ + BOOST_TEST(getMinFreeLand(15, 50) == 15u); +} + +BOOST_AUTO_TEST_CASE(getMinFreeLand_decreases_with_amount_of_mountains) +{ + BOOST_TEST(getMinFreeLand(30, 25) > getMinFreeLand(30, 50)); + BOOST_TEST(getMinFreeLand(30, 50) > getMinFreeLand(30, 75)); +} + +BOOST_AUTO_TEST_CASE(getMinFreeLand_keeps_space_for_headquarters) +{ + BOOST_TEST(getMinFreeLand(30, 100) == 4u); + BOOST_TEST(getMinFreeLand(5, 90) == 4u); + BOOST_TEST(getMinFreeLand(30, 1000) == 4u); +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_creates_more_mountains_for_higher_amount) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(256, 256); + settings.style = MapStyle::Mixed; + + const auto countMountainNodes = [&worldDesc, &settings](const unsigned short mountains) { + settings.mountains = mountains; + RandomUtility rnd(0); + const Map map = generateRandomMap(rnd, worldDesc, settings); + return selectPoints([&map](const MapPoint& pt) { return map.textureMap.any(pt, isMinableMountain); }, map.size) + .size(); + }; + + const auto noMountains = countMountainNodes(0); + const auto defaultMountains = countMountainNodes(50); + const auto maxMountains = countMountainNodes(100); + + BOOST_TEST(noMountains < defaultMountains); + BOOST_TEST(defaultMountains < maxMountains); +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_returns_valid_maps_for_maximum_amount_of_mountains) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(128, 128); + settings.mountains = 100; + + for(const unsigned numPlayers : {2u, MAX_PLAYERS}) + { + for(const MapStyle style : {MapStyle::Land, MapStyle::Mixed, MapStyle::Water}) + { + settings.numPlayers = numPlayers; + settings.style = style; + RandomUtility rnd(1); + + Map map = generateRandomMap(rnd, worldDesc, settings); + validateMap(map, settings.size, settings.numPlayers); + } + } +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_leaves_no_large_free_land) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + // Smaller maps do not contain enough free land to require additional mountains + settings.size = MapExtent(256, 256); + settings.mountainDistance = MountainDistance::Close; + // The foot of desert hills is buildable and therefore counts as free land + settings.mountains = 50; + settings.desert = 0; + settings.swamp = 0; + settings.specialObjects = false; + + // Maximum of the randomized free land to keep plus the transition textures added at the foot of mountains and + // desert hills + const unsigned amount = settings.mountains + settings.desert + settings.swamp; + const unsigned maxFreeLand = getMinFreeLand(static_cast(settings.mountainDistance), amount) + 5 + 3; + + for(const MapStyle style : {MapStyle::Land, MapStyle::Mixed}) + { + settings.style = style; + RandomUtility rnd(0); + + const Map map = generateRandomMap(rnd, worldDesc, settings); + const auto distances = distancesTo(map.size, [&map](const MapPoint& pt) { + return helpers::contains(map.barren, pt) || map.textureMap.any(pt, [](const TerrainDesc& t) { + return isWater(t) || isMountainOrSnowOrLava(t); + }); + }); + + BOOST_TEST(*std::max_element(distances.begin(), distances.end()) <= maxFreeLand); + } +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_returns_valid_maps_for_all_styles_and_mountain_distances) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(96, 96); + settings.numPlayers = 4; + + for(const MapStyle style : {MapStyle::Land, MapStyle::Mixed, MapStyle::Water}) + { + for(const MountainDistance distance : {MountainDistance::Close, MountainDistance::VeryFar}) + { + settings.style = style; + settings.mountainDistance = distance; + RandomUtility rnd(1); + + Map map = generateRandomMap(rnd, worldDesc, settings); + validateMap(map, settings.size, settings.numPlayers); + } + } +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_creates_no_deserts_and_swamps_if_disabled) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + settings.size = MapExtent(256, 256); + settings.mountains = 50; + settings.desert = 0; + settings.swamp = 0; + RandomUtility rnd(0); + + const Map map = generateRandomMap(rnd, worldDesc, settings); + + BOOST_TEST(map.barren.empty()); +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_creates_deserts_and_swamps_for_all_landscapes) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(256, 256); + settings.style = MapStyle::Land; + settings.mountainDistance = MountainDistance::Close; + settings.desert = 50; + settings.swamp = 50; + + for(unsigned landscape = 0; landscape < worldDesc.landscapes.size(); landscape++) + { + settings.type = DescIdx(landscape); + RandomUtility rnd(0); + + const Map map = generateRandomMap(rnd, worldDesc, settings); + validateMap(map, settings.size, settings.numPlayers); + + const auto count = [&map](bool (*predicate)(const TerrainDesc&)) { + return helpers::countIf(map.barren, [&](const MapPoint& pt) { return map.textureMap.all(pt, predicate); }); + }; + BOOST_TEST_CONTEXT("Landscape " << landscape) + { + BOOST_TEST(count(isImpassable) > 0); + BOOST_TEST(count(isCoastTerrain) > 0); + BOOST_TEST(helpers::count(map.objectTypes, 0xC8) > 0); + for(const MapPoint& pt : map.barren) + { + if(!map.textureMap.all(pt, isImpassable)) + continue; + // Swamps are flat and not used for fishing + BOOST_TEST_REQUIRE(map.resources[pt] != libsiedler2::R_Fish, "At point " << pt); + for(const MapPoint& neighbor : map.z.getNeighbours(pt)) + { + if(helpers::contains(map.barren, neighbor)) + BOOST_TEST_REQUIRE(map.z[pt] == map.z[neighbor], "At point " << pt); + } + } + } + } +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_returns_valid_maps_with_deserts_and_swamps_for_all_styles) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(128, 128); + settings.mountains = 100; + settings.desert = 100; + settings.swamp = 100; + + for(unsigned landscape = 0; landscape < worldDesc.landscapes.size(); landscape++) + { + for(const MapStyle style : {MapStyle::Land, MapStyle::Mixed, MapStyle::Water}) + { + for(const unsigned numPlayers : {2u, MAX_PLAYERS}) + { + settings.type = DescIdx(landscape); + settings.style = style; + settings.numPlayers = numPlayers; + RandomUtility rnd(1); + + Map map = generateRandomMap(rnd, worldDesc, settings); + validateMap(map, settings.size, settings.numPlayers); + } + } + } +} + +static unsigned countSpecialObjects(const Map& map) +{ + unsigned count = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(isSpecialObject(map.objectTypes[pt], map.objectInfos[pt])) + count++; + } + return count; +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_creates_no_special_objects_if_disabled) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + settings.size = MapExtent(128, 128); + settings.specialObjects = false; + RandomUtility rnd(0); + + const Map map = generateRandomMap(rnd, worldDesc, settings); + + BOOST_TEST(countSpecialObjects(map) == 0u); + BOOST_TEST(map.reserved.empty()); +} + +BOOST_AUTO_TEST_CASE(GenerateRandomMap_creates_a_few_special_objects_if_enabled) +{ + WorldDescription worldDesc; + loadGameData(worldDesc); + MapSettings settings; + + settings.size = MapExtent(192, 192); + settings.numPlayers = 4; + settings.specialObjects = true; + settings.trees = 100; + settings.stonePiles = 20; + + for(unsigned landscape = 0; landscape < worldDesc.landscapes.size(); landscape++) + { + for(const MapStyle style : {MapStyle::Land, MapStyle::Mixed, MapStyle::Water}) + { + settings.type = DescIdx(landscape); + settings.style = style; + RandomUtility rnd(2); + + const Map map = generateRandomMap(rnd, worldDesc, settings); + validateMap(map, settings.size, settings.numPlayers); + + BOOST_TEST_CONTEXT("Landscape " << landscape << " style " << static_cast(style)) + { + // The graveyard contains more than one special object + BOOST_TEST(countSpecialObjects(map) > 0u); + BOOST_TEST(countSpecialObjects(map) <= 16 * getNumSpecialScenes(map.size)); + BOOST_TEST(map.reserved.size() % 169 == 0u); + BOOST_TEST(map.reserved.size() > 0u); + BOOST_TEST(map.reserved.size() <= 169 * getNumSpecialScenes(map.size)); + } + } + } +} + BOOST_AUTO_TEST_CASE(GenerateRandomMap_returns_valid_mapfile_with_max_players) { rttr::test::TmpFolder tmpFolder; diff --git a/tests/s25Main/mapGenerator/testSpecialObjects.cpp b/tests/s25Main/mapGenerator/testSpecialObjects.cpp new file mode 100644 index 0000000000..e77b0fa64b --- /dev/null +++ b/tests/s25Main/mapGenerator/testSpecialObjects.cpp @@ -0,0 +1,599 @@ +// Copyright (C) 2005 - 2026 Settlers Freaks (sf-team at siedler25.org) +// +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "PointOutput.h" +#include "helpers/EnumRange.h" +#include "mapGenFixtures.h" +#include "mapGenerator/FreeLand.h" +#include "mapGenerator/Resources.h" +#include "mapGenerator/SpecialObjects.h" +#include "mapGenerator/TextureHelper.h" +#include "gameTypes/Direction.h" +#include "libsiedler2/enumTypes.h" +#include +#include +#include +#include + +using namespace rttr::mapGenerator; + +namespace { +constexpr uint8_t landHeight = 10; +constexpr unsigned numLandscapes = 3; + +struct SpecialObjectsFixture : MapGenFixture +{ + static bool isMeadow(const TerrainDesc& terrain) { return isBuildableLand(terrain) && terrain.s2Id == 0x08; } + + static bool isLushMeadow(const TerrainDesc& terrain) { return isBuildableLand(terrain) && terrain.s2Id == 0x0A; } + + /// Creates a flat map which is entirely covered by meadow + Map createLandMap(const MapExtent size, bool lush = false) const + { + Map map = createMap(size); + map.z.resize(size, landHeight); + const auto land = map.textureMap.find(lush ? isLushMeadow : isMeadow); + RTTR_FOREACH_PT(MapPoint, size) + { + map.textureMap.set(pt, land); + } + return map; + } +}; + +unsigned countObjects(const Map& map) +{ + unsigned count = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] != libsiedler2::OT_Empty) + count++; + } + return count; +} +} // namespace + +BOOST_FIXTURE_TEST_SUITE(SpecialObjectsTests, SpecialObjectsFixture) + +BOOST_AUTO_TEST_CASE(getNumSpecialScenes_returns_a_few_scenes_depending_on_map_size) +{ + BOOST_TEST(getNumSpecialScenes(MapExtent(32, 32)) == 1u); + BOOST_TEST(getNumSpecialScenes(MapExtent(64, 64)) < getNumSpecialScenes(MapExtent(128, 128))); + BOOST_TEST(getNumSpecialScenes(MapExtent(128, 128)) < getNumSpecialScenes(MapExtent(256, 256))); + BOOST_TEST(getNumSpecialScenes(MapExtent(1024, 1024)) <= 6u); +} + +BOOST_AUTO_TEST_CASE(findSceneSites_returns_requested_number_of_distant_sites) +{ + const Map map = createLandMap(MapExtent(96, 96)); + RandomUtility rnd(0); + + const auto sites = findSceneSites(map, rnd, 4); + + BOOST_TEST_REQUIRE(sites.size() == 4u); + for(unsigned i = 0; i < sites.size(); i++) + { + for(unsigned j = i + 1; j < sites.size(); j++) + BOOST_TEST(map.z.calcDistance(sites[i], sites[j]) >= 4 * sceneRadius); + } +} + +BOOST_AUTO_TEST_CASE(findSceneSites_finds_nothing_without_buildable_land) +{ + Map map = createMap(MapExtent(32, 32)); + const auto water = map.textureMap.find(isWater); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.textureMap.set(pt, water); + } + RandomUtility rnd(0); + + BOOST_TEST(findSceneSites(map, rnd, 3).empty()); +} + +BOOST_AUTO_TEST_CASE(findSceneSites_keeps_distance_to_obstacles_and_players) +{ + Map map = createLandMap(MapExtent(64, 64)); + const MapPoint hq(10, 10); + const MapPoint tree(40, 40); + const MapPoint swamp(20, 45); + map.hqPositions.push_back(hq); + map.harbors.push_back(Triangle(true, MapPoint(50, 12))); + map.objectTypes[tree] = libsiedler2::OT_TreeOrPalm; + map.textureMap.set(swamp, map.textureMap.find(isImpassable)); + + for(unsigned seed = 0; seed < 30; seed++) + { + RandomUtility rnd(seed); + for(const MapPoint& site : findSceneSites(map, rnd, 3)) + { + // Objects around headquarters and harbors are removed within a radius of 5 + BOOST_TEST_REQUIRE(map.z.calcDistance(site, hq) > sceneRadius + 5, "At point " << site); + BOOST_TEST_REQUIRE(map.z.calcDistance(site, MapPoint(50, 12)) > sceneRadius + 5, "At point " << site); + BOOST_TEST_REQUIRE(map.z.calcDistance(site, tree) > sceneCoreRadius + 1, "At point " << site); + BOOST_TEST_REQUIRE(map.z.calcDistance(site, swamp) > sceneCoreRadius + 1, "At point " << site); + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_surrounds_special_object_by_decoration_within_scene) +{ + for(unsigned i = 0; i < numLandscapes; i++) + { + landscape = DescIdx(i); + for(const SceneType type : helpers::EnumRange()) + { + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, type, style); + + BOOST_TEST_CONTEXT("Landscape " << i << " scene " << static_cast(type) << " style " + << static_cast(style) << " seed " << seed) + { + BOOST_TEST(isSpecialObject(map.objectTypes[center], map.objectInfos[center])); + BOOST_TEST(countObjects(map) >= 15u); + BOOST_TEST(map.reserved.size() == 169u); + RTTR_FOREACH_PT(MapPoint, map.size) + { + const bool inScene = map.z.calcDistance(center, pt) <= sceneRadius; + BOOST_TEST_REQUIRE(helpers::contains(map.reserved, pt) == inScene, "At point " << pt); + if(!inScene) + { + // The surrounding land is left untouched + BOOST_TEST_REQUIRE(map.objectTypes[pt] == libsiedler2::OT_Empty, "At point " << pt); + BOOST_TEST_REQUIRE(map.z[pt] == landHeight, "At point " << pt); + } + // Transitions may reach the triangles right next to the scene + if(map.z.calcDistance(center, pt) > sceneRadius + 1) + BOOST_TEST_REQUIRE(map.textureMap.all(pt, isMeadow), "At point " << pt); + if(map.textureMap.all(pt, isWater)) + BOOST_TEST_REQUIRE(map.objectTypes[pt] == libsiedler2::OT_Empty, "At point " << pt); + // Hills and hollows are smooth + for(const MapPoint& neighbor : map.z.getNeighbours(pt)) + { + const int difference = static_cast(map.z[pt]) - static_cast(map.z[neighbor]); + BOOST_TEST_REQUIRE(std::abs(difference) <= 2, "At point " << pt); + } + } + } + } + } + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_keeps_footprint_of_castle_ruin_free_and_even) +{ + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 10; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, SceneType::CastleRuin, style); + + BOOST_TEST(map.objectInfos[center] == OI_CastleRuin); + for(const Direction dir : {Direction::West, Direction::NorthWest, Direction::NorthEast}) + { + // The ruin covers some of its neighbors + BOOST_TEST_REQUIRE(map.objectTypes[map.z.getNeighbour(center, dir)] == libsiedler2::OT_Empty); + } + for(const MapPoint& pt : map.z.getNeighbours(center)) + BOOST_TEST_REQUIRE(map.z[pt] == map.z[center], "At point " << pt); + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_blends_ground_into_surrounding_land) +{ + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(0); + const auto isFlowers = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x0F; }; + + createScene(map, rnd, center, SceneType::RuinGrove, SceneStyle::Overgrown); + + // Flowers in the middle fade out via the textures between flowers and meadow + BOOST_TEST(map.textureMap.all(center, isFlowers)); + std::set textures; + RTTR_FOREACH_PT(MapPoint, map.size) + { + textures.insert(map.textureMap.getTextureId(map.getTextures()[pt].rsu)); + // Flowers never touch the meadow of the surrounding land directly + if(map.textureMap.any(pt, isFlowers)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isMeadow), "At point " << pt); + } + BOOST_TEST(textures.count(0x09) == 1u); + BOOST_TEST(textures.count(0x0A) == 1u); +} + +BOOST_AUTO_TEST_CASE(createScene_uses_all_transition_textures_between_dry_ground_and_meadow) +{ + const auto isSteppe = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x0E; }; + const auto isSavannah = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x00; }; + + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, SceneType::Camp, style); + + BOOST_TEST(map.textureMap.all(center, isSteppe)); + unsigned savannah = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.textureMap.any(pt, isSavannah)) + savannah++; + // Steppe is always separated from meadow by savannah + if(map.textureMap.any(pt, isSteppe)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isMeadow), "At point " << pt); + } + BOOST_TEST(savannah > 6u); + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_surrounds_pond_by_transitions_from_sand_to_meadow) +{ + const auto isSteppe = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x0E; }; + const auto isSavannah = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x00; }; + + for(const SceneType type : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, type, SceneStyle::Crag); + + BOOST_TEST_CONTEXT("Scene " << static_cast(type) << " seed " << seed) + { + unsigned water = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.textureMap.all(pt, isWater)) + water++; + // Water is enclosed by sand, sand by steppe and steppe by savannah + if(map.textureMap.any(pt, isWater)) + BOOST_TEST_REQUIRE( + map.textureMap.all(pt, [](const TerrainDesc& t) { return isWater(t) || isCoastTerrain(t); }), + "At point " << pt); + if(map.textureMap.any(pt, isCoastTerrain)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isMeadow), "At point " << pt); + if(map.textureMap.any(pt, isSteppe)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isMeadow), "At point " << pt); + if(map.textureMap.any(pt, isCoastTerrain)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isSavannah), "At point " << pt); + } + BOOST_TEST(water >= 2u); + } + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_adds_transitions_within_lush_meadow) +{ + // The most lush meadow is several textures away from sand but looks like any other meadow + const auto isGreen = [](const TerrainDesc& terrain) { return isBuildableLand(terrain) && terrain.humidity > 90; }; + const auto isSteppe = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x0E; }; + const auto isSavannah = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x00; }; + + for(const SceneType type : helpers::EnumRange()) + { + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + Map map = createLandMap(MapExtent(40, 40), true); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, type, style); + + BOOST_TEST_CONTEXT("Scene " << static_cast(type) << " style " << static_cast(style) + << " seed " << seed) + { + RTTR_FOREACH_PT(MapPoint, map.size) + { + // Sand meets steppe, steppe meets savannah and only savannah meets meadow + if(map.textureMap.any(pt, isCoastTerrain)) + { + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isGreen), "At point " << pt); + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isSavannah), "At point " << pt); + } + if(map.textureMap.any(pt, isSteppe)) + BOOST_TEST_REQUIRE(!map.textureMap.any(pt, isGreen), "At point " << pt); + } + } + } + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_leaves_other_landscapes_untouched) +{ + for(const SceneType type : helpers::EnumRange()) + { + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + // Water, a mountain and a tree are located in the outer part of the scene + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + const auto water = map.textureMap.find(isWater); + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(pt.x >= 26) + { + map.textureMap.set(pt, water); + map.z[pt] = map.height.minimum; + } + } + const MapPoint mountain(15, 15); + const MapPoint tree(17, 26); + map.textureMap.set(mountain, map.textureMap.find(isMinableMountain)); + map.z[mountain] = landHeight + 8; + map.objectTypes[tree] = libsiedler2::OT_TreeOrPalm; + map.objectInfos[tree] = libsiedler2::OI_TreeOrPalm_Begin; + const Map original = map; + RandomUtility rnd(seed); + + createScene(map, rnd, center, type, style); + + BOOST_TEST_CONTEXT("Scene " << static_cast(type) << " style " << static_cast(style) + << " seed " << seed) + { + BOOST_TEST(isSpecialObject(map.objectTypes[center], map.objectInfos[center])); + BOOST_TEST(map.objectTypes[tree] == original.objectTypes[tree]); + BOOST_TEST(map.objectInfos[tree] == original.objectInfos[tree]); + const auto isLand = [this](DescIdx texture) { + return isBuildableLand(worldDesc.get(texture)); + }; + RTTR_FOREACH_PT(MapPoint, map.size) + { + // Only triangles of buildable land are painted + const TexturePair& before = original.getTextures()[pt]; + const TexturePair& after = map.getTextures()[pt]; + BOOST_TEST_REQUIRE((isLand(before.rsu) || after.rsu == before.rsu), "At point " << pt); + BOOST_TEST_REQUIRE((isLand(before.lsd) || after.lsd == before.lsd), "At point " << pt); + // Nodes which are part of other landscapes keep their height and get no objects + if(original.textureMap.all(pt, isBuildableLand)) + continue; + BOOST_TEST_REQUIRE(map.z[pt] == original.z[pt], "At point " << pt); + BOOST_TEST_REQUIRE(map.objectTypes[pt] == original.objectTypes[pt], "At point " << pt); + } + } + } + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_adds_rim_around_rock) +{ + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(0); + const auto isRock = [](const TerrainDesc& terrain) { return terrain.s2Id == 0x22; }; + + createScene(map, rnd, center, SceneType::CastleRuin, SceneStyle::Overgrown); + + BOOST_TEST(map.textureMap.all(center, isRock)); + BOOST_TEST(map.z[center] > landHeight); + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.textureMap.any(pt, isRock)) + BOOST_TEST_REQUIRE(map.textureMap.all(pt, isBuildableMountain), "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(createScene_raises_crag_next_to_pond) +{ + for(unsigned seed = 0; seed < 10; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, SceneType::RuinGrove, SceneStyle::Crag); + + unsigned pond = 0; + unsigned rocks = 0; + uint8_t top = 0; + uint8_t waterLevel = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + top = std::max(top, map.z[pt]); + if(map.objectTypes[pt] == libsiedler2::OT_Stone1 || map.objectTypes[pt] == libsiedler2::OT_Stone2) + rocks++; + if(map.textureMap.all(pt, isWater)) + { + BOOST_TEST_REQUIRE((pond == 0 || map.z[pt] == waterLevel), "At point " << pt); + waterLevel = map.z[pt]; + pond++; + } + } + BOOST_TEST(pond >= 2u); + BOOST_TEST(rocks >= 2u); + BOOST_TEST(top >= landHeight + 3); + BOOST_TEST(waterLevel < landHeight); + } +} + +BOOST_AUTO_TEST_CASE(createScene_lines_road_of_avenue_with_trees) +{ + for(unsigned seed = 0; seed < 10; seed++) + { + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(map, rnd, center, SceneType::CastleRuin, SceneStyle::Avenue); + + // One of the six directions is a free road with trees on both sides + unsigned roads = 0; + for(const Direction dir : helpers::EnumRange()) + { + MapPoint pt = center; + bool isRoad = true; + for(unsigned i = 1; i <= sceneRadius; i++) + { + pt = map.z.getNeighbour(pt, dir); + isRoad &= map.objectTypes[pt] == libsiedler2::OT_Empty; + } + if(isRoad) + roads++; + } + BOOST_TEST(roads >= 1u); + unsigned trees = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] == libsiedler2::OT_TreeOrPalm || map.objectTypes[pt] == libsiedler2::OT_Palm + || map.objectTypes[pt] == libsiedler2::OT_Palm + 1) + trees++; + } + BOOST_TEST(trees == 8u); + } +} + +BOOST_AUTO_TEST_CASE(createScene_lines_trail_with_remains) +{ + Map map = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(0); + + createScene(map, rnd, center, SceneType::StoneCircle, SceneStyle::Trail); + + unsigned stones = 0; + RTTR_FOREACH_PT(MapPoint, map.size) + { + if(map.objectTypes[pt] == OT_Decoration && map.objectInfos[pt] >= 0x18 && map.objectInfos[pt] <= 0x1E) + stones++; + } + // Circle around the gate and the stones along the trail + BOOST_TEST(stones >= 6u + 5u); + BOOST_TEST((map.objectInfos[center] == OI_Gate || map.objectInfos[center] == OI_OpenGate)); +} + +BOOST_AUTO_TEST_CASE(createScene_places_single_tent_and_rows_of_graves_in_any_style) +{ + for(const SceneStyle style : helpers::EnumRange()) + { + for(unsigned seed = 0; seed < 5; seed++) + { + Map camp = createLandMap(MapExtent(40, 40)); + Map graveyard = createLandMap(MapExtent(40, 40)); + const MapPoint center(20, 20); + RandomUtility rnd(seed); + + createScene(camp, rnd, center, SceneType::Camp, style); + createScene(graveyard, rnd, center, SceneType::Graveyard, style); + + unsigned tents = 0; + unsigned graves = 0; + RTTR_FOREACH_PT(MapPoint, camp.size) + { + if(camp.objectTypes[pt] == OT_Decoration && camp.objectInfos[pt] == OI_Tent) + tents++; + if(graveyard.objectTypes[pt] == OT_Decoration && graveyard.objectInfos[pt] == OI_Cross) + graves++; + } + BOOST_TEST(tents == 1u); + BOOST_TEST(graves >= 7u); + } + } +} + +BOOST_AUTO_TEST_CASE(createScene_levels_ground_and_smooths_transition) +{ + Map map = createLandMap(MapExtent(48, 48)); + RTTR_FOREACH_PT(MapPoint, map.size) + { + map.z[pt] = static_cast(landHeight + pt.x / 2); + } + const MapPoint center(24, 24); + const uint8_t level = map.z[center]; + RandomUtility rnd(0); + + createScene(map, rnd, center, SceneType::Camp, SceneStyle::Trail); + + for(const MapPoint& pt : map.z.getPointsInRadiusWithCenter(center, sceneRadius)) + { + const unsigned distance = map.z.calcDistance(center, pt); + const int difference = static_cast(map.z[pt]) - static_cast(level); + const int tolerance = distance <= 3 ? 0 : static_cast(distance) - 3; + BOOST_TEST_REQUIRE(std::abs(difference) <= tolerance, "At point " << pt); + } +} + +BOOST_AUTO_TEST_CASE(addSpecialScenes_mixes_up_types_of_scenes) +{ + Map map = createLandMap(MapExtent(256, 256)); + RandomUtility rnd(0); + + const auto scenes = addSpecialScenes(map, rnd); + + BOOST_TEST_REQUIRE(scenes.size() == getNumSpecialScenes(map.size)); + std::set types; + for(const Scene& scene : scenes) + { + types.insert(scene.type); + BOOST_TEST(isSpecialObject(map.objectTypes[scene.center], map.objectInfos[scene.center])); + } + BOOST_TEST(types.size() == 5u); + BOOST_TEST(map.reserved.size() == 169 * scenes.size()); +} + +BOOST_AUTO_TEST_CASE(addSpecialScenes_varies_with_seed) +{ + Map map1 = createLandMap(MapExtent(64, 64)); + Map map2 = createLandMap(MapExtent(64, 64)); + RandomUtility rnd1(1); + RandomUtility rnd2(2); + + const auto scenes1 = addSpecialScenes(map1, rnd1); + const auto scenes2 = addSpecialScenes(map2, rnd2); + + BOOST_TEST_REQUIRE(scenes1.size() == 1u); + BOOST_TEST_REQUIRE(scenes2.size() == 1u); + BOOST_TEST(scenes1.front().center != scenes2.front().center); +} + +BOOST_AUTO_TEST_CASE(AddObjects_keeps_scenes_free_from_trees_and_stone_piles) +{ + Map map = createLandMap(MapExtent(48, 48)); + RandomUtility rnd(0); + const auto scenes = addSpecialScenes(map, rnd); + BOOST_TEST_REQUIRE(!scenes.empty()); + const auto typesBefore = map.objectTypes; + const auto infosBefore = map.objectInfos; + + MapSettings settings; + settings.trees = 100; + settings.stonePiles = 20; + addObjects(map, rnd, settings); + + BOOST_TEST(countObjects(map) > 500u); + for(const MapPoint& pt : map.reserved) + { + BOOST_TEST_REQUIRE(map.objectTypes[pt] == typesBefore[pt], "At point " << pt); + BOOST_TEST_REQUIRE(map.objectInfos[pt] == infosBefore[pt], "At point " << pt); + } +} + +BOOST_AUTO_TEST_SUITE_END()