Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): random maps roll a map type and biome, fair money and spawns
Olcay Seygan7d556963d141
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac95d04d4..8f1404c97 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1902,10 +1902,33 @@ The whole HUD is on the hardware. Four colours carry it, and they mean the samemarked roads to every other base, a middle road along the ground a tank would drive and two thatswing out wide to either side. Random maps made by an older version are different maps from thesame number.-- No two of them are the same shape. Nothing is mirrored, rotated or laid out on a ring. The whole- map is one field of noise, and the bases are found in it: the flattest ground first, then- whichever good ground is furthest from everything already taken. Some seeds give you four corners- and some give you a long diagonal, and where the fighting happens is different every time.+- The number picks what kind of map you get, the way an Age of Empires seed picks Arabia or a river+ map. There are seven. Plains roll gently with a pond or two. Highlands stand on shelves. Lake+ country spreads extra lakes and keeps them apart. A river map is cut in two by one river with+ fords across it. A canyon map has a few long gorges winding through it. A black forest is one+ wood from edge to edge, with clear rides cut from every base to the middle and round the ring of+ bases, so you can see an army coming down a ride. A massif lifts the middle into one table of+ high ground with a cliff all round and a ramp up from every side. Over the first thousand numbers+ each kind comes up between 131 and 159 times.+- The same number also picks what the ground is made of: green temperate fields with oaks and+ maples, desert sand with palms in thin stands, winter snow under snowed-in firs, or dry steppe.+ The two are picked apart, so a river can run through snow as well as through grass, and the light+ changes with the ground.+- Every player gets the same deal. The bases are found in the land rather than stamped on it, and+ then every layout tried is measured by the walk from each base to its nearest and second-nearest+ enemy, and the one where those walks come out most even is the one you play. Your home dock,+ your derricks and the money out in the field sit as far from your base as everybody else's do+ from theirs, and every one of them can be driven to.+- The ground is cleaner. The routes between bases used to be levelled into straight shelves that+ drew ruled lines across the map; they follow the hillside now. A lake bed climbs back up to its+ bank instead of ending at a square cut, and the bank stays above the water.+- Towns sit in the land. A town used to be a round plate pressed flat into the hills; now its+ streets keep the long roll of the hillside under them and the easing fades out past the last+ house. Trees grow in thickets with glades between them, every player has a stand of trees of his+ own near home, and no rock sits on a ramp that is the only way up.+- The computer attacks on every one of them. The roads it sends its armies down started about+ twenty steps to the side of the base they belonged to, and some of the side roads ended in a lake+ bed. Every road now leaves from its own base and runs over ground a tank can drive.- Nobody starts with their back against the edge of the map. A seventh of the map is kept clearof start positions on every side: there is ground behind a base to fall back into, and a wayround it for whoever is attacking. On a packed map the seats sit on a circle so the lastdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.hindex ef173757b..86769267e 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h@@ -34,7 +34,7 @@rather than desyncing partway through it. The fingerprint test intest_gameengine.cpp fails until the version and the recorded CRCs agree, sothe bump cannot be forgotten. */-#define RANDOM_MAP_GENERATOR_VERSION 11+#define RANDOM_MAP_GENERATOR_VERSION 12/// How much ground the map gives everybody, before the per-player share.enum RandomMapSizediff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cppindex b56735741..d2bb1dd08 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp@@ -91,12 +91,11 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;/* Rolling ground is the default, the way Twilight Flame is built: hills a unit can drive, not astack of tables. A second field cuts valleys, and only the peaks of a third field still siton a shelf, so some high ground drops off as a cliff and the rest of the map keeps its slope.- A shelf still uses this step so a peak that does flatten is steep enough at the rim. */+ A shelf still uses this step so a peak that does flatten is steep enough at the rim. How deep+ the valleys cut and where the shelves start is the map type's (theMapTypes). */#define RMG_TERRACE_STEP 24.0f ///< height bytes; a cliff needs a span of more than 15.7#define RMG_TERRACE_DETAIL 7.0f ///< bytes of roll on the ground, shelves included#define RMG_DETAIL_FEATURES 16.0f-#define RMG_VALLEY_DROP 34.0f ///< height bytes a canyon field can cut at its deepest-#define RMG_SHELF_RIDGE 0.42f ///< ridge noise above this may flatten into a shelf// Water. Basins flood the lowest pockets the noise left, following the valleys rather than// stamping a wobbly circle, and a stream is walked downhill from a high trough to join them.@@ -115,6 +114,8 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;#define RMG_LAKE_MIN_CELLS 96#define RMG_LAKE_AREA 0.012f ///< fraction of playable*playable each basin may drown#define RMG_LAKE_FILL_RISE 18.0f ///< height bytes a basin may climb from its seed+#define RMG_LAKE_EDGE_BAND 14.0f ///< cells inside the water margin where a basin climbs a false slope+#define RMG_LAKE_EDGE_RISE 30.0f ///< height bytes that slope adds at the margin itself#define RMG_LAKE_MIN_FILL 80 ///< cells; smaller is a puddle and is thrown back#define RMG_RIVER_MIN_LENGTH 36 ///< downhill steps before a stream counts#define RMG_POLYGON_MAX 96 ///< sides written into the water area@@ -128,6 +129,13 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;#define RMG_START_ROUGHNESS 2.6f ///< height bytes a base site may vary by, on average#define RMG_CIRCLE_PLAYERS 6 ///< this many seats and the starts sit on a ring#define RMG_CIRCLE_RADIUS 0.36f ///< fraction of the playable size, from the centre+#define RMG_START_RING_TURNS 6 ///< rotations of the ring tried within one seat's arc+#define RMG_START_RING_SIZES 2 ///< ring radii tried, each this much smaller than the last+#define RMG_START_RING_STEP 0.02f+#define RMG_START_CLOSE_COST 1.0f ///< score a layout loses for each share its closest pair gives up+#define RMG_START_CLIFF_COST 30 ///< flat steps a cliff cell is worth when seats are compared: the ring routes go a long way round one+#define RMG_START_NUDGES 4 ///< seat moves tried on the chosen layout+#define RMG_START_NUDGE_CELLS 12.0f ///< and how far one may go// Money. One dock beside each base, one more out where it has to be fought// over, and two oil derricks a player somewhere in between.@@ -140,6 +148,13 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;#define RMG_PILE_PAD 2.0f#define RMG_PILE_BLEND 5.0f#define RMG_SITE_CLEARANCE 7.0f ///< cells kept clear around anything placed+#define RMG_MONEY_WALK_STRETCH 1.1f ///< walk cells per straight-line cell a money ring is aimed at+#define RMG_MONEY_LEAD 8 ///< cells of walk a player's own money is ahead of every rival+#define RMG_MONEY_NO_RIVAL 1000000 ///< the lead of a cell no other start can walk to+#define RMG_CONTESTED_LEAD_MIN 2 ///< a contested dock is this many cells nearer its placer+#define RMG_CONTESTED_LEAD_MAX 6 ///< and no more, so it is still the neighbour's fight+#define RMG_ROUTE_LOCK_HALF_WIDTH 2 ///< cells either side of a start-to-money walk no later pad levels+#define RMG_MONEY_WALK_SLACK 4 ///< walk cells the finished map may add to a money walk before it is cut short/* Anything that stands on the ground gets the ground levelled under it first. A supply dock on aterrace edge is a dock with one corner in the air, and the game will not let a player build@@ -160,10 +175,15 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;#define RMG_TOWN_SET_BACK_MIN 5.0f ///< cells from the street centre to a building front#define RMG_TOWN_SET_BACK_MAX 8.0f#define RMG_TOWN_GAP_IN_100 22 ///< plots left empty, so a street has yards and corners+#define RMG_TOWN_EDGE_GAP_IN_100 45 ///< and this many more at the town's radius, fewer inside it+#define RMG_TOWN_LOT_PAD 3.0f ///< cells levelled under a building+#define RMG_TOWN_LOT_BLEND 7.0f+#define RMG_TOWN_GRADE_MARGIN 4.0f ///< cells of graded ground kept past the outermost frontage+#define RMG_TOWN_GRADE_FADE 14.0f ///< cells the grading eases back into the hills over+#define RMG_TOWN_GRADE_BLUR 9 ///< cells either side the ground is averaged over#define RMG_TOWN_JITTER 2.0f ///< cells a building sits off its own frontage line#define RMG_TOWN_DRY_MARGIN 4.0f ///< cells a building or a street keeps off the water-#define RMG_TOWN_ROAD "TwoLane"-+#define RMG_TOWN_REROLLS 6 ///< plans a map with no town yet tries for its last one// A street is laid in dry runs: what crosses water is dropped rather than driven into the lake.#define RMG_ROAD_STEP 2.0f ///< cells between two wet-or-dry samples along a segment#define RMG_ROAD_MIN_RUN 8.0f ///< shorter than this and the run is not worth a road@@ -173,11 +193,38 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;// Scenery. Counted against the ground rather than the players: a map twice the size wants four// times the trees, or a wood is a hedge with a field around it.-#define RMG_CELLS_PER_TREE 150.0f+#define RMG_CELLS_PER_TREE 60.0f ///< a ceiling the woods never reach, not the count+#define RMG_TREE_CELLS_EACH 110.0f ///< the most the woods field may plant: one tree to this many cells#define RMG_CELLS_PER_ROCK 2600.0f+#define RMG_ROCK_EDGE_CELLS 10 ///< no rock this close to the playable edge#define RMG_PROP_STRIDE 2#define RMG_FOREST_FEATURES 7.0f-#define RMG_FOREST_THRESHOLD 0.10f ///< of the forest field; under it, open ground+#define RMG_LANE_CLEAR 7 ///< cells either side of a route between bases that stay open+#define RMG_LANE_FRAME 18 ///< and out to here the woods thicken, so they line the route+#define RMG_LANE_FAR 40 ///< the lane distance field stops counting here+#define RMG_GROVE_RADIUS 7.0f ///< cells across a player's own stand of trees, from its middle+#define RMG_GROVE_DISTANCE 42.0f ///< cells from the start to that stand+#define RMG_GROVE_TREES 22++// A black forest: rides from each base to the middle and round the ring of bases, the rest trees.+#define RMG_RIDE_HALF_WIDTH 6.0f ///< cells either side of a ride's centre line kept clear+#define RMG_RIDE_WOBBLE 2.5f ///< cells the ride's edge wanders by+#define RMG_WOOD_CLUMP_SCALE 0.03f ///< of the clump field per cell: a thicket every thirty cells or so+#define RMG_WOOD_CLUMP_EDGE -0.05f ///< of the mixed field; under it, a glade between thickets+#define RMG_WOOD_BUDGET_CELLS 12.0f ///< ground cells per tree the budget allows++// A massif: the middle of the map lifted into a table with a cliff round it.+#define RMG_MASSIF_HEIGHT 44.0f ///< height bytes, almost two terrace steps+#define RMG_MASSIF_RADIUS 0.16f ///< fraction of the playable size, to the foot of the cliff+#define RMG_MASSIF_RIM 4.0f ///< cells the cliff takes from foot to top+#define RMG_MASSIF_WOBBLE 0.10f ///< share of the radius the outline wanders by+#define RMG_MASSIF_ROAD_TOP 3.0f ///< cells either side of a ramp's centre where it meets the top+#define RMG_MASSIF_ROAD_FOOT 6.0f ///< and where it meets the ground below, so the foot opens out+#define RMG_MASSIF_ROAD_BANK 4.0f ///< cells over which a ramp's sides ease back into the ground+#define RMG_MASSIF_ROAD_GRADE 3.0f ///< height bytes a ramp climbs per cell at most+#define RMG_MASSIF_ROAD_SIDE 2.0f ///< height bytes per cell a ramp's cut or fill banks out at+#define RMG_MASSIF_ROAD_WIDEST 8.0f ///< cells a bank may take at most, or a small map's rim is all ramp+#define RMG_MASSIF_ROCK_CLEAR 20.0f ///< cells round a ramp's middle that no rock stands in// What counts as a cliff. WorldHeightMap marks a cell impassable when its four// corners span more than this many world units (PATHFIND_CLIFF_SLOPE_LIMIT_F).@@ -186,6 +233,9 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;// bytes, which has to leave room under that span for the noise either side.#define RMG_PASS_MAX_STEP 8.0f#define RMG_PASS_HALF_WIDTH 2 ///< cells either side of the route that get cut+#define RMG_PASS_ROAD_SLOPE 3.0f ///< height bytes per cell the roadway may lean across+#define RMG_PASS_BANK_SLOPE 6.0f ///< and its banks, outside that+#define RMG_PASS_BANK_CELLS 6 ///< how far out a bank may reach#define RMG_PASS_ATTEMPTS 12//-----------------------------------------------------------------------------@@ -460,13 +510,130 @@ enum RMGTerrainClassRMG_TERRAIN_COUNT};-/// Index order matches RMGTerrainClass; the names are Terrain.ini's.-static const char *theTerrainClassNames[RMG_TERRAIN_COUNT] =+/* What kind of map a seed is. Each one bends the same height field, water and woods a different+ way, so the type reads off the overview before anybody looks at a start: plains are low and+ wooded with one pond and a stream, highlands stand on shelves, lake country spreads two more+ basins than usual and keeps them apart, a river map is cut in two with fords across it, and a+ canyon map has a few long gorges winding through it. A black forest is low ground under one+ wood from edge to edge, with clear rides cut through it from every base to the middle and round+ the ring of bases; trees do not stop a tank in this game, so the rides are the lanes an army+ can be seen in, not walls. A massif map lifts the middle into one table of high ground with a+ cliff all round it and a ramp up from each base's side. The starts, the money and every+ playability repair run the same on all of them. */+enum RMGMapType+{+ RMG_MAP_PLAINS = 0,+ RMG_MAP_HIGHLANDS,+ RMG_MAP_LAKES,+ RMG_MAP_RIVER,+ RMG_MAP_CANYON,+ RMG_MAP_FOREST,+ RMG_MAP_MASSIF,++ RMG_MAP_TYPE_COUNT+};++struct RMGMapTypeShape+{+ Real m_amplitude; ///< times RMG_AMPLITUDE+ Real m_valleyDrop; ///< height bytes the valley field cuts at its deepest+ Real m_gorgeWidth; ///< above zero: valleys are the thin band either side of the field's zero line+ Real m_shelfRidge; ///< ridge noise above this flattens into a shelf+ Int m_extraLakes; ///< basins on top of the usual one per two players, below zero fewer+ Real m_lakeArea; ///< times RMG_LAKE_AREA+ Bool m_river; ///< one river across the whole map, broken at fords, instead of a stream+ Real m_forestThreshold; ///< of the forest field; under it, open ground+ Bool m_woodland; ///< trees everywhere but the rides (RMG_RIDE_*)+ Real m_massif; ///< height bytes the middle of the map is lifted by, 0 for none+};++static const RMGMapTypeShape theMapTypes[RMG_MAP_TYPE_COUNT] =+{+ // amp valley gorge shelf lakes area river forest wood massif+ { 0.70f, 14.0f, 0.0f, 0.36f, -9, 0.7f, FALSE, 0.04f, FALSE, 0.0f }, // plains+ { 1.30f, 30.0f, 0.0f, 0.22f, -1, 0.8f, FALSE, 0.14f, FALSE, 0.0f }, // highlands+ { 0.85f, 30.0f, 0.0f, 0.42f, 2, 1.5f, FALSE, 0.12f, FALSE, 0.0f }, // lake country+ { 0.85f, 24.0f, 0.0f, 0.46f, -9, 1.0f, TRUE, 0.10f, FALSE, 0.0f }, // river and fords+ { 1.00f, 44.0f, 0.07f, 0.50f, -1, 0.8f, FALSE, 0.18f, FALSE, 0.0f }, // canyon+ { 0.60f, 12.0f, 0.0f, 0.50f, -9, 0.6f, FALSE, 0.0f, TRUE, 0.0f }, // black forest+ { 0.70f, 16.0f, 0.0f, 0.46f, -9, 0.7f, FALSE, 0.12f, FALSE, RMG_MASSIF_HEIGHT }, // massif+};++/* What the map is made of: the four ground textures in RMGTerrainClass order, the trees and rocks+ that stand on it, the street surface and the light. Every name is one Terrain.ini, Roads.ini or+ the object INI of the shipped game defines, and every texture is one the shipped terrain archives+ hold an image for. */+#define RMG_BIOME_TREES 4+#define RMG_BIOME_ROCKS 4++enum RMGBiomeKind+{+ RMG_BIOME_TEMPERATE = 0,+ RMG_BIOME_DESERT,+ RMG_BIOME_WINTER,+ RMG_BIOME_STEPPE,++ RMG_BIOME_COUNT+};++struct RMGBiome+{+ const char *m_textures[RMG_TERRAIN_COUNT];+ const char *m_trees[RMG_BIOME_TREES];+ const char *m_rocks[RMG_BIOME_ROCKS];+ const char *m_road;+ Real m_treeShare; ///< times the woods' planting chance+ Real m_terrainAmbient[3];+ Real m_terrainDiffuse[3];+ Real m_objectAmbient[3];+ Real m_objectDiffuse[3];+ Real m_sunDirection[3]; ///< x and y point the sun across the map, z takes it down+ UnsignedByte m_previewColours[RMG_TERRAIN_COUNT][3];+};++static const RMGBiome theBiomes[RMG_BIOME_COUNT] ={- "GrassType1",- "SandLargeType1",- "DirtType1",- "RocksType1"+ { // temperate: green fields, brown high ground+ { "GrassType1", "SandLargeType1", "DirtType1", "RocksType1" },+ { "TreeOak01", "TreeMaple1", "TreeDogwood1", "TreeFir01B" },+ { "Rocks1", "Rocks2", "RockClusterMedium01", "RockClusterSmall01" },+ "TwoLane", 1.0f,+ { 0.35f, 0.35f, 0.36f }, { 0.78f, 0.75f, 0.68f },+ { 0.45f, 0.45f, 0.47f }, { 0.82f, 0.79f, 0.72f },+ { -0.58f, 0.42f, -0.70f },+ { { 86, 122, 62 }, { 190, 176, 130 }, { 132, 112, 74 }, { 118, 118, 112 } }+ },+ { // desert: open sand, wet sand at the water, pale dirt on top, palms in thin stands+ { "SandLargeType2", "SandType3wet", "DirtMediumType3", "RocksType3" },+ { "TreePalm1", "TreePalm2", "TreePalm1short", "TreePalm2short" },+ { "Rocks1Brown", "Rocks2Brown", "Rocks3Brown", "RockClusterSmall01" },+ "TwoLaneOld", 0.35f,+ { 0.40f, 0.37f, 0.32f }, { 0.92f, 0.84f, 0.66f },+ { 0.50f, 0.47f, 0.42f }, { 0.95f, 0.88f, 0.72f },+ { -0.45f, 0.30f, -0.84f },+ { { 214, 190, 140 }, { 168, 138, 88 }, { 196, 172, 132 }, { 140, 132, 118 } }+ },+ { // winter: snow, slush at the water, deep snow on the heights, snowed-in firs+ { "SnowType1", "DirtSnowType1", "SnowLargeType1", "RocksMediumType1Snow" },+ { "TreeFir06Snow", "TreeFir07Snow", "TreePine4snow", "TreeSpruceSnow" },+ { "RockClusterSmallSnow01", "RockClusterMediumSnow01", "RockClusterLargeSnow01",+ "RockClusterSmallSnow01" },+ "TwoLaneOld2Snow", 1.0f,+ { 0.40f, 0.42f, 0.48f }, { 0.74f, 0.78f, 0.86f },+ { 0.48f, 0.50f, 0.55f }, { 0.78f, 0.80f, 0.88f },+ { -0.62f, 0.48f, -0.62f },+ { { 222, 226, 230 }, { 140, 132, 122 }, { 244, 246, 250 }, { 120, 124, 130 } }+ },+ { // steppe: dry golden ground, grassy sand at the water, red gravel hills, turning oaks+ { "DirtMediumType8", "SandMediumType7Grassy", "DirtType2", "RocksType1" },+ { "TreeOakFall1", "TreeOakFall3", "TreeOakFall5", "TreeBirch02" },+ { "Rocks1Brown", "Rocks3Brown", "RockClusterMedium01", "Rocks2" },+ "TwoLaneOld3", 0.75f,+ { 0.37f, 0.33f, 0.29f }, { 0.88f, 0.74f, 0.54f },+ { 0.46f, 0.42f, 0.38f }, { 0.90f, 0.78f, 0.60f },+ { -0.70f, 0.40f, -0.59f },+ { { 186, 150, 92 }, { 196, 176, 120 }, { 150, 96, 60 }, { 118, 118, 112 } }+ },};struct RMGPoint@@ -494,6 +661,14 @@ struct RMGObject#define RMG_FLAG_ROAD_POINT1 0x00000002#define RMG_FLAG_ROAD_POINT2 0x00000004+/// A spot flat and dry enough for a base, found before any seat is chosen.+struct RMGStartCandidate+{+ Real m_cellX;+ Real m_cellY;+ Real m_roughness;+};+/** The shape one town was rolled to be: how many streets it has each way, where each one runs inthe town's own coordinates, how deep its plots are and which way the whole grid is turned. It isrolled before a site is looked for, because the search needs the radius to keep the streets@@ -617,6 +792,17 @@ struct RMGSiteReal m_radius;};+/// A player's own money and the walk it was placed at, so the finished map can be held to it.+struct RMGMoneyWalk+{+ Int m_player;+ Int m_rival; ///< for a contested dock, the neighbour it has to stay further from; else -1+ Int m_object; ///< and the dock's index in m_objects+ Int m_cellX; ///< map cells, border included+ Int m_cellY;+ Int m_walk;+};+/** Everything derived from the settings, in one place, so the map bytes and thepreview tga are two views of the same layout rather than two guesses at it. */class RMGLayout@@ -631,15 +817,20 @@ public:Bool underwaterAtCell( Int x, Int y ) const;RandomMapSettings m_settings;+ const RMGMapTypeShape *m_type; ///< what kind of map the seed rolled+ const RMGBiome *m_biome; ///< and what it is made ofInt m_width; ///< map cells per side, border includedInt m_height;Real m_waterHeight; ///< height bytes; the surface of every lakestd::vector<RMGPoint> m_starts;std::vector<UnsignedByte> m_heights;+ std::vector<UnsignedByte> m_landHeights; ///< the height field eased onto its floor, swapped in once the lakes are grownstd::vector<UnsignedByte> m_terrain;std::vector<Short> m_blendIndex; ///< into m_blends, 0 for a cell with no blendstd::vector<char> m_passable;std::vector<RMGLake> m_lakes;+ std::vector<RMGPoint> m_riverLine; ///< a river map's centre line, inside the water margin+ Real m_riverAngle; ///< and the way it runsstd::vector<RMGObject> m_objects;std::vector< std::pair<Int, Int> > m_waypointLinks; ///< waypointID to waypointID, for WaypointsList@@ -659,17 +850,31 @@ public:private:void buildHeights( const UnsignedByte perm[512] );void placeLakes( const UnsignedByte perm[512] );- void growBasin( Int seedX, Int seedY, Int targetCells, Real fillRise, std::vector<Int> *painted );+ void growBasin( const UnsignedByte perm[512], Int seedX, Int seedY, Int targetCells, Real fillRise,+ std::vector<Int> *painted );+ Real lakeEdgeRise( const UnsignedByte perm[512], Int mapX, Int mapY ) const;void paintRiver( const UnsignedByte perm[512] );+ void paintMainRiver( const UnsignedByte perm[512] );+ void paintRiverStretches( const std::vector<Int>& fords );+ void openFordsAtStarts( const std::vector<UnsignedByte>& uncarved );void extractLakePolygons( void );- void buildShoreDistance( void );+ void buildShoreDistance( std::vector<Real> &dist, Bool straight ) const;Bool waterAllowedAt( Int mapX, Int mapY ) const;void carveLakeBasins( void );void buildLakeMask( void );void chooseStarts( void );+ void searchStarts( const std::vector<RMGStartCandidate>& candidates );+ void ringStarts( const std::vector<RMGStartCandidate>& candidates, Real angle, Real ring, Real edgeRing );+ void startWalks( const std::vector<Int>& cost, std::vector<Int>& walks ) const;+ static Real walkSpread( const std::vector<Int>& walks, Int *nearLowOut );+ void nudgeStarts( const std::vector<RMGStartCandidate>& candidates, const std::vector<Int>& cost, Int farthest );void flattenBases( void );void buildPassability( void );void connectStarts( void );+ Real massifClearance( Real cellX, Real cellY ) const;+ void carveMassifRamps( void );+ Real rideDistance( Real cellX, Real cellY ) const;+ Bool nearRamp( Real cellX, Real cellY, Real radius ) const;Bool carvePass( Int fromStart, Int toStart );Bool carvePassBetweenCells( Int fromX, Int fromY, Int toX, Int toY, Bool recordRamp,Real protectRadius, Real protectX, Real protectY );@@ -677,11 +882,16 @@ private:Real protectRadius, Real protectX, Real protectY );Bool carveStraightCorridor( Int fromX, Int fromY, Int toX, Int toY,Real protectRadius, Real protectX, Real protectY );+ void cutTowardLevel( Int x, Int y, Real level, Bool skipLake,+ Real protectRadius, Real protectX, Real protectY );+ void gradeTown( Real centreX, Real centreY, const RMGTownPlan& plan,+ Real acrossStart, Real acrossEnd, Real downStart, Real downEnd );Bool playableAtCell( Int x, Int y ) const;Int ringCrossings( Int startIndex ) const;void floodPlayableFrom( Int startIndex );Bool openSecondExit( Int startIndex );void ensurePlayability( void );+ void holdMoneyWalks( void );void startPerimeterToward( Int startIndex, Int targetX, Int targetY, Int *outX, Int *outY ) const;void buildTerrainClasses( const UnsignedByte perm[512] );void buildBlends( void );@@ -694,6 +904,12 @@ private:void placeBunkers( void );void placeShoreWaves( void );void placeScenery( const UnsignedByte perm[512] );+ Bool stepDownFlood( const std::vector<Int>& dist, Int *x, Int *y, Real fromX, Real fromY,+ Real toX, Real toY ) const;+ void buildLaneDistance( void );+ Int laneDistanceAt( Real cellX, Real cellY ) const;+ Bool sceneryMayStand( Real cellX, Real cellY ) const;+ void plantGroves( const char *const *theTreeNames, Int *propID, Int *treeBudget );void flattenPad( Real cellX, Real cellY, Real radius, Real blend );void addRoad( Real fromX, Real fromY, Real toX, Real toY );void addRoadClipped( Real fromX, Real fromY, Real toX, Real toY );@@ -716,6 +932,12 @@ private:Real outwardBearing( Real cellX, Real cellY ) const;Bool findContestedSite( Int startA, Int startB, Real minWalk, Real clearance, RMGPoint *out ) const;void floodDistancesFromCell( Int startX, Int startY, std::vector<Int>& dist ) const;+ void walkFromStarts( std::vector< std::vector<Int> >& walk, std::vector<Int>& owner,+ std::vector<Int>& lead );+ Bool findSiteByWalk( const std::vector< std::vector<Int> >& walk, const std::vector<Int>& owner,+ const std::vector<Int>& lead, Int player, Int target, Int band, Int minLead,+ Int maxLead, Real bearing, Real clearance, RMGPoint *out ) const;+ void lockRoute( const std::vector<Int>& walk, const RMGPoint& site );void reserveSite( Real cellX, Real cellY, Real radius );void addObject( const char *templateName, const char *uniqueID, Real cellX, Real cellY,Real angle );@@ -723,11 +945,27 @@ private:std::map<Int, Short> m_blendLookup; ///< tile and shape to the table entry that holds themstd::vector<RMGSite> m_sites; ///< everything placed so far, with its elbow room+ std::vector<char> m_routeLock; ///< cells on a walk to somebody's money, which pads leave alone+ std::vector<char> m_baseLevelled; ///< cells a base blend has touched+ std::vector<UnsignedByte> m_baseUnder; ///< and the ground it blended there+ std::vector<UnsignedByte> m_baseResult; ///< and what it left, so a second levelling can tell+ std::vector<RMGMoneyWalk> m_moneyWalks; ///< every walked placement of a player's own moneystd::vector<RMGPoint> m_ramps; ///< where a carved route changed layer, for the bunkersstd::vector<char> m_inLake; ///< cells the basins drowned, whatever the ground doesstd::vector<Real> m_shoreDist; ///< signed cells to shore: negative in the waterstd::vector<char> m_visited; ///< scratch for the flood fillInt m_startSearchStride;++ /** The ground route from one start to another, as map cell indices from the first, the way the+ "Center" attack path walks it. The woods are laid out against these. */+ struct RMGLane+ {+ Int m_from;+ Int m_to;+ std::vector<Int> m_cells;+ };+ std::vector<RMGLane> m_lanes;+ std::vector<UnsignedByte> m_laneDist; ///< cells to the nearest route, capped at RMG_LANE_FAR};//-----------------------------------------------------------------------------@@ -748,6 +986,7 @@ void RMGLayout::buildHeights( const UnsignedByte perm[512] )Real ridgeScale = scale * 2.2f;m_heights.resize( m_width * m_height );+ m_landHeights.resize( m_width * m_height );for( Int y = 0; y < m_height; y++ ){@@ -760,36 +999,111 @@ void RMGLayout::buildHeights( const UnsignedByte perm[512] )Real warpY = py + RMG_WARP_STRENGTH * fractalNoise( perm, px - 3.7f, py + 8.1f, 3 );Real raw = RMG_BASE_HEIGHT- + RMG_AMPLITUDE * fractalNoise( perm, warpX, warpY, RMG_OCTAVES );+ + RMG_AMPLITUDE * m_type->m_amplitude * fractalNoise( perm, warpX, warpY, RMG_OCTAVES );Real cellX = (Real)(x - RMG_BORDER_CELLS);Real cellY = (Real)(y - RMG_BORDER_CELLS);- Real valley = fractalNoise( perm, cellX * valleyScale + 13.0f,- cellY * valleyScale - 21.0f, 3 );- if( valley < -0.22f )+ /* The massif goes in before the valleys and is spared by them, so its top is one table+ and not a table with the valley field's ditches through it. The outline wanders with a+ noise read off the bearing from the middle, which keeps it one closed shape. */+ Real massif = 0.0f;+ if( m_type->m_massif > 0.0f )+ {+ Real dx = cellX - playable * 0.5f;+ Real dy = cellY - playable * 0.5f;+ Real r = sqrtf( dx * dx + dy * dy );+ Real foot = playable * RMG_MASSIF_RADIUS;+ if( r < foot * ( 1.0f + RMG_MASSIF_WOBBLE ) + 1.0f )+ {+ Real ux = ( r > 0.5f ) ? dx / r : 0.0f;+ Real uy = ( r > 0.5f ) ? dy / r : 0.0f;+ foot *= 1.0f + RMG_MASSIF_WOBBLE * fractalNoise( perm, ux * 1.7f + 41.0f, uy * 1.7f - 37.0f, 2 );+ Real t = ( foot - r ) / RMG_MASSIF_RIM;+ if( t > 1.0f ) t = 1.0f;+ if( t > 0.0f )+ massif = fadeCurve( t );+ }+ // One table at one height, with a quarter of the roll left on it, so the cliff stands+ // all the way round and not only where the ground outside happens to be low.+ Real table = RMG_BASE_HEIGHT + m_type->m_massif + 0.25f * ( raw - RMG_BASE_HEIGHT );+ if( table < raw + 20.0f )+ table = raw + 20.0f; // a hill under the table still ends up under it+ raw = lerpReal( raw, table, massif );+ }++ if( m_type->m_gorgeWidth > 0.0f )+ {+ /* At two fifths of the valley field's frequency and two octaves: a few long+ canyons that bend, not a maze. A third octave put a wiggle and a small closed loop+ on every stretch of the zero line, and each one drew two more cliff ribbons. */+ Real valley = fractalNoise( perm, cellX * valleyScale * 0.4f + 13.0f,+ cellY * valleyScale * 0.4f - 21.0f, 2 );+ /* A gorge is the thin band along the field's zero line, which winds and forks across+ the whole map the way a canyon system does, where the low tail of the field only+ ever makes separate hollows. The fade keeps a flat floor and a flat rim with the+ drop between them, so a wall is steep at its middle and drivable at both ends. A+ slower field decides where the zero line is a canyon at all, so a gorge runs out+ into open ground instead of every branch of the line being cut. */+ Real off = fabsf( valley );+ if( off < m_type->m_gorgeWidth )+ {+ Real reach = fractalNoise( perm, cellX * valleyScale * 0.2f - 41.0f,+ cellY * valleyScale * 0.2f + 7.0f, 2 );+ Real depth = ( reach + 0.24f ) / 0.24f;+ if( depth < 0.0f ) depth = 0.0f;+ if( depth > 1.0f ) depth = 1.0f;+ raw -= fadeCurve( 1.0f - off / m_type->m_gorgeWidth ) * fadeCurve( depth )+ * m_type->m_valleyDrop;+ }+ }+ else{- Real cut = ( -0.22f - valley ) / 0.78f;- raw -= cut * cut * RMG_VALLEY_DROP;+ Real valley = fractalNoise( perm, cellX * valleyScale + 13.0f,+ cellY * valleyScale - 21.0f, 3 );+ if( massif > 0.0f )+ valley = lerpReal( valley, 0.0f, massif );+ if( valley < -0.22f )+ {+ Real cut = ( -0.22f - valley ) / 0.78f;+ raw -= cut * cut * m_type->m_valleyDrop;+ }}Real ridge = fractalNoise( perm, cellX * ridgeScale + 19.0f,cellY * ridgeScale - 8.0f, 3 );Real shelf = 0.0f;- if( ridge > RMG_SHELF_RIDGE )- shelf = ( ridge - RMG_SHELF_RIDGE ) / ( 1.0f - RMG_SHELF_RIDGE );+ if( ridge > m_type->m_shelfRidge )+ shelf = ( ridge - m_type->m_shelfRidge ) / ( 1.0f - m_type->m_shelfRidge );shelf = shelf * shelf * shelf;Real layer = floorf( raw / RMG_TERRACE_STEP ) * RMG_TERRACE_STEP;Real h = lerpReal( raw, layer, shelf );- h += RMG_TERRACE_DETAIL * fractalNoise( perm, (Real)x * detailScale + 61.0f,- (Real)y * detailScale - 29.0f, 2 );+ /* Ground under the lake bank used to be lifted to the bank once the lakes were carved,+ and on a highland map a fifth of the playable area came out as one dead flat sheet at+ that height. The land is eased onto a floor instead, keeping the full slope down to+ softFloor + softRange and a falling share of it below, so a valley bottom still rolls+ and the detail on top of it never reaches under the bank. The lakes are still grown on+ the field without the floor: on the eased ground every low pocket is within a basin's+ climb of every other, and the water spread over whole valleys. */+ Real softFloor = m_waterHeight + RMG_LAKE_BANK + 5.0f;+ Real softRange = 16.0f;+ Real eased = h;+ if( eased < softFloor + softRange )+ eased = softFloor + softRange / ( 1.0f + ( softFloor + softRange - eased ) / softRange );++ Real detail = RMG_TERRACE_DETAIL * fractalNoise( perm, (Real)x * detailScale + 61.0f,+ (Real)y * detailScale - 29.0f, 2 );+ h += detail;+ eased += detail;if( h < 1.0f ) h = 1.0f;if( h > 254.0f ) h = 254.0f;+ if( eased > 254.0f ) eased = 254.0f;m_heights[cellIndex( x, y )] = (UnsignedByte)(h + 0.5f);+ m_landHeights[cellIndex( x, y )] = (UnsignedByte)(eased + 0.5f);}}}@@ -902,17 +1216,52 @@ Bool RMGLayout::waterAllowedAt( Int mapX, Int mapY ) constreturn TRUE;}+/** Height bytes a basin pretends the ground rises by near the edge of the water margin. A flood+ that ran into the margin itself stopped on it, and the lake came out cut along a ruled line+ parallel to the map border. Against this slope it stops on a contour of the ground plus the+ slope instead, and the noise on the band's width keeps that contour from running parallel to+ the border on flat ground. */+Real RMGLayout::lakeEdgeRise( const UnsignedByte perm[512], Int mapX, Int mapY ) const+{+ Int px = mapX - RMG_BORDER_CELLS;+ Int py = mapY - RMG_BORDER_CELLS;+ Int last = m_settings.m_playableCells - 1;+ Int edge = px;+ if( py < edge ) edge = py;+ if( last - px < edge ) edge = last - px;+ if( last - py < edge ) edge = last - py;++ Real inside = (Real)edge - RMG_LAKE_SHORE;+ if( inside >= RMG_LAKE_EDGE_BAND + 6.0f )+ return 0.0f;++ inside += 6.0f * fractalNoise( perm, (Real)px * 0.06f - 71.0f, (Real)py * 0.06f + 37.0f, 2 );+ if( inside >= RMG_LAKE_EDGE_BAND )+ return 0.0f;+ if( inside < 0.0f )+ inside = 0.0f;++ Real t = 1.0f - inside / RMG_LAKE_EDGE_BAND;+ return t * t * RMG_LAKE_EDGE_RISE;+}+/** Signed cells to the nearest shore, from the basin mask. Negative is water. Built once so- every later test is a bilinear sample instead of a walk of the polygons. */-void RMGLayout::buildShoreDistance( void )+ every later test is a bilinear sample instead of a walk of the polygons.++ Both measures are a two-pass chamfer. The city-block one is what the starts, the pads and the+ money were tuned on and stays theirs. The straight one, over the 5x5 neighbourhood and within+ two percent of the true distance in every direction, is what the beach is cut from: in city+ blocks the contours of a shore running at forty-five degrees are staircases, and a beach that+ climbs fifty height bytes in ten cells came out as a stack of one-cell terraces, each step a+ rock-textured stripe down the slope. */+void RMGLayout::buildShoreDistance( std::vector<Real> &dist, Bool straight ) const{const Int n = m_width * m_height;- m_shoreDist.assign( n, 1.0e9f );+ dist.assign( n, 1.0e9f );if( m_inLake.empty() )return;- std::vector<Int> queue;static const Int offsetX[4] = { 1, -1, 0, 0 };static const Int offsetY[4] = { 0, 0, 1, -1 };@@ -939,43 +1288,47 @@ void RMGLayout::buildShoreDistance( void )if( !shore )continue;- m_shoreDist[index] = 0.0f;- queue.push_back( index );+ dist[index] = 0.0f;}}- UnsignedInt head = 0;- while( head < queue.size() )+ // The half of the 5x5 neighbourhood that comes before a cell in raster order, the two axis+ // steps first; the backward pass reads the same offsets negated.+ static const Int chamferX[8] = { -1, 0, -1, 1, -1, 1, -2, 2 };+ static const Int chamferY[8] = { 0, -1, -1, -1, -2, -2, -1, -1 };+ static const Real chamferCost[8] = { 1.0f, 1.0f, 1.41421356f, 1.41421356f,+ 2.23606798f, 2.23606798f, 2.23606798f, 2.23606798f };+ Int taps = straight ? 8 : 2;+ for( Int pass = 0; pass < 2; pass++ ){- Int index = queue[head++];- Int x = index % m_width;- Int y = index / m_width;- Real here = m_shoreDist[index];-- for( Int i = 0; i < 4; i++ )+ Int sign = pass == 0 ? 1 : -1;+ for( Int step = 0; step < n; step++ ){- Int nx = x + offsetX[i];- Int ny = y + offsetY[i];- if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )- continue;-- Int next = cellIndex( nx, ny );- Real step = here + 1.0f;- if( step >= m_shoreDist[next] )- continue;-- m_shoreDist[next] = step;- queue.push_back( next );+ Int index = pass == 0 ? step : n - 1 - step;+ Int x = index % m_width;+ Int y = index / m_width;+ Real best = dist[index];+ for( Int i = 0; i < taps; i++ )+ {+ Int nx = x + sign * chamferX[i];+ Int ny = y + sign * chamferY[i];+ if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )+ continue;+ Real through = dist[cellIndex( nx, ny )] + chamferCost[i];+ if( through < best )+ best = through;+ }+ dist[index] = best;}}for( Int i = 0; i < n; i++ ){- Real d = m_shoreDist[i];+ Real d = dist[i];if( m_inLake[i] )- m_shoreDist[i] = -( d + 0.5f );+ dist[i] = -( d + 0.5f );else- m_shoreDist[i] = d + 0.5f;+ dist[i] = d + 0.5f;}}@@ -984,7 +1337,7 @@ void RMGLayout::buildLakeMask( void )if( m_inLake.empty() )m_inLake.assign( m_width * m_height, 0 );- buildShoreDistance();+ buildShoreDistance( m_shoreDist, FALSE );}Bool RMGLayout::underwaterAtCell( Int x, Int y ) const@@ -995,8 +1348,8 @@ Bool RMGLayout::underwaterAtCell( Int x, Int y ) const/** Lowest-first flood from a seed. The open list is the basin's rim ordered by height, so thewater follows the valley and stops at a ridge instead of growing into a circle. */-void RMGLayout::growBasin( Int seedX, Int seedY, Int targetCells, Real fillRise,- std::vector<Int> *painted )+void RMGLayout::growBasin( const UnsignedByte perm[512], Int seedX, Int seedY, Int targetCells,+ Real fillRise, std::vector<Int> *painted ){painted->clear();if( !waterAllowedAt( seedX, seedY ) )@@ -1032,7 +1385,11 @@ void RMGLayout::growBasin( Int seedX, Int seedY, Int targetCells, Real fillRise,static const Int offsetX[4] = { 1, -1, 0, 0 };static const Int offsetY[4] = { 0, 0, 1, -1 };- while( !open.empty() && (Int)painted->size() < targetCells )+ /* A cell the edge slope turns away still counts against the basin's size, so a lake that runs+ into the margin ends there smaller rather than spilling the cells it lost back into the+ middle of the map, where they would sit between two starts. */+ Int edgeTurned = 0;+ while( !open.empty() && (Int)painted->size() + edgeTurned < targetCells ){std::pop_heap( open.begin(), open.end() );RMGBasinCell cheapest = open.back();@@ -1044,8 +1401,13 @@ void RMGLayout::growBasin( Int seedX, Int seedY, Int targetCells, Real fillRise,Int x = index % m_width;Int y = index / m_width;- if( (Real)m_heights[index] > maxH )+ if( (Real)cheapest.m_cost > maxH )+ continue;+ if( !painted->empty() && (Real)cheapest.m_cost + lakeEdgeRise( perm, x, y ) > maxH )+ {+ edgeTurned++;continue;+ }m_inLake[index] = 1;painted->push_back( index );@@ -1237,6 +1599,127 @@ void RMGLayout::paintRiver( const UnsignedByte perm[512] )}}+/** A river map's river: one band of water through the middle of the map from one side to the+ other, at one of eight angles the seed picks, wandering either side of its line. Both ends stop+ at the margin every lake keeps off the map edge, so the ends are ways across. It goes in unbroken+ here; the fords are cut once the starts are known (openFordsAtStarts). */+void RMGLayout::paintMainRiver( const UnsignedByte perm[512] )+{+ Int playable = m_settings.m_playableCells;+ Real centre = (Real)playable * 0.5f;+ m_riverAngle = (Real)(hashCell( m_settings.m_seed, 9001, 41 ) % 8U) * (PI * 0.125f);+ Real alongX = Cos( m_riverAngle );+ Real alongY = Sin( m_riverAngle );+ Real wander = (Real)playable * 0.07f;++ m_riverLine.clear();+ for( Int step = -playable; step <= playable; step++ )+ {+ Real t = (Real)step;+ Real side = wander * fractalNoise( perm, t * 0.011f + 7.5f, 3.25f, 2 );++ RMGPoint p;+ p.m_cellX = centre + alongX * t - alongY * side;+ p.m_cellY = centre + alongY * t + alongX * side;+ Int mapX = (Int)floorf( p.m_cellX + 0.5f ) + RMG_BORDER_CELLS;+ Int mapY = (Int)floorf( p.m_cellY + 0.5f ) + RMG_BORDER_CELLS;+ if( !waterAllowedAt( mapX, mapY ) )+ continue;+ m_riverLine.push_back( p );+ }++ std::vector<Int> noFords;+ paintRiverStretches( noFords );+}++/** Paint the river along its line, leaving dry the steps either side of each ford's index. The+ basin carve turns each gap into a low crossing between two beaches, and every stretch between+ two fords is a water area of its own. */+void RMGLayout::paintRiverStretches( const std::vector<Int>& fords )+{+ Real half = 4.0f + (Real)m_settings.m_playableCells * 0.012f;+ Real fordHalf = half + 7.0f; ///< steps either side of a ford's middle left dry+ const std::vector<RMGPoint>& line = m_riverLine;++ Int n = (Int)line.size();+ Int reach = (Int)( half + 0.5f );+ Int radiusSq = (Int)( half * half + 0.5f );++ for( Int i = 0; i < n; i++ )+ {+ Bool atAFord = FALSE;+ for( UnsignedInt ford = 0; ford < fords.size(); ford++ )+ {+ if( fabsf( (Real)( i - fords[ford] ) ) < fordHalf )+ atAFord = TRUE;+ }+ if( atAFord )+ continue;++ Int cx = (Int)floorf( line[i].m_cellX + 0.5f ) + RMG_BORDER_CELLS;+ Int cy = (Int)floorf( line[i].m_cellY + 0.5f ) + RMG_BORDER_CELLS;+ for( Int dy = -reach; dy <= reach; dy++ )+ {+ for( Int dx = -reach; dx <= reach; dx++ )+ {+ if( dx * dx + dy * dy > radiusSq )+ continue;+ if( !waterAllowedAt( cx + dx, cy + dy ) )+ continue;+ m_inLake[cellIndex( cx + dx, cy + dy )] = 1;+ }+ }+ }+}++/** The fords go where the starts are: one at the point of the river nearest each start, two+ that land close together made one. A seat on the ring and its mirror on the far bank share a+ ford, so nobody's way across is further than anybody else's. The river is repainted with the+ gaps and the basin carved again from the ground as it stood before the first carve. */+void RMGLayout::openFordsAtStarts( const std::vector<UnsignedByte>& uncarved )+{+ if( !m_type->m_river || m_riverLine.empty() )+ return;++ Real fordHalf = 4.0f + (Real)m_settings.m_playableCells * 0.012f + 7.0f;+ std::vector<Int> nearest;+ for( UnsignedInt s = 0; s < m_starts.size(); s++ )+ {+ Int best = 0;+ Real bestDistance = 1.0e9f;+ for( UnsignedInt i = 0; i < m_riverLine.size(); i++ )+ {+ Real dx = m_riverLine[i].m_cellX - m_starts[s].m_cellX;+ Real dy = m_riverLine[i].m_cellY - m_starts[s].m_cellY;+ Real distance = dx * dx + dy * dy;+ if( distance < bestDistance )+ {+ bestDistance = distance;+ best = (Int)i;+ }+ }+ nearest.push_back( best );+ }+ std::sort( nearest.begin(), nearest.end() );++ std::vector<Int> fords;+ UnsignedInt first = 0;+ for( UnsignedInt i = 1; i <= nearest.size(); i++ )+ {+ if( i < nearest.size() && (Real)( nearest[i] - nearest[first] ) < fordHalf * 2.0f )+ continue;+ fords.push_back( ( nearest[first] + nearest[i - 1] ) / 2 );+ first = i;+ }++ m_inLake.assign( m_width * m_height, 0 );+ paintRiverStretches( fords );+ extractLakePolygons();+ buildLakeMask();+ m_heights = uncarved;+ carveLakeBasins();+}+static Int rmgVertexKey( Int x, Int y ){return ( y << 16 ) | ( x & 0xFFFF );@@ -1533,14 +2016,20 @@ void RMGLayout::placeLakes( const UnsignedByte perm[512] )m_lakes.clear();m_inLake.assign( m_width * m_height, 0 );m_shoreDist.clear();+ m_riverLine.clear();+ m_riverAngle = 0.0f;if( m_settings.m_playableCells < RMG_LAKE_MIN_CELLS )return;Int playable = m_settings.m_playableCells;- Int wanted = ( m_settings.m_numPlayers + 2 ) / 2;+ Int wanted = ( m_settings.m_numPlayers + 2 ) / 2 + m_type->m_extraLakes;+ if( m_type->m_river )+ wanted = 0;+ else if( wanted < 1 )+ wanted = 1;Int area = playable * playable;- Int baseTarget = (Int)( (Real)area * RMG_LAKE_AREA );+ Int baseTarget = (Int)( (Real)area * RMG_LAKE_AREA * m_type->m_lakeArea );if( baseTarget < RMG_LAKE_MIN_FILL )baseTarget = RMG_LAKE_MIN_FILL;@@ -1595,19 +2084,36 @@ void RMGLayout::placeLakes( const UnsignedByte perm[512] )std::sort( seeds.begin(), seeds.end() );+ /* Lake country spreads its basins out. The lowest pockets tend to sit in one valley, and a+ basin grown beside another joins it, so without a gap the map gets one big lake where it+ asked for five. */+ Real lakeGap = ( m_type->m_extraLakes > 0 ) ? (Real)playable * 0.2f : 0.0f;+ std::vector<RMGPoint> lakeSeeds;+Int grown = 0;for( UnsignedInt i = 0; i < seeds.size() && grown < wanted; i++ ){if( m_inLake[cellIndex( seeds[i].m_x, seeds[i].m_y )] )continue;+ Bool crowded = FALSE;+ for( UnsignedInt k = 0; k < lakeSeeds.size(); k++ )+ {+ Real dx = (Real)seeds[i].m_x - lakeSeeds[k].m_cellX;+ Real dy = (Real)seeds[i].m_y - lakeSeeds[k].m_cellY;+ if( dx * dx + dy * dy < lakeGap * lakeGap )+ crowded = TRUE;+ }+ if( crowded )+ continue;+UnsignedInt hash = hashCell( m_settings.m_seed, seeds[i].m_x, seeds[i].m_y );Int target = (Int)( (Real)baseTarget * ( 0.75f + 0.5f * (Real)( hash % 1000U ) / 1000.0f ) );if( target < RMG_LAKE_MIN_FILL )target = RMG_LAKE_MIN_FILL;std::vector<Int> painted;- growBasin( seeds[i].m_x, seeds[i].m_y, target, RMG_LAKE_FILL_RISE, &painted );+ growBasin( perm, seeds[i].m_x, seeds[i].m_y, target, RMG_LAKE_FILL_RISE, &painted );if( (Int)painted.size() < RMG_LAKE_MIN_FILL ){for( UnsignedInt p = 0; p < painted.size(); p++ )@@ -1615,13 +2121,24 @@ void RMGLayout::placeLakes( const UnsignedByte perm[512] )continue;}+ RMGPoint grownAt;+ grownAt.m_cellX = (Real)seeds[i].m_x;+ grownAt.m_cellY = (Real)seeds[i].m_y;+ lakeSeeds.push_back( grownAt );grown++;}+ if( m_type->m_river )+ {+ paintMainRiver( perm );+ extractLakePolygons();+ return;+ }+if( grown == 0 && !seeds.empty() ){std::vector<Int> painted;- growBasin( seeds[0].m_x, seeds[0].m_y, RMG_LAKE_MIN_FILL * 2, RMG_LAKE_FILL_RISE * 2.0f,+ growBasin( perm, seeds[0].m_x, seeds[0].m_y, RMG_LAKE_MIN_FILL * 2, RMG_LAKE_FILL_RISE * 2.0f,&painted );if( (Int)painted.size() < RMG_LAKE_MIN_FILL ){@@ -1647,15 +2164,14 @@ void RMGLayout::carveLakeBasins( void )Real bed = RMG_BASE_HEIGHT - RMG_WATER_DROP - RMG_LAKE_DEPTH;Real atTheWaterline = m_waterHeight - 1.0f;+ std::vector<Real> straightShore;+ buildShoreDistance( straightShore, TRUE );+for( Int y = 0; y < m_height; y++ ){for( Int x = 0; x < m_width; x++ ){- Real px = (Real)(x - RMG_BORDER_CELLS);- Real py = (Real)(y - RMG_BORDER_CELLS);-- Real distanceToShore;- insideLake( px, py, &distanceToShore );+ Real distanceToShore = straightShore[cellIndex( x, y )];if( distanceToShore >= RMG_LAKE_SHORE )continue;@@ -1740,10 +2256,9 @@ Real RMGLayout::distanceToNearestStart( Real cellX, Real cellY ) const}/** The starts are found, not placed: every spot the search looks at is scored- for how flat and how dry it is, the flattest one starts the list, and each- one after that is whichever good site is furthest from the sites already- taken. Nothing about the map is turned round or mirrored to make them fair -- they are all standing on ground the same noise field made. */+ for how flat and how dry it is, and a seat only ever lands on one of those.+ Only a river map is mirrored; everywhere else the seats stand on ground the+ same noise field made, and fairness is the walk between them, measured. */void RMGLayout::chooseStarts( void ){m_starts.clear();@@ -1760,8 +2275,7 @@ void RMGLayout::chooseStarts( void )if( inset > margin && playable - 2 * inset >= (Int)(4.0f * RMG_FLAT_RADIUS) )margin = inset;- struct RMGCandidate { Real m_cellX, m_cellY, m_roughness; };- std::vector<RMGCandidate> candidates;+ std::vector<RMGStartCandidate> candidates;for( Int y = margin; y < playable - margin; y += m_startSearchStride ){@@ -1770,6 +2284,11 @@ void RMGLayout::chooseStarts( void )Int mapX = x + RMG_BORDER_CELLS;Int mapY = y + RMG_BORDER_CELLS;+ // The massif is the ground everybody climbs to, not a base: its top is level enough to+ // pass as one, and a seat up there would own every ramp.+ if( m_type->m_massif > 0.0f && massifClearance( (Real)x, (Real)y ) < RMG_BLEND_RADIUS )+ continue;+// Far enough that flattening the base does not leave a puddle in the middle of it,// and that a river clipping the disc cannot leave a cliff on the pad.Real distanceToShore;@@ -1801,7 +2320,7 @@ void RMGLayout::chooseStarts( void )if( roughness > RMG_START_ROUGHNESS * 3.0f )continue;- RMGCandidate candidate;+ RMGStartCandidate candidate;candidate.m_cellX = (Real)x;candidate.m_cellY = (Real)y;candidate.m_roughness = roughness;@@ -1824,132 +2343,517 @@ void RMGLayout::chooseStarts( void )return;}- /* Six seats and the furthest-from-the-rest search walks the last ones into the remaining- corners. A ring with the seed rotating it, snapped onto the flat candidates, keeps the- edge inset and stops that pile-up. Two and four players stay on the search, which is how- a duel gets a diagonal instead of a pie. */- if( m_settings.m_numPlayers >= RMG_CIRCLE_PLAYERS )+ /* A river map with an even count sits on a ring, turned half a seat off the river's line,+ so every seat has a mirror image on the far bank and the same walk to it. Left to the search,+ the river's dead band pushed one seat of four out on its own, twice as far from a fight as+ the other three. */+ Int players = m_settings.m_numPlayers;+ Real ringLimit = (Real)playable * 0.5f - (Real)margin;+ Bool riverRing = m_type->m_river && !m_riverLine.empty() && players % 2 == 0;+ if( riverRing ){- Real centre = (Real)playable * 0.5f;Real ring = (Real)playable * RMG_CIRCLE_RADIUS;- Real maxRing = (Real)playable * 0.5f - (Real)margin;- if( ring > maxRing )- ring = maxRing;+ if( ring > ringLimit )+ ring = ringLimit;+ /* Two or four seats on a river map go out to the edge of the start box instead, as far as the+ search would have put them, and leave the middle to the river and the towns. */+ ringStarts( candidates, m_riverAngle + PI / (Real)players, ring, players <= 4 ? ringLimit : 0.0f );+ return;+ }- Real rot = (Real)(hashCell( m_settings.m_seed, 5, 11 ) % 8U) * (PI * 0.25f);- std::vector<char> used( candidates.size(), 0 );- Real hardFloor = 2.0f * RMG_FLAT_RADIUS + 6.0f;+ // A duel is fair by symmetry: each base is the other's nearest enemy, at one walk.+ if( players == 2 )+ {+ searchStarts( candidates );+ return;+ }- for( Int seat = 0; seat < m_settings.m_numPlayers; seat++ )+ /* Three seats and up, a straight line between two bases says little about the walk: a lake, a+ canyon wall or a cliff band between one pair and not the next had one seat of s42's four at+ 153 steps from its nearest enemy and another at 246. So several layouts are tried - the+ search's own, and a ring at a few sizes and turns, each seat snapped onto flat ground - and+ every one is walked. Water blocks the walk and cliffs cost extra, because the passes cut later+ run up a ramp rather than straight over. The layout kept is the one whose nearest and+ second-nearest enemy walks are most nearly the same for every seat, without giving away+ distance. */+ const Int cellCount = m_width * m_height;+ std::vector<Int> cost( cellCount, -1 );+ for( Int y = 0; y < m_height - 1; y++ )+ {+ for( Int x = 0; x < m_width - 1; x++ ){- Real angle = rot + 2.0f * PI * (Real)seat / (Real)m_settings.m_numPlayers;- Real targetX = centre + ring * Cos( angle );- Real targetY = centre + ring * Sin( angle );+ if( underwaterAtCell( x, y ) )+ continue;+ cost[cellIndex( x, y )] = cellSpanWorld( x, y ) > RMG_CLIFF_WORLD_SPAN ? RMG_START_CLIFF_COST : 1;+ }+ }- Real bestScore = 1.0e9f;- UnsignedInt best = 0;- Bool foundClear = FALSE;- Bool anyUnused = FALSE;+ std::vector< std::vector<RMGPoint> > layouts;- for( UnsignedInt i = 0; i < candidates.size(); i++ )- {- if( used[i] )- continue;- anyUnused = TRUE;+ // Six seats and the furthest-from-the-rest search walks the last ones into the corners.+ if( players < RMG_CIRCLE_PLAYERS )+ {+ searchStarts( candidates );+ layouts.push_back( m_starts );+ }- Real distance = distanceToNearestStart( candidates[i].m_cellX, candidates[i].m_cellY );- Bool clearOfTheFloor = m_starts.empty() || distance >= hardFloor;- if( foundClear && !clearOfTheFloor )- continue;+ Real seedTurn = (Real)(hashCell( m_settings.m_seed, 5, 11 ) % 8U) * (PI * 0.25f);+ Real seatArc = 2.0f * PI / (Real)players;+ for( Int size = 0; size < RMG_START_RING_SIZES; size++ )+ {+ Real ring = (Real)playable * (RMG_CIRCLE_RADIUS - RMG_START_RING_STEP * (Real)size);+ if( ring > ringLimit )+ ring = ringLimit;- Real dx = candidates[i].m_cellX - targetX;- Real dy = candidates[i].m_cellY - targetY;- Real score = sqrtf( dx * dx + dy * dy ) + candidates[i].m_roughness * 0.5f;- if( score < bestScore || (clearOfTheFloor && !foundClear) )- {- bestScore = score;- best = i;- foundClear = clearOfTheFloor;- }- }+ for( Int turn = 0; turn < RMG_START_RING_TURNS; turn++ )+ {+ ringStarts( candidates, seedTurn + seatArc * (Real)turn / (Real)RMG_START_RING_TURNS, ring, 0.0f );+ if( (Int)m_starts.size() == players )+ layouts.push_back( m_starts );+ }+ }- if( !anyUnused )- break;+ if( layouts.empty() )+ {+ searchStarts( candidates );+ return;+ }- used[best] = 1;- RMGPoint start;- start.m_cellX = candidates[best].m_cellX;- start.m_cellY = candidates[best].m_cellY;- m_starts.push_back( start );+ std::vector<Real> spreads( layouts.size(), 0.0f );+ std::vector<Int> closest( layouts.size(), 0 );+ Int farthest = 1;+ std::vector<Int> walks;++ for( UnsignedInt layout = 0; layout < layouts.size(); layout++ )+ {+ m_starts = layouts[layout];+ startWalks( cost, walks );++ Int nearLow;+ spreads[layout] = walkSpread( walks, &nearLow );+ closest[layout] = nearLow;+ if( nearLow > farthest )+ farthest = nearLow;+ }++ UnsignedInt best = 0;+ Real bestScore = 1.0e9f;+ for( UnsignedInt layout = 0; layout < layouts.size(); layout++ )+ {+ Real score = spreads[layout] + RMG_START_CLOSE_COST * (1.0f - (Real)closest[layout] / (Real)farthest);+ if( score < bestScore )+ {+ bestScore = score;+ best = layout;}- return;}- // The flattest candidate opens the list.- UnsignedInt flattest = 0;- for( UnsignedInt i = 1; i < candidates.size(); i++ )+ m_starts = layouts[best];++ nudgeStarts( candidates, cost, farthest );+}++/** How far a layout is from every seat having the same walk to its nearest and second-nearest+ enemy; 1.5 is perfect. The shortest nearest walk comes back as well. */+Real RMGLayout::walkSpread( const std::vector<Int>& walks, Int *nearLowOut )+{+ Int nearLow = 0x7FFFFFFF, nearHigh = 0, secondLow = 0x7FFFFFFF, secondHigh = 0;+ for( UnsignedInt i = 0; i * 2 + 1 < walks.size(); i++ ){- if( candidates[i].m_roughness < candidates[flattest].m_roughness )- flattest = i;+ Int nearest = walks[i * 2];+ Int second = walks[i * 2 + 1];+ if( nearest < 1 )+ nearest = 1;+ if( second < 1 )+ second = 1;+ if( nearest < nearLow ) nearLow = nearest;+ if( nearest > nearHigh ) nearHigh = nearest;+ if( second < secondLow ) secondLow = second;+ if( second > secondHigh ) secondHigh = second;}- RMGPoint start;- start.m_cellX = candidates[flattest].m_cellX;- start.m_cellY = candidates[flattest].m_cellY;- m_starts.push_back( start );+ *nearLowOut = nearLow;+ return (Real)nearHigh / (Real)nearLow + 0.5f * (Real)secondHigh / (Real)secondLow;+}- /* Two base discs may not touch, whatever the map looks like. A candidate inside this is not- scored against the others at all; only a map with nowhere else to go falls back to it. */+/** The layouts are rings, and a ring is even only in straight lines: a canyon wall or a lake+ between one pair of seats and not the next leaves one seat walking further to a fight than+ its neighbours. So the seat furthest off the mean walk is moved, a few cells along the+ candidates, by about as much as it is off, and the move is kept only if the walks measure+ more even afterwards. A handful of tries, because every one is a fresh set of walks. */+void RMGLayout::nudgeStarts( const std::vector<RMGStartCandidate>& candidates, const std::vector<Int>& cost, Int farthest )+{+ Int players = (Int)m_starts.size();Real hardFloor = 2.0f * RMG_FLAT_RADIUS + 6.0f;- while( (Int)m_starts.size() < m_settings.m_numPlayers )+ std::vector<Int> walks;+ startWalks( cost, walks );+ Int nearLow;+ Real bestScore = walkSpread( walks, &nearLow ) + RMG_START_CLOSE_COST * (1.0f - (Real)nearLow / (Real)farthest);++ std::vector<char> tried( players, 0 );+ for( Int attempt = 0; attempt < RMG_START_NUDGES; attempt++ ){- Real bestScore = -1.0e9f;- UnsignedInt bestCandidate = 0;- Bool foundClearOne = FALSE;+ Real mean = 0.0f;+ for( Int i = 0; i < players; i++ )+ mean += (Real)walks[i * 2];+ mean /= (Real)players;++ // The seat furthest off the mean that has not already failed to move.+ Int seat = -1;+ Real worst = 0.0f;+ for( Int i = 0; i < players; i++ )+ {+ Real off = fabsf( (Real)walks[i * 2] - mean );+ if( !tried[i] && off > worst )+ {+ worst = off;+ seat = i;+ }+ }+ if( seat < 0 || worst < 2.0f )+ break;++ // Its nearest enemy in a straight line stands in for the one it walks to.+ Int partner = -1;+ Real partnerDistance = 1.0e9f;+ for( Int j = 0; j < players; j++ )+ {+ if( j == seat )+ continue;+ Real dx = m_starts[seat].m_cellX - m_starts[j].m_cellX;+ Real dy = m_starts[seat].m_cellY - m_starts[j].m_cellY;+ Real distance = sqrtf( dx * dx + dy * dy );+ if( distance < partnerDistance )+ {+ partnerDistance = distance;+ partner = j;+ }+ }++ Real want = mean - (Real)walks[seat * 2];+ if( want > RMG_START_NUDGE_CELLS ) want = RMG_START_NUDGE_CELLS;+ if( want < -RMG_START_NUDGE_CELLS ) want = -RMG_START_NUDGE_CELLS;+ RMGPoint here = m_starts[seat];+ Real bestFit = 1.0e9f;+ Int pick = -1;for( UnsignedInt i = 0; i < candidates.size(); i++ ){- Real distance = distanceToNearestStart( candidates[i].m_cellX, candidates[i].m_cellY );+ Real mx = candidates[i].m_cellX - here.m_cellX;+ Real my = candidates[i].m_cellY - here.m_cellY;+ if( mx * mx + my * my > RMG_START_NUDGE_CELLS * RMG_START_NUDGE_CELLS || (mx == 0.0f && my == 0.0f) )+ continue;- Bool clearOfTheFloor = distance >= hardFloor;- if( foundClearOne && !clearOfTheFloor )+ Bool clear = TRUE;+ for( Int j = 0; j < players && clear; j++ )+ {+ if( j == seat )+ continue;+ Real dx = candidates[i].m_cellX - m_starts[j].m_cellX;+ Real dy = candidates[i].m_cellY - m_starts[j].m_cellY;+ clear = dx * dx + dy * dy >= hardFloor * hardFloor;+ }+ if( !clear )continue;- /* Distance first, flatness second, and distance is never traded away: a base that- gives up ten cells of separation for slightly better ground is a base sharing its- half of the map with a neighbour, and then both of them are fighting over one- supply dock while the far side of the map stands empty. */- Real score = distance - candidates[i].m_roughness * 2.0f;- if( score > bestScore || (clearOfTheFloor && !foundClearOne) )+ Real dx = candidates[i].m_cellX - m_starts[partner].m_cellX;+ Real dy = candidates[i].m_cellY - m_starts[partner].m_cellY;+ Real fit = fabsf( sqrtf( dx * dx + dy * dy ) - partnerDistance - want ) + candidates[i].m_roughness * 0.5f;+ if( fit < bestFit ){- bestScore = score;- bestCandidate = i;- foundClearOne = clearOfTheFloor;+ bestFit = fit;+ pick = (Int)i;}}- start.m_cellX = candidates[bestCandidate].m_cellX;- start.m_cellY = candidates[bestCandidate].m_cellY;- m_starts.push_back( start );+ tried[seat] = 1;+ if( pick < 0 )+ continue;++ m_starts[seat].m_cellX = candidates[pick].m_cellX;+ m_starts[seat].m_cellY = candidates[pick].m_cellY;+ std::vector<Int> moved;+ startWalks( cost, moved );+ Real score = walkSpread( moved, &nearLow ) + RMG_START_CLOSE_COST * (1.0f - (Real)nearLow / (Real)farthest);+ if( score < bestScore )+ {+ bestScore = score;+ walks = moved;+ for( Int i = 0; i < players; i++ )+ tried[i] = 0;+ tried[seat] = 1; // the next try goes to another seat+ }+ else+ m_starts[seat] = here;}}-/// Flatten a disc under each start so a base can be laid out on it.-void RMGLayout::flattenBases( void )+/** The walk from each seat to its nearest and second-nearest enemy: a Dial flood over the cost+ grid, stopped at the second seat it reaches, so it covers the ground between neighbours and not+ the map. The route is the cheapest one, which goes round a cliff band the way the ring routes+ carved later do, and what is kept is its length in steps, which is what a unit walks. A seat+ cut off by water is priced at three times the straight-line steps. */+void RMGLayout::startWalks( const std::vector<Int>& cost, std::vector<Int>& walks ) const{- std::vector<Real> startHeights;- std::vector<Real> flatRadii;- std::vector<Real> blendRadii;+ std::vector<Int> stepsTo( m_width * m_height, 0 );+ Int count = (Int)m_starts.size();+ walks.assign( count * 2, 0 );- for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ std::vector<Int> seatAt( m_width * m_height, -1 );+ std::vector<Int> cells( count, 0 );+ for( Int i = 0; i < count; i++ ){- Int mapX = (Int)(m_starts[i].m_cellX + 0.5f) + RMG_BORDER_CELLS;- Int mapY = (Int)(m_starts[i].m_cellY + 0.5f) + RMG_BORDER_CELLS;- startHeights.push_back( (Real)m_heights[cellIndex( mapX, mapY )] );+ Int x = (Int)(m_starts[i].m_cellX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(m_starts[i].m_cellY + 0.5f) + RMG_BORDER_CELLS;+ cells[i] = cellIndex( x, y );+ seatAt[cells[i]] = i;+ }- /* Two discs at different heights meeting in the middle is a cliff between two bases, so- on a map too cramped to hold everybody at the full radius each disc gives way rather+ const Int buckets = RMG_START_CLIFF_COST + 1;+ std::vector< std::vector<Int> > open( buckets );+ std::vector<Int> dist( m_width * m_height, -1 );+ std::vector<Int> touched;+ std::vector<Int> reached( count, -1 );++ static const Int offsetX[4] = { 1, -1, 0, 0 };+ static const Int offsetY[4] = { 0, 0, 1, -1 };++ for( Int from = 0; from < count; from++ )+ {+ Int found = 0;+ for( Int i = 0; i < count; i++ )+ reached[i] = -1;+ for( Int b = 0; b < buckets; b++ )+ open[b].clear();++ dist[cells[from]] = 0;+ stepsTo[cells[from]] = 0;+ touched.push_back( cells[from] );+ open[0].push_back( cells[from] );+ Int pending = 1;++ for( Int here = 0; pending > 0 && found < 2; here++ )+ {+ std::vector<Int>& bucket = open[here % buckets];+ for( UnsignedInt k = 0; k < bucket.size() && found < 2; k++ )+ {+ Int index = bucket[k];+ pending--;+ if( dist[index] != here )+ continue;++ Int seat = seatAt[index];+ if( seat >= 0 && seat != from )+ {+ reached[seat] = here;+ walks[from * 2 + found] = stepsTo[index];+ found++;+ }++ Int x = index % m_width;+ Int y = index / m_width;+ for( Int i = 0; i < 4; i++ )+ {+ Int nx = x + offsetX[i];+ Int ny = y + offsetY[i];+ if( nx < 0 || ny < 0 || nx >= m_width - 1 || ny >= m_height - 1 )+ continue;++ Int next = ny * m_width + nx;+ if( cost[next] < 0 )+ continue;++ Int step = here + cost[next];+ if( dist[next] >= 0 && dist[next] <= step )+ continue;++ if( dist[next] < 0 )+ touched.push_back( next );+ dist[next] = step;+ stepsTo[next] = stepsTo[index] + 1;+ open[step % buckets].push_back( next );+ pending++;+ }+ }+ bucket.clear();+ }++ for( UnsignedInt t = 0; t < touched.size(); t++ )+ dist[touched[t]] = -1;+ touched.clear();++ if( found < 2 )+ {+ Int nearest = found > 0 ? walks[from * 2] : 0x7FFFFFFF;+ Int second = 0x7FFFFFFF;+ for( Int j = 0; j < count; j++ )+ {+ if( j == from || reached[j] >= 0 )+ continue;++ Real dx = m_starts[from].m_cellX - m_starts[j].m_cellX;+ Real dy = m_starts[from].m_cellY - m_starts[j].m_cellY;+ Int walk = 3 * (Int)(fabsf( dx ) + fabsf( dy ));+ if( walk < nearest )+ {+ second = nearest;+ nearest = walk;+ }+ else if( walk < second )+ second = walk;+ }+ walks[from * 2] = nearest;+ walks[from * 2 + 1] = second;+ }++ // Reached in order of cost, which a cliff can put the longer walk first.+ if( walks[from * 2] > walks[from * 2 + 1] )+ std::swap( walks[from * 2], walks[from * 2 + 1] );+ }+}++/** Seats at even turns round a ring, each snapped to the nearest flat candidate the others leave.+ With an edge ring, each seat goes out to the edge of the start box instead: a quarter turn keeps+ the larger of |cos| and |sin|, so every seat is the same distance out. */+void RMGLayout::ringStarts( const std::vector<RMGStartCandidate>& candidates, Real angle, Real ring, Real edgeRing )+{+ m_starts.clear();++ Real centre = (Real)m_settings.m_playableCells * 0.5f;+ std::vector<char> used( candidates.size(), 0 );+ Real hardFloor = 2.0f * RMG_FLAT_RADIUS + 6.0f;++ for( Int seat = 0; seat < m_settings.m_numPlayers; seat++ )+ {+ Real seatAngle = angle + 2.0f * PI * (Real)seat / (Real)m_settings.m_numPlayers;+ Real seatRing = ring;+ if( edgeRing > 0.0f )+ {+ Real reach = fabsf( Cos( seatAngle ) );+ if( fabsf( Sin( seatAngle ) ) > reach )+ reach = fabsf( Sin( seatAngle ) );+ seatRing = edgeRing / reach;+ }+ Real targetX = centre + seatRing * Cos( seatAngle );+ Real targetY = centre + seatRing * Sin( seatAngle );++ Real bestScore = 1.0e9f;+ UnsignedInt best = 0;+ Bool foundClear = FALSE;+ Bool anyUnused = FALSE;++ for( UnsignedInt i = 0; i < candidates.size(); i++ )+ {+ if( used[i] )+ continue;+ anyUnused = TRUE;++ Real distance = distanceToNearestStart( candidates[i].m_cellX, candidates[i].m_cellY );+ Bool clearOfTheFloor = m_starts.empty() || distance >= hardFloor;+ if( foundClear && !clearOfTheFloor )+ continue;++ Real dx = candidates[i].m_cellX - targetX;+ Real dy = candidates[i].m_cellY - targetY;+ Real score = sqrtf( dx * dx + dy * dy ) + candidates[i].m_roughness * 0.5f;+ if( score < bestScore || (clearOfTheFloor && !foundClear) )+ {+ bestScore = score;+ best = i;+ foundClear = clearOfTheFloor;+ }+ }++ if( !anyUnused )+ break;++ used[best] = 1;+ RMGPoint start;+ start.m_cellX = candidates[best].m_cellX;+ start.m_cellY = candidates[best].m_cellY;+ m_starts.push_back( start );+ }+}++/** The flattest candidate first, then each seat after it on whichever good site is furthest from+ the ones already taken. */+void RMGLayout::searchStarts( const std::vector<RMGStartCandidate>& candidates )+{+ m_starts.clear();++ // The flattest candidate opens the list.+ UnsignedInt flattest = 0;+ for( UnsignedInt i = 1; i < candidates.size(); i++ )+ {+ if( candidates[i].m_roughness < candidates[flattest].m_roughness )+ flattest = i;+ }++ RMGPoint start;+ start.m_cellX = candidates[flattest].m_cellX;+ start.m_cellY = candidates[flattest].m_cellY;+ m_starts.push_back( start );++ /* Two base discs may not touch, whatever the map looks like. A candidate inside this is not+ scored against the others at all; only a map with nowhere else to go falls back to it. */+ Real hardFloor = 2.0f * RMG_FLAT_RADIUS + 6.0f;++ while( (Int)m_starts.size() < m_settings.m_numPlayers )+ {+ Real bestScore = -1.0e9f;+ UnsignedInt bestCandidate = 0;+ Bool foundClearOne = FALSE;++ for( UnsignedInt i = 0; i < candidates.size(); i++ )+ {+ Real distance = distanceToNearestStart( candidates[i].m_cellX, candidates[i].m_cellY );++ Bool clearOfTheFloor = distance >= hardFloor;+ if( foundClearOne && !clearOfTheFloor )+ continue;++ /* Distance first, flatness second, and distance is never traded away: a base that+ gives up ten cells of separation for slightly better ground is a base sharing its+ half of the map with a neighbour, and then both of them are fighting over one+ supply dock while the far side of the map stands empty. */+ Real score = distance - candidates[i].m_roughness * 2.0f;+ if( score > bestScore || (clearOfTheFloor && !foundClearOne) )+ {+ bestScore = score;+ bestCandidate = i;+ foundClearOne = clearOfTheFloor;+ }+ }++ start.m_cellX = candidates[bestCandidate].m_cellX;+ start.m_cellY = candidates[bestCandidate].m_cellY;+ m_starts.push_back( start );+ }+}++/// Flatten a disc under each start so a base can be laid out on it.+void RMGLayout::flattenBases( void )+{+ if( m_baseLevelled.size() != m_heights.size() )+ {+ m_baseLevelled.assign( m_heights.size(), 0 );+ m_baseUnder.assign( m_heights.size(), 0 );+ m_baseResult.assign( m_heights.size(), 0 );+ }++ std::vector<Real> startHeights;+ std::vector<Real> flatRadii;+ std::vector<Real> blendRadii;++ for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ {+ Int mapX = (Int)(m_starts[i].m_cellX + 0.5f) + RMG_BORDER_CELLS;+ Int mapY = (Int)(m_starts[i].m_cellY + 0.5f) + RMG_BORDER_CELLS;+ startHeights.push_back( (Real)m_heights[cellIndex( mapX, mapY )] );++ /* Two discs at different heights meeting in the middle is a cliff between two bases, so+ on a map too cramped to hold everybody at the full radius each disc gives way ratherthan overlapping its neighbour. */Real nearestOther = 1.0e9f;for( UnsignedInt j = 0; j < m_starts.size(); j++ )@@ -1978,10 +2882,29 @@ void RMGLayout::flattenBases( void )blendRadii.push_back( blend );}- for( Int y = 0; y < m_height; y++ )+ /* Only the squares round each start can be inside a blend, so only those are walked; a cell+ two squares share is levelled once. Every pass of the ring routes calls this, and walking+ the whole map each time was most of what connecting the starts cost. */+ Real reach = 0.0f;+ for( UnsignedInt i = 0; i < blendRadii.size(); i++ ){- for( Int x = 0; x < m_width; x++ )+ if( blendRadii[i] > reach )+ reach = blendRadii[i];+ }+ Int box = (Int)reach + 2;+ std::vector<char> walked( m_heights.size(), 0 );++ for( UnsignedInt s = 0; s < m_starts.size(); s++ )+ for( Int y = (Int)m_starts[s].m_cellY + RMG_BORDER_CELLS - box; y <= (Int)m_starts[s].m_cellY + RMG_BORDER_CELLS + box; y++ )+ {+ if( y < 0 || y >= m_height )+ continue;+ for( Int x = (Int)m_starts[s].m_cellX + RMG_BORDER_CELLS - box; x <= (Int)m_starts[s].m_cellX + RMG_BORDER_CELLS + box; x++ ){+ if( x < 0 || x >= m_width || walked[cellIndex( x, y )] )+ continue;+ walked[cellIndex( x, y )] = 1;+Real px = (Real)(x - RMG_BORDER_CELLS);Real py = (Real)(y - RMG_BORDER_CELLS);@@ -2009,12 +2932,24 @@ void RMGLayout::flattenBases( void )t = (nearest - flatRadii[nearestIndex])/ (blendRadii[nearestIndex] - flatRadii[nearestIndex]);- Real h = lerpReal( startHeights[nearestIndex], (Real)m_heights[cellIndex( x, y )],- fadeCurve( t ) );+ /* Blend against the ground as it stood before the last levelling, unless something has+ moved this cell since. Blending the blend again on every call pulled the ring towards+ the base a little more each time while its outer edge stayed put, and after the ring+ route and the money walks had each levelled it, that edge stood as a cliff round the+ base. */+ Int c = cellIndex( x, y );+ UnsignedByte under = m_heights[c];+ if( m_baseLevelled[c] && m_heights[c] == m_baseResult[c] )+ under = m_baseUnder[c];++ Real h = lerpReal( startHeights[nearestIndex], (Real)under, fadeCurve( t ) );if( h < 1.0f ) h = 1.0f;if( h > 254.0f ) h = 254.0f;- m_heights[cellIndex( x, y )] = (UnsignedByte)(h + 0.5f);+ m_heights[c] = (UnsignedByte)(h + 0.5f);+ m_baseLevelled[c] = 1;+ m_baseUnder[c] = under;+ m_baseResult[c] = m_heights[c];}}@@ -2087,9 +3022,11 @@ Bool RMGLayout::carvePassBetweenCells( Int fromX, Int fromY, Int toX, Int toY, Bstd::vector<Int> cost( cellCount, 0x7FFFFFFF );std::vector<Int> cameFrom( cellCount, -1 );- const Int flatCost = 1;- const Int cliffCost = 60;- const Int waterCost = 250;+ /* Walking ground costs its climb as well as its length, so a route keeps to the contour where+ one is on offer and leaves less ground for the earthwork to move. */+ const Int flatCost = 4;+ const Int cliffCost = 240;+ const Int waterCost = 1000;/* Dijkstra over a binary heap of (cost, cell). A linear scan of the open list was fine on a96-cell map and is not on a 456-cell one: the open list runs to tens of thousands of cells@@ -2141,7 +3078,8 @@ Bool RMGLayout::carvePassBetweenCells( Int fromX, Int fromY, Int toX, Int toY, Bif( nx < 1 || ny < 1 || nx >= m_width - 2 || ny >= m_height - 2 )continue;- Int step = flatCost;+ Int climb = (Int)m_heights[cellIndex( nx, ny )] - (Int)m_heights[index];+ Int step = flatCost + ((climb >= 0) ? climb : -climb);if( m_passable[cellIndex( nx, ny )] == 0 )step = underwaterAtCell( nx, ny ) ? waterCost : cliffCost;@@ -2247,38 +3185,62 @@ void RMGLayout::applyRouteProfile( const std::vector<Int>& route, Bool recordRam}for( UnsignedInt i = 0; i < route.size(); i++ )- {- Int x = route[i] % m_width;- Int y = route[i] / m_width;+ cutTowardLevel( route[i] % m_width, route[i] / m_width, profile[i], FALSE,+ protectRadius, protectX, protectY );+}++/** Earthwork round one cell of a route, and no more of it than the route needs. The ground near the+ route is only moved where it stands further from the route's level than a bank of fixed slope+ allows, so a road over gentle ground leaves it as it was, and a ramp through a terrace step is cut+ as a trough whose sides lean back. Levelling a strip to the route's height did the opposite: on+ every hillside the strip ran across, it left a flat shelf with a rim, and a 4-neighbour route on+ open ground is a dead straight line, so each one drew a ruled seam across the map. */+void RMGLayout::cutTowardLevel( Int x, Int y, Real level, Bool skipLake,+ Real protectRadius, Real protectX, Real protectY )+{+ const Int reach = RMG_PASS_HALF_WIDTH + RMG_PASS_BANK_CELLS;- for( Int dy = -RMG_PASS_HALF_WIDTH - 2; dy <= RMG_PASS_HALF_WIDTH + 2; dy++ )+ for( Int dy = -reach; dy <= reach; dy++ )+ {+ for( Int dx = -reach; dx <= reach; dx++ ){- for( Int dx = -RMG_PASS_HALF_WIDTH - 2; dx <= RMG_PASS_HALF_WIDTH + 2; dx++ )+ Int nx = x + dx;+ Int ny = y + dy;+ if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )+ continue;+ if( skipLake && m_inLake[cellIndex( nx, ny )] )+ continue;++ if( protectRadius > 0.0f ){- Int nx = x + dx;- Int ny = y + dy;- if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )+ Real px = (Real)nx - protectX;+ Real py = (Real)ny - protectY;+ if( sqrtf( px * px + py * py ) < protectRadius )continue;+ }- if( protectRadius > 0.0f )- {- Real px = (Real)nx - protectX;- Real py = (Real)ny - protectY;- if( sqrtf( px * px + py * py ) < protectRadius )- continue;- }-- Real distance = sqrtf( (Real)(dx * dx + dy * dy) );- Real t = (distance - (Real)RMG_PASS_HALF_WIDTH) / 2.0f;- if( t < 0.0f ) t = 0.0f;- if( t > 1.0f ) continue;+ Real distance = sqrtf( (Real)(dx * dx + dy * dy) );+ if( distance > (Real)reach )+ continue;- Real h = lerpReal( profile[i], (Real)m_heights[cellIndex( nx, ny )], fadeCurve( t ) );- if( h < 1.0f ) h = 1.0f;- if( h > 254.0f ) h = 254.0f;+ // Gentle across the roadway itself, steeper on the banks, both under the step a unit climbs.+ Real allowance = distance * RMG_PASS_ROAD_SLOPE;+ if( distance > (Real)RMG_PASS_HALF_WIDTH )+ allowance = (Real)RMG_PASS_HALF_WIDTH * RMG_PASS_ROAD_SLOPE+ + (distance - (Real)RMG_PASS_HALF_WIDTH) * RMG_PASS_BANK_SLOPE;++ Real ground = (Real)m_heights[cellIndex( nx, ny )];+ Real h = ground;+ if( h > level + allowance )+ h = level + allowance;+ if( h < level - allowance )+ h = level - allowance;+ if( h == ground )+ continue;- m_heights[cellIndex( nx, ny )] = (UnsignedByte)(h + 0.5f);- }+ if( h < 1.0f ) h = 1.0f;+ if( h > 254.0f ) h = 254.0f;+ m_heights[cellIndex( nx, ny )] = (UnsignedByte)(h + 0.5f);}}}@@ -2370,6 +3332,250 @@ void RMGLayout::connectStarts( void )buildPassability();}+/// Cells from the outermost the massif's foot can reach, negative inside it.+Real RMGLayout::massifClearance( Real cellX, Real cellY ) const+{+ Real playable = (Real)m_settings.m_playableCells;+ Real dx = cellX - playable * 0.5f;+ Real dy = cellY - playable * 0.5f;+ return sqrtf( dx * dx + dy * dy ) - playable * RMG_MASSIF_RADIUS * ( 1.0f + RMG_MASSIF_WOBBLE );+}++/** One ramp up the massif for each base, on the bearing from the middle to that base, so every seat+ has its own way onto the high ground and the same length of climb as the next one. The route+ search would find a ramp too, but only for a pair it had to join, and it joins them round the+ foot of the massif rather than over it, which leaves the top as a table nobody can reach. */+void RMGLayout::carveMassifRamps( void )+{+ Real playable = (Real)m_settings.m_playableCells;+ Real centre = playable * 0.5f;+ Real outer = playable * RMG_MASSIF_RADIUS * ( 1.0f + RMG_MASSIF_WOBBLE );+ Real inner = playable * RMG_MASSIF_RADIUS * ( 1.0f - RMG_MASSIF_WOBBLE ) - RMG_MASSIF_RIM;++ for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ {+ Real dx = m_starts[i].m_cellX - centre;+ Real dy = m_starts[i].m_cellY - centre;+ Real length = sqrtf( dx * dx + dy * dy );+ if( length < 1.0f )+ continue;+ Real ux = dx / length;+ Real uy = dy / length;++ // Out far enough that the climb is a slope a tank takes, and no further than the base's ring.+ Real foot = outer + 12.0f;+ if( foot > length - RMG_BLEND_RADIUS )+ foot = length - RMG_BLEND_RADIUS;+ Real top = inner - 6.0f;+ if( top < 2.0f )+ top = 2.0f;+ if( foot <= top )+ continue;++ Real footX = centre + ux * foot + (Real)RMG_BORDER_CELLS;+ Real footY = centre + uy * foot + (Real)RMG_BORDER_CELLS;+ Real topX = centre + ux * top + (Real)RMG_BORDER_CELLS;+ Real topY = centre + uy * top + (Real)RMG_BORDER_CELLS;+ Real baseX = m_starts[i].m_cellX + (Real)RMG_BORDER_CELLS;+ Real baseY = m_starts[i].m_cellY + (Real)RMG_BORDER_CELLS;++ /* A graded road rather than a corridor cut to one width: the climb eases in at both ends,+ the road opens out towards the foot the way a spur of spoil would, and its sides blend+ into the ground over several cells. A narrow cut with steep banks read from above as a+ spike in the cliff, half causeway outside and half notch inside. */+ Real span = foot - top;++ /* The road's level along its centre line is the ground's own profile with the cliff graded+ out of it: two thirds of it the highest line under the ground that climbs no faster than+ RMG_MASSIF_ROAD_GRADE, a third the lowest line over it, so most of the climb is a cutting+ in the table and only a short spur stands out on the plain. Where the ground is gentler than the+ grade both lines are the ground, so the road only changes the cliff band. It used to run+ one eased line from a height read on the table to one read at the foot, and that line+ stayed level for a dozen cells past the rim while the ground beside it rolled, which drew+ every ramp as a straight flat strip out of the massif. */+ Real profileFrom = top - 0.25f * span - 1.0f;+ Int profileCount = (Int)( 1.5f * span ) + 4;+ std::vector<Real> ground( profileCount );+ for( Int s = 0; s < profileCount; s++ )+ {+ Real along = profileFrom + (Real)s;+ Int cx = (Int)( centre + ux * along + (Real)RMG_BORDER_CELLS + 0.5f );+ Int cy = (Int)( centre + uy * along + (Real)RMG_BORDER_CELLS + 0.5f );+ if( cx < 0 ) cx = 0;+ if( cy < 0 ) cy = 0;+ if( cx >= m_width ) cx = m_width - 1;+ if( cy >= m_height ) cy = m_height - 1;+ Real g = (Real)m_heights[cellIndex( cx, cy )];+ if( g < m_waterHeight + 2.0f )+ g = m_waterHeight + 2.0f;+ ground[s] = g;+ }+ std::vector<Real> graded( profileCount );+ for( Int s = 0; s < profileCount; s++ )+ {+ Real under = 1.0e9f;+ Real over = -1.0e9f;+ for( Int j = 0; j < profileCount; j++ )+ {+ Real reach = RMG_MASSIF_ROAD_GRADE * (Real)( s > j ? s - j : j - s );+ if( ground[j] + reach < under )+ under = ground[j] + reach;+ if( ground[j] - reach > over )+ over = ground[j] - reach;+ }+ graded[s] = ( 2.0f * under + over ) / 3.0f;+ }+ // A short running mean takes the crease off both ends of the climb without steepening it.+ std::vector<Real> level( profileCount );+ for( Int s = 0; s < profileCount; s++ )+ {+ Real sum = 0.0f;+ Int count = 0;+ for( Int j = s - 2; j <= s + 2; j++ )+ {+ if( j < 0 || j >= profileCount )+ continue;+ sum += graded[j];+ count++;+ }+ level[s] = sum / (Real)count;+ }+ Int reach = (Int)( RMG_MASSIF_ROAD_FOOT + RMG_MASSIF_ROAD_WIDEST + 0.25f * span ) + 1;+ Int loX = (Int)( footX < topX ? footX : topX ) - reach;+ Int hiX = (Int)( footX > topX ? footX : topX ) + reach;+ Int loY = (Int)( footY < topY ? footY : topY ) - reach;+ Int hiY = (Int)( footY > topY ? footY : topY ) + reach;+ for( Int y = loY; y <= hiY; y++ )+ {+ for( Int x = loX; x <= hiX; x++ )+ {+ if( x < 0 || y < 0 || x >= m_width || y >= m_height )+ continue;+ if( m_inLake[cellIndex( x, y )] )+ continue;+ Real bx = (Real)x - baseX;+ Real by = (Real)y - baseY;+ if( bx * bx + by * by < RMG_BLEND_RADIUS * RMG_BLEND_RADIUS )+ continue;++ Real px = (Real)x - (Real)RMG_BORDER_CELLS - centre;+ Real py = (Real)y - (Real)RMG_BORDER_CELLS - centre;+ Real along = px * ux + py * uy;+ Real across = fabsf( px * uy - py * ux );+ Real t = ( along - top ) / span; // 0 at the top, 1 at the foot+ if( t < -0.25f || t > 1.25f )+ continue;+ Real tc = t < 0.0f ? 0.0f : ( t > 1.0f ? 1.0f : t );++ Real at = along - profileFrom;+ Int s0 = (Int)at;+ if( s0 < 0 ) s0 = 0;+ if( s0 > profileCount - 2 ) s0 = profileCount - 2;+ Real f = at - (Real)s0;+ if( f < 0.0f ) f = 0.0f;+ if( f > 1.0f ) f = 1.0f;+ Real roadLevel = lerpReal( level[s0], level[s0 + 1], f );+ Real centreGround = lerpReal( ground[s0], ground[s0 + 1], f );+ Real cut = fabsf( roadLevel - centreGround );++ // The deeper the cut or the higher the fill, the wider its sides, so a bank stands at+ // one slope the whole way along instead of a wall where the road meets the rim.+ Real bank = cut / RMG_MASSIF_ROAD_SIDE;+ if( bank > RMG_MASSIF_ROAD_WIDEST )+ bank = RMG_MASSIF_ROAD_WIDEST;+ if( bank < RMG_MASSIF_ROAD_BANK )+ bank = RMG_MASSIF_ROAD_BANK;+ Real half = lerpReal( RMG_MASSIF_ROAD_TOP, RMG_MASSIF_ROAD_FOOT, tc );+ Real weight = 1.0f;+ if( across > half )+ weight = 1.0f - fadeCurve( ( across - half ) / bank < 1.0f ? ( across - half ) / bank : 1.0f );+ // Past either end the road hands back to the ground over a quarter of its length.+ if( t < 0.0f )+ weight *= 1.0f - fadeCurve( -t * 4.0f );+ else if( t > 1.0f )+ weight *= 1.0f - fadeCurve( ( t - 1.0f ) * 4.0f );+ if( weight <= 0.0f )+ continue;++ /* Where the road only follows the ground it is laid as an offset over the ground+ beside it, so the strip rolls with its sides. Where it cuts or fills the cliff it is+ laid level across, so a rim crossing the road at a slant leaves no step in it. */+ Real here = (Real)m_heights[cellIndex( x, y )];+ Real work = cut / 6.0f;+ if( work > 1.0f ) work = 1.0f;+ Real target = lerpReal( here + roadLevel - centreGround, roadLevel, work );+ Real h = lerpReal( here, target, weight );+ if( h < 1.0f ) h = 1.0f;+ if( h > 254.0f ) h = 254.0f;+ m_heights[cellIndex( x, y )] = (UnsignedByte)( h + 0.5f );+ }+ }++ RMGPoint ramp;+ ramp.m_cellX = centre + ux * ( foot + top ) * 0.5f;+ ramp.m_cellY = centre + uy * ( foot + top ) * 0.5f;+ m_ramps.push_back( ramp );+ }++ buildPassability();+}++/** Cells from the nearest ride of a black forest: the spoke from each base to the middle, and the+ ring through the bases at their mean distance from it, which is the ride between neighbours. */+Real RMGLayout::rideDistance( Real cellX, Real cellY ) const+{+ Real centre = (Real)m_settings.m_playableCells * 0.5f;+ Real ring = 0.0f;+ Real nearest = 1.0e9f;++ for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ {+ Real sx = m_starts[i].m_cellX - centre;+ Real sy = m_starts[i].m_cellY - centre;+ Real length2 = sx * sx + sy * sy;+ ring += sqrtf( length2 );+ if( length2 < 1.0f )+ continue;++ // Distance to the segment from the middle out to the base.+ Real px = cellX - centre;+ Real py = cellY - centre;+ Real t = ( px * sx + py * sy ) / length2;+ if( t < 0.0f ) t = 0.0f;+ if( t > 1.0f ) t = 1.0f;+ Real ex = px - sx * t;+ Real ey = py - sy * t;+ Real d = sqrtf( ex * ex + ey * ey );+ if( d < nearest )+ nearest = d;+ }++ if( !m_starts.empty() )+ {+ ring /= (Real)m_starts.size();+ Real dx = cellX - centre;+ Real dy = cellY - centre;+ Real d = fabsf( sqrtf( dx * dx + dy * dy ) - ring );+ if( d < nearest )+ nearest = d;+ }++ return nearest;+}++/// Whether a cell lies within this many cells of the middle of any ramp a route or the massif cut.+Bool RMGLayout::nearRamp( Real cellX, Real cellY, Real radius ) const+{+ for( UnsignedInt i = 0; i < m_ramps.size(); i++ )+ {+ Real dx = cellX - m_ramps[i].m_cellX;+ Real dy = cellY - m_ramps[i].m_cellY;+ if( dx * dx + dy * dy < radius * radius )+ return TRUE;+ }+ return FALSE;+}+//-----------------------------------------------------------------------------// Playability after pads: a second way out of each base, and a walk to the money//-----------------------------------------------------------------------------@@ -2529,48 +3735,13 @@ Bool RMGLayout::carveStraightCorridor( Int fromX, Int fromY, Int toX, Int toY,if( fromHeight < waterFloor ) fromHeight = waterFloor;if( toHeight < waterFloor ) toHeight = waterFloor;- const Int halfWidth = RMG_PASS_HALF_WIDTH + 1;-for( Int i = 0; i <= steps; i++ ){Int x = fromX + spanX * i / steps;Int y = fromY + spanY * i / steps;Real along = (Real)i / (Real)steps;- Real level = lerpReal( fromHeight, toHeight, along );-- for( Int dy = -halfWidth; dy <= halfWidth; dy++ )- {- for( Int dx = -halfWidth; dx <= halfWidth; dx++ )- {- Int nx = x + dx;- Int ny = y + dy;- if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )- continue;- if( m_inLake[cellIndex( nx, ny )] )- continue;-- if( protectRadius > 0.0f )- {- Real px = (Real)nx - protectX;- Real py = (Real)ny - protectY;- if( sqrtf( px * px + py * py ) < protectRadius )- continue;- }-- Real distance = sqrtf( (Real)(dx * dx + dy * dy) );- if( distance > (Real)halfWidth )- continue;-- Real t = (distance - (Real)RMG_PASS_HALF_WIDTH) / 2.0f;- if( t < 0.0f ) t = 0.0f;- if( t > 1.0f ) continue;-- Real h = lerpReal( level, (Real)m_heights[cellIndex( nx, ny )], fadeCurve( t ) );- if( h < 1.0f ) h = 1.0f;- if( h > 254.0f ) h = 254.0f;- m_heights[cellIndex( nx, ny )] = (UnsignedByte)(h + 0.5f);- }- }+ cutTowardLevel( x, y, lerpReal( fromHeight, toHeight, along ), TRUE,+ protectRadius, protectX, protectY );}return TRUE;@@ -2819,6 +3990,100 @@ void RMGLayout::ensurePlayability( void )buildPassability();}+/** Hold every player's own money to the walk it was placed at. Whatever came after the placement+ can lengthen one: a second exit cut through a base rim, a dock on a lake bank whose pad and the+ base's last levelling leave a step between them. A walk that grew past the slack gets a ramp cut+ from the base's edge straight to the money, the same repair an unreachable dock gets.+ A contested dock also has to stay on its placer's side of the midline. On open ground a walk is+ as short as it gets and a ramp cannot win it back, so a dock that ended up a cell or two over the+ line is slid across its own pad instead: on one canyon map both docks between two seats had gone+ to one of them, five money to seven. */+void RMGLayout::holdMoneyWalks( void )+{+ buildPassability();++ Int players = (Int)m_starts.size();+ std::vector< std::vector<Int> > dist( players );+ std::vector<char> flooded( players, 0 );+ for( Int player = 0; player < players; player++ )+ {+ for( UnsignedInt m = 0; m < m_moneyWalks.size(); m++ )+ {+ const RMGMoneyWalk& money = m_moneyWalks[m];+ if( money.m_player != player )+ continue;++ for( Int pass = 0; pass < 2; pass++ )+ {+ Int who[2] = { player, money.m_rival };+ for( Int k = 0; k < 2; k++ )+ {+ if( who[k] < 0 || flooded[who[k]] )+ continue;+ floodDistancesFromCell( (Int)(m_starts[who[k]].m_cellX + 0.5f) + RMG_BORDER_CELLS,+ (Int)(m_starts[who[k]].m_cellY + 0.5f) + RMG_BORDER_CELLS,+ dist[who[k]] );+ flooded[who[k]] = 1;+ }+ if( pass == 1 )+ break;++ Int now = dist[player][cellIndex( money.m_cellX, money.m_cellY )];+ if( now >= 0 && now <= money.m_walk + RMG_MONEY_WALK_SLACK )+ break;++ Int fromX, fromY;+ startPerimeterToward( player, money.m_cellX, money.m_cellY, &fromX, &fromY );+ Real protectX = m_starts[player].m_cellX + (Real)RMG_BORDER_CELLS;+ Real protectY = m_starts[player].m_cellY + (Real)RMG_BORDER_CELLS;+ if( !carvePassBetweenCells( fromX, fromY, money.m_cellX, money.m_cellY, FALSE,+ RMG_FLAT_RADIUS, protectX, protectY ) )+ break;++ buildPassability();+ flooded.assign( players, 0 );+ }++ if( money.m_rival < 0 || money.m_object < 0 )+ continue;++ const std::vector<Int>& mine = dist[player];+ const std::vector<Int>& theirs = dist[money.m_rival];+ Int cell = cellIndex( money.m_cellX, money.m_cellY );+ if( mine[cell] >= 0 && ( theirs[cell] < 0 || mine[cell] + RMG_CONTESTED_LEAD_MIN <= theirs[cell] ) )+ continue;++ // The nearest cell on the pad that gives the placer its lead back, if there is one.+ const Int reach = (Int)RMG_PAD_RADIUS - 1;+ Int bestX = 0, bestY = 0, bestOff = -1;+ for( Int dy = -reach; dy <= reach; dy++ )+ {+ for( Int dx = -reach; dx <= reach; dx++ )+ {+ Int off = dx * dx + dy * dy;+ if( off > reach * reach || ( bestOff >= 0 && off >= bestOff ) )+ continue;+ Int c = cellIndex( money.m_cellX + dx, money.m_cellY + dy );+ if( mine[c] < 0 || theirs[c] < 0 )+ continue;+ Int lead = theirs[c] - mine[c];+ if( lead < RMG_CONTESTED_LEAD_MIN || lead > RMG_CONTESTED_LEAD_MAX )+ continue;+ bestX = dx;+ bestY = dy;+ bestOff = off;+ }+ }+ if( bestOff < 0 )+ continue;++ RMGObject& dock = m_objects[money.m_object];+ dock.m_worldX += (Real)bestX * MAP_XY_FACTOR;+ dock.m_worldY += (Real)bestY * MAP_XY_FACTOR;+ }+ }+}+//-----------------------------------------------------------------------------// Texture classes and their blends//-----------------------------------------------------------------------------@@ -2844,15 +4109,22 @@ void RMGLayout::buildTerrainClasses( const UnsignedByte perm[512] )UnsignedByte terrainClass = RMG_TERRAIN_GRASS;// Sand runs from the water up the whole beach, which is what makes a lake read as a lake- // with a shore rather than a hole of water cut in the grass.- if( height < m_waterHeight + 8.0f + wobble * 3.0f )+ // with a shore rather than a hole of water cut in the grass. Only near water, though: a+ // dry hollow on a highland map is low without being a beach.+ Real distanceToShore;+ insideLake( (Real)(x - RMG_BORDER_CELLS), (Real)(y - RMG_BORDER_CELLS), &distanceToShore );++ if( height < m_waterHeight + 8.0f + wobble * 3.0f &&+ distanceToShore < RMG_LAKE_SHORE + 8.0f )terrainClass = RMG_TERRAIN_SAND;else if( span > RMG_CLIFF_WORLD_SPAN * (0.45f + wobble * 0.12f) )terrainClass = RMG_TERRAIN_ROCK;// Dry high ground. The offset is in height bytes rather than a fraction of the// amplitude: five octaves only reach a third of their nominal range, so a fraction of// it puts the line above anything the noise ever climbs to.- else if( height > RMG_BASE_HEIGHT + 8.0f + wobble * 5.0f )+ // The line scales with the map type's relief, so a plain still has its brown rises and+ // highlands are not brown from the foot of every hill.+ else if( height > RMG_BASE_HEIGHT + ( 8.0f + wobble * 5.0f ) * m_type->m_amplitude )terrainClass = RMG_TERRAIN_DIRT;m_terrain[cellIndex( x, y )] = terrainClass;@@ -3096,6 +4368,9 @@ void RMGLayout::flattenPad( Real cellX, Real cellY, Real radius, Real blend )if( underwaterAtCell( x, y ) )continue;+ if( !m_routeLock.empty() && m_routeLock[cellIndex( x, y )] )+ continue;+Real distance = sqrtf( (Real)(dx * dx + dy * dy) );if( distance >= blend )continue;@@ -3143,12 +4418,167 @@ void RMGLayout::flattenPad( Real cellX, Real cellY, Real radius, Real blend )}}+/** The ground a town stands on, eased rather than levelled. Inside the street grid the relief is+ averaged over a wide window, which takes a terrace step out of a street and leaves the long roll+ of the hill in it; outside the grid that easing fades back into the ground as it was. The shape+ is the grid's own turned rectangle, so a town is a block of streets on a hillside and not a+ round plate pressed into it. Water, the beach and anything already placed keep their ground. */+void RMGLayout::gradeTown( Real centreX, Real centreY, const RMGTownPlan& plan,+ Real acrossStart, Real acrossEnd, Real downStart, Real downEnd )+{+ Real fromAcross = acrossStart - RMG_TOWN_GRADE_MARGIN;+ Real toAcross = acrossEnd + RMG_TOWN_GRADE_MARGIN;+ Real fromDown = downStart - RMG_TOWN_GRADE_MARGIN;+ Real toDown = downEnd + RMG_TOWN_GRADE_MARGIN;++ Real farAcross = (fabsf( fromAcross ) > fabsf( toAcross )) ? fabsf( fromAcross ) : fabsf( toAcross );+ Real farDown = (fabsf( fromDown ) > fabsf( toDown )) ? fabsf( fromDown ) : fabsf( toDown );+ Int reach = (Int)(sqrtf( farAcross * farAcross + farDown * farDown ) + RMG_TOWN_GRADE_FADE) + 1;++ Int centreCellX = (Int)(centreX + 0.5f) + RMG_BORDER_CELLS;+ Int centreCellY = (Int)(centreY + 0.5f) + RMG_BORDER_CELLS;++ const Int blur = RMG_TOWN_GRADE_BLUR;+ Int left = centreCellX - reach - 2 * blur;+ Int top = centreCellY - reach - 2 * blur;+ Int right = centreCellX + reach + 2 * blur;+ Int bottom = centreCellY + reach + 2 * blur;+ if( left < 0 ) left = 0;+ if( top < 0 ) top = 0;+ if( right > m_width - 1 ) right = m_width - 1;+ if( bottom > m_height - 1 ) bottom = m_height - 1;+ if( right <= left || bottom <= top )+ return;++ Int spanX = right - left + 1;+ Int spanY = bottom - top + 1;+ std::vector<Real> field( spanX * spanY );+ std::vector<Real> scratch( spanX * spanY );++ Int x, y;+ for( y = 0; y < spanY; y++ )+ for( x = 0; x < spanX; x++ )+ field[y * spanX + x] = (Real)m_heights[cellIndex( left + x, top + y )];++ // Two box passes each way, which is a tent: a step comes out as an even slope with no corner.+ for( Int pass = 0; pass < 2; pass++ )+ {+ for( y = 0; y < spanY; y++ )+ {+ for( x = 0; x < spanX; x++ )+ {+ Real total = 0.0f;+ Int count = 0;+ for( Int k = x - blur; k <= x + blur; k++ )+ {+ if( k < 0 || k >= spanX )+ continue;+ total += field[y * spanX + k];+ count++;+ }+ scratch[y * spanX + x] = total / (Real)count;+ }+ }++ for( y = 0; y < spanY; y++ )+ {+ for( x = 0; x < spanX; x++ )+ {+ Real total = 0.0f;+ Int count = 0;+ for( Int k = y - blur; k <= y + blur; k++ )+ {+ if( k < 0 || k >= spanY )+ continue;+ total += scratch[k * spanX + x];+ count++;+ }+ field[y * spanX + x] = total / (Real)count;+ }+ }+ }++ Real cosine = Cos( plan.m_rotation );+ Real sine = Sin( plan.m_rotation );+ Real bankLevel = m_waterHeight + RMG_LAKE_BANK;+ Real siteFade = RMG_TOWN_GRADE_FADE * 0.5f;++ for( y = centreCellY - reach; y <= centreCellY + reach; y++ )+ {+ for( x = centreCellX - reach; x <= centreCellX + reach; x++ )+ {+ if( x < left || y < top || x > right || y > bottom )+ continue;+ if( underwaterAtCell( x, y ) )+ continue;++ Real playX = (Real)(x - RMG_BORDER_CELLS);+ Real playY = (Real)(y - RMG_BORDER_CELLS);+ Real dx = playX - centreX;+ Real dy = playY - centreY;+ Real across = dx * cosine + dy * sine;+ Real down = dy * cosine - dx * sine;++ Real outAcross = 0.0f;+ if( across < fromAcross ) outAcross = fromAcross - across;+ else if( across > toAcross ) outAcross = across - toAcross;+ Real outDown = 0.0f;+ if( down < fromDown ) outDown = fromDown - down;+ else if( down > toDown ) outDown = down - toDown;++ Real outside = sqrtf( outAcross * outAcross + outDown * outDown );+ if( outside >= RMG_TOWN_GRADE_FADE )+ continue;++ Real weight = 1.0f - fadeCurve( outside / RMG_TOWN_GRADE_FADE );++ Real distanceToShore;+ insideLake( playX, playY, &distanceToShore );+ if( distanceToShore < RMG_PAD_SHORE_KEEP )+ continue;+ Real shoreT = (distanceToShore - RMG_PAD_SHORE_KEEP) / RMG_LAKE_SHORE;+ if( shoreT < 1.0f )+ weight *= shoreT;++ Bool onReserved = FALSE;+ for( UnsignedInt s = 0; s < m_sites.size(); s++ )+ {+ Real sx = playX - m_sites[s].m_cellX;+ Real sy = playY - m_sites[s].m_cellY;+ Real clear = sqrtf( sx * sx + sy * sy ) - m_sites[s].m_radius;+ if( clear < 0.0f )+ {+ onReserved = TRUE;+ break;+ }+ if( clear < siteFade )+ weight *= clear / siteFade;+ }+ if( onReserved || weight <= 0.0f )+ continue;++ Real ground = (Real)m_heights[cellIndex( x, y )];+ Real graded = field[(y - top) * spanX + (x - left)];++ // Averaging in a lake bed must not sink dry ground under the water line.+ Real lowest = (ground < bankLevel) ? ground : bankLevel;+ if( graded < lowest )+ graded = lowest;++ Real h = lerpReal( ground, graded, weight );+ if( h < 1.0f ) h = 1.0f;+ if( h > 254.0f ) h = 254.0f;+ m_heights[cellIndex( x, y )] = (UnsignedByte)(h + 0.5f);+ }+ }+}+/** One road segment, as the two objects W3DRoadBuffer pairs up. They have to stay next to eachother in the object list, which is why this writes both and nothing goes between them. */void RMGLayout::addRoad( Real fromX, Real fromY, Real toX, Real toY ){RMGObject point;- point.m_templateName = RMG_TOWN_ROAD;+ point.m_templateName = m_biome->m_road;point.m_uniqueID = AsciiString::TheEmptyString;point.m_angle = 0.0f;point.m_waypointID = 0;@@ -3537,148 +4967,391 @@ Bool RMGLayout::findContestedSite( Int startA, Int startB, Real minWalk, Real clreturn found;}-/** A supply dock beside every base, one more out in the middle of the map for- each player to fight over, and two oil derricks a player scattered between- them. Home money sits on one ring shared by every start; the contested dock- is a walk that is about as long from both sides. */+/** Walk distances from every start over the ground as it stands, and for each cell the start+ that walks there first and by how many cells it beats the next one. A tie goes to the lower+ seat, the way anything that counts ownership by walk breaks it too. */+void RMGLayout::walkFromStarts( std::vector< std::vector<Int> >& walk, std::vector<Int>& owner,+ std::vector<Int>& lead )+{+ /* The build levels the bases once more after everything is placed, and a pad that crept into a+ base's blend ring comes out of that with a step in it. Walk the ground as it will end up. */+ flattenBases();+ buildPassability();++ Int players = (Int)m_starts.size();+ walk.resize( players );+ for( Int i = 0; i < players; i++ )+ {+ Int x = (Int)(m_starts[i].m_cellX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(m_starts[i].m_cellY + 0.5f) + RMG_BORDER_CELLS;+ floodDistancesFromCell( x, y, walk[i] );+ }++ Int cells = m_width * m_height;+ owner.assign( cells, -1 );+ lead.assign( cells, 0 );+ for( Int c = 0; c < cells; c++ )+ {+ Int best = -1;+ Int second = -1;+ for( Int i = 0; i < players; i++ )+ {+ Int d = walk[i][c];+ if( d < 0 )+ continue;+ if( best < 0 || d < walk[best][c] )+ {+ second = best;+ best = i;+ }+ else if( second < 0 || d < walk[second][c] )+ second = i;+ }++ owner[c] = best;+ if( best >= 0 )+ lead[c] = ( second < 0 ) ? RMG_MONEY_NO_RIVAL : walk[second][c] - walk[best][c];+ }+}++/** A spot this player walks to in target cells, give or take the band, and reaches before anybody+ else by minLead to maxLead cells. Ownership is the walk, not the ring: a dock eighteen cells+ out in a straight line is forty on foot when a cliff is in the way, and a derrick put on the+ flank of an eight-seat ring is closer to the neighbour than to the player it was meant for. */+Bool RMGLayout::findSiteByWalk( const std::vector< std::vector<Int> >& walk,+ const std::vector<Int>& owner, const std::vector<Int>& lead,+ Int player, Int target, Int band, Int minLead, Int maxLead,+ Real bearing, Real clearance, RMGPoint *out ) const+{+ const std::vector<Int>& mine = walk[player];+ Real startX = m_starts[player].m_cellX;+ Real startY = m_starts[player].m_cellY;+ Real playable = (Real)m_settings.m_playableCells;+ Real ring = (Real)target / RMG_MONEY_WALK_STRETCH;+ Real edge = 4.0f + clearance;+ Real dryMargin = 4.0f + clearance * 0.5f;+ if( dryMargin > 26.0f )+ dryMargin = 26.0f;++ Real bestScore = 1.0e9f;+ Bool found = FALSE;++ for( Int y = RMG_BORDER_CELLS; y < m_height - RMG_BORDER_CELLS; y++ )+ {+ for( Int x = RMG_BORDER_CELLS; x < m_width - RMG_BORDER_CELLS; x++ )+ {+ Int index = cellIndex( x, y );+ if( owner[index] != player )+ continue;++ Int off = mine[index] - target;+ if( off < 0 )+ off = -off;+ if( off > band || lead[index] < minLead || lead[index] > maxLead )+ continue;++ Real cellX = (Real)(x - RMG_BORDER_CELLS);+ Real cellY = (Real)(y - RMG_BORDER_CELLS);+ if( cellX < edge || cellY < edge || cellX > playable - edge || cellY > playable - edge )+ continue;++ Real turn = ATan2( cellY - startY, cellX - startX ) - bearing;+ while( turn > PI )+ turn -= 2.0f * PI;+ while( turn < -PI )+ turn += 2.0f * PI;++ /* Among spots of equal walk, the one that is also on the straight-line ring, so a seat+ does not get its money as far on foot but a lot further as the crow flies. */+ Real dx = cellX - startX;+ Real dy = cellY - startY;+ Real straight = sqrtf( dx * dx + dy * dy ) - ring;++ // roughness only ever adds, so a spot already worse than the best skips the costly checks+ Real score = (Real)off + fabsf( turn ) * 4.0f + fabsf( straight ) * 0.5f;+ if( score >= bestScore )+ continue;++ Real distanceToShore;+ insideLake( cellX, cellY, &distanceToShore );+ if( distanceToShore < dryMargin )+ continue;++ if( !siteIsClear( cellX, cellY, clearance ) )+ continue;++ score += roughnessAt( x, y, 5 ) * 0.35f;+ if( score < bestScore )+ {+ bestScore = score;+ out->m_cellX = cellX;+ out->m_cellY = cellY;+ found = TRUE;+ }+ }+ }++ return found;+}++/** Mark the walk from a start to its money so that no later pad - a town, a bunker on a ramp -+ levels the ground it runs over. A bunker pad beside a base on a hill used to leave a step+ across the way to the dock, and the dock twenty cells from the yard became forty-five. The+ route is the flood walked backwards from the site, downhill in walk count, a band either side. */+void RMGLayout::lockRoute( const std::vector<Int>& walk, const RMGPoint& site )+{+ if( m_routeLock.size() != m_heights.size() )+ m_routeLock.assign( m_heights.size(), 0 );++ static const Int offsetX[4] = { 1, -1, 0, 0 };+ static const Int offsetY[4] = { 0, 0, 1, -1 };++ Int x = (Int)(site.m_cellX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(site.m_cellY + 0.5f) + RMG_BORDER_CELLS;+ Int here = walk[cellIndex( x, y )];++ while( here > 0 )+ {+ for( Int dy = -RMG_ROUTE_LOCK_HALF_WIDTH; dy <= RMG_ROUTE_LOCK_HALF_WIDTH; dy++ )+ {+ for( Int dx = -RMG_ROUTE_LOCK_HALF_WIDTH; dx <= RMG_ROUTE_LOCK_HALF_WIDTH; dx++ )+ {+ Int lx = x + dx;+ Int ly = y + dy;+ if( lx >= 0 && ly >= 0 && lx < m_width && ly < m_height )+ m_routeLock[cellIndex( lx, ly )] = 1;+ }+ }++ Bool stepped = FALSE;+ for( Int k = 0; k < 4 && !stepped; k++ )+ {+ Int nx = x + offsetX[k];+ Int ny = y + offsetY[k];+ if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )+ continue;+ if( walk[cellIndex( nx, ny )] == here - 1 )+ {+ x = nx;+ y = ny;+ here--;+ stepped = TRUE;+ }+ }+ if( !stepped )+ break;+ }+}++/** Every player's money, placed by walking rather than by ring: a home dock, two derricks and two+ small piles that each player reaches first, by a clear lead, at the same walk give or take a+ couple of cells for every seat. Then one contested dock a player, on the walk midline with the+ neighbour who shares it, a few cells to the placing player's side so each seat owns exactly+ one. The ground is re-walked between kinds because every pad moves a slope. All of it is laid+ before towns and bunkers, whose pads are kept off the reserved sites, so nothing walls it. */void RMGLayout::placeSupplyAndDerricks( void ){Int supplyID = 1;Int derrickID = 1;+ Int pileID = 1;Real playable = (Real)m_settings.m_playableCells;+ Int players = (Int)m_starts.size();++ std::vector< std::vector<Int> > walk;+ std::vector<Int> owner;+ std::vector<Int> lead;- /* Same ring and the same compass slot for every start: outward from the map centre,- then the next 45-degree hole if that ray is water. Independent flattest-on-the-ring- search was how one player opened on a dock at 18 and the next at 30 behind a lake. */Real homeRing = RMG_HOME_SUPPLY_MIN + 4.0f + hashUnit( m_settings.m_seed, 19, 1 ) * 8.0f;+ Real derrickRing = RMG_BLEND_RADIUS + 8.0f + hashUnit( m_settings.m_seed, 23, 2 ) * 8.0f;+ Real pileRing = derrickRing + 24.0f + hashUnit( m_settings.m_seed, 29, 3 ) * 6.0f;- for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ struct RMGMoney{- Real outward = outwardBearing( m_starts[i].m_cellX, m_starts[i].m_cellY );- RMGPoint best;- if( !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, homeRing, 6.0f,- outward, RMG_SITE_CLEARANCE, &best ) &&- !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, homeRing, 10.0f,- outward, RMG_SITE_CLEARANCE * 0.5f, &best ) &&- !findSiteNear( m_starts[i].m_cellX, m_starts[i].m_cellY, RMG_HOME_SUPPLY_MIN,- RMG_HOME_SUPPLY_MAX * 2.0f, 1.0f, &best ) )- continue;-- Real angle = snapAngle45( ATan2( m_starts[i].m_cellY - best.m_cellY,- m_starts[i].m_cellX - best.m_cellX ) );-- AsciiString uniqueID;- uniqueID.format( "SupplyDock %d", supplyID++ );- addObject( "SupplyDock", uniqueID.str(), best.m_cellX, best.m_cellY, angle );- flattenPad( best.m_cellX, best.m_cellY, RMG_PAD_RADIUS, RMG_PAD_BLEND );- reserveSite( best.m_cellX, best.m_cellY, RMG_SITE_CLEARANCE );- }+ const char *m_template;+ const char *m_name;+ Real m_ring; ///< cells in a straight line; the walk target is a little longer+ Real m_turn; ///< preferred bearing off the outward one+ Real m_clearance;+ Real m_pad;+ Real m_blend;+ };+ const RMGMoney theMoney[] =+ {+ { "SupplyDock", "SupplyDock", homeRing, 0.0f, RMG_SITE_CLEARANCE, RMG_PAD_RADIUS, RMG_PAD_BLEND },+ { "TechOilDerrick", "Derrick", derrickRing, PI * 0.5f, RMG_SITE_CLEARANCE, RMG_PAD_RADIUS, RMG_PAD_BLEND },+ { "TechOilDerrick", "Derrick", derrickRing + 12.0f, -PI * 0.5f, RMG_SITE_CLEARANCE, RMG_PAD_RADIUS, RMG_PAD_BLEND },+ { "SupplyPileSmall", "SupplyPile", pileRing, PI * 0.25f, RMG_PILE_CLEARANCE, RMG_PILE_PAD, RMG_PILE_BLEND },+ { "SupplyPileSmall", "SupplyPile", pileRing + 10.0f, -PI * 0.25f, RMG_PILE_CLEARANCE, RMG_PILE_PAD, RMG_PILE_BLEND },+ };+ const Int numMoney = sizeof(theMoney) / sizeof(theMoney[0]);+ static const Int theBands[] = { 1, 3, 6, 10 };+ const Int numBands = sizeof(theBands) / sizeof(theBands[0]);- /* One contested dock a player, on that player's side of the line to their nearest- neighbour, not the global flattest cell between them (which the first seat in the- list used to take, leaving the second a leftover). */- for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ for( Int m = 0; m < numMoney; m++ ){- Real nearest = 1.0e9f;- UnsignedInt nearestIndex = i;- for( UnsignedInt j = 0; j < m_starts.size(); j++ )+ const RMGMoney& money = theMoney[m];+ walkFromStarts( walk, owner, lead );+ Int target = (Int)(money.m_ring * RMG_MONEY_WALK_STRETCH + 0.5f);++ for( Int i = 0; i < players; i++ ){- if( j == i )- continue;+ Real sx = m_starts[i].m_cellX;+ Real sy = m_starts[i].m_cellY;+ Real bearing = outwardBearing( sx, sy ) + money.m_turn;- Real dx = m_starts[i].m_cellX - m_starts[j].m_cellX;- Real dy = m_starts[i].m_cellY - m_starts[j].m_cellY;- Real distance = sqrtf( dx * dx + dy * dy );- if( distance < nearest )+ RMGPoint site;+ Bool found = FALSE;+ Bool walked = TRUE;+ for( Int b = 0; b < numBands && !found; b++ )+ found = findSiteByWalk( walk, owner, lead, i, target, theBands[b], RMG_MONEY_LEAD,+ RMG_MONEY_NO_RIVAL, bearing, money.m_clearance, &site );+ if( !found )+ found = findSiteByWalk( walk, owner, lead, i, target, 16, 1, RMG_MONEY_NO_RIVAL,+ bearing, money.m_clearance * 0.5f, &site );+ if( !found ){- nearest = distance;- nearestIndex = j;+ walked = FALSE;+ found = findSiteOnCompass( sx, sy, money.m_ring, 12.0f, bearing, 3.0f, &site ) ||+ findSiteNear( sx, sy, money.m_ring - 8.0f, money.m_ring + 20.0f, 2.0f, &site );}- }+ if( !found )+ continue;- Real toward = snapAngle45( ATan2( m_starts[nearestIndex].m_cellY - m_starts[i].m_cellY,- m_starts[nearestIndex].m_cellX - m_starts[i].m_cellX ) );- Real radius = nearest * 0.42f;- if( radius < RMG_HOME_SUPPLY_MAX + 4.0f )- radius = RMG_HOME_SUPPLY_MAX + 4.0f;- if( radius > playable * 0.38f )- radius = playable * 0.38f;+ // Lock the walk first, so the pad's own blend does not lengthen the walk it was chosen by.+ if( walked )+ {+ RMGMoneyWalk planned;+ planned.m_player = i;+ planned.m_rival = -1;+ planned.m_object = -1;+ planned.m_cellX = (Int)(site.m_cellX + 0.5f) + RMG_BORDER_CELLS;+ planned.m_cellY = (Int)(site.m_cellY + 0.5f) + RMG_BORDER_CELLS;+ planned.m_walk = walk[i][cellIndex( planned.m_cellX, planned.m_cellY )];+ m_moneyWalks.push_back( planned );+ }+ if( walked )+ lockRoute( walk[i], site );+ flattenPad( site.m_cellX, site.m_cellY, money.m_pad, money.m_blend );- RMGPoint site;- if( !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, radius, 8.0f,- toward, RMG_SITE_CLEARANCE, &site ) &&- !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, radius, 12.0f,- toward, 3.0f, &site ) &&- !findContestedSite( (Int)i, (Int)nearestIndex, RMG_BLEND_RADIUS, 3.0f, &site ) )- continue;+ Real angle = snapAngle45( ATan2( sy - site.m_cellY, sx - site.m_cellX ) );- Real angle = snapAngle45( ATan2( m_starts[i].m_cellY - site.m_cellY,- m_starts[i].m_cellX - site.m_cellX ) );+ Int *counter = &pileID;+ if( strcmp( money.m_template, "SupplyDock" ) == 0 )+ counter = &supplyID;+ else if( strcmp( money.m_template, "TechOilDerrick" ) == 0 )+ counter = &derrickID;- AsciiString uniqueID;- uniqueID.format( "SupplyDock %d", supplyID++ );- addObject( "SupplyDock", uniqueID.str(), site.m_cellX, site.m_cellY, angle );- flattenPad( site.m_cellX, site.m_cellY, RMG_PAD_RADIUS, RMG_PAD_BLEND );- reserveSite( site.m_cellX, site.m_cellY, RMG_SITE_CLEARANCE );+ AsciiString uniqueID;+ uniqueID.format( "%s %d", money.m_name, (*counter)++ );+ addObject( money.m_template, uniqueID.str(), site.m_cellX, site.m_cellY, angle );+ reserveSite( site.m_cellX, site.m_cellY, money.m_clearance );+ }}- // Flanks: +90 and -90 from outward, same ring for every start.- Real derrickRing = RMG_BLEND_RADIUS + 8.0f + hashUnit( m_settings.m_seed, 23, 2 ) * 8.0f;- static const Real derrickTurn[2] = { PI * 0.5f, -PI * 0.5f };- for( Int round = 0; round < RMG_DERRICKS_PER_PLAYER; round++ )+ /* The contested docks: one walk target for every seat, half the shortest walk any player has+ to a neighbour, so no seat's fight is closer to home than another's. */+ walkFromStarts( walk, owner, lead );+ std::vector<Int> rival( players, -1 );+ Int contestedWalk = -1;+ for( Int i = 0; i < players; i++ ){- Real ring = derrickRing + (Real)round * 12.0f;- for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ Int nearestWalk = -1;+ for( Int j = 0; j < players; j++ ){- Real bearing = outwardBearing( m_starts[i].m_cellX, m_starts[i].m_cellY ) + derrickTurn[round];- RMGPoint site;- if( !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, ring, 6.0f,- bearing, RMG_SITE_CLEARANCE, &site ) &&- !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, ring, 12.0f,- bearing, 3.0f, &site ) &&- !findSiteNear( m_starts[i].m_cellX, m_starts[i].m_cellY, ring - 8.0f,- ring + 20.0f, 3.0f, &site ) )+ if( j == i )continue;-- Real angle = snapAngle45( ATan2( m_starts[i].m_cellY - site.m_cellY,- m_starts[i].m_cellX - site.m_cellX ) );-- AsciiString uniqueID;- uniqueID.format( "Derrick %d", derrickID++ );- addObject( "TechOilDerrick", uniqueID.str(), site.m_cellX, site.m_cellY, angle );- flattenPad( site.m_cellX, site.m_cellY, RMG_PAD_RADIUS, RMG_PAD_BLEND );- reserveSite( site.m_cellX, site.m_cellY, RMG_SITE_CLEARANCE );+ Int x = (Int)(m_starts[j].m_cellX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(m_starts[j].m_cellY + 0.5f) + RMG_BORDER_CELLS;+ Int d = walk[i][cellIndex( x, y )];+ if( d >= 0 && ( nearestWalk < 0 || d < nearestWalk ) )+ {+ nearestWalk = d;+ rival[i] = j;+ }}+ if( nearestWalk >= 0 && ( contestedWalk < 0 || nearestWalk / 2 < contestedWalk ) )+ contestedWalk = nearestWalk / 2;}- /* Small supply piles on the diagonals, past the derricks. */- Int pileID = 1;- Real pileRing = derrickRing + 24.0f + hashUnit( m_settings.m_seed, 29, 3 ) * 6.0f;- static const Real pileTurn[2] = { PI * 0.25f, -PI * 0.25f };- for( Int round = 0; round < RMG_SMALL_PILES_PER_PLAYER; round++ )+ static const Int theContestedBands[] = { 3, 8, 16, 1000 };+ const Int numContestedBands = sizeof(theContestedBands) / sizeof(theContestedBands[0]);+ for( Int i = 0; i < players; i++ ){- Real ring = pileRing + (Real)round * 10.0f;- for( UnsignedInt i = 0; i < m_starts.size(); i++ )+ Real sx = m_starts[i].m_cellX;+ Real sy = m_starts[i].m_cellY;+ RMGPoint site;+ Bool found = FALSE;++ if( rival[i] >= 0 && contestedWalk > 0 ){- Real bearing = outwardBearing( m_starts[i].m_cellX, m_starts[i].m_cellY ) + pileTurn[round];- RMGPoint site;- if( !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, ring, 6.0f,- bearing, RMG_PILE_CLEARANCE, &site ) &&- !findSiteOnCompass( m_starts[i].m_cellX, m_starts[i].m_cellY, ring, 12.0f,- bearing, 2.0f, &site ) &&- !findSiteNear( m_starts[i].m_cellX, m_starts[i].m_cellY, ring - 10.0f,- ring + 18.0f, 2.0f, &site ) )- continue;+ Real toward = ATan2( m_starts[rival[i]].m_cellY - sy, m_starts[rival[i]].m_cellX - sx );+ for( Int b = 0; b < numContestedBands && !found; b++ )+ found = findSiteByWalk( walk, owner, lead, i, contestedWalk, theContestedBands[b],+ RMG_CONTESTED_LEAD_MIN, RMG_CONTESTED_LEAD_MAX, toward,+ RMG_SITE_CLEARANCE, &site );+ if( !found )+ found = findSiteByWalk( walk, owner, lead, i, contestedWalk, 1000, 1,+ RMG_CONTESTED_LEAD_MAX * 2, toward, 3.0f, &site );+ if( found )+ {+ RMGMoneyWalk planned;+ planned.m_player = i;+ planned.m_rival = rival[i];+ planned.m_object = (Int)m_objects.size(); // added just below+ planned.m_cellX = (Int)(site.m_cellX + 0.5f) + RMG_BORDER_CELLS;+ planned.m_cellY = (Int)(site.m_cellY + 0.5f) + RMG_BORDER_CELLS;+ planned.m_walk = walk[i][cellIndex( planned.m_cellX, planned.m_cellY )];+ m_moneyWalks.push_back( planned );++ lockRoute( walk[i], site );+ lockRoute( walk[rival[i]], site );+ flattenPad( site.m_cellX, site.m_cellY, RMG_PAD_RADIUS, RMG_PAD_BLEND );+ }+ }+ Bool padded = found;++ if( !found )+ {+ // old way: on this player's side of the straight line to the nearest neighbour+ Real nearest = 1.0e9f;+ Int nearestIndex = i;+ for( Int j = 0; j < players; j++ )+ {+ if( j == i )+ continue;+ Real dx = sx - m_starts[j].m_cellX;+ Real dy = sy - m_starts[j].m_cellY;+ Real distance = sqrtf( dx * dx + dy * dy );+ if( distance < nearest )+ {+ nearest = distance;+ nearestIndex = j;+ }+ }- Real angle = snapAngle45( ATan2( m_starts[i].m_cellY - site.m_cellY,- m_starts[i].m_cellX - site.m_cellX ) );+ Real toward = snapAngle45( ATan2( m_starts[nearestIndex].m_cellY - sy,+ m_starts[nearestIndex].m_cellX - sx ) );+ Real radius = nearest * 0.42f;+ if( radius < RMG_HOME_SUPPLY_MAX + 4.0f )+ radius = RMG_HOME_SUPPLY_MAX + 4.0f;+ if( radius > playable * 0.38f )+ radius = playable * 0.38f;- AsciiString uniqueID;- uniqueID.format( "SupplyPile %d", pileID++ );- addObject( "SupplyPileSmall", uniqueID.str(), site.m_cellX, site.m_cellY, angle );- flattenPad( site.m_cellX, site.m_cellY, RMG_PILE_PAD, RMG_PILE_BLEND );- reserveSite( site.m_cellX, site.m_cellY, RMG_PILE_CLEARANCE );+ found = findSiteOnCompass( sx, sy, radius, 12.0f, toward, 3.0f, &site ) ||+ findContestedSite( i, nearestIndex, RMG_BLEND_RADIUS, 3.0f, &site );}++ if( !found )+ continue;++ Real angle = snapAngle45( ATan2( sy - site.m_cellY, sx - site.m_cellX ) );++ AsciiString uniqueID;+ uniqueID.format( "SupplyDock %d", supplyID++ );+ addObject( "SupplyDock", uniqueID.str(), site.m_cellX, site.m_cellY, angle );+ if( !padded )+ flattenPad( site.m_cellX, site.m_cellY, RMG_PAD_RADIUS, RMG_PAD_BLEND );+ reserveSite( site.m_cellX, site.m_cellY, RMG_SITE_CLEARANCE );}}@@ -3707,25 +5380,42 @@ void RMGLayout::placeTowns( void )if( towns < 2 )towns = 2;+ Int townsPlaced = 0;for( Int town = 0; town < towns; town++ ){+ /* The next start along when this one's surroundings are full: a river or the money can take+ all the room near one base and leave plenty near the next. Then the middle of the map,+ which is between everybody by construction. A map about to end with no town at all rolls+ the last one again, smaller or turned, until one fits. */+ Int rolls = (town == towns - 1 && townsPlaced == 0) ? RMG_TOWN_REROLLS : 1;RMGTownPlan plan;- rollTownPlan( m_settings.m_seed, town, &plan );+ RMGPoint site;+ Bool found = FALSE;+ for( Int roll = 0; roll < rolls && !found; roll++ )+ {+ rollTownPlan( m_settings.m_seed, town + 16 * roll, &plan );- // Out of everybody's base, in the ground between them, which is where a town is worth- // fighting through rather than one more thing in somebody's back garden.- Real inner = RMG_BLEND_RADIUS + plan.m_radius + 6.0f;- Real outer = inner + (Real)m_settings.m_playableCells * 0.22f;- UnsignedInt which = (UnsignedInt)town % (UnsignedInt)m_starts.size();+ // Out of everybody's base, in the ground between them, which is where a town is worth+ // fighting through rather than one more thing in somebody's back garden.+ Real inner = RMG_BLEND_RADIUS + plan.m_radius + 6.0f;+ Real outer = inner + (Real)m_settings.m_playableCells * 0.22f;+ UnsignedInt which = (UnsignedInt)town % (UnsignedInt)m_starts.size();- RMGPoint site;- if( !findSiteNear( m_starts[which].m_cellX, m_starts[which].m_cellY, inner, outer,- plan.m_radius, &site ) )+ for( UnsignedInt tried = 0; tried < m_starts.size() && !found; tried++ )+ {+ UnsignedInt around = ( which + tried ) % (UnsignedInt)m_starts.size();+ found = findSiteNear( m_starts[around].m_cellX, m_starts[around].m_cellY, inner, outer,+ plan.m_radius, &site );+ }+ if( !found )+ {+ Real middle = (Real)m_settings.m_playableCells * 0.5f;+ found = findSiteNear( middle, middle, 0.0f, middle, plan.m_radius, &site );+ }+ }+ if( !found )continue;-- // The whole town sits on one level: streets that run downhill through a terrace edge are- // streets with a cliff across them.- flattenPad( site.m_cellX, site.m_cellY, plan.m_radius, plan.m_radius + 12.0f );+ townsPlaced++;UnsignedInt hash = hashCell( m_settings.m_seed + 613, (Int)site.m_cellX, (Int)site.m_cellY );Int nameOffset = (Int)(hash % (UnsignedInt)numStreetNames);@@ -3735,6 +5425,8 @@ void RMGLayout::placeTowns( void )Real downEnd = plan.m_downAt[plan.m_streetsDown - 1] + plan.m_setBack;Real downStart = plan.m_downAt[0] - plan.m_setBack;+ gradeTown( site.m_cellX, site.m_cellY, plan, acrossStart, acrossEnd, downStart, downEnd );+Int line;Real fromX, fromY, toX, toY;@@ -3782,11 +5474,6 @@ void RMGLayout::placeTowns( void )for( Int side = 0; side < 2; side++ ){- UnsignedInt plotHash = hashCell( m_settings.m_seed + 6139,- town * 64 + line * 4 + side, plot );- if( plotHash % 100U < RMG_TOWN_GAP_IN_100 )- continue;-Real jitter = (hashUnit( m_settings.m_seed + 6141, town * 64 + line * 4 + side,plot ) - 0.5f) * 2.0f * RMG_TOWN_JITTER;Real back = (side == 0) ? -plan.m_setBack - jitter : plan.m_setBack + jitter;@@ -3805,9 +5492,23 @@ void RMGLayout::placeTowns( void )facing += PI * 0.5f;}+ /* Built up in the middle and thinning out towards the edge, where a town turns+ into yards and then fields, rather than the same density out to a hard line. */+ Real outX = (buildingX - site.m_cellX) / plan.m_radius;+ Real outY = (buildingY - site.m_cellY) / plan.m_radius;+ UnsignedInt gap = RMG_TOWN_GAP_IN_100+ + (UnsignedInt)(RMG_TOWN_EDGE_GAP_IN_100 * (outX * outX + outY * outY));+ UnsignedInt plotHash = hashCell( m_settings.m_seed + 6139,+ town * 64 + line * 4 + side, plot );+ if( plotHash % 100U < gap )+ continue;+if( !dryAt( buildingX, buildingY, RMG_TOWN_DRY_MARGIN ) )continue;+ // Each building on its own small level, so a street down a slope steps.+ flattenPad( buildingX, buildingY, RMG_TOWN_LOT_PAD, RMG_TOWN_LOT_BLEND );+AsciiString uniqueID;uniqueID.format( "Civilian %d", buildingID++ );addObject( theStreetNames[(nameOffset + buildingID) % numStreetNames],@@ -3907,18 +5608,190 @@ void RMGLayout::placeShoreWaves( void )}}-/** Trees stand in woods rather than in a sprinkle: a slow noise field decides- where a wood is, a per-cell hash decides which cells of it are used, and the- species is chosen per wood so one stand does not hold four kinds of tree.- Rocks go where the ground is already rock. */+/** How far every cell is from the routes the bases are joined by, each start's two nearest+ neighbours' routes. Counted in cells regardless of the ground, since it is only asked how open+ a stretch of map should be kept. */+void RMGLayout::buildLaneDistance( void )+{+ m_laneDist.assign( m_width * m_height, (UnsignedByte)RMG_LANE_FAR );+ std::vector<Int> queue;++ // A route counts when it is one of the two shortest out of either of its starts.+ for( UnsignedInt lane = 0; lane < m_lanes.size(); lane++ )+ {+ Int ends[2] = { m_lanes[lane].m_from, m_lanes[lane].m_to };+ Bool neighbours = FALSE;+ for( Int e = 0; e < 2 && !neighbours; e++ )+ {+ Int shorter = 0;+ for( UnsignedInt other = 0; other < m_lanes.size(); other++ )+ {+ if( other == lane )+ continue;+ if( m_lanes[other].m_from != ends[e] && m_lanes[other].m_to != ends[e] )+ continue;+ if( m_lanes[other].m_cells.size() < m_lanes[lane].m_cells.size() ||+ ( m_lanes[other].m_cells.size() == m_lanes[lane].m_cells.size() && other < lane ) )+ shorter++;+ }+ neighbours = shorter < 2;+ }+ if( !neighbours )+ continue;++ for( UnsignedInt c = 0; c < m_lanes[lane].m_cells.size(); c++ )+ {+ Int index = m_lanes[lane].m_cells[c];+ if( m_laneDist[index] != 0 )+ {+ m_laneDist[index] = 0;+ queue.push_back( index );+ }+ }+ }++ static const Int offsetX[4] = { 1, -1, 0, 0 };+ static const Int offsetY[4] = { 0, 0, 1, -1 };++ UnsignedInt head = 0;+ while( head < queue.size() )+ {+ Int index = queue[head++];+ Int here = m_laneDist[index];+ if( here + 1 >= RMG_LANE_FAR )+ continue;+ Int x = index % m_width;+ Int y = index / m_width;+ for( Int k = 0; k < 4; k++ )+ {+ Int nx = x + offsetX[k];+ Int ny = y + offsetY[k];+ if( nx < 0 || ny < 0 || nx >= m_width || ny >= m_height )+ continue;+ Int next = cellIndex( nx, ny );+ if( m_laneDist[next] <= here + 1 )+ continue;+ m_laneDist[next] = (UnsignedByte)(here + 1);+ queue.push_back( next );+ }+ }+}++Int RMGLayout::laneDistanceAt( Real cellX, Real cellY ) const+{+ if( m_laneDist.empty() )+ return RMG_LANE_FAR;+ Int x = (Int)(cellX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(cellY + 0.5f) + RMG_BORDER_CELLS;+ if( x < 0 || y < 0 || x >= m_width || y >= m_height )+ return RMG_LANE_FAR;+ return m_laneDist[cellIndex( x, y )];+}++/** Whether a tree may stand here: on dry walkable ground, out of the bases, off every placed site,+ off every walk to somebody's money and out of the open strip along a route. */+Bool RMGLayout::sceneryMayStand( Real cellX, Real cellY ) const+{+ Int mapX = (Int)(cellX + 0.5f) + RMG_BORDER_CELLS;+ Int mapY = (Int)(cellY + 0.5f) + RMG_BORDER_CELLS;+ if( mapX < 1 || mapY < 1 || mapX >= m_width - 1 || mapY >= m_height - 1 )+ return FALSE;+ if( !passableAtCell( mapX, mapY ) )+ return FALSE;++ Real distanceToShore;+ insideLake( cellX, cellY, &distanceToShore );+ if( distanceToShore < 3.0f )+ return FALSE;++ if( distanceToNearestStart( cellX, cellY ) < RMG_BLEND_RADIUS )+ return FALSE;+ if( !siteIsClear( cellX, cellY, 3.0f ) )+ return FALSE;+ if( !m_routeLock.empty() && m_routeLock[cellIndex( mapX, mapY )] )+ return FALSE;++ return laneDistanceAt( cellX, cellY ) >= RMG_LANE_CLEAR;+}++/** Every player's own stand of trees, AoE's wood beside the base: the same distance out for every+ seat, a quarter turn off the way the base faces outward, and off the money and the routes. */+void RMGLayout::plantGroves( const char *const *theTreeNames, Int *propID, Int *treeBudget )+{+ static const Int turn[8] = { 0, 1, -1, 2, -2, 3, -3, 4 };+ std::vector<RMGPoint> groves;++ for( UnsignedInt start = 0; start < m_starts.size(); start++ )+ {+ const RMGPoint& base = m_starts[start];+ Real preferred = outwardBearing( base.m_cellX, base.m_cellY ) + PI * 0.5f;++ RMGPoint grove;+ Bool found = FALSE;+ for( Int k = 0; k < 8 && !found; k++ )+ {+ Real bearing = preferred + (Real)turn[k] * (PI * 0.25f);+ if( !findSiteOnBearing( base.m_cellX, base.m_cellY, RMG_GROVE_DISTANCE, 6.0f, bearing,+ RMG_GROVE_RADIUS, &grove ) )+ continue;+ if( laneDistanceAt( grove.m_cellX, grove.m_cellY ) < RMG_LANE_CLEAR + (Int)RMG_GROVE_RADIUS )+ continue;+ found = TRUE;+ }+ if( !found )+ continue;+ groves.push_back( grove );++ UnsignedInt woodHash = hashCell( m_settings.m_seed + 40011, (Int)start, 0 );+ for( Int tree = 0; tree < RMG_GROVE_TREES && *treeBudget > 0; tree++ )+ {+ // Square root of the spread, so the stand is as thick at its middle as at its rim.+ Real spread = sqrtf( hashUnit( m_settings.m_seed + 40013, (Int)start, tree ) );+ Real angle = hashUnit( m_settings.m_seed + 40017, (Int)start, tree ) * 2.0f * PI;+ Real x = grove.m_cellX + Cos( angle ) * spread * RMG_GROVE_RADIUS;+ Real y = grove.m_cellY + Sin( angle ) * spread * RMG_GROVE_RADIUS;+ if( !sceneryMayStand( x, y ) )+ continue;++ AsciiString uniqueID;+ uniqueID.format( "Prop %d", (*propID)++ );+ addObject( theTreeNames[( woodHash + (UnsignedInt)(tree / 8) ) % (UnsignedInt)RMG_BIOME_TREES],+ uniqueID.str(), x, y, snapAngle45( angle ) );+ (*treeBudget)--;+ }+ }++ // Reserved after planting, so the woods field does not fill a stand back in tree by tree.+ for( UnsignedInt g = 0; g < groves.size(); g++ )+ reserveSite( groves[g].m_cellX, groves[g].m_cellY, RMG_GROVE_RADIUS );+}++/// A spot the woods field would plant, and how deep into its wood it lies.+struct RMGTreeSpot+{+ Real m_x;+ Real m_y;+ Int m_depth; ///< the field's value times 10000, compared as an integer+ Real m_angle;+ UnsignedInt m_wood;+};++static bool deeperInTheWood( const RMGTreeSpot& a, const RMGTreeSpot& b )+{+ return a.m_depth > b.m_depth;+}++/** Trees stand in woods rather than in a sprinkle: a slow noise field decides where a wood is, a+ per-cell hash decides which cells of it are used, and the species is chosen per wood so one+ stand does not hold four kinds of tree. The woods thicken beside a route, so they line the way+ between two bases and leave the route itself open. Rocks go where the ground is already rock. */void RMGLayout::placeScenery( const UnsignedByte perm[512] ){- static const char *theTreeNames[] = { "TreeDogwood1", "TreeFir01B", "TreeCherryBlossom01",- "TreeCherryBlossom02" };- static const char *theRockNames[] = { "Rocks1", "Rocks2", "Rocks3", "RockClusterMedium01",- "RockClusterSmall01" };- const Int numTreeNames = sizeof(theTreeNames) / sizeof(theTreeNames[0]);- const Int numRockNames = sizeof(theRockNames) / sizeof(theRockNames[0]);+ const char *const *theTreeNames = m_biome->m_trees;+ const char *const *theRockNames = m_biome->m_rocks;+ const Int numTreeNames = RMG_BIOME_TREES;+ const Int numRockNames = RMG_BIOME_ROCKS;+ const Real forestThreshold = m_type->m_forestThreshold;Real playable = (Real)m_settings.m_playableCells;Real forestScale = RMG_FOREST_FEATURES / playable;@@ -3928,32 +5801,40 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )would put every tree in the top of the map, so it sits high enough that an ordinary mapnever reaches it. */Real area = playable * playable;- Int treeBudget = (Int)(area / RMG_CELLS_PER_TREE);+ const Bool woodland = m_type->m_woodland;+ Int treeBudget = (Int)(area / ( woodland ? RMG_WOOD_BUDGET_CELLS : RMG_CELLS_PER_TREE ));+ // A base in a black forest sits in a clearing a good deal wider than its levelled ground.+ const Real baseClearing = woodland ? RMG_BLEND_RADIUS + 10.0f : RMG_BLEND_RADIUS;Int rockBudget = (Int)(area / RMG_CELLS_PER_ROCK);Int propID = 1;- for( Int y = 2; y < m_settings.m_playableCells - 2; y += RMG_PROP_STRIDE )+ buildLaneDistance();+ plantGroves( theTreeNames, &propID, &treeBudget );++ /* Rows are taken in four interleaved passes, so a rock budget that does run out leaves the+ whole map evenly thinner rather than its top bare. */+ std::vector<RMGTreeSpot> spots;++ const Int passes = 4;+ const Int rowsPerPass = ( m_settings.m_playableCells - 4 ) / ( passes * RMG_PROP_STRIDE ) + 1;+ for( Int row = 0; row < passes * rowsPerPass; row++ ){+ Int y = 2 + ( row / rowsPerPass ) * RMG_PROP_STRIDE + ( row % rowsPerPass ) * passes * RMG_PROP_STRIDE;+ if( y >= m_settings.m_playableCells - 2 )+ continue;+for( Int x = 2; x < m_settings.m_playableCells - 2; x += RMG_PROP_STRIDE ){if( treeBudget <= 0 && rockBudget <= 0 )- return;+ break;Int mapX = x + RMG_BORDER_CELLS;Int mapY = y + RMG_BORDER_CELLS;- if( !passableAtCell( mapX, mapY ) )- continue;-- Real distanceToShore;- insideLake( (Real)x, (Real)y, &distanceToShore );- if( distanceToShore < 3.0f )- continue;-- // Bases and everything already placed keep their elbow room.- if( distanceToNearestStart( (Real)x, (Real)y ) < RMG_BLEND_RADIUS )+ // Bases, routes, money walks and everything already placed keep their elbow room.+ if( !sceneryMayStand( (Real)x, (Real)y ) )continue;- if( !siteIsClear( (Real)x, (Real)y, 3.0f ) )+ if( woodland && distanceToNearestStart( (Real)x, (Real)y ) < baseClearing )continue;UnsignedInt hash = hashCell( m_settings.m_seed + 7717, x, y );@@ -3971,6 +5852,23 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )continue;if( (hash >> 24) % 100U > 25U )continue;+ // The ground steepens where the playable area meets the border, and rocks set along+ // that line stand in a ruled row round the map.+ if( x < RMG_ROCK_EDGE_CELLS || y < RMG_ROCK_EDGE_CELLS ||+ x >= m_settings.m_playableCells - RMG_ROCK_EDGE_CELLS ||+ y >= m_settings.m_playableCells - RMG_ROCK_EDGE_CELLS )+ continue;+ // A ramp's sides are steep too, and a rock there blocks the one way up.+ if( nearRamp( (Real)x, (Real)y, RMG_MASSIF_ROCK_CLEAR ) )+ continue;+ // Nor round the massif's cliff, where they would stand in a ring drawn with compasses.+ if( m_type->m_massif > 0.0f )+ {+ Real clearance = massifClearance( (Real)x, (Real)y );+ if( clearance < 3.0f &&+ clearance > -2.0f * playable * RMG_MASSIF_RADIUS * RMG_MASSIF_WOBBLE - RMG_MASSIF_RIM - 3.0f )+ continue;+ }AsciiString uniqueID;uniqueID.format( "Prop %d", propID++ );@@ -3994,25 +5892,98 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )forestY * 2.3f - 4.0f, 2 );Real density = fractalNoise( perm, warpX, warpY, 4 );- if( density < RMG_FOREST_THRESHOLD )- continue;+ Real chance;+ if( woodland )+ {+ /* One wood over the whole map and nothing on the rides. The ride's edge wanders on a+ noise of its own so it reads as a cut through trees, not a ruled band. Inside the wood+ a faster field makes thickets with glades between them, and the slow field makes whole+ quarters of the map thicker or thinner, so the canopy is not one even speckle. A+ thin-treed biome still gets a wood, only a lighter one. */+ Real wobble = RMG_RIDE_WOBBLE * fractalNoise( perm, (Real)x * 0.07f + 3.0f,+ (Real)y * 0.07f + 77.0f, 2 );+ if( rideDistance( (Real)x, (Real)y ) < RMG_RIDE_HALF_WIDTH + wobble )+ continue;+ Real clump = fractalNoise( perm, (Real)x * RMG_WOOD_CLUMP_SCALE + 31.0f,+ (Real)y * RMG_WOOD_CLUMP_SCALE - 57.0f, 3 );+ density = 0.65f * clump + 0.35f * density;+ /* A glade keeps the odd tree, so the wood is still a wood between its thickets. Those+ are counted as deep as a thicket's heart, so a capped map thins the thickets' fringes+ and not the glades down to bare ground. */+ if( density >= RMG_WOOD_CLUMP_EDGE )+ {+ chance = 0.05f + ( density - RMG_WOOD_CLUMP_EDGE ) * 0.8f;+ }+ else+ {+ // In tufts of a few trees off a fast field, not one tree here and one there.+ Real tuft = fractalNoise( perm, (Real)x * 0.16f + 5.0f, (Real)y * 0.16f + 11.0f, 1 );+ chance = tuft > 0.25f ? 0.12f : 0.0f;+ density = 1.0f;+ }+ if( chance > 0.25f )+ chance = 0.25f;+ chance *= 0.5f + 0.5f * m_biome->m_treeShare;+ }+ else+ {+ /* Beside a route a wood that is nearly there comes in up to the open strip, so the route+ reads as a way through the trees. Out in open country it adds nothing: a route across+ a field stays a route across a field rather than an avenue. */+ Int lane = laneDistanceAt( (Real)x, (Real)y );+ if( lane < RMG_LANE_FRAME && density > forestThreshold - 0.14f )+ density += 0.12f * (Real)( RMG_LANE_FRAME - lane ) / (Real)( RMG_LANE_FRAME - RMG_LANE_CLEAR );++ /* A wood starts a little further into the field than before and fills in faster, so+ what stands is a few thick clumps with open ground between them, not a thin dusting. */+ const Real clumpEdge = forestThreshold + 0.05f;+ if( density < clumpEdge )+ continue;- Real chance = (density - RMG_FOREST_THRESHOLD) * 0.55f;- if( chance > 0.16f )- chance = 0.16f;+ chance = 0.05f + (density - clumpEdge) * 1.5f;+ if( chance > 0.5f )+ chance = 0.5f;+ chance *= m_biome->m_treeShare;+ }if( (Real)((hash >> 24) % 1000U) / 1000.0f > chance )continue;- // The wood, not the tree, picks the species.- UnsignedInt woodHash = hashCell( m_settings.m_seed + 40009, x / 16, y / 16 );-- AsciiString uniqueID;- uniqueID.format( "Prop %d", propID++ );- addObject( theTreeNames[woodHash % (UnsignedInt)numTreeNames], uniqueID.str(),- (Real)x + jitterX, (Real)y + jitterY, angle );- treeBudget--;+ RMGTreeSpot spot;+ spot.m_x = (Real)x + jitterX;+ spot.m_y = (Real)y + jitterY;+ spot.m_depth = (Int)( density * 10000.0f );+ spot.m_angle = angle;+ spot.m_wood = hashCell( m_settings.m_seed + 40009, x / 16, y / 16 ); // the wood, not the tree, picks the species+ spots.push_back( spot );}}++ /* The field says where the woods are and how deep into one each spot is; the ground says how+ many trees the map holds. When the field asks for more than that, the trees deepest in a+ wood are kept and the thin fringes go, so a well wooded map has fewer, thick woods rather+ than the same woods thinned out. How many that is comes from the map type, the biome and+ the seed: plains are the most wooded and canyons the least, a desert has a third of a+ forest's trees, and two seeds of one kind still differ by up to half again. A black forest+ takes the most of all, but still a number: an uncapped canopy came to six thousand trees on+ an eight-player map, and every one of them is drawn every frame. */+ Real share = woodland ? 0.5f + 0.5f * m_biome->m_treeShare : m_biome->m_treeShare;+ Real wooded = ( woodland ? 1.8f : 1.3f - 4.0f * forestThreshold ) * share+ * ( 0.75f + 0.5f * hashUnit( m_settings.m_seed, 9001, 17 ) );+ UnsignedInt target = (UnsignedInt)( area / RMG_TREE_CELLS_EACH * wooded );+ if( spots.size() > target )+ {+ std::stable_sort( spots.begin(), spots.end(), deeperInTheWood );+ spots.resize( target );+ }++ for( UnsignedInt s = 0; s < spots.size() && treeBudget > 0; s++ )+ {+ AsciiString uniqueID;+ uniqueID.format( "Prop %d", propID++ );+ addObject( theTreeNames[spots[s].m_wood % (UnsignedInt)numTreeNames], uniqueID.str(),+ spots[s].m_x, spots[s].m_y, spots[s].m_angle );+ treeBudget--;+ }}/** One waypoint every this many cells along an approach path. */@@ -4053,14 +6024,17 @@ void RMGLayout::addApproachPaths( Int *waypointID )m_waypointLinks.clear();static const char *LANES[3] = { "Center", "Flank", "Backdoor" };static const Real BULGE[3] = { 0.0f, RMG_APPROACH_BULGE, -RMG_APPROACH_BULGE };- static const Int STEP_X[4] = { 1, -1, 0, 0 };- static const Int STEP_Y[4] = { 0, 0, 1, -1 };+ m_lanes.clear();++ /* The starts are playable-area cells and the flood runs on map cells, border included. These+ paths used to flood from the start's playable cell read as a map cell, twenty cells short on+ both axes, so every waypoint but the last stood on ground offset from the real route. */std::vector<Int> dist;for( UnsignedInt target = 0; target < m_starts.size(); target++ ){- const Int targetX = (Int)m_starts[target].m_cellX;- const Int targetY = (Int)m_starts[target].m_cellY;+ const Int targetX = (Int)(m_starts[target].m_cellX + 0.5f) + RMG_BORDER_CELLS;+ const Int targetY = (Int)(m_starts[target].m_cellY + 0.5f) + RMG_BORDER_CELLS;floodDistancesFromCell( targetX, targetY, dist );for( UnsignedInt from = 0; from < m_starts.size(); from++ )@@ -4079,33 +6053,47 @@ void RMGLayout::addApproachPaths( Int *waypointID ){Int previous = 0;Int step = 0;- Int x = (Int)fromX;- Int y = (Int)fromY;+ Int x = (Int)(fromX + 0.5f) + RMG_BORDER_CELLS;+ Int y = (Int)(fromY + 0.5f) + RMG_BORDER_CELLS;if( lane == 0 && dist[cellIndex( x, y )] > 0 ){+ // One route per pair of starts is kept for the woods to be laid out against.+ RMGLane *route = NULL;+ if( from < target )+ {+ m_lanes.push_back( RMGLane() );+ route = &m_lanes.back();+ route->m_from = (Int)from;+ route->m_to = (Int)target;+ route->m_cells.push_back( cellIndex( x, y ) );+ }+// downhill on the flood from the target: the route a unit would drive+ const Real lineFromX = (Real)x;+ const Real lineFromY = (Real)y;Int walked = 0;+ Bool due = FALSE;while( dist[cellIndex( x, y )] > 0 ){- const Int here = dist[cellIndex( x, y )];- Bool stepped = FALSE;- for( Int n = 0; n < 4 && !stepped; n++ )- {- const Int nx = x + STEP_X[n];- const Int ny = y + STEP_Y[n];- if( nx < 0 || ny < 0 || nx >= m_width - 1 || ny >= m_height - 1 )- continue;- if( dist[cellIndex( nx, ny )] == here - 1 )- {- x = nx;- y = ny;- stepped = TRUE;- }- }- if( !stepped )+ if( !stepDownFlood( dist, &x, &y, lineFromX, lineFromY, (Real)targetX, (Real)targetY ) )break; // a breadth-first flood always leaves one; this only guards the loop+ if( route )+ route->m_cells.push_back( cellIndex( x, y ) );if( ++walked % RMG_APPROACH_SPACING_CELLS == 0 )- addApproachWaypoint( LANES[lane], (Int)target, (Int)from, step++, (Real)x, (Real)y, waypointID, &previous );+ due = TRUE;+ if( !due )+ continue;+ /* The flood walks a beach the water polygon still covers, where the ground stands+ just above the surface; a waypoint there is in the water to every unit, so it+ waits for the first dry cell further on. */+ Real shore;+ insideLake( (Real)(x - RMG_BORDER_CELLS), (Real)(y - RMG_BORDER_CELLS), &shore );+ if( shore < 2.0f )+ continue;+ addApproachWaypoint( LANES[lane], (Int)target, (Int)from, step++,+ (Real)(x - RMG_BORDER_CELLS), (Real)(y - RMG_BORDER_CELLS),+ waypointID, &previous );+ due = FALSE;}}else@@ -4127,11 +6115,19 @@ void RMGLayout::addApproachPaths( Int *waypointID ){if( abs( ox ) != ring && abs( oy ) != ring )continue;- const Int cx = (Int)px + ox;- const Int cy = (Int)py + oy;+ const Int cx = (Int)(px + 0.5f) + ox + RMG_BORDER_CELLS;+ const Int cy = (Int)(py + 0.5f) + oy + RMG_BORDER_CELLS;if( cx < 0 || cy < 0 || cx >= m_width - 1 || cy >= m_height - 1 || dist[cellIndex( cx, cy )] < 0 )continue;- addApproachWaypoint( LANES[lane], (Int)target, (Int)from, step++, (Real)cx, (Real)cy, waypointID, &previous );+ /* A lake bed is flat ground to the flood, but the water polygon over it+ closes it to every unit, and it reaches a little past the shore line. */+ Real shore;+ insideLake( (Real)(cx - RMG_BORDER_CELLS), (Real)(cy - RMG_BORDER_CELLS), &shore );+ if( shore < 2.0f )+ continue;+ addApproachWaypoint( LANES[lane], (Int)target, (Int)from, step++,+ (Real)(cx - RMG_BORDER_CELLS), (Real)(cy - RMG_BORDER_CELLS),+ waypointID, &previous );found = TRUE;}}@@ -4145,10 +6141,60 @@ void RMGLayout::addApproachPaths( Int *waypointID )}}+/** One step down a flood, in map cells. Of the neighbours one step nearer, the one that keeps+ closest to the straight line between the two ends, so a walk over open ground runs along that+ line in a fine staircase instead of all the way along one axis and then all the way along the+ other. FALSE at the bottom of the flood. */+Bool RMGLayout::stepDownFlood( const std::vector<Int>& dist, Int *x, Int *y, Real fromX, Real fromY,+ Real toX, Real toY ) const+{+ static const Int offsetX[4] = { 1, -1, 0, 0 };+ static const Int offsetY[4] = { 0, 0, 1, -1 };++ const Int here = dist[cellIndex( *x, *y )];+ if( here <= 0 )+ return FALSE;++ Real lineX = toX - fromX;+ Real lineY = toY - fromY;+ Real length = sqrtf( lineX * lineX + lineY * lineY );+ if( length < 1.0f )+ length = 1.0f;++ Int bestX = -1, bestY = -1;+ Real best = 1.0e9f;+ for( Int n = 0; n < 4; n++ )+ {+ const Int nx = *x + offsetX[n];+ const Int ny = *y + offsetY[n];+ if( nx < 0 || ny < 0 || nx >= m_width - 1 || ny >= m_height - 1 )+ continue;+ if( dist[cellIndex( nx, ny )] != here - 1 )+ continue;++ Real off = fabsf( ( (Real)nx - fromX ) * lineY - ( (Real)ny - fromY ) * lineX ) / length;+ if( off < best )+ {+ best = off;+ bestX = nx;+ bestY = ny;+ }+ }++ if( bestX < 0 )+ return FALSE;+ *x = bestX;+ *y = bestY;+ return TRUE;+}+void RMGLayout::buildObjects( const UnsignedByte perm[512] ){m_objects.clear();m_sites.clear();+ m_routeLock.clear();+ m_moneyWalks.clear();+ m_laneDist.clear();Int waypointID = 1;for( UnsignedInt i = 0; i < m_starts.size(); i++ )@@ -4167,8 +6213,20 @@ void RMGLayout::buildObjects( const UnsignedByte perm[512] )}addApproachPaths( &waypointID );+ /* The money and the towns level and grade the ground they stand on, and on the massif's edge+ that turns the cliff into a slope. They keep off it, and off the top as well, which is ground+ to fight for rather than to farm; the bunkers and the trees placed after may still go there. */+ const UnsignedInt massifSite = m_sites.size();+ if( m_type->m_massif > 0.0f )+ {+ Real middle = (Real)m_settings.m_playableCells * 0.5f;+ reserveSite( middle, middle, (Real)m_settings.m_playableCells * RMG_MASSIF_RADIUS * ( 1.0f + RMG_MASSIF_WOBBLE )+ + RMG_MASSIF_RIM );+ }placeSupplyAndDerricks();placeTowns();+ if( m_type->m_massif > 0.0f )+ m_sites.erase( m_sites.begin() + massifSite );placeBunkers();placeShoreWaves();placeScenery( perm );@@ -4192,6 +6250,13 @@ void RMGLayout::build( const RandomMapSettings& settings )m_settings = settings;RandomMapGenerator::clampSettings( m_settings );+ /* The seed picks what kind of map this is and what it is made of, apart from each other, so a+ river can run through snow as well as through grass. Neither depends on the player count:+ the same seed is the same kind of map for two players and for eight. Over the first thousand+ seeds each of the seven kinds comes up between 131 and 159 times. */+ m_type = &theMapTypes[hashCell( m_settings.m_seed, 9001, 8 ) % (UnsignedInt)RMG_MAP_TYPE_COUNT];+ m_biome = &theBiomes[hashCell( m_settings.m_seed, 9001, 1 ) % (UnsignedInt)RMG_BIOME_COUNT];+m_width = m_settings.m_playableCells + 2 * RMG_BORDER_CELLS;m_height = m_width;m_waterHeight = RMG_BASE_HEIGHT - RMG_WATER_DROP;@@ -4202,14 +6267,23 @@ void RMGLayout::build( const RandomMapSettings& settings )buildHeights( perm );placeLakes( perm );+ m_heights.swap( m_landHeights );+ m_landHeights.clear();buildLakeMask();+ std::vector<UnsignedByte> uncarved;+ if( m_type->m_river )+ uncarved = m_heights;carveLakeBasins();chooseStarts();+ m_baseLevelled.clear();+ openFordsAtStarts( uncarved );flattenBases();m_ramps.clear();connectStarts();+ if( m_type->m_massif > 0.0f )+ carveMassifRamps();/* Objects before textures, because placing them changes the ground: every dock, derrick,bunker and town levels a pad under itself, and a pad moves the cliffs and the shore lines@@ -4219,6 +6293,8 @@ void RMGLayout::build( const RandomMapSettings& settings )buildObjects( perm );ensurePlayability();flattenBases();+ // After the last levelling: levelling again would ease a cut ramp back into the base's ring.+ holdMoneyWalks();buildTerrainClasses( perm );buildBlends();@@ -4488,14 +6564,13 @@ static void writePolygonTriggers( MapChunkWriter& w, const RMGLayout& layout )the dusk the shipped maps all override, so a generated map looked like somebody had turned thesun off. These are written for all four times of day: the map has no scripts to change the hourwith, and a player who forces one should still be able to see the ground. */-static void writeGlobalLighting( MapChunkWriter& w )+static void writeGlobalLighting( MapChunkWriter& w, const RMGBiome& biome ){- // x and y point the sun across the map, z takes it down onto the ground.- static const Real theSunDirection[3] = { -0.58f, 0.42f, -0.70f };- static const Real theTerrainAmbient[3] = { 0.35f, 0.35f, 0.36f };- static const Real theTerrainDiffuse[3] = { 0.78f, 0.75f, 0.68f };- static const Real theObjectAmbient[3] = { 0.45f, 0.45f, 0.47f };- static const Real theObjectDiffuse[3] = { 0.82f, 0.79f, 0.72f };+ const Real *theSunDirection = biome.m_sunDirection;+ const Real *theTerrainAmbient = biome.m_terrainAmbient;+ const Real *theTerrainDiffuse = biome.m_terrainDiffuse;+ const Real *theObjectAmbient = biome.m_objectAmbient;+ const Real *theObjectDiffuse = biome.m_objectDiffuse;w.openChunk( "GlobalLighting", K_LIGHTING_VERSION_3 );w.writeInt( TIME_OF_DAY_AFTERNOON );@@ -4638,7 +6713,7 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vectow.writeInt( RMG_TILES_PER_CLASS );w.writeInt( RMG_TILE_SHEET_WIDTH );w.writeInt( 0 ); // legacy field- w.writeAsciiString( theTerrainClassNames[terrainClass] );+ w.writeAsciiString( layout.m_biome->m_textures[terrainClass] );}w.writeInt( 0 ); // no edge tiles@@ -4690,7 +6765,7 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vectowritePolygonTriggers( w, layout );/***************GLOBAL LIGHTING DATA ***************/- writeGlobalLighting( w );+ writeGlobalLighting( w, *layout.m_biome );/***************WAYPOINT LINKS ***************/// read after every waypoint exists (TerrainLogic::loadMap), so its place in the file is free@@ -4751,14 +6826,8 @@ void RandomMapGenerator::generatePreview( const RandomMapSettings& settings,tgaBytes.clear();writeTgaHeader( tgaBytes, pixels );- // Ground colours, in the RMGTerrainClass order, plus water and the marks.- static const UnsignedByte theGroundColours[RMG_TERRAIN_COUNT][3] =- {- { 86, 122, 62 }, // grass- { 190, 176, 130 }, // sand- { 132, 112, 74 }, // dirt- { 118, 118, 112 } // rock- };+ // Ground colours are the biome's, in the RMGTerrainClass order; water and the marks are fixed.+ const UnsignedByte (*theGroundColours)[3] = layout.m_biome->m_previewColours;static const UnsignedByte theWaterColour[3] = { 48, 86, 130 };static const UnsignedByte theStartColour[3] = { 240, 240, 240 };static const UnsignedByte theCliffColour[3] = { 58, 54, 50 };diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex 38ad45b57..30eab28b1 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -7991,6 +7991,8 @@ struct RMGParsestd::vector<Int> m_firstTiles;std::vector<AsciiString> m_waypointNames;std::vector<Coord3D> m_waypointPositions;+ std::vector<AsciiString> m_pathWaypointNames; ///< the approach paths' waypoints, "Center2_from1_0"+ std::vector<Coord3D> m_pathWaypointPositions;std::vector<AsciiString> m_objectNames;std::vector<UnsignedByte> m_heights;std::vector<Short> m_tiles;@@ -8207,6 +8209,11 @@ static Bool RMGParseObject( DataChunkInput &file, DataChunkInfo *info, void * )theRMGParse.m_waypointNames.push_back( d.getAsciiString( NAMEKEY( "waypointName" ) ) );theRMGParse.m_waypointPositions.push_back( loc );}+ else if( d.getType( NAMEKEY( "waypointID" ) ) == Dict::DICT_INT )+ {+ theRMGParse.m_pathWaypointNames.push_back( d.getAsciiString( NAMEKEY( "waypointName" ) ) );+ theRMGParse.m_pathWaypointPositions.push_back( loc );+ }return TRUE;}@@ -8465,6 +8472,11 @@ TEST(the_cliffs_are_where_the_layout_put_them_and_never_between_two_players)RandomMapSettings settings;+ /* Rolling ground is the default and only some peaks sit on a shelf, so one seed may have no+ cliff at all now that a base's blend ring no longer leaves a rim. Across the sixteen maps the+ shelves have to show up somewhere. */+ Int totalCliffCells = 0;+for( Int players = 2; players <= 8; players += 2 ){settings.m_numPlayers = players;@@ -8497,7 +8509,7 @@ TEST(the_cliffs_are_where_the_layout_put_them_and_never_between_two_players)}CHECK( highest > lowest + 8 ); // terrain, not a parade ground- CHECK( numCliffCells > 0 ); // the ridge is supposed to be a cliff+ totalCliffCells += numCliffCells;// Nothing steep within a base radius of a start, or the base cannot be laid out.for( Int i = 0; i < players; i++ )@@ -8576,6 +8588,8 @@ TEST(the_cliffs_are_where_the_layout_put_them_and_never_between_two_players)}}}++ CHECK( totalCliffCells > 0 ); // the ridges are supposed to be cliffs}//-------------------------------------------------------------------------------------------------@@ -9689,6 +9703,53 @@ TEST(a_generated_map_carries_an_attack_path_to_every_start)}}+//-------------------------------------------------------------------------------------------------+/** The approach paths flooded from a start's playable cell read as a map cell, twenty cells short on+ both axes, so a "Center" path set off from ground twenty-odd cells beside the base it named. Every+ path waypoint has to stand on ground the starts can walk to, and the first "Center" waypoint lies+ one waypoint spacing (twelve steps) out from the base the path leaves. The flank points once+ snapped onto lake beds the flood counts as flat ground; seed 42 at four players had ten of them. */+//-------------------------------------------------------------------------------------------------+TEST(an_attack_path_leaves_from_its_own_base_over_walkable_ground)+{+ CHECK( bootOnce() );++ RandomMapSettings settings;+ settings.m_seed = 42;+ settings.m_numPlayers = 4;+ settings.m_playableCells = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 4 );+ std::vector<char> bytes;+ RandomMapGenerator::generate( settings, bytes );+ parseGeneratedMap( bytes );++ CHECK_EQ( (Int)theRMGParse.m_waypointPositions.size(), settings.m_numPlayers );+ CHECK( !theRMGParse.m_pathWaypointPositions.empty() );++ Int startX, startY;+ RMGWorldToCell( theRMGParse.m_waypointPositions[0], &startX, &startY );+ std::vector<char> seen;+ RMGFloodFillWalkable( startX, startY, seen );++ Int firstSteps = 0;+ for( UnsignedInt w = 0; w < theRMGParse.m_pathWaypointPositions.size(); w++ )+ {+ const Coord3D& at = theRMGParse.m_pathWaypointPositions[w];+ CHECK( RMGSeenHasObjectAt( seen, at ) );++ Int target = 0, from = 0, step = -1;+ if( sscanf( theRMGParse.m_pathWaypointNames[w].str(), "Center%d_from%d_%d", &target, &from, &step ) != 3 ||+ step != 0 )+ continue;+ CHECK( from >= 1 && from <= settings.m_numPlayers );+ const Coord3D& base = theRMGParse.m_waypointPositions[from - 1];+ Real dx = ( at.x - base.x ) / MAP_XY_FACTOR;+ Real dy = ( at.y - base.y ) / MAP_XY_FACTOR;+ CHECK( dx * dx + dy * dy <= 13.0f * 13.0f );+ firstSteps++;+ }+ CHECK_EQ( firstSteps, settings.m_numPlayers * ( settings.m_numPlayers - 1 ) );+}+//-------------------------------------------------------------------------------------------------/** The seed is worthless across two builds unless both builds turn it into the same bytes, andnothing warns anybody when they stop doing so. These numbers are that warning: change the@@ -9699,14 +9760,14 @@ TEST(the_generator_still_turns_a_seed_into_the_bytes_it_used_to){CHECK( bootOnce() );- CHECK_EQ( RANDOM_MAP_GENERATOR_VERSION, 11 );+ CHECK_EQ( RANDOM_MAP_GENERATOR_VERSION, 12 );struct RMGFingerprint { Int m_seed, m_players, m_cells; UnsignedInt m_crc; };static const RMGFingerprint theFingerprints[] ={- { 0, 2, 64, 0x2D2AF5EF },- { 12345, 4, 96, 0xD1B4AB2D },- { 7, 8, 128, 0x5A40EFA4 },+ { 0, 2, 64, 0x784968C4 },+ { 12345, 4, 96, 0xCF747041 },+ { 7, 8, 128, 0xC7C6D183 },};const Int numFingerprints = sizeof(theFingerprints) / sizeof(theFingerprints[0]);@@ -9930,6 +9991,175 @@ TEST(the_ground_is_textured_by_what_the_ground_is_doing)CHECK( numCliffCells < numCells / 20 );}+//-------------------------------------------------------------------------------------------------+/** The seed picks a kind of map and what it is made of, the way an Age of Empires seed picks+ Arabia or a river map and a desert or a forest. Over a couple of dozen seeds every ground set+ has to turn up, and the water has to differ in kind as well as in place: a river map is cut+ into several stretches at its fords, a plain has a pond or two.++ Two of the kinds are told apart by what stands on them and how high the middle is. A black+ forest has trees in nearly every patch of ground away from the bases, and none on the ride from+ a base to the middle. A massif lifts the middle well above the ring the bases stand on, and the+ top is ground a unit from player one's base can drive onto. Forty seeds hold three forests and+ six massifs; on 128 cells the thresholds pick out all three forests and four of the massifs, and+ no seed of another kind. */+//-------------------------------------------------------------------------------------------------+TEST(a_seed_picks_its_map_type_and_its_ground)+{+ CHECK( bootOnce() );++ std::set<std::string> groundSets;+ std::set<Int> waterCounts;+ Int woodedMaps = 0;+ Int massifMaps = 0;++ for( Int seed = 1; seed <= 40; seed++ )+ {+ RandomMapSettings settings;+ settings.m_seed = seed;+ settings.m_playableCells = 128;+ settings.m_numPlayers = 2;++ std::vector<char> bytes;+ RandomMapGenerator::generate( settings, bytes );+ parseGeneratedMap( bytes );++ CHECK_EQ( theRMGParse.m_numTextureClasses, 4 );+ std::string ground;+ for( Int i = 0; i < 4 && i < (Int)theRMGParse.m_textureNames.size(); i++ )+ {+ ground += theRMGParse.m_textureNames[i].str();+ ground += ";";+ }+ groundSets.insert( ground );+ waterCounts.insert( theRMGParse.m_numWaterAreas );++ const Real playable = (Real)settings.m_playableCells;+ const Real centre = playable * 0.5f;+ Real startX[2], startY[2];+ for( Int i = 0; i < 2; i++ )+ {+ startX[i] = theRMGParse.m_waypointPositions[i].x / MAP_XY_FACTOR;+ startY[i] = theRMGParse.m_waypointPositions[i].y / MAP_XY_FACTOR;+ }++ // Patches of 16 cells with a tree in them, out of those clear of both bases.+ const Int patch = 16;+ const Int patches = settings.m_playableCells / patch;+ std::vector<char> wooded( patches * patches, 0 );+ Int rideTrees = 0;+ for( Int i = 0; i < (Int)theRMGParse.m_objectNames.size(); i++ )+ {+ if( strncmp( theRMGParse.m_objectNames[i].str(), "Tree", 4 ) != 0 )+ continue;+ Real tx = theRMGParse.m_objectPositions[i].x / MAP_XY_FACTOR;+ Real ty = theRMGParse.m_objectPositions[i].y / MAP_XY_FACTOR;+ Int px = (Int)tx / patch;+ Int py = (Int)ty / patch;+ if( px >= 0 && py >= 0 && px < patches && py < patches )+ wooded[py * patches + px] = 1;++ for( Int s = 0; s < 2; s++ )+ {+ Real sx = startX[s] - centre;+ Real sy = startY[s] - centre;+ Real length2 = sx * sx + sy * sy;+ if( length2 < 1.0f )+ continue;+ Real t = ( ( tx - centre ) * sx + ( ty - centre ) * sy ) / length2;+ if( t < 0.0f || t > 1.0f )+ continue;+ Real ex = tx - centre - sx * t;+ Real ey = ty - centre - sy * t;+ if( ex * ex + ey * ey < 1.5f * 1.5f )+ rideTrees++;+ }+ }+ Int open = 0, covered = 0;+ for( Int py = 0; py < patches; py++ )+ {+ for( Int px = 0; px < patches; px++ )+ {+ Real cx = ( (Real)px + 0.5f ) * (Real)patch;+ Real cy = ( (Real)py + 0.5f ) * (Real)patch;+ Bool nearBase = FALSE;+ for( Int s = 0; s < 2; s++ )+ {+ Real dx = cx - startX[s];+ Real dy = cy - startY[s];+ if( dx * dx + dy * dy < 44.0f * 44.0f )+ nearBase = TRUE;+ }+ if( nearBase )+ continue;+ open++;+ if( wooded[py * patches + px] )+ covered++;+ }+ }+ if( open > 0 && covered * 10 >= open * 8 )+ {+ woodedMaps++;+ CHECK_EQ( rideTrees, 0 );+ }++ // The middle against the ring the bases stand on.+ const Int width = theRMGParse.m_width;+ const Int border = theRMGParse.m_border;+ Real middle = 0.0f;+ Int middleSamples = 0;+ for( Int dy = -6; dy <= 6; dy++ )+ {+ for( Int dx = -6; dx <= 6; dx++ )+ {+ if( dx * dx + dy * dy > 36 )+ continue;+ middle += (Real)theRMGParse.m_heights[( (Int)centre + dy + border ) * width + (Int)centre + dx + border];+ middleSamples++;+ }+ }+ middle /= (Real)middleSamples;+ Real ring = 0.0f;+ for( Int k = 0; k < 32; k++ )+ {+ Real angle = 2.0f * PI * (Real)k / 32.0f;+ Int x = (Int)( centre + playable * 0.32f * Cos( angle ) ) + border;+ Int y = (Int)( centre + playable * 0.32f * Sin( angle ) ) + border;+ ring += (Real)theRMGParse.m_heights[y * width + x];+ }+ ring /= 32.0f;++ // And how many bearings out of the middle run into a cliff before they reach that ring.+ Int walled = 0;+ for( Int k = 0; k < 64; k++ )+ {+ Real angle = 2.0f * PI * (Real)k / 64.0f;+ for( Real r = 0.0f; r < playable * 0.30f; r += 1.0f )+ {+ Int x = (Int)( centre + r * Cos( angle ) ) + border;+ Int y = (Int)( centre + r * Sin( angle ) ) + border;+ if( RMGCellSpan( x, y ) > 9.8f )+ {+ walled++;+ break;+ }+ }+ }+ if( middle > ring + 45.0f && walled >= 48 )+ {+ massifMaps++;+ std::vector<char> seen;+ RMGFloodFillFromFirstStart( seen );+ CHECK( seen[( (Int)centre + border ) * width + (Int)centre + border] );+ }+ }++ CHECK_EQ( (Int)groundSets.size(), 4 );+ CHECK( waterCounts.size() >= 3 );+ CHECK( woodedMaps >= 1 );+ CHECK( massifMaps >= 1 );+}+//////////////////////////////////////////////////////////////////////////////// Headless runs//////////////////////////////////////////////////////////////////////////////