Skip to content

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.

feat(gameengine): random map generator version 18, 62 defects fixed

Olcay Seygande808faebc9c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 021c4c497..f29363646 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -125,6 +125,17 @@ found and fixed, EA's own, not port damage.**
- A map built from an official map takes its sizes from that map. Medium is the original's own size for as many players as it seats, the room they would have on it: a Twilight Flame map is 477 cells a side for two to eight players, where four used to get 304 and eight 416, and each player past the original's seats adds one seat's ground. Extra Large is 708. Surprise me keeps the sizes it always had.
- Bases on raised ground, as on Twilight Flame, now share one stretch of high ground the way the original's do, and each has its ways down widened and one more running straight toward the middle. They used to stand on separate plateaus with a narrow gap between them, and armies queued in it. Over three eight-player matches at Medium size, units stood blocked on the way 163 times per thousand frames, against 205 on Twilight Flame itself and 319 before; four players over five matches 80 against the original's 67, where they used to block twice as often.
- A map built from a river map keeps a bridge over its river at every size. The smallest two-player Silent River map had none: the bases left no clear ground for one, so now the crossing that runs least into a base takes the bridge.
+- Random maps took a long list of repairs this version, from a run through 62 reported defects, each fix measured on the maps before and after. The price is plain: a random map is built from its name, and this build builds different maps from the same names, so it refuses the names an older version made. A replay recorded on a generated map in 3.5.1 or earlier will not play on this build, and a lobby or saved game that names one cannot rebuild it.
+- Towns on a river keep their houses. A map copied from Heartland Shield cut its river town round the middle of the water instead of round the houses, and kept 12 of the original's 42. The same map now holds 17 houses on the crossing, a 4-player map that had 4 holds 22, and an 8-player map holds 42. The bridge ends stay dry, and a town that still has to lose houses says so.
+- Roads run like roads. A copied map laid its roads in short pieces that jogged along a 45 degree grid and stopped three cells short of the road they were meant to meet, and every end was cut square. On one Heartland map there are 61 pieces where there were 104, each nearly twice as long (19 cells against 11), the 21 grid jogs are gone, no end is cut square (42 before) and four proper junctions appear where there were none. A road no longer starts in the open from a copied base.
+- No more seams in the ground texture. Where a copied map met two grounds, the edge between them was cut square, 16% of all edges on Heartland Shield, Twilight Flame and Silent River. It is 3.7% on Heartland, 0.8% on Twilight, 1.7% on Silent River and 2.4% on Tournament Island, below what the shipped Heartland has (5.9%). Rocky river banks with no water in them are mostly gone too: 868 stray bank cells on a 4-player Heartland map are 91, and the sea floor on Bombardment Beach is sea floor in 87 to 97% of its wet cells, where it was 8 to 18%.
+- Cliff faces are drawn as rock. A cliff used to be the ground texture stretched down the slope, a grey stripe. It now carries the stone's own texture, laid the way the shipped maps lay it: about two steep rock cells in three on a Twilight-style map and on a map copied from an original. A cliff that stretched its texture more than twice as far as it should came to 28% of the faces on a Twilight-style map and 19% on a copied Twilight Flame, and now to 9% and 5%.
+- Seas come back at their share. Bombardment Beach copies had no sea at 4 players (a message said no coast was clear) and now have 17% water against the original's 18%, with 2 and 8 players at 18%. Tournament Island at 8 players went from 37% water to 45% against the original's 47%. The smallest 4-player island is still short at 37%.
+- Docks and oil derricks stay on dry ground inside the map. Island maps stranded them in the sea, and copied maps put some past the edge: on Tournament Island a player's own dock was 117 cells away and is 23, on a 4-player Heartland map 98 and now 24, and no dock on the Twilight Flame test maps stands off the edge. Rivers no longer dam up against a dock or a derrick: 663 cells of river bed left dry round the money on one Heartland map are 18.
+- Every seat gets the same base and the same money. A Twilight Flame copy gave every other seat a lower base than its neighbour's, a different one from the original, and no oil derrick at all; all eight now stand on the same base at the same height, every player has 2 derricks and every gap between two bases has 4 supply piles, where seven of eight gaps had none. On plain maps the contested docks are shared out by bearing round the middle: a 4-player seed that gave 3, 3, 1 and 1 docks to the nearest seat gives 2, 2, 2 and 2.
+- Woods are woods. Trees on generated maps stood in a solid grid, a quarter to a third of them ringed by other trees on every side. The ringed share is down to 5% and the edge of a wood is ragged.
+- The deepest pits on Twilight-style maps are pits. They could wrap past the bottom of the height scale and come out as a needle of mountain, 97 cells of them on one 8-player map; none now. A lake no longer sits under the flat ground of a base (119 cells on one 2-player map, none now), across 30 test maps the closest town building to a base is 44 cells away where it was 14, and a pond left behind a river ford is dry ground.
+- A map copied from an original can no longer come out smaller than that map's smallest size, whatever the player count.
- The player count starts at the number of seats already taken in the room. The tab, the map type and the size you used last are remembered for the next time.
- In a LAN or online room the other players do not download anything: the map's name carries its recipe, and their own game builds the same map from it and checks it against yours. A room that records stats keeps to the official list.
- Random maps used to be reachable only by a hidden command-line switch that added five rows to the skirmish list.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h
index d7377e6aa..4890f5353 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 in
test_gameengine.cpp fails until the version and the recorded CRCs agree, so
the bump cannot be forgotten. */
-#define RANDOM_MAP_GENERATOR_VERSION 17
+#define RANDOM_MAP_GENERATOR_VERSION 18
/** How much ground the map gives everybody, before the per-player share. Players see them as
Tiny, Small, Medium, Large and Extra Large. */
@@ -148,6 +148,26 @@ extern Bool generatedMapTemplate( const AsciiString& path, AsciiString& template
extern Bool generatedMapWireName( const AsciiString& folder, AsciiString& wireOut );
extern Bool generatedMapFromWireName( const AsciiString& wire, AsciiString& folderOut );
+/** One cliff mapping of a BlendTileData chunk, in the order WorldHeightMap::ParseBlendTileData reads
+ it (version 5 on): the texture coordinates of a cell's four corners, 0 (x, y), 1 (x + 1, y),
+ 2 (x + 1, y + 1), 3 (x, y + 1), in TEXTURE_WIDTH units from the class's corner in the terrain
+ texture, and a tile of the class they are for. */
+struct RMGCliffInfo
+{
+ Int m_tileIndex;
+ Real m_u[4], m_v[4];
+ Bool m_flip;
+
+ RMGCliffInfo() : m_tileIndex(0), m_flip(FALSE) { for( Int k = 0; k < 4; k++ ) m_u[k] = m_v[k] = 0.0f; }
+};
+
+/** The cliff mapping both writers bake from the final heights: a cell of a cliff class whose first
+ tile and sheet width are in sheetFirst and sheetWidth (-1 and 0 for any other cell) and that rises
+ steeply takes its texture off the face rather than off the plane. indexOut is the per-cell array
+ of the chunk, infoOut the entries with the unwritten default at 0. */
+extern void rmgCliffMapping( const std::vector<Int>& heights, Int width, Int height, const std::vector<Int>& sheetFirst,
+ const std::vector<Int>& sheetWidth, std::vector<Short>& indexOut, std::vector<RMGCliffInfo>& infoOut );
+
/** A ChunkInputStream over a block of memory, so a generated map can be handed
to the same readers that parse maps off disk. */
class MemoryChunkInputStream : public ChunkInputStream
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapTemplate.h b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapTemplate.h
index b73299846..a861e5cd8 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapTemplate.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapTemplate.h
@@ -78,6 +78,11 @@ extern Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<c
RMGCivilianTest civilian, std::vector<char>& mapBytes, std::vector<char> *previewBytes,
RMGTemplateReport *report );
+/** The share of the height up to the lower of two copied plateau bases a cell between them is raised
+ by: sum is the cell's chamfer distances to the two (three a straight step) added, pairLeast the
+ least such sum anywhere. A pair further apart than a corridor is not joined at all. */
+extern Real rmgJoinShare( Int pairLeast, Int sum );
+
/** RandomMapGenerator.cpp's half: the generator's map for these settings on plain open ground, with
no scenery, towns or bunkers. */
extern void rmgBuildSkeleton( const RandomMapSettings& settings, std::vector<char>& mapBytes );
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
index d8a107417..6c77df23a 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
@@ -68,10 +68,26 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
// edges, so it is scenery, not play space.
#define RMG_BORDER_CELLS 20
-// Each texture class is read as the four tiles of a 2x2 sheet.
+// A texture class the sheet table (theTextureSheets) does not know is read as the four tiles of a 2x2
+// sheet, which every terrain image holds.
#define RMG_TILES_PER_CLASS 4
#define RMG_TILE_SHEET_WIDTH 2
+// The cliff mapping (rmgCliffMapping). A cliff class's cell takes one when both its edges down the fall
+// rise more than this many height bytes: WorldBuilder's limit (WHeightMapEdit::doCliffAdjustment, half
+// its STRETCH_LIMIT over HEIGHT_SCALE), past which a face drawn by its height stretches the tile no
+// more than 1.6 times.
+#define RMG_CLIFF_UV_RISE 12
+// Entries the reader holds, the default at 0 included (NUM_CLIFF_INFO in WorldHeightMap.h); a chunk
+// claiming more throws ERROR_CORRUPT_FILE_FORMAT, so the mapping keeps the steepest cells under it.
+#define RMG_NUM_CLIFF_INFO 32384
+// A cell is 32 texels of a TEXTURE_WIDTH that is 32 tiles of 64, so 1/64 of it; a height byte is a
+// sixteenth of a cell's width (MAP_HEIGHT_SCALE over MAP_XY_FACTOR), 1/1024. The mapping counts in
+// 2048ths, which keeps every coordinate it writes exact in a float, whatever the rounding mode.
+#define RMG_CLIFF_UV_UNITS 2048
+#define RMG_CLIFF_UV_CELL 32 ///< RMG_CLIFF_UV_UNITS a cell across
+#define RMG_CLIFF_UV_BYTE 2 ///< and a height byte up
+
// How big a map is: a floor everybody gets, plus a share for each player. A normal two-player map
// is 248 cells across, which is 2480 world units - about what a shipped duel map measures - and an
// eight-player one is 416. An eight-player huge map is 672, a little under Death Valley's 710 with
@@ -127,6 +143,7 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
#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_FORD_STUB_STEPS 4.0f ///< river steps past a ford's half-width a stretch beside it must run, or it goes dry
#define RMG_POLYGON_MAX 96 ///< sides written into the water area
// A start position gets a flat disc to build on, easing back into the terrain.
@@ -135,10 +152,13 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
#define RMG_BASE_FLAT_FLOOR 14.2f ///< cells of flat round a start on every bearing, the pathfinder's square inside it
#define RMG_BASE_FLAT_SWING 5.5f ///< cells the flat edge wanders out past that floor
#define RMG_BASE_BLEND_SWING 0.6f ///< share of its width the blend's outer edge wanders out by
+#define RMG_BASE_SHORE_RAMP 4.0f ///< cells past the flat's edge over which a lake takes the blend back
#define RMG_START_MARGIN 10.0f ///< cells of playable area kept outside the blend disc
#define RMG_START_EDGE_FRACTION 0.14f ///< and this much of the map besides, so a base has ground behind it
#define RMG_START_STRIDE 3 ///< cells between the spots the search looks at
#define RMG_START_ROUGHNESS 2.6f ///< height bytes a base site may vary by, on average
+#define RMG_START_STRICT_SITES_EACH 4 ///< dry-flat sites per seat under which the looser sites are taken too
+#define RMG_START_LOOSE_PENALTY 4.0f ///< roughness added to a site only the looser shore test passes
#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
@@ -197,7 +217,9 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
#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_REROLLS 6 ///< plans a map with no town yet tries for its last one
+#define RMG_TOWN_REROLLS 6 ///< plans a town tries, and as many small ones after for a map with no town yet
+#define RMG_TOWN_SMALL_BLOCK_MAX 22.0f ///< the widest block of a small plan
+#define RMG_TOWN_START_CLEAR ( RMG_BLEND_RADIUS + 2.0f ) ///< cells round every start no building stands in
// A street is laid a block at a time, and a block that reaches water stops at the bank.
#define RMG_ROAD_STEP 2.0f ///< cells between two wet-or-dry samples along a block
#define RMG_ROAD_MIN_RUN 12.0f ///< cells; a street from a crossing to the bank shorter than this is a stub
@@ -212,6 +234,8 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
#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_ROCK_ACCEPT_IN_256 67U ///< rocky cells out of 256 that get a rock, a quarter
+#define RMG_TREE_EDGE_RAGGED 1500U ///< depth units (density x 10000) a tree's place in the cap is shuffled by
#define RMG_FOREST_FEATURES 7.0f
#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
@@ -705,6 +729,63 @@ static const RMGStyle theStyles[] =
};
static const Int RMG_STYLE_COUNT = sizeof(theStyles) / sizeof(theStyles[0]);
+/* How many tiles each ground image above holds and how many across, as every shipped map that uses
+ it declares it in its BlendTileData (MapsZH.big and the base game's maps.big agree on every one).
+ WorldHeightMap's readTexClass loads a width by width block of the image only when the class asks
+ for no more tiles than the image has: declared smaller, a class draws one corner of its art over
+ and over (every class here was four tiles two across, so the twilight style's cliff was a quarter
+ of CliffLargeType10 repeating every four cells), and declared bigger it draws nothing. */
+struct RMGTextureSheet
+{
+ const char *m_name;
+ Int m_tiles, m_width;
+};
+
+static const RMGTextureSheet theTextureSheets[] =
+{
+ { "GrassType1", 4, 2 }, { "SandLargeType1", 36, 6 }, { "DirtType1", 4, 2 },
+ { "RocksType1", 4, 2 }, { "SandLargeType2", 36, 6 }, { "SandType3wet", 4, 2 },
+ { "DirtMediumType3", 16, 4 }, { "RocksType3", 4, 2 }, { "SnowType1", 4, 2 },
+ { "DirtSnowType1", 16, 4 }, { "SnowLargeType1", 36, 6 }, { "RocksMediumType1Snow", 16, 4 },
+ { "DirtMediumType8", 16, 4 }, { "SandMediumType7Grassy", 16, 4 }, { "DirtType2", 4, 2 },
+ { "DirtMediumType10", 16, 4 }, { "SandMediumType6", 16, 4 }, { "SandMediumType10", 16, 4 },
+ { "CliffLargeType10", 16, 4 },
+};
+
+static void rmgTextureSheet( const char *name, Int& tiles, Int& width )
+{
+ tiles = RMG_TILES_PER_CLASS;
+ width = RMG_TILE_SHEET_WIDTH;
+ for( Int i = 0; i < (Int)( sizeof(theTextureSheets) / sizeof(theTextureSheets[0]) ); i++ )
+ {
+ if( strcmp( theTextureSheets[i].m_name, name ) == 0 )
+ {
+ tiles = theTextureSheets[i].m_tiles;
+ width = theTextureSheets[i].m_width;
+ }
+ }
+}
+
+/// A class's first tile: the classes lie one after another in RMGTerrainClass order.
+static Int rmgClassFirstTile( const RMGBiome& biome, Int terrainClass )
+{
+ Int first = 0;
+ for( Int c = 0; c < terrainClass; c++ )
+ {
+ Int tiles, width;
+ rmgTextureSheet( biome.m_textures[c], tiles, width );
+ first += tiles;
+ }
+ return first;
+}
+
+static Int rmgClassWidth( const RMGBiome& biome, Int terrainClass )
+{
+ Int tiles, width;
+ rmgTextureSheet( biome.m_textures[terrainClass], tiles, width );
+ return width;
+}
+
/// The bowl a style stands on: rolling low ground, no shelves, no water, thin woods.
static const RMGMapTypeShape theBowlType =
// amp valley gorge shelf lakes area river forest wood massif
@@ -798,7 +879,8 @@ struct RMGTownPlan
Real m_downAt[RMG_TOWN_MAX_STREETS];
Real m_plotLength;
Real m_setBack;
- Real m_radius; ///< from the middle to the far side of the outermost frontage
+ Real m_radius; ///< from the middle to the far corner of the outermost frontage
+ Real m_thinRadius; ///< what the thinning towards the edge is measured against
};
/// A hash read as a fraction of one, which is how every choice a town makes is made.
@@ -824,7 +906,7 @@ static Real snapAngle45( Real angle )
}
/// Where one direction's streets run, spaced unevenly and centred on the town. Returns the span.
-static Real rollStreetLines( Int seed, Int town, Int streets, Real *out )
+static Real rollStreetLines( Int seed, Int town, Int streets, Real blockMax, Real *out )
{
Real at = 0.0f;
Int line;
@@ -832,7 +914,7 @@ static Real rollStreetLines( Int seed, Int town, Int streets, Real *out )
for( line = 0; line < streets; line++ )
{
out[line] = at;
- at += lerpReal( RMG_TOWN_BLOCK_MIN, RMG_TOWN_BLOCK_MAX, hashUnit( seed, town, line ) );
+ at += lerpReal( RMG_TOWN_BLOCK_MIN, blockMax, hashUnit( seed, town, line ) );
}
Real span = out[streets - 1];
@@ -842,11 +924,13 @@ static Real rollStreetLines( Int seed, Int town, Int streets, Real *out )
return span;
}
-static void rollTownPlan( Int seed, Int town, RMGTownPlan *plan )
+/** smallest: the fewest streets each way and the closest blocks, the plan a map tries once the
+ town it rolled has found no room anywhere. */
+static void rollTownPlan( Int seed, Int town, Bool smallest, RMGTownPlan *plan )
{
plan->m_rotation = (Real)(hashCell( seed + 613, town, 0 ) % 8U) * (PI * 0.25f);
- const UnsignedInt streetChoices = (UnsignedInt)(RMG_TOWN_MAX_STREETS - RMG_TOWN_MIN_STREETS + 1);
+ const UnsignedInt streetChoices = smallest ? 1U : (UnsignedInt)(RMG_TOWN_MAX_STREETS - RMG_TOWN_MIN_STREETS + 1);
plan->m_streetsAcross = RMG_TOWN_MIN_STREETS +
(Int)(hashCell( seed + 613, town, 1 ) % streetChoices);
plan->m_streetsDown = RMG_TOWN_MIN_STREETS +
@@ -857,11 +941,20 @@ static void rollTownPlan( Int seed, Int town, RMGTownPlan *plan )
plan->m_setBack = lerpReal( RMG_TOWN_SET_BACK_MIN, RMG_TOWN_SET_BACK_MAX,
hashUnit( seed + 613, town, 4 ) );
- Real spanAcross = rollStreetLines( seed + 6131, town, plan->m_streetsAcross, plan->m_acrossAt );
- Real spanDown = rollStreetLines( seed + 6133, town, plan->m_streetsDown, plan->m_downAt );
+ const Real blockMax = smallest ? RMG_TOWN_SMALL_BLOCK_MAX : RMG_TOWN_BLOCK_MAX;
+ Real spanAcross = rollStreetLines( seed + 6131, town, plan->m_streetsAcross, blockMax, plan->m_acrossAt );
+ Real spanDown = rollStreetLines( seed + 6133, town, plan->m_streetsDown, blockMax, plan->m_downAt );
Real span = (spanAcross > spanDown) ? spanAcross : spanDown;
- plan->m_radius = span * 0.5f + plan->m_setBack + 4.0f;
+ /* Every clearance a town is placed with - the map's edge, the money, the starts - is this
+ radius, so it reaches the corner plot: a building stands its set-back and its jitter off the
+ outermost street, and the corner of the grid is that far out on both axes at once. Half the
+ longer side, as it was, let corner buildings stand on a supply pile or past the map's edge.
+ The thinning keeps measuring against the half side, so a town is no denser than it was. */
+ Real halfAcross = spanAcross * 0.5f + plan->m_setBack + RMG_TOWN_JITTER;
+ Real halfDown = spanDown * 0.5f + plan->m_setBack + RMG_TOWN_JITTER;
+ plan->m_radius = sqrtf( halfAcross * halfAcross + halfDown * halfDown ) + 4.0f;
+ plan->m_thinRadius = span * 0.5f + plan->m_setBack + 4.0f;
}
/// A point in the town's own coordinates, put where the map has it.
@@ -1068,7 +1161,9 @@ private:
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;
+ Int maxLead, Real bearing, Real clearance, RMGPoint *out, Int rival = -1,
+ Int rivalMaxLead = RMG_MONEY_NO_RIVAL ) const;
+ Bool placersSide( Int mapX, Int mapY, Int player, Int rival, Int maxLead ) 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,
@@ -1382,6 +1477,9 @@ void RMGLayout::buildHeights( const UnsignedByte perm[512] )
if( h < 1.0f ) h = 1.0f;
if( h > 254.0f ) h = 254.0f;
+ // A style skips the soft floor, so its pits go below nought; a negative float cast to a
+ // byte is undefined, and on x64 it wrapped -3 to 253, a spike field in every deep pit.
+ if( eased < 1.0f ) eased = 1.0f;
if( eased > 254.0f ) eased = 254.0f;
m_heights[cellIndex( x, y )] = (UnsignedByte)(h + 0.5f);
@@ -1927,15 +2025,54 @@ void RMGLayout::paintRiverStretches( const std::vector<Int>& fords )
Int reach = (Int)( half + 0.5f );
Int radiusSq = (Int)( half * half + 0.5f );
+ std::vector<char> dry( n, 0 );
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;
+ dry[i] = 1;
+ }
+ }
+
+ /* A stretch cut off between a ford and the end of the river, or between two fords, that is too
+ short to read as river is a square pond capping the line: the end is already a way across and
+ a pond there serves nothing. It goes dry with the ford beside it. The length scales with the
+ ford, so a small map's real stretches stay, and the longest stretch always stays, so a river
+ map keeps its river. */
+ if( !fords.empty() )
+ {
+ const Int minRun = (Int)( fordHalf + RMG_FORD_STUB_STEPS );
+ Int longestFrom = -1, longest = 0;
+ for( Int i = 0; i < n; )
+ {
+ Int end = i;
+ while( end < n && dry[end] == dry[i] )
+ end++;
+ if( !dry[i] && end - i > longest )
+ {
+ longest = end - i;
+ longestFrom = i;
+ }
+ i = end;
+ }
+ for( Int i = 0; i < n; )
+ {
+ Int end = i;
+ while( end < n && dry[end] == dry[i] )
+ end++;
+ if( !dry[i] && i != longestFrom && end - i < minRun )
+ {
+ for( Int k = i; k < end; k++ )
+ dry[k] = 1;
+ }
+ i = end;
}
- if( atAFord )
+ }
+
+ for( Int i = 0; i < n; i++ )
+ {
+ if( dry[i] )
continue;
Int cx = (Int)floorf( line[i].m_cellX + 0.5f ) + RMG_BORDER_CELLS;
@@ -2559,6 +2696,16 @@ void RMGLayout::chooseStarts( void )
std::vector<RMGStartCandidate> candidates;
+ /* The whole levelled flat has to be dry with a beach to spare, not just the inner disc: the
+ shore distance is city-block, which reads a diagonal half again as far as it is, and a base
+ levelled over the edge of a lake raised the lake bed under the water polygon into dry ground.
+ Sampling the flat cell by cell makes the reach a true circle. A map whose lakes leave too few
+ such sites to seat everyone with room to choose also takes the inner-disc sites, after the dry
+ ones and marked rougher, so a seat still prefers a dry flat and only a lake-crowded map ends
+ up on the looser kind. A handful of strict sites alone ran the ring search out of seats. */
+ UnsignedInt strictNext = 0; // both passes walk the same grid in the same order
+ for( Int pass = 0; pass < 2
+ && ( pass == 0 || (Int)candidates.size() < m_settings.m_numPlayers * RMG_START_STRICT_SITES_EACH ); pass++ )
for( Int y = margin; y < playable - margin; y += m_startSearchStride )
{
for( Int x = margin; x < playable - margin; x += m_startSearchStride )
@@ -2566,6 +2713,16 @@ void RMGLayout::chooseStarts( void )
Int mapX = x + RMG_BORDER_CELLS;
Int mapY = y + RMG_BORDER_CELLS;
+ /* A strict site passes the loose test too, and is in the list already. The strict ones
+ lead the list in walk order, so one index steps through them; once it reaches the
+ loose ones it points behind the walk and never matches again. */
+ if( pass == 1 && strictNext < candidates.size() && candidates[strictNext].m_cellX == (Real)x
+ && candidates[strictNext].m_cellY == (Real)y )
+ {
+ strictNext++;
+ continue;
+ }
+
// 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 )
@@ -2579,7 +2736,8 @@ void RMGLayout::chooseStarts( void )
continue;
Bool discDry = TRUE;
- Int disc = (Int)RMG_FLAT_RADIUS;
+ Int disc = pass == 0 ? (Int)( RMG_BASE_FLAT_FLOOR + RMG_BASE_FLAT_SWING ) : (Int)RMG_FLAT_RADIUS;
+ Real dryShore = pass == 0 ? RMG_PAD_SHORE_KEEP + 0.5f * RMG_LAKE_SHORE : 4.0f;
for( Int dy = -disc; dy <= disc && discDry; dy++ )
{
for( Int dx = -disc; dx <= disc; dx++ )
@@ -2588,7 +2746,7 @@ void RMGLayout::chooseStarts( void )
continue;
Real shore;
insideLake( (Real)( x + dx ), (Real)( y + dy ), &shore );
- if( shore < 4.0f )
+ if( shore < dryShore )
{
discDry = FALSE;
break;
@@ -2605,7 +2763,7 @@ void RMGLayout::chooseStarts( void )
RMGStartCandidate candidate;
candidate.m_cellX = (Real)x;
candidate.m_cellY = (Real)y;
- candidate.m_roughness = roughness;
+ candidate.m_roughness = pass == 0 ? roughness : roughness + RMG_START_LOOSE_PENALTY;
candidates.push_back( candidate );
}
}
@@ -3305,6 +3463,26 @@ void RMGLayout::shapeBases( void )
if( nearest > flatR )
t = (nearest - flatR) / (blendR - flatR);
+ /* The ring keeps off the lake the way a pad does: water and its beach are never levelled,
+ and nearer the shore the ground keeps more of its own slope down to the water. The pull
+ starts at nothing on the flat's edge and comes in over a few cells, so the base's lake
+ side eases down instead of dropping off a kerb. Levelled to the start's height, the ring
+ used to raise the bed of a lake beside the base into dry ground under the water. */
+ Real shore;
+ insideLake( px, py, &shore );
+ if( shore < RMG_PAD_SHORE_KEEP )
+ continue;
+ Real shoreT = ( shore - RMG_PAD_SHORE_KEEP ) / RMG_LAKE_SHORE;
+ if( shoreT < 1.0f )
+ {
+ Real ramp = ( nearest - flatR ) / RMG_BASE_SHORE_RAMP;
+ if( ramp < 0.0f ) ramp = 0.0f;
+ if( ramp > 1.0f ) ramp = 1.0f;
+ Real want = ( 1.0f - shoreT ) * ramp;
+ if( t < want )
+ t = want;
+ }
+
m_baseCells.push_back( cellIndex( x, y ) );
m_baseBlendT.push_back( t );
m_baseOwners.push_back( (UnsignedByte)nearestIndex );
@@ -4434,6 +4612,8 @@ void RMGLayout::holdMoneyWalks( void )
Int lead = theirs[c] - mine[c];
if( lead < RMG_CONTESTED_LEAD_MIN || lead > RMG_CONTESTED_LEAD_MAX )
continue;
+ if( !placersSide( money.m_cellX + dx, money.m_cellY + dy, player, money.m_rival, RMG_MONEY_NO_RIVAL ) )
+ continue;
bestX = dx;
bestY = dy;
bestOff = off;
@@ -4842,7 +5022,7 @@ void RMGLayout::buildBlends( void )
for( Int i = 0; i < count; i++ )
{
Bool flipped = theBlendShapes[shapes[i]].m_flip < 0 && count == 2 && flip > 0;
- Int tile = tileIndexForCell( x, y, classes[i] * RMG_TILES_PER_CLASS, RMG_TILE_SHEET_WIDTH );
+ Int tile = tileIndexForCell( x, y, rmgClassFirstTile( *m_biome, classes[i] ), rmgClassWidth( *m_biome, classes[i] ) );
Short entry = blendEntryFor( tile, shapes[i], flipped );
if( i == 0 )
m_blendIndex[cellIndex( x, y )] = entry;
@@ -5615,7 +5795,8 @@ void RMGLayout::walkFromStarts( std::vector< std::vector<Int> >& walk, std::vect
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
+ Real bearing, Real clearance, RMGPoint *out, Int rival,
+ Int rivalMaxLead ) const
{
const std::vector<Int>& mine = walk[player];
Real startX = m_starts[player].m_cellX;
@@ -5641,7 +5822,15 @@ Bool RMGLayout::findSiteByWalk( const std::vector< std::vector<Int> >& walk,
Int off = mine[index] - target;
if( off < 0 )
off = -off;
- if( off > band || lead[index] < minLead || lead[index] > maxLead )
+ /* A contested dock leads against its rival, not against whoever is second nearest: the
+ lead counted against the next seat round the other way put a dock meant for one gap in
+ the gap beside it, which then had two. */
+ Int cellLead = lead[index];
+ if( rival >= 0 )
+ cellLead = walk[rival][index] < 0 ? RMG_MONEY_NO_RIVAL : walk[rival][index] - mine[index];
+ if( off > band || cellLead < minLead || cellLead > maxLead )
+ continue;
+ if( rival >= 0 && !placersSide( x, y, player, rival, rivalMaxLead ) )
continue;
Real cellX = (Real)(x - RMG_BORDER_CELLS);
@@ -5688,6 +5877,27 @@ Bool RMGLayout::findSiteByWalk( const std::vector< std::vector<Int> >& walk,
return found;
}
+/** The walk the flood counts is four-way, so on a ring turned off the axes a contested dock could
+ lead its placer by three steps and still stand twenty cells nearer the rival in a straight line
+ and on the game's own eight-way paths. The dock has to be on the placer's side as the crow flies
+ as well, by RMG_CONTESTED_LEAD_MIN to maxLead cells: octile distance in tenths (10 straight, 14
+ diagonal, as the pathfinder counts), integer, from the cell to each start's own cell. */
+Bool RMGLayout::placersSide( Int mapX, Int mapY, Int player, Int rival, Int maxLead ) const
+{
+ Int cellX = mapX - RMG_BORDER_CELLS;
+ Int cellY = mapY - RMG_BORDER_CELLS;
+ Int octile[2];
+ Int who[2] = { player, rival };
+ for( Int k = 0; k < 2; k++ )
+ {
+ Int dx = abs( cellX - (Int)( m_starts[who[k]].m_cellX + 0.5f ) );
+ Int dy = abs( cellY - (Int)( m_starts[who[k]].m_cellY + 0.5f ) );
+ octile[k] = dx > dy ? dx * 10 + dy * 4 : dy * 10 + dx * 4;
+ }
+ Int lead = octile[1] - octile[0];
+ return lead >= RMG_CONTESTED_LEAD_MIN * 10 && lead <= maxLead * 10;
+}
+
/** 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
@@ -5874,28 +6084,59 @@ void RMGLayout::placeSupplyAndDerricks( void )
return;
/* 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. */
+ to its rival, so no seat's fight is closer to home than another's. With three seats or more
+ the rival is the next seat round the middle of the map, so every gap between two neighbours
+ gets one dock and every seat places one. The nearest seat by walk, as it was, ties both ring
+ neighbours on a square ring and gave the lowest index both: two docks in one gap, none in the
+ gap across from it. A next seat that cannot be walked to gives way to the nearest one. */
walkFromStarts( walk, owner, lead );
std::vector<Int> rival( players, -1 );
+ if( players >= 3 )
+ {
+ Real middle = playable * 0.5f;
+ std::vector<Real> bearing( players );
+ std::vector<Int> seatsRound;
+ for( Int i = 0; i < players; i++ )
+ {
+ bearing[i] = ATan2( m_starts[i].m_cellY - middle, m_starts[i].m_cellX - middle );
+ // by bearing, ties by index: insertion keeps it stable
+ Int at = (Int)seatsRound.size();
+ while( at > 0 && bearing[seatsRound[at - 1]] > bearing[i] )
+ at--;
+ seatsRound.insert( seatsRound.begin() + at, i );
+ }
+ for( Int k = 0; k < players; k++ )
+ rival[seatsRound[k]] = seatsRound[( k + 1 ) % players];
+ }
Int contestedWalk = -1;
for( Int i = 0; i < players; i++ )
{
- Int nearestWalk = -1;
- for( Int j = 0; j < players; j++ )
+ Int rivalWalk = -1;
+ if( rival[i] >= 0 )
{
- if( j == i )
- continue;
- 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 ) )
+ Int x = (Int)(m_starts[rival[i]].m_cellX + 0.5f) + RMG_BORDER_CELLS;
+ Int y = (Int)(m_starts[rival[i]].m_cellY + 0.5f) + RMG_BORDER_CELLS;
+ rivalWalk = walk[i][cellIndex( x, y )];
+ }
+ if( rivalWalk < 0 )
+ {
+ rival[i] = -1;
+ for( Int j = 0; j < players; j++ )
{
- nearestWalk = d;
- rival[i] = j;
+ if( j == i )
+ continue;
+ 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 && ( rivalWalk < 0 || d < rivalWalk ) )
+ {
+ rivalWalk = d;
+ rival[i] = j;
+ }
}
}
- if( nearestWalk >= 0 && ( contestedWalk < 0 || nearestWalk / 2 < contestedWalk ) )
- contestedWalk = nearestWalk / 2;
+ if( rivalWalk >= 0 && ( contestedWalk < 0 || rivalWalk / 2 < contestedWalk ) )
+ contestedWalk = rivalWalk / 2;
}
static const Int theContestedBands[] = { 3, 8, 16, 1000 };
@@ -5911,12 +6152,21 @@ void RMGLayout::placeSupplyAndDerricks( void )
{
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 );
+ RMG_SITE_CLEARANCE, &site, rival[i] );
+ /* Where the four-way walk favours the placer, every spot it gives a small lead is
+ nearer the rival in a straight line, so the lead window moves to the straight line
+ instead and the walk only has to agree on who gets there first. */
+ if( !found )
+ found = findSiteByWalk( walk, owner, lead, i, contestedWalk, theContestedBands[b],
+ RMG_CONTESTED_LEAD_MIN, RMG_MONEY_NO_RIVAL, toward,
+ RMG_SITE_CLEARANCE, &site, rival[i], RMG_CONTESTED_LEAD_MAX );
+ }
if( !found )
found = findSiteByWalk( walk, owner, lead, i, contestedWalk, 1000, 1,
- RMG_CONTESTED_LEAD_MAX * 2, toward, 3.0f, &site );
+ RMG_CONTESTED_LEAD_MAX * 2, toward, 3.0f, &site, rival[i] );
if( found )
{
RMGMoneyWalk planned;
@@ -6010,15 +6260,17 @@ void RMGLayout::placeTowns( void )
{
/* 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;
+ which is between everybody by construction. A plan that fits nowhere is rolled again, and a
+ map about to end with no town at all then tries as many of the smallest plan, three streets
+ each way on the closest blocks: with one roll a town, a third of the four-seat maps ended
+ with no town, though a small one had room. */
+ Int rolls = (town == towns - 1 && townsPlaced == 0) ? 2 * RMG_TOWN_REROLLS : RMG_TOWN_REROLLS;
RMGTownPlan plan;
RMGPoint site;
Bool found = FALSE;
for( Int roll = 0; roll < rolls && !found; roll++ )
{
- rollTownPlan( m_settings.m_seed, town + 16 * roll, &plan );
+ rollTownPlan( m_settings.m_seed, town + 16 * roll, roll >= RMG_TOWN_REROLLS, &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.
@@ -6129,8 +6381,8 @@ void RMGLayout::placeTowns( void )
/* 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;
+ Real outX = (buildingX - site.m_cellX) / plan.m_thinRadius;
+ Real outY = (buildingY - site.m_cellY) / plan.m_thinRadius;
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,
@@ -6490,7 +6742,8 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )
{
if( rockBudget <= 0 )
continue;
- if( (hash >> 24) % 100U > 25U )
+ // a quarter of the rocky cells: the top eight bits are 0 to 255, never a hundred and more
+ if( (hash >> 24) >= RMG_ROCK_ACCEPT_IN_256 )
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.
@@ -6564,6 +6817,17 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )
if( chance > 0.25f )
chance = 0.25f;
chance *= 0.5f + 0.5f * m_biome->m_treeShare;
+ /* The wood's chances were tuned against the old eight-bit per-mille test, which planted
+ ( floor( 1000 c ) + 1 ) / 256 of the cells: nearly all of them at the cap, a third in a
+ tuft. Read straight as a fraction under the exact test below, the same numbers left a
+ black forest a third to two thirds short of its tree count. The old rate is kept here;
+ the cap that trims the pool to the target is what thins the wood, not this. */
+ if( chance > 0.0f )
+ {
+ chance = (Real)( (Int)( chance * 1000.0f ) + 1 ) / 256.0f;
+ if( chance > 1.0f )
+ chance = 1.0f;
+ }
}
else
{
@@ -6580,18 +6844,25 @@ void RMGLayout::placeScenery( const UnsignedByte perm[512] )
if( density < clumpEdge )
continue;
- chance = 0.05f + (density - clumpEdge) * 1.5f;
- if( chance > 0.5f )
- chance = 0.5f;
- chance *= m_biome->m_treeShare;
+ /* Not scaled by the biome's tree share: the share already sets how many trees the map
+ holds (target, below), and taking it off the chance as well left a desert or a
+ Twilight wood a pool a quarter the size of the count it was calibrated to. */
+ chance = 0.08f + (density - clumpEdge) * 3.0f;
+ if( chance > 0.7f )
+ chance = 0.7f;
}
- if( (Real)((hash >> 24) % 1000U) / 1000.0f > chance )
+ /* Ten bits of the hash read as a fraction of one. The eight bits this used to read as a
+ per-mille only ever came to a quarter, so every chance over that planted every cell of
+ the stride and the woods stood as a solid grid. */
+ if( (hash >> 22) >= (UnsignedInt)( chance * 1024.0f ) )
continue;
RMGTreeSpot spot;
spot.m_x = (Real)x + jitterX;
spot.m_y = (Real)y + jitterY;
- spot.m_depth = (Int)( density * 10000.0f );
+ // the depth the cap trims by, ragged by a slice of the hash so the kept edge of a wood is a
+ // band rather than one contour line
+ spot.m_depth = (Int)( density * 10000.0f ) + (Int)( hashCell( m_settings.m_seed + 7723, x, y ) % RMG_TREE_EDGE_RAGGED );
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 );
@@ -6868,7 +7139,16 @@ void RMGLayout::buildObjects( const UnsignedByte perm[512] )
// the shipped map a style comes from has neither a town nor a bunker on it, and a skeleton gets
// its towns and its dressing from the template
if( !m_style && !m_skeleton )
+ {
+ /* A town keeps out of every base's levelled ring, not only the one it is placed beside: a
+ start reserves its flat disc alone, and a building in the ring sat on a pad the base's
+ levelling then cut through. The rings are the towns' alone, so they go again after. */
+ const UnsignedInt startRings = m_sites.size();
+ for( UnsignedInt i = 0; i < m_starts.size(); i++ )
+ reserveSite( m_starts[i].m_cellX, m_starts[i].m_cellY, RMG_TOWN_START_CLEAR );
placeTowns();
+ m_sites.erase( m_sites.begin() + startRings, m_sites.begin() + startRings + m_starts.size() );
+ }
if( m_type->m_massif > 0.0f )
m_sites.erase( m_sites.begin() + massifSite );
if( m_skeleton )
@@ -7409,7 +7689,7 @@ void RandomMapGenerator::clampSettings( RandomMapSettings& settings )
map's own size and the other counts scale off it the way the normal size does. */
if( settings.m_playableCells <= 0 )
{
- settings.m_playableCells = cellsFor( RANDOM_MAP_SIZE_NORMAL, settings.m_numPlayers );
+ settings.m_playableCells = cellsFor( RANDOM_MAP_SIZE_NORMAL, settings.m_numPlayers, settings.m_template );
if( settings.m_style > 0 )
{
const RMGStyle& style = theStyles[settings.m_style - 1];
@@ -7419,6 +7699,16 @@ void RandomMapGenerator::clampSettings( RandomMapSettings& settings )
}
}
+ /* A template's smallest size is the least ground its seats can be spread over. The size buttons
+ never go under it, but a typed cell count or a name read back can, and eight seats on a 64-cell
+ field came out as eight pads in a heap with a third of the objects outside play. */
+ if( !settings.m_template.isEmpty() )
+ {
+ Int tiny = cellsFor( RANDOM_MAP_SIZE_TINY, settings.m_numPlayers, settings.m_template );
+ if( settings.m_playableCells < tiny )
+ settings.m_playableCells = tiny;
+ }
+
if( settings.m_playableCells < MIN_CELLS ) settings.m_playableCells = MIN_CELLS;
if( settings.m_playableCells > MAX_CELLS ) settings.m_playableCells = MAX_CELLS;
}
@@ -7433,6 +7723,150 @@ Int RandomMapGenerator::styleNamed( const char *name )
return 0;
}
+/* The planar tiling lays a class's sheet flat over the ground, two cells a tile, so a face that rises
+ g bytes a cell shows the same 32 texels over sqrt(100 + (0.625 g)^2) world units: the twilight
+ style's rim, 29 bytes a cell at the median, drew its rock half as sharp along the fall as across
+ it, and the template's pads and canyons are steeper still. WorldHeightMap::getUVForTileIndex takes
+ a cell's coordinates out of its cliff entry instead, when it has one of its own class, so the faces
+ get one here the way WorldBuilder's doCliffAdjustment bakes them.
+
+ V is the height, as WorldBuilder has it: a byte is 1/1024 of TEXTURE_WIDTH, which is the true
+ length of a steep face and does not depend on which way it falls. Every corner a face's cells share
+ takes the same V, so a face is one piece of texture with no seam inside it. A cell's corners have
+ to lie inside its class's block of the terrain texture, 128 bytes tall for a sheet four tiles
+ across, and the sheet tiles, so V starts the block again every block's height. WorldBuilder centred
+ a face in one block and squeezed a taller one; the rim and ridge of a twilight bowl climb 166 bytes,
+ and squeezed to 128 their gentler cells came out worse than the plane. A cell that a restart height
+ runs through cannot hold both sides of it, so each face (an 8-connected patch of mapped cells of
+ one class) restarts at the heights where fewest of its cells cross, which is mostly the flat of a
+ plateau where it has none, and a cell that still crosses keeps the plane.
+
+ U runs across the fall: along y on a cell that falls more along x, along x otherwise, a whole sheet
+ period behind the cell so the four corners stay inside the block. That is the planar U itself on a
+ cell falling along y, so its seam with the flat ground beside it is in V alone.
+
+ Height alone gives an edge that does not rise no texture at all, so a cell takes the mapping only
+ when both its edges down the fall rise more than WorldBuilder's limit: then no edge down the fall
+ is drawn more than 1.6 times stretched, where the plane drew the twilight rim at 2 and more, and
+ none across it worse than the plane. WorldBuilder maps on any one steep edge and nudges flat
+ corners up afterwards (minHeightDelta), which seams a face; a rim's top and foot cells keep the
+ plane here instead. A cell whose class is no cliff keeps the planar tiling too, and so do the
+ blends of other classes drawn over a mapped cell, which the renderer matches to the entry's class. */
+void rmgCliffMapping( const std::vector<Int>& heights, Int W, Int H, const std::vector<Int>& sheetFirst,
+ const std::vector<Int>& sheetWidth, std::vector<Short>& indexOut, std::vector<RMGCliffInfo>& infoOut )
+{
+ indexOut.assign( W * H, 0 );
+ infoOut.assign( 1, RMGCliffInfo() );
+
+ // the cells that rise down both edges along their fall, and their lowest and highest corner
+ std::vector<Int> lowest( W * H, -1 ), highest( W * H, -1 );
+ for( Int y = 0; y + 1 < H; y++ )
+ {
+ for( Int x = 0; x + 1 < W; x++ )
+ {
+ const Int i = y * W + x;
+ if( sheetFirst[i] < 0 || sheetWidth[i] < 1 )
+ continue;
+ const Int h[4] = { heights[i], heights[i + 1], heights[i + W + 1], heights[i + W] };
+ const Int alongX = std::min( abs( h[0] - h[1] ), abs( h[3] - h[2] ) );
+ const Int alongY = std::min( abs( h[0] - h[3] ), abs( h[1] - h[2] ) );
+ const Bool fallsAlongX = std::max( abs( h[0] - h[1] ), abs( h[3] - h[2] ) ) >= std::max( abs( h[0] - h[3] ), abs( h[1] - h[2] ) );
+ if( ( fallsAlongX ? alongX : alongY ) <= RMG_CLIFF_UV_RISE )
+ continue;
+ lowest[i] = std::min( std::min( h[0], h[1] ), std::min( h[2], h[3] ) );
+ highest[i] = std::max( std::max( h[0], h[1] ), std::max( h[2], h[3] ) );
+ }
+ }
+
+ // the faces, flooded in raster order, and the cells of each
+ std::vector<Int> face( W * H, -1 ), faceStart, faceCells, stack;
+ for( Int seed = 0; seed < W * H; seed++ )
+ {
+ if( lowest[seed] < 0 || face[seed] >= 0 )
+ continue;
+ const Int f = (Int)faceStart.size();
+ faceStart.push_back( (Int)faceCells.size() );
+ face[seed] = f;
+ stack.push_back( seed );
+ while( !stack.empty() )
+ {
+ const Int i = stack.back(), x = i % W, y = i / W;
+ stack.pop_back();
+ faceCells.push_back( i );
+ for( Int dy = -1; dy <= 1; dy++ )
+ {
+ for( Int dx = -1; dx <= 1; dx++ )
+ {
+ const Int nx = x + dx, ny = y + dy, n = ny * W + nx;
+ if( nx < 0 || ny < 0 || nx >= W || ny >= H || lowest[n] < 0 || face[n] >= 0 || sheetFirst[n] != sheetFirst[seed] )
+ continue;
+ face[n] = f;
+ stack.push_back( n );
+ }
+ }
+ }
+ }
+ faceStart.push_back( (Int)faceCells.size() );
+
+ // each face's restart: of the heights a block apart, the lowest phase the fewest of its cells
+ // cross; a cell crosses one strictly between its lowest and highest corner
+ std::vector<Int> phase( faceStart.size() - 1, 0 ), crossing;
+ for( Int f = 0; f + 1 < (Int)faceStart.size(); f++ )
+ {
+ const Int sheetBytes = sheetWidth[faceCells[faceStart[f]]] * RMG_CLIFF_UV_CELL * 2 / RMG_CLIFF_UV_BYTE;
+ crossing.assign( sheetBytes, 0 );
+ for( Int c = faceStart[f]; c < faceStart[f + 1]; c++ )
+ for( Int t = lowest[faceCells[c]] + 1; t < highest[faceCells[c]]; t++ )
+ crossing[t % sheetBytes]++;
+ for( Int p = 1; p < sheetBytes; p++ )
+ if( crossing[p] < crossing[phase[f]] )
+ phase[f] = p;
+ }
+
+ // a cell its face's restart still runs through keeps the plane, and more cells than the reader
+ // takes keep the steepest
+ std::vector< std::pair<Int, Int> > cells;
+ std::vector<Int> restart( W * H, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ if( lowest[i] < 0 )
+ continue;
+ const Int sheetBytes = sheetWidth[i] * RMG_CLIFF_UV_CELL * 2 / RMG_CLIFF_UV_BYTE, p = phase[face[i]];
+ const Int below = lowest[i] - p >= 0 ? ( lowest[i] - p ) / sheetBytes : -( ( p - lowest[i] + sheetBytes - 1 ) / sheetBytes );
+ restart[i] = p + below * sheetBytes;
+ if( highest[i] - restart[i] > sheetBytes )
+ continue;
+ cells.push_back( std::make_pair( lowest[i] - highest[i], i ) );
+ }
+ if( (Int)cells.size() > RMG_NUM_CLIFF_INFO - 1 )
+ {
+ std::sort( cells.begin(), cells.end() );
+ cells.resize( RMG_NUM_CLIFF_INFO - 1 );
+ std::sort( cells.begin(), cells.end(), []( const std::pair<Int, Int>& a, const std::pair<Int, Int>& b ) { return a.second < b.second; } );
+ }
+
+ for( size_t c = 0; c < cells.size(); c++ )
+ {
+ const Int i = cells[c].second, x = i % W, y = i / W, w = sheetWidth[i];
+ const Int h[4] = { heights[i], heights[i + 1], heights[i + W + 1], heights[i + W] };
+ const Bool fallsAlongX = std::max( abs( h[0] - h[1] ), abs( h[3] - h[2] ) ) >= std::max( abs( h[0] - h[3] ), abs( h[1] - h[2] ) );
+ const Int along = fallsAlongX ? y : x, period = 2 * w, behind = along - along % period;
+ const Int corner[4][2] = { { x, y }, { x + 1, y }, { x + 1, y + 1 }, { x, y + 1 } };
+ RMGCliffInfo info;
+ info.m_tileIndex = sheetFirst[i] << 2;
+ for( Int k = 0; k < 4; k++ )
+ {
+ const Int u = ( corner[k][fallsAlongX ? 1 : 0] - behind ) * RMG_CLIFF_UV_CELL;
+ const Int v = -( h[k] - restart[i] ) * RMG_CLIFF_UV_BYTE;
+ info.m_u[k] = (Real)u / (Real)RMG_CLIFF_UV_UNITS;
+ info.m_v[k] = (Real)v / (Real)RMG_CLIFF_UV_UNITS;
+ }
+ info.m_flip = abs( h[2] - h[0] ) >= abs( h[3] - h[1] );
+ indexOut[i] = (Short)infoOut.size();
+ infoOut.push_back( info );
+ }
+}
+
/// The CkMp stream for a built layout.
static void writeLayout( const RMGLayout& layout, std::vector<char>& mapBytes )
{
@@ -7459,37 +7893,50 @@ static void writeLayout( const RMGLayout& layout, std::vector<char>& mapBytes )
// passability bits in the file, below it works them out from the heights.
{
std::vector<Short> tiles( dataSize );
- std::vector<Short> zeroes( dataSize, 0 );
+ std::vector<Int> heights( layout.m_heights.begin(), layout.m_heights.end() );
+ std::vector<Int> sheetFirst( dataSize, -1 ), sheetWidth( dataSize, 0 );
+ const RMGBiome& biome = *layout.m_biome;
for( Int y = 0; y < height; y++ )
{
for( Int x = 0; x < width; x++ )
{
- Int terrainClass = layout.m_terrain[layout.cellIndex( x, y )];
- tiles[layout.cellIndex( x, y )] = tileIndexForCell( x, y,
- terrainClass * RMG_TILES_PER_CLASS, RMG_TILE_SHEET_WIDTH );
+ const Int i = layout.cellIndex( x, y ), terrainClass = layout.m_terrain[i];
+ const Int first = rmgClassFirstTile( biome, terrainClass ), sheet = rmgClassWidth( biome, terrainClass );
+ tiles[i] = tileIndexForCell( x, y, first, sheet );
+ // the rock is what the generator paints its faces with
+ if( terrainClass == RMG_TERRAIN_ROCK )
+ {
+ sheetFirst[i] = first;
+ sheetWidth[i] = sheet;
+ }
}
}
+ std::vector<Short> cliffIndex;
+ std::vector<RMGCliffInfo> cliffInfo;
+ rmgCliffMapping( heights, width, height, sheetFirst, sheetWidth, cliffIndex, cliffInfo );
w.openChunk( "BlendTileData", K_BLEND_TILE_VERSION_6 );
w.writeInt( dataSize );
w.writeBytes( &tiles[0], dataSize * sizeof(Short) );
w.writeBytes( &layout.m_blendIndex[0], dataSize * sizeof(Short) );
w.writeBytes( &layout.m_extraBlendIndex[0], dataSize * sizeof(Short) );
- w.writeBytes( &zeroes[0], dataSize * sizeof(Short) ); // cliff info
+ w.writeBytes( &cliffIndex[0], dataSize * sizeof(Short) );
- w.writeInt( RMG_TERRAIN_COUNT * RMG_TILES_PER_CLASS ); // bitmap tiles
+ w.writeInt( rmgClassFirstTile( biome, RMG_TERRAIN_COUNT ) ); // bitmap tiles
w.writeInt( (Int)layout.m_blends.size() );
- w.writeInt( 1 ); // cliff infos: entry 0 is the default
+ w.writeInt( (Int)cliffInfo.size() ); // entry 0 is the default and is never written
w.writeInt( RMG_TERRAIN_COUNT );
for( Int terrainClass = 0; terrainClass < RMG_TERRAIN_COUNT; terrainClass++ )
{
- w.writeInt( terrainClass * RMG_TILES_PER_CLASS ); // first tile
- w.writeInt( RMG_TILES_PER_CLASS );
- w.writeInt( RMG_TILE_SHEET_WIDTH );
+ Int tilesInClass, sheet;
+ rmgTextureSheet( biome.m_textures[terrainClass], tilesInClass, sheet );
+ w.writeInt( rmgClassFirstTile( biome, terrainClass ) );
+ w.writeInt( tilesInClass );
+ w.writeInt( sheet );
w.writeInt( 0 ); // legacy field
- w.writeAsciiString( layout.m_biome->m_textures[terrainClass] );
+ w.writeAsciiString( biome.m_textures[terrainClass] );
}
w.writeInt( 0 ); // no edge tiles
@@ -7509,6 +7956,19 @@ static void writeLayout( const RMGLayout& layout, std::vector<char>& mapBytes )
w.writeInt( -1 ); // no custom blend edge class: use the alpha
w.writeInt( RMG_BLEND_FLAG_VALUE );
}
+
+ // the cliff mappings, in the order the reader takes them from version 5 on
+ for( UnsignedInt i = 1; i < cliffInfo.size(); i++ )
+ {
+ w.writeInt( cliffInfo[i].m_tileIndex );
+ for( Int k = 0; k < 4; k++ )
+ {
+ w.writeReal( cliffInfo[i].m_u[k] );
+ w.writeReal( cliffInfo[i].m_v[k] );
+ }
+ w.writeByte( cliffInfo[i].m_flip ? 1 : 0 );
+ w.writeByte( 0 ); // not a mutant: WorldBuilder's mark for a cell it gave up on
+ }
w.closeChunk();
}
@@ -7927,7 +8387,8 @@ Bool generatedMapFromWireName( const AsciiString& wire, AsciiString& folderOut )
}
// ponytail: the first shipped map whose letters match wins, so two folders sharing four letters
- // leave the later one out of LAN games; a fifth letter when that ever happens
+ // leave the later one out of LAN games; a fifth letter when that ever happens, which a test over
+ // every shipped map folder says (every_shipped_map_has_wire_letters_of_its_own)
FilenameList maps;
TheFileSystem->getFileListInDirectory( AsciiString( "Maps\\" ), AsciiString( "*.map" ), maps, TRUE );
AsciiString token;
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapTemplate.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapTemplate.cpp
index fc6f3af33..0d43b301a 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapTemplate.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapTemplate.cpp
@@ -81,7 +81,10 @@ const Real PAD_OPEN = 24.0f; // the base's reach on open ground
const Real PAD_CLIFF = 0.25f; // of a base plateau's rim, the share that must fall away for it to be a plateau
const Real PAD_SPACING = 0.45f; // of the nearest two starts' distance, the most a pad's radius may be
const Real PAD_SCALE_LEAST = 0.5f;
+const Real PAD_BEARING_SLACK = 0.05f; // radians a seat, the misses within which bases count as facing the seats as well
const Int PAD_CORRIDOR = 28; // cells between two plateau bases, Twilight Flame's narrowest way from one to the next; a narrower way is filled
+const Int JOIN_FADE = 16; // cells of the two bases' summed distance over which a filled way falls back to the ground past it: eight cells aside
+const Real PAD_SITE_LEAST = 20.0f; // cells a dock or derrick pulled in off the map's edge keeps from its start, past the command centre
const Real PAD_SHORE = 4.0f; // cells a pad stays off the exemplar's water
const Real RAMP_STEEP = 8.0f; // bytes a cell, the steepest a cut ramp climbs
const Int WIDE_RAMP_HALF = 16; // cells either side of its walk, a scaled plateau's ramp: Twilight Flame's 22 and the cliffs' growth
@@ -91,8 +94,11 @@ const Int CROSS_WET = 100; // water cells in a town's box that put the town o
const Int CROSS_STEP = 8; // cells between the places tried for a crossing along its river
const Real CALM_EASE = 20.0f; // cells over which a river's wander comes back past a crossing
const Real BRIDGE_DECK = 4.0f; // cells a bridge's deck takes along its river
+const Real BRIDGE_END = 4.0f; // cells round a river bridge's end raised to its bank
const Real CROSS_GUARD = 0.3f; // how far into a pad's fade a crossing may reach
const Int CROSS_LEAST = 20; // cells a side, the least of a crossing cut down to fit: a bridge and its banks
+const Int CROSS_CROPS = 6; // the cuts of a crossing tried, the whole of it first
+const Real CROSS_CROP[CROSS_CROPS] = { 1.0f, 0.75f, 0.55f, 0.4f, 0.3f, 0.2f };
const Int REPAIR_ROUNDS = 4;
const Real SLOPE_REACH = 100.0f;
const Int PILE_FLAT = 4;
@@ -123,6 +129,17 @@ const Int ROAD_SPACING = 2;
const Real ROAD_TOLERANCE = 1.5f;
const Int ROAD_CLEAR = 3;
const Real ROAD_MIN = 60.0f;
+// a road is pulled straight up to this many cells ahead, where the straight line costs no more than
+// this many thousandths of the path it replaces (so a pull never climbs what the path went round)
+const Int ROAD_PULL_REACH = 64;
+const Int ROAD_PULL_SLACK = 1100;
+// a bend kept closer than this to where two roads meet folds into the meeting point: a sliver shorter
+// than half a road's width turns the renderer's tee inside out
+const Real ROAD_JOIN_SNAP = 3.0f;
+// how far from where it was cut a road looks for the road it ran into, in cells
+const Int ROAD_JOIN_REACH = 6;
+// a copied road end flagged to join another road, with none this near, is a stub left in the open
+const Real ROAD_STUB_REACH = 3.0f;
const Real COAST_EDGE = 0.4f;
const Real FULL_EDGE = 0.9f;
const Real RIVER_SLOPE = 3.0f;
@@ -131,7 +148,23 @@ const Int TOWN_STEP = 8;
const Int TOWN_RELIEF = 50;
const Int TOWN_LEAST = 30; // cells a side, the least of a town cut down to fit
const Int PATH_CELLS = 4;
+// what the quilt matches a cell on beside its height, a bit each (Exemplar::ground): the target's
+// GROUND_STRIP is a planned road's clearance, the exemplar's a road strip's texture class
+const UnsignedByte GROUND_CLIFF = 1, GROUND_WET = 2, GROUND_SHORE = 4, GROUND_STRIP = 8;
+// a mismatch's price in quarters of a cliff's: a sea laid on land's ground, bank sand off the shore,
+// and a road strip where no road runs (one way: plain ground under a new road costs nothing)
+const Int PRICE_CLIFF = 4, PRICE_WET = 4, PRICE_SHORE = 2, PRICE_STRIP = 4;
+const Int SHORE_GROUND = 4; // cells off its water a bank's ground lies: Heartland Shield's bank sand in 2849 of 2855 cells
+const Int STRIP_LIFT = 4; // a class this many times as common along the roads as over the map is a road's strip
+// cells round a start on a template whose bases are not raised that the quilt never copies: that
+// ground is the flattest there is, so a flat map matched it everywhere (Bombardment Beach's start dirt
+// on 43% of its maps against 12% of it); a pad brings it along. PAD_INNER: 34 left Bombardment's eight
+// seats too little of it, 9% against the template's 12%
+const Int BASE_GROUND = 24;
const Int BRIDGE_CLEAR = 6;
+// cells from a cell of the wrong steepness to the exemplar's cell whose texture it takes instead: past
+// it a new cliff takes the exemplar's commonest cliff texture and new flat ground keeps its own
+const Int TEXTURE_REACH = 16;
const Int CLUMP_CELLS = 5;
const Int TREE_TRIES = 40;
@@ -417,6 +450,38 @@ void reach( const Mask& passable, Int W, Int H, Int start, Mask& seen )
}
}
+/// Each cell's nearest seed's class, four-way steps and no further than reach, else -1: one flood from
+/// every seed at once, the seeds in raster order, and the first to come to a cell keeps it.
+void nearestClass( const Mask& seed, const std::vector<Int>& cls, Int W, Int H, Int reach, std::vector<Int>& out )
+{
+ out.assign( W * H, -1 );
+ std::vector<Int> steps( W * H, -1 ), queue;
+ queue.reserve( W * H );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ if( !seed[i] ) continue;
+ out[i] = cls[i];
+ steps[i] = 0;
+ queue.push_back( i );
+ }
+ for( size_t head = 0; head < queue.size(); head++ )
+ {
+ Int i = queue[head];
+ if( steps[i] >= reach ) continue;
+ Int x = i % W, y = i / W;
+ const Int n[4] = { x + 1 < W ? i + 1 : -1, x > 0 ? i - 1 : -1, y + 1 < H ? i + W : -1, y > 0 ? i - W : -1 };
+ for( Int k = 0; k < 4; k++ )
+ {
+ if( n[k] >= 0 && steps[n[k]] < 0 )
+ {
+ steps[n[k]] = steps[i] + 1;
+ out[n[k]] = out[i];
+ queue.push_back( n[k] );
+ }
+ }
+ }
+}
+
/// scipy's label: four-way pieces of the set, numbered from 1 in raster order of their first cell.
Int labelPieces( const Mask& m, Int W, Int H, std::vector<Int>& labels )
{
@@ -1053,7 +1118,7 @@ struct InvCanyon { Real floorDz, width, length, winding, centreShare; Bool reach
struct InvMesa { Int area; Real radius, topDz, centreShare; Int exits; Mask near; };
struct InvBridge { AsciiString name; Real length; Int over; Real endsDz[2]; Real centreShare; Int onMesa; Int water; };
struct InvRoad { AsciiString name; Int segments; Real length, outsideLength, segmentLength; Int flags[2]; };
-struct InvTown { Int buildings; Real box[4]; Real centreShare; };
+struct InvTown { Int buildings; Real box[4]; Real centreShare; std::vector<YX> houses; }; ///< houses: grid cells, border in
struct InvTech { AsciiString name; Real centreShare; Int onMesa; };
enum { OVER_WATER, OVER_GAP, OVER_GROUND };
@@ -1075,6 +1140,7 @@ struct Inventory
std::vector<AsciiString> pileCompany; ///< what stands with half the piles or more
Bool split;
Int roadExits;
+ Mask roadLines; ///< the cells every road segment's line crosses, towns' streets too
};
/// Length along the cells' main axis, mean width, and how far the centre line wanders (mapfeatures.shape).
@@ -1378,6 +1444,7 @@ void takeInventory( const SynthMap& m, const Levels& lv, CivilianTest civilian,
// bridges and roads, as the engine pairs them: a POINT1 object and the POINT2 one after it
struct Segment { AsciiString name; Real x1, y1, x2, y2; Int f1, f2; };
std::vector<Segment> segments;
+ inv.roadLines.assign( W * H, 0 );
for( size_t k = 0; k + 1 < m.things.size(); k++ )
{
const MapThing&p = m.things[k];
@@ -1429,6 +1496,7 @@ void takeInventory( const SynthMap& m, const Levels& lv, CivilianTest civilian,
s.x1 = p.x + b; s.y1 = p.y + b; s.x2 = q.x + b; s.y2 = q.y + b;
s.f1 = p.flags; s.f2 = q.flags;
segments.push_back( s );
+ lineCells( yx( s.y1, s.x1 ), yx( s.y2, s.x2 ), W, H, inv.roadLines );
}
}
@@ -1468,6 +1536,7 @@ void takeInventory( const SynthMap& m, const Levels& lv, CivilianTest civilian,
town.box[0] = std::min( town.box[0], t.x ); town.box[1] = std::min( town.box[1], t.y );
town.box[2] = std::max( town.box[2], t.x ); town.box[3] = std::max( town.box[3], t.y );
sy += t.y + b; sx += t.x + b;
+ town.houses.push_back( yx( t.y + b, t.x + b ) );
}
places.where( sy / members[k].size(), sx / members[k].size(), &town.centreShare, NULL );
inv.towns.push_back( town );
@@ -1628,9 +1697,17 @@ struct Exemplar
std::vector<Scenery> scenery;
std::vector<Int> trees; ///< trees a cell
Real treeDensity;
- Mask town;
+ Mask town; ///< ground the quilt never copies: towns, and the bases of a flat template
+ Mask ground; ///< GROUND_ bits a cell: cliff, water, shore, road strip
+ Bool hasWater;
Field detail; ///< t less its own blur: the detail the quilting copies
std::vector<Int> guide64, detail256;
+ std::vector<Int> blendOver; ///< cells of class c carrying a blend of class k, at c * classes + k
+ std::vector<Int> classRank; ///< a class's place by how much more often it lies over the others than under
+ Mask steep; ///< the exemplar's cliffs by its own heights, cliffOf's rule
+ Mask cliffTexture; ///< a class whose name says cliff
+ std::vector<Int> steepClass; ///< the class of the nearest steep cell painted as cliff, or the commonest such; -1 none
+ std::vector<Int> openClass; ///< the class of the nearest cell not steep, -1 past TEXTURE_REACH
Bool load( const std::vector<char>& data, CivilianTest civilian )
{
@@ -1702,6 +1779,60 @@ struct Exemplar
blendShape.push_back( (Int)( std::lower_bound( shapes.begin(), shapes.end(), key ) - shapes.begin() ) );
}
+ // which class the exemplar lays over which, for the blends blendChunk works out again: the count of
+ // each pair, and one order of all of them for the pairs the exemplar never puts side by side
+ const Int NC = std::max( (Int)m.classes.size(), 1 );
+ blendOver.assign( NC * NC, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ const Short layer[2] = { m.blends[i], m.extras[i] };
+ for( Int l = 0; l < 2; l++ )
+ if( layer[l] > 0 && layer[l] < (Int)entries.size() && blendClass[layer[l]] != cls[i] )
+ blendOver[cls[i] * NC + blendClass[layer[l]]]++;
+ }
+ std::vector< std::pair<Int, Int> > net;
+ for( Int k = 0; k < NC; k++ )
+ {
+ Int over = 0;
+ for( Int c = 0; c < NC; c++ )
+ over += blendOver[c * NC + k] - blendOver[k * NC + c];
+ net.push_back( std::make_pair( over, k ) );
+ }
+ std::sort( net.begin(), net.end() );
+ classRank.assign( NC, 0 );
+ for( Int r = 0; r < NC; r++ )
+ classRank[net[r].second] = r;
+
+ // the exemplar's cliffs by its heights, the rule the new map's are found by (its cliff bits are also
+ // painted under flat sea and river beds), and for each cell the class of the nearest cliff painted
+ // as cliff and of the nearest ground that is no cliff, which blendChunk paints a cell with when the
+ // new heights made it the other one
+ spanCliff( lv.h, W, H, steep );
+ cliffTexture.assign( NC, 0 );
+ for( size_t c = 0; c < m.classes.size(); c++ )
+ {
+ AsciiString lower = m.classes[c].name;
+ lower.toLower();
+ cliffTexture[c] = strstr( lower.str(), "cliff" ) != NULL;
+ }
+ Mask rockFace( W * H ), notSteep( W * H );
+ std::vector<Int> faces( NC, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ rockFace[i] = steep[i] && cliffTexture[cls[i]];
+ notSteep[i] = !steep[i];
+ faces[cls[i]] += rockFace[i];
+ }
+ Int commonest = -1;
+ for( Int c = 0; c < NC; c++ )
+ if( faces[c] > 0 && ( commonest < 0 || faces[c] > faces[commonest] ) )
+ commonest = c;
+ nearestClass( rockFace, cls, W, H, TEXTURE_REACH, steepClass );
+ nearestClass( notSteep, cls, W, H, TEXTURE_REACH, openClass );
+ for( Int i = 0; i < W * H; i++ )
+ if( steepClass[i] < 0 )
+ steepClass[i] = commonest;
+
// the scenery that moves with the ground, by the cell it stands on
static const char *const theScenery[] = { "Tree", "Rocks", "RockCluster", "Tent", "Amb_", "AmbientWind", "WoodTower", "QuonsetHut" };
std::vector< std::pair<Int, Int> > keyed; // cell, thing
@@ -1765,6 +1896,39 @@ struct Exemplar
for( Int x = std::max( (Int)box[0] + b - TOWN_MARGIN, 0 ); x < std::min( (Int)box[2] + b + TOWN_MARGIN + 1, W ); x++ )
town[y * W + x] = 1;
}
+ // and a base not raised over the map goes only with its pad
+ if( lv.plateau - lv.bowl <= MIN_RELIEF )
+ for( size_t s = 0; s < lv.startY.size(); s++ )
+ for( Int y = std::max( lv.startY[s] - BASE_GROUND, 0 ); y <= std::min( lv.startY[s] + BASE_GROUND, H - 1 ); y++ )
+ for( Int x = std::max( lv.startX[s] - BASE_GROUND, 0 ); x <= std::min( lv.startX[s] + BASE_GROUND, W - 1 ); x++ )
+ if( ( y - lv.startY[s] ) * ( y - lv.startY[s] ) + ( x - lv.startX[s] ) * ( x - lv.startX[s] ) <= BASE_GROUND * BASE_GROUND )
+ town[y * W + x] = 1;
+
+ // what the quilt matches besides height. The water and its bank: a sea laid on the map takes the
+ // exemplar's sea bed, and the bank sand stays by water. The road strips: the classes far commoner
+ // along the roads than anywhere, which the quilt otherwise scattered as broken paths over open ground.
+ Mask shore, alongRoads;
+ maskGrow( wetAll, W, H, SHORE_GROUND, shore );
+ maskGrow( inv.roadLines, W, H, 1, alongRoads );
+ std::vector<Int64> along( m.classes.size() + 1, 0 ), over( m.classes.size() + 1, 0 );
+ Int64 alongAll = 0, overAll = 0;
+ hasWater = FALSE;
+ for( Int y = b; y < b + m.playY; y++ )
+ for( Int x = b; x < b + m.playX; x++ )
+ {
+ const Int i = y * W + x;
+ over[cls[i]]++;
+ overAll++;
+ along[cls[i]] += alongRoads[i];
+ alongAll += alongRoads[i];
+ hasWater = hasWater || wetAll[i];
+ }
+ ground.resize( W * H );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ const Bool strip = alongAll > 0 && along[cls[i]] * overAll > STRIP_LIFT * over[cls[i]] * alongAll;
+ ground[i] = ( m.cliff[i] ? GROUND_CLIFF : 0 ) | ( wetAll[i] ? GROUND_WET : 0 ) | ( shore[i] ? GROUND_SHORE : 0 ) | ( strip ? GROUND_STRIP : 0 );
+ }
Field blur;
boxMean( lv.t, W, H, DETAIL_RADIUS, blur );
@@ -2072,9 +2236,21 @@ struct Composer
Frame f;
Int seed;
Int W, H;
- Field keepBefore; ///< protection() before the features, which the towns keep off
+ /// protection()'s pad and site rings on the skeleton, which the towns keep off. Its slope term is
+ /// left out: the skeleton is plains, so that term marked the upper half of every gentle hill
+ /// within SLOPE_REACH of a start, a fifth of a small map, and left no ground for a town, while the
+ /// ramps it meant are the copied pads', laid over the skeleton before the towns.
+ Field padsBefore;
std::vector<Copy> pads; ///< the exemplar's base round every start
+ /// The crossing cut to one of CROSS_CROP's shares.
+ struct Crop
+ {
+ Int box[4]; ///< source cells y0, x0, y1, x1, the last two past the end
+ YX pivot; ///< the river's middle in the cut, where it meets the generated line
+ Real along, across; ///< the cut's reach from the pivot along the river and across it
+ };
+
/// The exemplar's towns that stand on its river, as one box with the river through it.
struct Crossing
{
@@ -2085,6 +2261,7 @@ struct Composer
Mask wet; ///< the exemplar's water, its size
std::vector<Int> towns;
std::vector<Int> bridges; ///< the first of each pair of bridge objects inside the box
+ Crop crops[CROSS_CROPS];
};
Crossing cross;
@@ -2140,61 +2317,132 @@ struct Composer
cross.angle = 0.5f * ATan2( (Real)( 2.0 * sxy ), (Real)( sxx - syy ) );
cross.centre = yx( (Real)my, (Real)mx );
for( size_t p = 0; p + 1 < src.m.things.size(); p++ )
- if( ( src.m.things[p].flags & FLAG_BRIDGE_POINT1 ) && ( src.m.things[p + 1].flags & FLAG_BRIDGE_POINT2 ) && bridgeIn( box, (Int)p ) )
+ if( ( src.m.things[p].flags & FLAG_BRIDGE_POINT1 ) && ( src.m.things[p + 1].flags & FLAG_BRIDGE_POINT2 ) && bridgeIn( box, (Int)p, 0 ) )
cross.bridges.push_back( (Int)p );
cross.found = TRUE;
+
+ // the river towns' houses and the water, summed over the box, for the cuts
+ const Int BW = box[3] - box[1], BH = box[2] - box[0];
+ Mask houseCells( BW * BH, 0 );
+ for( size_t k = 0; k < cross.towns.size(); k++ )
+ {
+ const std::vector<YX>& houses = src.inv.towns[cross.towns[k]].houses;
+ for( size_t j = 0; j < houses.size(); j++ )
+ {
+ Int y = (Int)houses[j].y - box[0], x = (Int)houses[j].x - box[1];
+ if( y >= 0 && y < BH && x >= 0 && x < BW ) houseCells[y * BW + x]++;
+ }
+ }
+ std::vector<Int> houseSum( ( BW + 1 ) * ( BH + 1 ), 0 ), wetSum( ( BW + 1 ) * ( BH + 1 ), 0 );
+ for( Int y = 0; y < BH; y++ )
+ for( Int x = 0; x < BW; x++ )
+ {
+ Int i = ( y + 1 ) * ( BW + 1 ) + x + 1, up = y * ( BW + 1 ) + x + 1, left = ( y + 1 ) * ( BW + 1 ) + x, both = y * ( BW + 1 ) + x;
+ houseSum[i] = houseCells[y * BW + x] + houseSum[up] + houseSum[left] - houseSum[both];
+ wetSum[i] = cross.wet[( y + box[0] ) * SW + x + box[1]] + wetSum[up] + wetSum[left] - wetSum[both];
+ }
+ for( Int at = 0; at < CROSS_CROPS; at++ )
+ cropCrossing( at, houseSum, wetSum );
}
- /// Whether both ends of the bridge pair starting at thing p stand inside the source box.
- Bool bridgeIn( const Int box[4], Int p ) const
+ /// Whether both ends of the bridge pair starting at thing p stand inside the source box, margin
+ /// cells or more in from its edge.
+ Bool bridgeIn( const Int box[4], Int p, Int margin ) const
{
Bool inside = TRUE;
for( Int g = 0; g < 2; g++ )
{
Real y = src.m.things[p + g].y + src.m.border, x = src.m.things[p + g].x + src.m.border;
- inside = inside && box[0] <= y && y < box[2] && box[1] <= x && x < box[3];
+ inside = inside && box[0] + margin <= y && y < box[2] - margin && box[1] + margin <= x && x < box[3] - margin;
}
return inside;
}
- /// The crossing's box cut to share of its size round the river's middle and grown over the bridge
- /// nearest that middle, so a small cut still carries one, and its reach from that middle along the
- /// river and across it.
- void cropCrossing( Real share, Int out[4], Real *along, Real *across ) const
+ /** The crossing's box cut to CROSS_CROP[at] of its size: of the windows of that size with the
+ river in them, the one holding the most of the crossing's bridges whole and clear of the fade a
+ copy's edge blends over, then the most of the river towns' houses, ties to the lowest row and
+ column. A bridge end on that fade would stand on the carved bed, under the water; such a bridge
+ stays the crossing's and layCrossing raises its ends to the bank. The pivot is the middle
+ of the water in the cut, so the cut's river lies on the generated line wherever the cut sits. */
+ void cropCrossing( Int at, const std::vector<Int>& houseSum, const std::vector<Int>& wetSum )
{
+ const Int BW = cross.box[3] - cross.box[1], margin = (Int)COPY_FADE;
+ Crop& crop = cross.crops[at];
+ Int size[2];
for( Int a = 0; a < 2; a++ )
{
Int lo = cross.box[a], hi = cross.box[a + 2];
- Int size = std::min( hi - lo, std::max( roundi( ( hi - lo ) * share ), CROSS_LEAST ) );
- Real middle = a == 0 ? cross.centre.y : cross.centre.x;
- Int from = clampi( roundi( middle - 0.5f * size ), lo, hi - size );
- out[a] = from;
- out[a + 2] = from + size;
+ size[a] = std::min( hi - lo, std::max( roundi( ( hi - lo ) * CROSS_CROP[at] ), CROSS_LEAST ) );
+ }
+ auto sum = [&]( const std::vector<Int>& s, const Int b[4] ) -> Int
+ {
+ Int y0 = b[0] - cross.box[0], x0 = b[1] - cross.box[1], y1 = b[2] - cross.box[0], x1 = b[3] - cross.box[1];
+ return s[y1 * ( BW + 1 ) + x1] - s[y0 * ( BW + 1 ) + x1] - s[y1 * ( BW + 1 ) + x0] + s[y0 * ( BW + 1 ) + x0];
+ };
+ // a bridge the window holds counts above every house: the bridges handed back to the river often
+ // find no crossing of their own clear of the sites
+ Int most = -1;
+ for( Int y = cross.box[0]; y + size[0] <= cross.box[2]; y++ )
+ {
+ for( Int x = cross.box[1]; x + size[1] <= cross.box[3]; x++ )
+ {
+ const Int window[4] = { y, x, y + size[0], x + size[1] };
+ if( sum( wetSum, window ) < CROSS_WET )
+ continue;
+ Int bridged = 0;
+ for( size_t k = 0; k < cross.bridges.size(); k++ )
+ bridged += bridgeIn( window, cross.bridges[k], margin );
+ Int worth = sum( houseSum, window ) + bridged * 0x10000;
+ if( worth <= most )
+ continue;
+ most = worth;
+ memcpy( crop.box, window, sizeof(window) );
+ }
+ }
+ if( most < 0 )
+ {
+ // no window that small holds CROSS_WET of the river: the box's middle
+ for( Int a = 0; a < 2; a++ )
+ {
+ Real middle = a == 0 ? cross.centre.y : cross.centre.x;
+ Int from = clampi( roundi( middle - 0.5f * size[a] ), cross.box[a], cross.box[a + 2] - size[a] );
+ crop.box[a] = from;
+ crop.box[a + 2] = from + size[a];
+ }
}
+ /* A cut too small to hold any bridge is grown over the one nearest its middle. Handed back to
+ the river, the bridges of a small map found no crossing clear of the sites and the river was
+ left with one, or none; the grown bridge's ends lie on the fade and layCrossing raises them. */
Int nearest = -1;
Real least = 1.0e9f;
+ const Real midY = 0.5f * ( crop.box[0] + crop.box[2] ), midX = 0.5f * ( crop.box[1] + crop.box[3] );
for( size_t k = 0; k < cross.bridges.size(); k++ )
{
- if( bridgeIn( out, cross.bridges[k] ) ) { nearest = -1; break; }
+ if( bridgeIn( crop.box, cross.bridges[k], 0 ) ) { nearest = -1; break; }
const MapThing& one = src.m.things[cross.bridges[k]];
const MapThing& two = src.m.things[cross.bridges[k] + 1];
- Real d = hypotr( 0.5f * ( one.y + two.y ) + src.m.border - cross.centre.y, 0.5f * ( one.x + two.x ) + src.m.border - cross.centre.x );
+ Real d = hypotr( 0.5f * ( one.y + two.y ) + src.m.border - midY, 0.5f * ( one.x + two.x ) + src.m.border - midX );
if( d < least ) { least = d; nearest = cross.bridges[k]; }
}
for( Int g = 0; nearest >= 0 && g < 2; g++ )
{
const MapThing& end = src.m.things[nearest + g];
- out[0] = std::min( out[0], (Int)( end.y + src.m.border ) );
- out[1] = std::min( out[1], (Int)( end.x + src.m.border ) );
- out[2] = std::max( out[2], (Int)( end.y + src.m.border ) + 1 );
- out[3] = std::max( out[3], (Int)( end.x + src.m.border ) + 1 );
- }
- *along = *across = 0.0f;
+ crop.box[0] = std::min( crop.box[0], (Int)( end.y + src.m.border ) );
+ crop.box[1] = std::min( crop.box[1], (Int)( end.x + src.m.border ) );
+ crop.box[2] = std::max( crop.box[2], (Int)( end.y + src.m.border ) + 1 );
+ crop.box[3] = std::max( crop.box[3], (Int)( end.x + src.m.border ) + 1 );
+ }
+ Int wetCells = 0, wetY = 0, wetX = 0;
+ for( Int y = crop.box[0]; y < crop.box[2]; y++ )
+ for( Int x = crop.box[1]; x < crop.box[3]; x++ )
+ if( cross.wet[y * src.m.W + x] ) { wetCells++; wetY += y; wetX += x; }
+ crop.pivot = wetCells ? yx( (Real)wetY / wetCells, (Real)wetX / wetCells ) : cross.centre;
+ crop.along = crop.across = 0.0f;
for( Int c = 0; c < 4; c++ )
{
- Real cy = (Real)out[c < 2 ? 0 : 2] - cross.centre.y, cx = (Real)out[c % 2 ? 3 : 1] - cross.centre.x;
- *along = std::max( *along, fabsf( cx * Cos( cross.angle ) + cy * Sin( cross.angle ) ) );
- *across = std::max( *across, fabsf( cy * Cos( cross.angle ) - cx * Sin( cross.angle ) ) );
+ Real cy = (Real)crop.box[c < 2 ? 0 : 2] - crop.pivot.y, cx = (Real)crop.box[c % 2 ? 3 : 1] - crop.pivot.x;
+ crop.along = std::max( crop.along, fabsf( cx * Cos( cross.angle ) + cy * Sin( cross.angle ) ) );
+ crop.across = std::max( crop.across, fabsf( cy * Cos( cross.angle ) - cx * Sin( cross.angle ) ) );
}
}
@@ -2230,13 +2478,15 @@ struct Composer
/** The exemplar's plateau bases are one stretch of high ground with the basin below it; copied
round the skeleton's starts they stand apart, and a way between two of them narrower than
PAD_CORRIDOR is where Twilight Flame's armies queued. Such a way is raised to the lower
- plateau's height, so the bases join as they do on the exemplar; a wider one stays a valley. */
+ plateau's height, so the bases join as they do on the exemplar; a wider one stays a valley.
+ The raised way falls back to the ground past it over JOIN_FADE, where a hard edge left a wall
+ of 160 bytes in one cell; the distances are a 3-4 chamfer, round rather than diamond-cornered. */
void joinPlateaus( Field& h ) const
{
- const Int SW = src.m.W, SH = src.m.H;
+ const Int SW = src.m.W, SH = src.m.H, FAR = 0x3fffffff;
+ const Int inside = 3 * PAD_CORRIDOR, reachSum = 3 * ( PAD_CORRIDOR + JOIN_FADE );
std::vector< std::vector<Int> > steps( pads.size() );
std::vector<Real> tops( pads.size(), 0.0f );
- std::vector<Int> queue;
for( size_t p = 0; p < pads.size(); p++ )
{
if( !pads[p].raised ) continue;
@@ -2245,8 +2495,7 @@ struct Composer
const Real half = 0.5f * ( top + c.pivot );
tops[p] = c.pivot + c.lift + ( top - c.pivot ) * c.heightScale;
std::vector<Int>& d = steps[p];
- d.assign( W * H, -1 );
- queue.clear();
+ d.assign( W * H, FAR );
Int area[4];
c.bounds( W, H, area );
for( Int y = area[0]; y <= area[2]; y++ )
@@ -2256,29 +2505,63 @@ struct Composer
YX s = c.toSource( (Real)y, (Real)x );
if( src.lv.h[clampi( roundi( s.y ), 0, SH - 1 ) * SW + clampi( roundi( s.x ), 0, SW - 1 )] < half ) continue;
d[y * W + x] = 0;
- queue.push_back( y * W + x );
}
- for( size_t head = 0; head < queue.size(); head++ )
- {
- Int i = queue[head], x = i % W, y = i / W;
- if( d[i] >= PAD_CORRIDOR ) continue;
- const Int n[4] = { x + 1 < W ? i + 1 : -1, x > 0 ? i - 1 : -1, y + 1 < H ? i + W : -1, y > 0 ? i - W : -1 };
- for( Int j = 0; j < 4; j++ )
+ // three a straight step, four a diagonal one: a forward and a backward raster pass
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ Int i = y * W + x, v = d[i];
+ if( x > 0 ) v = std::min( v, d[i - 1] + 3 );
+ if( y > 0 )
+ {
+ v = std::min( v, d[i - W] + 3 );
+ if( x > 0 ) v = std::min( v, d[i - W - 1] + 4 );
+ if( x + 1 < W ) v = std::min( v, d[i - W + 1] + 4 );
+ }
+ d[i] = v;
+ }
+ for( Int y = H - 1; y >= 0; y-- )
+ for( Int x = W - 1; x >= 0; x-- )
{
- if( n[j] < 0 || d[n[j]] >= 0 ) continue;
- d[n[j]] = d[i] + 1;
- queue.push_back( n[j] );
+ Int i = y * W + x, v = d[i];
+ if( x + 1 < W ) v = std::min( v, d[i + 1] + 3 );
+ if( y + 1 < H )
+ {
+ v = std::min( v, d[i + W] + 3 );
+ if( x + 1 < W ) v = std::min( v, d[i + W + 1] + 4 );
+ if( x > 0 ) v = std::min( v, d[i + W - 1] + 4 );
+ }
+ d[i] = v;
}
- }
}
+ // each pair's least summed distance, its real gap (rmgJoinShare)
+ const size_t n = pads.size();
+ std::vector<Int> pairLeast( n * n, FAR );
for( Int i = 0; i < W * H; i++ )
+ for( size_t p = 0; p < n; p++ )
+ {
+ if( steps[p].empty() || steps[p][i] >= inside ) continue;
+ for( size_t q = p + 1; q < n; q++ )
+ if( !steps[q].empty() )
+ pairLeast[p * n + q] = std::min( pairLeast[p * n + q], steps[p][i] + steps[q][i] );
+ }
+ // each cell rises by the most any pair lifts it, so the order of the pairs does not matter
+ for( Int i = 0; i < W * H; i++ )
+ {
+ Real rise = 0.0f;
for( size_t p = 0; p < pads.size(); p++ )
{
- if( steps[p].empty() || steps[p][i] < 0 ) continue;
+ if( steps[p].empty() || steps[p][i] >= reachSum ) continue;
for( size_t q = p + 1; q < pads.size(); q++ )
- if( !steps[q].empty() && steps[q][i] >= 0 && steps[p][i] + steps[q][i] < PAD_CORRIDOR )
- h[i] = std::max( h[i], std::min( tops[p], tops[q] ) );
+ {
+ if( steps[q].empty() ) continue;
+ const Real gap = std::min( tops[p], tops[q] ) - h[i];
+ if( gap <= 0.0f ) continue;
+ rise = std::max( rise, rmgJoinShare( pairLeast[p * n + q], steps[p][i] + steps[q][i] ) * gap );
+ }
}
+ h[i] += rise;
+ }
}
// The skeleton's own lakes filled to their rims: the exemplar's water takes their place.
@@ -2501,6 +2784,15 @@ struct Composer
h[y * W + x] = value;
}
+ // disc, raising only: ground already over the value keeps its height
+ void discAtLeast( Field& h, YX p, Real r, Real value ) const
+ {
+ for( Int y = std::max( 0, (Int)( p.y - r ) - 1 ); y <= std::min( H - 1, (Int)( p.y + r ) + 1 ); y++ )
+ for( Int x = std::max( 0, (Int)( p.x - r ) - 1 ); x <= std::min( W - 1, (Int)( p.x + r ) + 1 ); x++ )
+ if( hypotr( y - p.y, x - p.x ) <= r )
+ h[y * W + x] = std::max( h[y * W + x], value );
+ }
+
void discMask( Mask& m, YX p, Real r ) const
{
for( Int y = std::max( 0, (Int)( p.y - r ) - 1 ); y <= std::min( H - 1, (Int)( p.y + r ) + 1 ); y++ )
@@ -2632,8 +2924,15 @@ struct Composer
const Int bd = skm.border;
const Real y0 = (Real)bd, x0 = (Real)bd, y1 = (Real)( bd + skm.playY - 1 ), x1 = (Real)( bd + skm.playX - 1 );
const Real margin = SHORE_CELLS + VALLEY_CELLS;
+ /* The coast bends round the sites instead of stopping short of the nearest: every start's and
+ site's guard and a beach past it stay land whatever the width, so one pad near the edge
+ no longer takes the whole sea away. The width is then the share's worth of the cells left. */
+ Field fixedLand, fromStarts;
+ seaLand( f.padRadius + 10.0f + SHORE_CELLS, SITE_OUTER + 10.0f + SHORE_CELLS, fixedLand, fromStarts );
+ Int playCount = 0;
+ for( Int i = 0; i < W * H; i++ ) playCount += f.play[i];
Real bestWidth = 0.0f, bestTie = 0.0f;
- Int bestTurn = -1;
+ Int bestTurn = -1, bestSea = 0;
Field bestD, d( W * H );
std::vector<Int> bestFull, bestWet;
Bool bestCorner = FALSE;
@@ -2666,8 +2965,6 @@ struct Composer
else corner = FALSE;
}
Real phase = hashUnit( seed, 95, turn ) * 6.283f;
- Real cap = 1.0e9f, top = -1.0e9f;
- Bool guarded = FALSE;
order.clear();
for( Int y = 0; y < H; y++ )
{
@@ -2687,23 +2984,25 @@ struct Composer
v = edge[wetEdges[0]];
v += COAST_WOBBLE * Sin( 2.0f * PI_R * ( y + x ) / 97.0f + phase );
d[i] = v;
- top = std::max( top, v );
- if( f.guarded( i ) ) { cap = std::min( cap, v ); guarded = TRUE; }
- if( f.play[i] ) order.push_back( v );
+ // a cell is sea once the width passes its v, unless it is held land
+ if( f.play[i] && fixedLand[i] < 0.0f ) order.push_back( v );
}
}
- cap = guarded ? cap - margin : top;
- size_t at = std::min( (size_t)( sea.share * order.size() ), order.size() - 1 );
+ if( order.empty() )
+ continue;
+ size_t at = std::min( (size_t)( sea.share * playCount ), order.size() - 1 );
std::nth_element( order.begin(), order.begin() + at, order.end() );
- Real width = std::min( order[at], cap );
+ Real width = order[at];
+ Int seaCells = (Int)at;
+ // the most sea, then the coast that bends least round the land it holds: the narrowest
Real tie = hashUnit( seed, 96, turn );
- if( bestTurn < 0 || width > bestWidth || ( width == bestWidth && tie < bestTie ) )
+ if( bestTurn < 0 || seaCells > bestSea || ( seaCells == bestSea && ( width < bestWidth || ( width == bestWidth && tie < bestTie ) ) ) )
{
- bestTurn = turn; bestWidth = width; bestTie = tie;
+ bestTurn = turn; bestWidth = width; bestTie = tie; bestSea = seaCells;
bestD = d; bestFull = full; bestWet = wetEdges; bestCorner = corner; bestCornerAt = cornerAt;
}
}
- if( bestWidth <= 0.0f )
+ if( bestTurn < 0 || bestWidth <= 0.0f )
{
plan.note( "sea of %d cells (no coast clear of the sites)", sea.area );
return;
@@ -2734,45 +3033,84 @@ struct Composer
}
else
boxes.push_back( std::vector<YX>( strips[bestWet[0]], strips[bestWet[0]] + 4 ) );
- for( Int i = 0; i < W * H; i++ ) bestD[i] -= bestWidth;
+ for( Int i = 0; i < W * H; i++ ) bestD[i] = std::max( bestD[i] - bestWidth, fixedLand[i] );
laySea( h, plan, sea, bestD, boxes );
}
- // An island map's sea: land round every start, dock and derrick and the middle (synthmap.carve_islands).
- void carveIslands( Field& h, Plan& plan, Int index ) const
+ /** Ground a sea leaves dry whatever its size, as inland cells (over 0 is land): startLand round each
+ start, siteLand round each dock and derrick and the middle, and unless the exemplar's water parts
+ the starts, a causeway from each start to the middle and from each dock and derrick to the
+ nearer of the middle and its nearest start, so nothing stands on an island of its own. fromStarts
+ is each cell's distance to the nearest start. */
+ void seaLand( Real startLand, Real siteLand, Field& fixedLand, Field& fromStarts ) const
{
- const InvWater& sea = src.inv.water[index];
- Field fixedLand( W * H ), fromStarts( W * H );
- std::vector<YX> sitesAndMiddle( f.sites.begin() + f.starts.size(), f.sites.end() );
- sitesAndMiddle.push_back( yx( f.cy, f.cx ) );
- std::vector<YX> coreSites;
- for( size_t k = 0; k < sitesAndMiddle.size(); k++ )
- coreSites.push_back( yx( (Real)(Int)sitesAndMiddle[k].y, (Real)(Int)sitesAndMiddle[k].x ) );
- // a dock's ground and a beach, and every pad on land: a pad stops short of the exemplar's water
- const Real siteLand = SITE_OUTER + 10.0f + SHORE_CELLS;
- Real phase = hashUnit( seed, 95, 0 ) * 6.283f;
+ fixedLand.assign( W * H, 0.0f );
+ fromStarts.assign( W * H, 0.0f );
+ const YX middle = yx( f.cy, f.cx );
+ std::vector<YX> coreSites, anchors;
+ for( size_t k = f.starts.size(); k < f.sites.size(); k++ )
+ {
+ YX p = yx( (Real)(Int)f.sites[k].y, (Real)(Int)f.sites[k].x );
+ YX to = middle;
+ Real best = hypotr( p.y - middle.y, p.x - middle.x );
+ for( size_t s = 0; s < f.starts.size(); s++ )
+ {
+ Real d = hypotr( p.y - f.starts[s].y, p.x - f.starts[s].x );
+ if( d < best ) { best = d; to = f.starts[s]; }
+ }
+ coreSites.push_back( p );
+ anchors.push_back( to );
+ }
+ const YX core = yx( (Real)(Int)f.cy, (Real)(Int)f.cx );
+ const Bool causeways = !src.inv.split;
for( Int y = 0; y < H; y++ )
{
for( Int x = 0; x < W; x++ )
{
Int i = y * W + x;
- Real ds = 1.0e9f, dsite = 1.0e9f, droad = 1.0e9f;
+ Real ds = 1.0e9f, droad = 1.0e9f;
for( size_t s = 0; s < f.starts.size(); s++ )
{
ds = std::min( ds, hypotr( y - f.starts[s].y, x - f.starts[s].x ) );
- if( !src.inv.split )
- droad = std::min( droad, segmentDistance( (Real)y, (Real)x, f.starts[s], yx( f.cy, f.cx ) ) );
+ if( causeways )
+ droad = std::min( droad, segmentDistance( (Real)y, (Real)x, f.starts[s], middle ) );
}
+ Real dsite = hypotr( y - core.y, x - core.x );
for( size_t s = 0; s < coreSites.size(); s++ )
+ {
dsite = std::min( dsite, hypotr( y - coreSites[s].y, x - coreSites[s].x ) );
- Real wobble = COAST_WOBBLE * Sin( 2.0f * PI_R * ( y + x ) / 97.0f + phase ) * Sin( 2.0f * PI_R * ( y - x ) / 131.0f );
+ if( causeways )
+ droad = std::min( droad, segmentDistance( (Real)y, (Real)x, coreSites[s], anchors[s] ) );
+ }
fromStarts[i] = ds;
- fixedLand[i] = std::max( siteLand - dsite, CAUSEWAY_CELLS - droad ) + wobble;
+ fixedLand[i] = std::max( std::max( siteLand - dsite, CAUSEWAY_CELLS - droad ), startLand - ds );
+ }
+ }
+ }
+
+ // An island map's sea: land round every start, dock and derrick and the middle (synthmap.carve_islands).
+ void carveIslands( Field& h, Plan& plan, Int index ) const
+ {
+ const InvWater& sea = src.inv.water[index];
+ /* A dock's or derrick's guard on land, its beach inside the guard's fade, and the starts' land the
+ radius's: the floors are cells, not shares, so on a small map with every seat filled a
+ beach-wide margin more round every site was a third of the sea. */
+ Field fixedLand, fromStarts;
+ seaLand( 0.0f, SITE_OUTER + 10.0f, fixedLand, fromStarts );
+ Real phase = hashUnit( seed, 95, 0 ) * 6.283f;
+ for( Int y = 0; y < H; y++ )
+ {
+ for( Int x = 0; x < W; x++ )
+ {
+ Int i = y * W + x;
+ Real wobble = COAST_WOBBLE * Sin( 2.0f * PI_R * ( y + x ) / 97.0f + phase ) * Sin( 2.0f * PI_R * ( y - x ) / 131.0f );
+ fixedLand[i] += wobble;
fromStarts[i] -= wobble; // land = max(radius - ds, fixed - wobble) + wobble
}
}
- // land(radius) = max(radius - fromStarts + wobble, fixedLand), as fromStarts already holds -wobble
- Real least = std::max( PAD_OUTER, f.padRadius ) + SHORE_CELLS;
+ // land(radius) = max(radius - fromStarts + wobble, fixedLand), as fromStarts already holds -wobble;
+ // the least a beach past the pad, whatever the pad was scaled to
+ Real least = f.padRadius + SHORE_CELLS;
Real radius = least;
Int playCount = 0;
for( Int i = 0; i < W * H; i++ ) playCount += f.play[i];
@@ -2800,7 +3138,10 @@ struct Composer
// The sea where inland is under 0: its bed, a beach, higher ground cut back (synthmap.lay_sea).
void laySea( Field& h, Plan& plan, const InvWater& sea, const Field& inlandField, const std::vector< std::vector<YX> >& boxes ) const
{
- Real surface = std::max( skel.bowl + sea.surface - src.lv.bowl, SEA_FLOOR );
+ /* The exemplar's bowl is the median of every playable height, and on an island map half of those
+ are sea bed: the bowl comes out under the land and the sea a byte or two under the skeleton's
+ ground, a coast flat at the waterline. The exemplar's own bank over its water bounds it. */
+ Real surface = std::max( std::min( skel.bowl + sea.surface - src.lv.bowl, skel.bowl - std::max( sea.bank, 4.0f ) ), SEA_FLOOR );
Real bed = std::max( surface - std::max( sea.depth, 6.0f ), 0.0f );
Mask footprint( W * H, 0 );
for( size_t k = 0; k < boxes.size(); k++ )
@@ -2883,6 +3224,7 @@ struct Composer
Real calmAt, calmReach; ///< no wander within calmReach of calmAt, where the crossing lies; 0 for none
Real calmWidth; ///< the crossing's reach across the river
Int crop[4]; ///< the crossing's box as it fitted
+ Int cropAt; ///< which of the crossing's cuts that is, CROSS_CROPS for none
};
/// The crossing laid along the line with its middle at s, turned so its river runs the line's way,
@@ -2895,7 +3237,7 @@ struct Composer
best.spinBy( 0.0f );
best.spinBy( line.angle - best.angle( cross.angle ) );
best.target = Frame::point( line.angle, line.my, line.mx, s, 0.0f );
- best.source = cross.centre;
+ best.source = cross.crops[line.cropAt].pivot;
best.scale = 1.0f;
best.radius = best.core = 0.0f;
best.lift = best.pivot = 0.0f;
@@ -2908,14 +3250,14 @@ struct Composer
}
/// The first place along the line, out from its middle, where the crossing lies clear of every
- /// pad, dock and derrick and inside the map; the whole of it, or cut down to its middle.
+ /// pad, dock and derrick and inside the map; the whole of it, or the first of its cuts that fits.
Bool calmSpot( LineSpec& line ) const
{
- static const Real theCrops[] = { 1.0f, 0.75f, 0.55f, 0.4f, 0.3f, 0.2f };
- for( Int crop = 0; crop < (Int)( sizeof(theCrops) / sizeof(theCrops[0]) ); crop++ )
+ for( Int crop = 0; crop < CROSS_CROPS; crop++ )
{
- Real along, across;
- cropCrossing( theCrops[crop], line.crop, &along, &across );
+ const Crop& cut = cross.crops[crop];
+ memcpy( line.crop, cut.box, sizeof(line.crop) );
+ line.cropAt = crop;
for( Int step = 0; step * CROSS_STEP < f.half; step++ )
{
for( Int sign = -1; sign <= 1; sign += 2 )
@@ -2932,12 +3274,13 @@ struct Composer
clear = f.play[y * W + x] && f.guard[y * W + x] < CROSS_GUARD;
if( !clear ) continue;
line.calmAt = s;
- line.calmReach = along + CALM_EASE;
- line.calmWidth = across;
+ line.calmReach = cut.along + CALM_EASE;
+ line.calmWidth = cut.across;
return TRUE;
}
}
}
+ line.cropAt = CROSS_CROPS;
return FALSE;
}
@@ -2949,7 +3292,7 @@ struct Composer
return;
size_t inside = 0;
for( size_t k = 0; k < cross.bridges.size(); k++ )
- inside += bridgeIn( line.crop, cross.bridges[k] );
+ inside += bridgeIn( line.crop, cross.bridges[k], 0 );
out.resize( out.size() - std::min( out.size(), inside ) );
}
@@ -2974,20 +3317,39 @@ struct Composer
plan.level[i] = cross.wet[o] ? surface : -1.0f;
}
}
+ /* Every bridge inside the cut stays the crossing's: handed back to the river it found no
+ crossing clear of the sites and was lost. One whose end falls on the fade ring would stand
+ on the carved bed there, so its ends are raised to the bank, as the river does its own. */
const Int sb = src.m.border;
+ const Real bank = surface + std::max( river.bank, 4.0f );
for( size_t k = 0; k < cross.bridges.size(); k++ )
{
- if( !bridgeIn( line.crop, cross.bridges[k] ) ) continue;
+ if( !bridgeIn( line.crop, cross.bridges[k], 0 ) ) continue;
const MapThing& one = src.m.things[cross.bridges[k]];
const MapThing& two = src.m.things[cross.bridges[k] + 1];
PlannedBridge bridge;
bridge.name = one.name;
bridge.a = c.toTarget( one.y + sb, one.x + sb );
bridge.z = c.toTarget( two.y + sb, two.x + sb );
+ if( !bridgeIn( line.crop, cross.bridges[k], (Int)COPY_FADE ) )
+ {
+ discAtLeast( h, bridge.a, BRIDGE_END, bank );
+ discAtLeast( h, bridge.z, BRIDGE_END, bank );
+ }
plan.bridges.push_back( bridge );
}
+ // a river town is done whatever the cut carried: stamped again it would stand twice where the cut
+ // kept part of it, and bring its river banks onto dry ground; what the cut left is said
for( size_t k = 0; k < cross.towns.size(); k++ )
+ {
+ const InvTown& town = src.inv.towns[cross.towns[k]];
+ Int carried = 0;
+ for( size_t j = 0; j < town.houses.size(); j++ )
+ carried += c.carries( town.houses[j].y, town.houses[j].x );
+ if( carried < town.buildings )
+ plan.note( "town of %d buildings on the river (%d on the crossing)", town.buildings, carried );
plan.townDone[cross.towns[k]] = 1;
+ }
}
void riverBridges( Int index, std::vector<const InvBridge *>& out ) const
@@ -3012,6 +3374,7 @@ struct Composer
line.salt = salt;
line.calmAt = line.calmReach = line.calmWidth = 0.0f;
memset( line.crop, 0, sizeof(line.crop) );
+ line.cropAt = CROSS_CROPS;
if( crossing )
calmSpot( line );
return line;
@@ -3022,9 +3385,11 @@ struct Composer
return std::max( skel.bowl + river.surface - src.lv.bowl, river.depth + 2.0f );
}
- // A river along line (synthmap.carve_river); meetsOut says whether its water ran onto water already there.
+ /* A river along line (synthmap.carve_river); meetsOut says whether its water ran onto water already
+ there, dammedOut how many cells of its bed a pad, dock or derrick held dry. */
void carveRiver( const Field& h, Plan& plan, const InvWater& river, Int index, const LineSpec& line,
- const std::vector<const InvBridge *>& bridges, Bool hasSurface, Real givenSurface, Field& out, Bool *meetsOut ) const
+ const std::vector<const InvBridge *>& bridges, Bool hasSurface, Real givenSurface, Field& out, Bool *meetsOut,
+ Int *dammedOut = NULL ) const
{
Real surface = hasSurface ? givenSurface : riverSurface( river );
Real bed = surface - river.depth;
@@ -3144,6 +3509,7 @@ struct Composer
Real reachC = half + SHORE_CELLS + VALLEY_CELLS + ( 255.0f - bank ) / RIVER_SLOPE + amp + 2.0f;
out = h;
Bool meets = FALSE;
+ Int dammed = 0;
Real sFrom = anchored ? line.sLo - VALLEY_CELLS : line.sLo;
for( Int y = 0; y < H; y++ )
{
@@ -3161,6 +3527,7 @@ struct Composer
narrow = std::min( narrow, 1.0f - ( 1.0f - to ) * fade( ( 24.0f - fabsf( s - sites[k] ) ) / 12.0f ) );
}
Real inner = half * narrow;
+ Real edge = inner + 0.5f * SHORE_CELLS + 2.0f; // the polygon's reach
Real d = fabsf( c - wander( s ) );
Real outside = d - inner - SHORE_CELLS - VALLEY_CELLS;
Real target = d < inner ? bed :
@@ -3170,19 +3537,42 @@ struct Composer
// a branch fades out behind its junction, in the main river's bed rather than across the map
Real ends = std::min( anchored ? VALLEY_CELLS + ( s - line.sLo ) : s - line.sLo, line.sHi - s );
Real w = fade( ends / VALLEY_CELLS ) * ( 1.0f - f.guard[i] );
+ Bool within = s >= line.sLo && s <= line.sHi;
+ // and behind it is the main river's far bank, dry ground no lower than the plane, not a trench
+ if( !within )
+ target = std::max( target, surface + 1.0f );
Real cut = h[i] - w * std::max( h[i] - target, 0.0f );
out[i] = std::min( h[i], cut );
- Bool within = s >= line.sLo && s <= line.sHi;
+ /* Past the waterline the ground keeps over the plane, falling away at a bank's slope: a canyon
+ or low ground beside the river would sit under it outside the polygon, the water hanging
+ over dry ground. As much as the cut, so it fades where the cut does, at the river's ends
+ and into a pad's guard, rather than stop in a step. */
+ if( d >= edge && !plan.wet[i] )
+ {
+ Real levee = surface + 1.0f - RIVER_SLOPE * ( d - edge );
+ if( levee > out[i] )
+ out[i] += w * ( levee - out[i] );
+ }
+ /* The plane lies over the whole band, but the water only where the cut went under it: where a
+ pad, dock or derrick held its ground the bed is dry, and wet there would freeze a trench
+ and tell the towns and bridges there is water where there is none. The level stays, so
+ the ground under the plane is still lifted clear of it rather than left a pond. */
if( within && d < inner + 0.5f * SHORE_CELLS )
{
- meets = meets || plan.wet[i];
- plan.wet[i] = 1;
+ if( out[i] < surface )
+ {
+ meets = meets || plan.wet[i];
+ plan.wet[i] = 1;
+ }
+ else if( d < inner && f.guard[i] > 0.5f )
+ dammed++;
plan.level[i] = std::max( plan.level[i], surface );
}
if( d >= inner && out[i] < h[i] - 0.5f ) plan.gentle[i] = 1;
}
}
if( meetsOut ) *meetsOut = meets;
+ if( dammedOut ) *dammedOut = dammed;
// the water area: the waterline either side of the bed, every eight cells along
WaterPoly poly;
@@ -3214,8 +3604,8 @@ struct Composer
{
YX a, z;
bridgeEnds( sites[k], 0.5f * ours[k]->length, &a, &z );
- disc( out, a, 4.0f, bank );
- disc( out, z, 4.0f, bank );
+ disc( out, a, BRIDGE_END, bank );
+ disc( out, z, BRIDGE_END, bank );
discMask( plan.gentle, a, 10.0f );
discMask( plan.gentle, z, 10.0f );
PlannedBridge bridge;
@@ -3229,26 +3619,26 @@ struct Composer
struct RiverScore
{
Bool meets, splits;
- Bool blocked; ///< the line runs through a pad
+ Int blocked; ///< 2 the line runs through a pad, 1 a dock, derrick or pad's edge holds part of its bed dry
Bool shape; ///< it reaches the edge where the exemplar's does not, or the other way
Bool near;
- Bool lost; ///< the crossing found no room on it
+ Int cropAt; ///< the cut of the crossing that found room on it, CROSS_CROPS for none: the less cut, the more town
Real off, clear;
bool operator<( const RiverScore& o ) const
{
// the river whole and between the starts first; the town on it where that leaves room
if( meets != o.meets ) return !meets;
if( splits != o.splits ) return !splits;
- if( blocked != o.blocked ) return !blocked;
+ if( blocked != o.blocked ) return blocked < o.blocked;
if( shape != o.shape ) return !shape;
if( near != o.near ) return !near;
- if( lost != o.lost ) return !lost;
+ if( cropAt != o.cropAt ) return cropAt < o.cropAt;
if( off != o.off ) return off < o.off;
return -clear < -o.clear;
}
Bool sameHead( const RiverScore& o ) const
{
- return meets == o.meets && splits == o.splits && blocked == o.blocked && shape == o.shape && near == o.near && lost == o.lost;
+ return meets == o.meets && splits == o.splits && blocked == o.blocked && shape == o.shape && near == o.near && cropAt == o.cropAt;
}
};
@@ -3281,24 +3671,26 @@ struct Composer
Plan trial = plan;
LineSpec line = riverLine( river, salt, sign * share * f.half, edge, crossing );
Bool meets = FALSE;
+ Int dammed = 0;
bridgesOutside( line, allBridges, outside );
- carveRiver( h, trial, river, index, line, outside, FALSE, 0.0f, out, &meets );
+ carveRiver( h, trial, river, index, line, outside, FALSE, 0.0f, out, &meets, &dammed );
Real clear;
Bool split;
judge( out, trial, &clear, &split );
- // a line through a pad leaves the river dry where the pad keeps its ground; past a dock
- // it only narrows to a ford
- Bool blocked = FALSE;
- for( Real v = line.sLo; v < line.sHi && !blocked; v += 4.0f )
+ /* A line through a pad leaves the river dry where the pad keeps its ground, the worst; one
+ over a dock or derrick is dammed there right across, two pools under one plane: the bed
+ the carve could not cut is counted, the river's wander and width included. */
+ Bool throughPad = FALSE;
+ for( Real v = line.sLo; v < line.sHi && !throughPad; v += 4.0f )
{
YX p = Frame::point( line.angle, line.my, line.mx, v, 0.0f );
- for( size_t s = 0; s < f.starts.size() && !blocked; s++ )
- blocked = hypotr( p.y - f.starts[s].y, p.x - f.starts[s].x ) < f.padRadius + 0.5f * COPY_FADE;
+ for( size_t s = 0; s < f.starts.size() && !throughPad; s++ )
+ throughPad = hypotr( p.y - f.starts[s].y, p.x - f.starts[s].x ) < f.padRadius + 0.5f * COPY_FADE;
}
Ranked r;
- r.score.blocked = blocked;
+ r.score.blocked = throughPad ? 2 : dammed > 0 ? 1 : 0;
r.score.shape = edge != river.reachesEdge;
- r.score.lost = crossing && line.calmReach <= 0.0f;
+ r.score.cropAt = line.cropAt;
r.score.meets = meets;
r.score.splits = split && !maySplit;
r.score.near = clear < want;
@@ -3414,7 +3806,7 @@ struct Composer
} );
Bool have = FALSE;
LineSpec bestLine;
- Int bestSplit = 0, bestNear = 0, bestNotes = 0;
+ Int bestSplit = 0, bestBridge = 0, bestNear = 0, bestNotes = 0;
Real bestClearness = 0.0f;
Field out;
for( Int r = 0; r < BRANCH_TRIES && r < (Int)ranked.size(); r++ )
@@ -3429,19 +3821,42 @@ struct Composer
line.salt = 85;
line.calmAt = line.calmReach = line.calmWidth = 0.0f;
memset( line.crop, 0, sizeof(line.crop) );
+ line.cropAt = CROSS_CROPS;
Plan trial = plan;
carveRiver( h, trial, river, index, line, bridges, TRUE, mainLine.surface, out, NULL );
Real clear;
Bool split;
judge( out, trial, &clear, &split );
+ /* The bridges already over the rivers have their ends raised to the bank, and a branch carved
+ after them cuts through whatever it passes: an end its cut lowers or wets anywhere on the
+ ground raised for it is a deck diving into the water. */
+ Int sBridge = 0;
+ for( size_t k = 0; k < plan.bridges.size(); k++ )
+ {
+ const YX ends[2] = { plan.bridges[k].a, plan.bridges[k].z };
+ for( Int g = 0; g < 2; g++ )
+ {
+ Bool hit = FALSE;
+ const Int ey = roundi( ends[g].y ), ex = roundi( ends[g].x ), reach = (Int)BRIDGE_END - 1;
+ for( Int dy = -reach; dy <= reach && !hit; dy++ )
+ for( Int dx = -reach; dx <= reach && !hit; dx++ )
+ {
+ Int y = ey + dy, x = ex + dx;
+ if( dy * dy + dx * dx > reach * reach || y < 0 || y >= H || x < 0 || x >= W ) continue;
+ Int i = y * W + x;
+ hit = ( trial.wet[i] && !plan.wet[i] ) || out[i] < h[i] - 0.5f;
+ }
+ sBridge += hit;
+ }
+ }
Int sSplit = split && !maySplit, sNear = clear < want, sNotes = (Int)trial.notes.size();
- Bool better = !have || sSplit < bestSplit || ( sSplit == bestSplit && ( sNear < bestNear ||
- ( sNear == bestNear && ( sNotes < bestNotes || ( sNotes == bestNotes && ranked[r].clearness < bestClearness ) ) ) ) );
+ Bool better = !have || sSplit < bestSplit || ( sSplit == bestSplit && ( sBridge < bestBridge || ( sBridge == bestBridge &&
+ ( sNear < bestNear || ( sNear == bestNear && ( sNotes < bestNotes || ( sNotes == bestNotes && ranked[r].clearness < bestClearness ) ) ) ) ) ) );
if( better )
{
have = TRUE;
bestLine = line;
- bestSplit = sSplit; bestNear = sNear; bestNotes = sNotes; bestClearness = ranked[r].clearness;
+ bestSplit = sSplit; bestBridge = sBridge; bestNear = sNear; bestNotes = sNotes; bestClearness = ranked[r].clearness;
}
}
if( !have )
@@ -3449,6 +3864,12 @@ struct Composer
plan.note( "river branch of %d cells (no way off the main river clear of the sites)", river.area );
return;
}
+ // a working bridge is worth more than the branch
+ if( bestBridge > 0 )
+ {
+ plan.note( "river branch of %d cells (no way off the main river clear of its bridges)", river.area );
+ return;
+ }
carveRiver( h, plan, river, index, bestLine, bridges, TRUE, mainLine.surface, out, NULL );
h.swap( out );
}
@@ -3459,7 +3880,9 @@ struct Composer
const Int b = src.m.border;
Mask taken( W * H );
for( Int i = 0; i < W * H; i++ )
- taken[i] = plan.keepout[i] || plan.wet[i] || f.guarded( i ) || !f.play[i] || keepBefore[i] > 0.05f;
+ taken[i] = plan.keepout[i] || plan.wet[i] || f.guarded( i ) || !f.play[i] || padsBefore[i] > 0.05f
+ // nor on any copy's ground, fade and all: flattened there a town would level a pad's ramps
+ || plan.fixedWeight[i] > 0.0f;
std::vector<Int> order;
for( size_t t = 0; t < src.inv.towns.size(); t++ ) order.push_back( (Int)t );
std::stable_sort( order.begin(), order.end(), [&]( Int a, Int c ) { return src.inv.towns[a].buildings > src.inv.towns[c].buildings; } );
@@ -3475,14 +3898,24 @@ struct Composer
integral( taken, count );
Int spotY = -1, spotX = -1, sy = fullY, sx = fullX, rows = fullRows, cols = fullCols;
Real best = 0.0f;
- // the whole town, or where there is no room for it its middle, cut down twice
+ // the whole town, or where there is no room for it the part of it with the most houses, cut down twice
static const Real theCrops[] = { 1.0f, 0.75f, 0.55f };
for( Int crop = 0; crop < 3 && spotY < 0; crop++ )
{
rows = std::min( fullRows, std::max( roundi( fullRows * theCrops[crop] ), TOWN_LEAST ) );
cols = std::min( fullCols, std::max( roundi( fullCols * theCrops[crop] ), TOWN_LEAST ) );
- sy = fullY + ( fullRows - rows ) / 2;
- sx = fullX + ( fullCols - cols ) / 2;
+ Int most = -1;
+ for( Int y = fullY; y <= fullY + fullRows - rows; y++ )
+ for( Int x = fullX; x <= fullX + fullCols - cols; x++ )
+ {
+ Int houses = 0;
+ for( size_t j = 0; j < town.houses.size(); j++ )
+ houses += y <= town.houses[j].y && town.houses[j].y < y + rows && x <= town.houses[j].x && town.houses[j].x < x + cols;
+ if( houses <= most ) continue;
+ most = houses;
+ sy = y;
+ sx = x;
+ }
for( Int ty = 6; ty < H - rows - 6; ty += TOWN_STEP )
{
for( Int tx = 6; tx < W - cols - 6; tx += TOWN_STEP )
@@ -3808,7 +4241,76 @@ struct Composer
stop[y * W + x] = 1;
for( size_t s = 0; s < plan.tech.size(); s++ ) discMask( stop, yx( (Real)plan.tech[s].y, (Real)plan.tech[s].x ), TECH_FLAT + 2 - 0.01f );
for( size_t s = 0; s < f.docks.size(); s++ ) discMask( stop, f.docks[s], SITE_INNER - 0.01f );
- Mask used( W * H, 0 );
+ Mask used( W * H, 0 ), onRoad( W * H, 0 ), junction( W * H, 0 );
+ auto stepCost = [&]( Int i, Int j ) -> Int
+ {
+ Int step = ( cost[i] + cost[j] ) / 2;
+ return i / W != j / W && i % W != j % W ? step * 1414 / 1000 : step;
+ };
+ auto spaceOut = [&]( Int c )
+ {
+ Int y = c / W, x = c % W;
+ for( Int yy = std::max( y - ROAD_SPACING, 0 ); yy <= std::min( y + ROAD_SPACING, H - 1 ); yy++ )
+ for( Int xx = std::max( x - ROAD_SPACING, 0 ); xx <= std::min( x + ROAD_SPACING, W - 1 ); xx++ )
+ used[yy * W + xx] = 1;
+ };
+ // the cell of a laid road nearest c, nearest first then lowest index; -1 when the spacing there came from
+ // a run that laid nothing. It looks further than the spacing: the spacing is also grown round the run,
+ // and the road laid along it may have been pulled a few cells off
+ auto roadNear = [&]( Int c ) -> Int
+ {
+ Int y = c / W, x = c % W, best = -1, bestD = ROAD_JOIN_REACH + 1;
+ for( Int yy = std::max( y - ROAD_JOIN_REACH, 0 ); yy <= std::min( y + ROAD_JOIN_REACH, H - 1 ); yy++ )
+ for( Int xx = std::max( x - ROAD_JOIN_REACH, 0 ); xx <= std::min( x + ROAD_JOIN_REACH, W - 1 ); xx++ )
+ {
+ Int d = std::max( abs( yy - y ), abs( xx - x ) );
+ if( onRoad[yy * W + xx] && d < bestD ) { bestD = d; best = yy * W + xx; }
+ }
+ return best;
+ };
+ // the cells from a to z, one a step on the longer axis, rounded half away from zero
+ auto walkLine = [&]( Int a, Int z, std::vector<Int>& out )
+ {
+ Int ay = a / W, ax = a % W, dy = z / W - ay, dx = z % W - ax;
+ Int steps = std::max( abs( dy ), abs( dx ) );
+ for( Int s = 1; s <= steps; s++ )
+ {
+ Int y = ay + ( 2 * dy * s + ( dy >= 0 ? steps : -steps ) ) / ( 2 * steps );
+ Int x = ax + ( 2 * dx * s + ( dx >= 0 ? steps : -steps ) ) / ( 2 * steps );
+ out.push_back( y * W + x );
+ }
+ };
+ // Dijkstra's octilinear path pulled straight: from each kept cell to the farthest cell ahead that a
+ // straight line reaches over open ground, clear of stops and other roads, for little more than the path
+ // costs; a dogleg on even ground costs the same as its straight line, so it goes
+ auto pull = [&]( const std::vector<Int>& piece, std::vector<Int>& out )
+ {
+ std::vector<Int64> along( piece.size(), 0 );
+ for( size_t c = 1; c < piece.size(); c++ ) along[c] = along[c - 1] + stepCost( piece[c - 1], piece[c] );
+ out.assign( 1, piece[0] );
+ std::vector<Int> line;
+ for( Int k = 0; k + 1 < (Int)piece.size(); )
+ {
+ Int next = k + 1;
+ for( Int j = std::min( (Int)piece.size() - 1, k + ROAD_PULL_REACH ); j > k + 1; j-- )
+ {
+ line.clear();
+ walkLine( piece[k], piece[j], line );
+ Int64 spent = 0;
+ Bool clear = TRUE;
+ for( size_t c = 0; c < line.size() && clear; c++ )
+ {
+ spent += stepCost( c ? line[c - 1] : piece[k], line[c] );
+ clear = c + 1 == line.size() || ( open[line[c]] && !stop[line[c]] && !used[line[c]] );
+ }
+ if( clear && spent * 1000 <= ( along[j] - along[k] ) * ROAD_PULL_SLACK ) { next = j; break; }
+ }
+ line.clear();
+ walkLine( piece[k], piece[next], line );
+ out.insert( out.end(), line.begin(), line.end() );
+ k = next;
+ }
+ };
std::vector< std::vector<Int> > polylines;
Int laid = 0;
for( size_t k = 0; k < tree.size() && laid < wanted; k++ )
@@ -3818,29 +4320,44 @@ struct Composer
for( Int c = tree[k].v; c >= 0; c = previous[c] ) back.push_back( c );
for( Int c = (Int)back.size() - 1; c >= 0; c-- ) run.push_back( back[c] );
for( Int c = tree[k].u; c >= 0; c = previous[c] ) run.push_back( c );
- std::vector<Int> piece;
+ // a piece that leaves or runs into an earlier road's spacing starts or ends on that road, so the two
+ // share a point and the renderer joins them
+ std::vector<Int> piece, pulled;
+ Int head = -1;
+ const size_t before = polylines.size();
+ auto lay = [&]( Int tail )
+ {
+ if( (Int)piece.size() > ROAD_LEAST )
+ {
+ pull( piece, pulled );
+ if( head >= 0 ) { pulled.insert( pulled.begin(), head ); junction[head] = 1; }
+ if( tail >= 0 ) { pulled.push_back( tail ); junction[tail] = 1; }
+ for( size_t c = 0; c < pulled.size(); c++ ) onRoad[pulled[c]] = 1;
+ polylines.push_back( pulled );
+ }
+ piece.clear();
+ head = -1;
+ };
for( size_t r = 0; r < run.size(); r++ )
{
Int y = run[r] / W, x = run[r] % W;
Bool jump = r > 0 && std::max( abs( y - run[r - 1] / W ), abs( x - run[r - 1] % W ) ) > 1;
if( stop[run[r]] || used[run[r]] || jump )
{
- if( (Int)piece.size() > ROAD_LEAST ) polylines.push_back( piece );
- piece.clear();
+ lay( !jump && !stop[run[r]] ? roadNear( run[r] ) : -1 );
if( !stop[run[r]] && !used[run[r]] ) piece.push_back( run[r] );
continue;
}
+ if( piece.empty() && r > 0 && used[run[r - 1]] && !stop[run[r - 1]] )
+ head = roadNear( run[r - 1] );
piece.push_back( run[r] );
}
- if( (Int)piece.size() > ROAD_LEAST ) polylines.push_back( piece );
+ lay( -1 );
+ // the spacing round what was laid, as drawn, and round the rest of the run, which later runs share
+ for( size_t p = before; p < polylines.size(); p++ )
+ for( size_t c = 0; c < polylines[p].size(); c++ ) spaceOut( polylines[p][c] );
for( size_t r = 0; r < run.size(); r++ )
- {
- if( stop[run[r]] ) continue;
- Int y = run[r] / W, x = run[r] % W;
- for( Int yy = std::max( y - ROAD_SPACING, 0 ); yy <= std::min( y + ROAD_SPACING, H - 1 ); yy++ )
- for( Int xx = std::max( x - ROAD_SPACING, 0 ); xx <= std::min( x + ROAD_SPACING, W - 1 ); xx++ )
- used[yy * W + xx] = 1;
- }
+ if( !stop[run[r]] ) spaceOut( run[r] );
laid = 0;
for( size_t p = 0; p < polylines.size(); p++ ) laid += (Int)polylines[p].size();
}
@@ -3856,15 +4373,30 @@ struct Composer
owed[pick] -= polylines[p].size();
std::vector<YX> cells;
for( size_t c = 0; c < polylines[p].size(); c++ ) cells.push_back( yx( (Real)( polylines[p][c] / W ), (Real)( polylines[p][c] % W ) ) );
+ // where a later road meets this one is a point of its own, simplified up to and on from, so both
+ // roads hold exactly that point; a bend that close to it folds in
std::vector<YX> simple;
- simplify( cells, 0, (Int)cells.size() - 1, simple );
+ for( Int from = 0, to = 1; to < (Int)cells.size(); to++ )
+ {
+ if( to + 1 < (Int)cells.size() && !junction[polylines[p][to]] ) continue;
+ size_t first = simple.size();
+ simplify( cells, from, to, simple );
+ for( size_t s = simple.size() - 1; s > first; s-- )
+ {
+ Real toStart = hypotr( simple[s].y - cells[from].y, simple[s].x - cells[from].x );
+ Real toEnd = hypotr( simple[s].y - cells[to].y, simple[s].x - cells[to].x );
+ if( toStart < ROAD_JOIN_SNAP || toEnd < ROAD_JOIN_SNAP ) simple.erase( simple.begin() + s );
+ }
+ from = to;
+ }
simple.push_back( cells.back() );
PlannedRoad road;
road.name = roads[pick]->name;
Real step = std::max( roads[pick]->segmentLength, 1.0f );
+ // as many pieces an edge as the exemplar's mean segment fits best, not the most it fits
for( size_t s = 0; s + 1 < simple.size(); s++ )
{
- Int pieces = std::max( (Int)ceilf( hypotr( simple[s + 1].y - simple[s].y, simple[s + 1].x - simple[s].x ) / step ), 1 );
+ Int pieces = std::max( roundi( hypotr( simple[s + 1].y - simple[s].y, simple[s + 1].x - simple[s].x ) / step ), 1 );
for( Int q = 0; q < pieces; q++ )
road.points.push_back( yx( simple[s].y + ( simple[s + 1].y - simple[s].y ) * q / pieces, simple[s].x + ( simple[s + 1].x - simple[s].x ) * q / pieces ) );
}
@@ -4073,7 +4605,7 @@ void positions( Int size, std::vector<Int>& out )
/// One source cell for every target cell. The stamps go first and are never written over.
Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const Field& keep, Int seed,
const std::vector<Stamp>& stamps, const std::vector<Int>& fixedSource, const Mask& treesAllowed, Int64 treeRateQ16,
- std::vector<Int>& syMap, std::vector<Int>& sxMap )
+ const Mask& targetGround, std::vector<Int>& syMap, std::vector<Int>& sxMap )
{
const Int TW = skm.W, TH = skm.H, SW = src.m.W, SH = src.m.H;
std::vector<Int> weight( TW * TH ), targetGuide( TW * TH );
@@ -4083,7 +4615,17 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
{
weight[i] = roundi( 4.0f * ( 1.0f + 4.0f * keep[i] ) );
targetGuide[i] = roundi( skel.guide[i] * 64.0f );
+ targetCliff[i] |= targetGround[i];
}
+ // a target's ground bits against a source's, in quarters of a cliff
+ Int price[16][16];
+ for( Int t = 0; t < 16; t++ )
+ for( Int s = 0; s < 16; s++ )
+ {
+ const Int differ = s ^ t;
+ price[t][s] = PRICE_CLIFF * ( ( differ & GROUND_CLIFF ) != 0 ) + PRICE_WET * ( ( differ & GROUND_WET ) != 0 ) +
+ PRICE_SHORE * ( ( differ & GROUND_SHORE ) != 0 ) + PRICE_STRIP * ( ( s & GROUND_STRIP ) && !( t & GROUND_STRIP ) );
+ }
// source patches touching a town or reaching past the playable ground (the border is the edge
// cells drawn out, stripes in a quilt) are never picked
@@ -4108,7 +4650,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
for( Int x = 0; x < GW; x++ )
{
coarseGuide[y * GW + x] = src.guide64[( y * COARSE ) * SW + x * COARSE];
- coarseCliff[y * GW + x] = src.m.cliff[( y * COARSE ) * SW + x * COARSE];
+ coarseCliff[y * GW + x] = src.ground[( y * COARSE ) * SW + x * COARSE];
}
std::vector<Byte> coarseBanned( ny * nx );
for( Int y = 0; y < ny; y++ )
@@ -4169,7 +4711,8 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
for( Int b = 0; b < PATCH / COARSE; b += COARSE_SKIP )
{
Int t = ( ty + a * COARSE ) * TW + tx + b * COARSE;
- const Int g = targetGuide[t], c = targetCliff[t], w = weight[t];
+ const Int g = targetGuide[t], w = weight[t];
+ const Int *p = price[targetCliff[t]];
total += w;
for( Int cy = 0; cy < ny; cy++ )
{
@@ -4181,7 +4724,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
Int d = g - guideRow[cx];
r1[cx] += w * d;
r2[cx] += w * d * d;
- rc[cx] += w * ( cliffRow[cx] != c );
+ rc[cx] += w * p[cliffRow[cx]];
}
}
}
@@ -4190,7 +4733,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
{
Int64 a1 = s1[k];
coarseCost[k] = coarseBanned[k] ? ( (Int64)1 << 62 ) :
- ( (Int64)s2[k] * 1024 - a1 * a1 * 1024 / total ) / total + ( a1 * a1 * 512 / total ) / total + (Int64)2458 * 1024 * sc[k] / total;
+ ( (Int64)s2[k] * 1024 - a1 * a1 * 1024 / total ) / total + ( a1 * a1 * 512 / total ) / total + (Int64)2458 * 256 * sc[k] / total;
order[k] = k;
}
std::partial_sort( order.begin(), order.begin() + std::min( REFINE, ny * nx ), order.end(),
@@ -4235,7 +4778,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
const UnsignedByte *tc = &targetCliff[( ty + i ) * TW + tx];
const Int *tw = &weight[( ty + i ) * TW + tx];
const Int *sg = &src.guide64[( sy + i ) * SW + sx];
- const UnsignedByte *scl = &src.m.cliff[( sy + i ) * SW + sx];
+ const UnsignedByte *scl = &src.ground[( sy + i ) * SW + sx];
const UnsignedByte *have = &filled[( ty + i ) * TW + tx];
const UnsignedByte *allowed = &treesAllowed[( ty + i ) * TW + tx];
const Int *det = &src.detail256[( sy + i ) * SW + sx];
@@ -4248,7 +4791,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
Int d = tg[j] - sg[j];
a1 += tw[j] * d;
a2 += tw[j] * d * d;
- cl += tw[j] * ( scl[j] != tc[j] );
+ cl += tw[j] * price[tc[j]][scl[j]];
if( have[j] )
{
Int e = det[j] - out[j];
@@ -4258,7 +4801,7 @@ Int quilt( const Exemplar& src, const SynthMap& skm, const Levels& skel, const F
held += trees[j];
}
}
- Int64 cost = ( a2 * 1024 - a1 * a1 * 1024 / wTotal ) / wTotal + ( a1 * a1 * 512 / wTotal ) / wTotal + 2458 * 1024 * cl / wTotal;
+ Int64 cost = ( a2 * 1024 - a1 * a1 * 1024 / wTotal ) / wTotal + ( a1 * a1 * 512 / wTotal ) / wTotal + 2458 * 256 * cl / wTotal;
if( haveCells )
cost += 2 * 1024 * over / haveCells;
Int64 off = held * 65536 - expected;
@@ -4415,6 +4958,7 @@ void movedObject( const SynthMap& from, Int thing, RawMap& raw, Real cy, Real cx
mirrored moves the corners, and the flags are those of the corners where they land. */
enum { BLEND_HORIZONTAL, BLEND_VERTICAL, BLEND_RIGHT, BLEND_LEFT, BLEND_INVERTED, BLEND_LONG };
const char BLEND_INVERTED_BIT = 0x1;
+const char BLEND_FLIPPED_BIT = 0x2; // FLIPPED_MASK: a side blend cut the way the cell's diagonal blend cuts it
static Int blendCorners( const char flags[6] )
{
@@ -4463,13 +5007,50 @@ static Int turnedCorners( Int corners, Int quarterTurn )
return out;
}
-/// BlendTileData version 8: every cell's class and blends from its source cell, the tiles worked out
-/// again for where the cell landed, the blends turned as the copy that brought them, the exemplar's
-/// texture table and the cliff bits (synthmap.blend_chunk).
+/// The most of these corners a blend can paint: the corners themselves when the renderer has the shape,
+/// else the largest shape inside them (two opposite corners, or all four, have none).
+static Int drawableCorners( Int corners )
+{
+ static const Int theDrawn[] = { 0x6, 0x9, 0xC, 0x3, 0x4, 0x2, 0xE, 0x7, 0x8, 0x1, 0xD, 0xB };
+ Int best = 0, most = 0;
+ for( size_t k = 0; k < sizeof(theDrawn) / sizeof(theDrawn[0]); k++ )
+ {
+ const Int c = theDrawn[k], count = ( c & 1 ) + ( ( c >> 1 ) & 1 ) + ( ( c >> 2 ) & 1 ) + ( ( c >> 3 ) & 1 );
+ if( ( c & ~corners ) == 0 && count > most )
+ {
+ best = c;
+ most = count;
+ }
+ }
+ return best;
+}
+
+/** BlendTileData version 8: every cell's class and blends from its source cell, the tiles worked out
+ again for where the cell landed, the blends turned as the copy that brought them, the exemplar's
+ texture table and the cliff bits (synthmap.blend_chunk).
+
+ A blend is drawn for the cell's neighbours, so it holds only where they are the source cell's
+ neighbours. Where the quilt's seams, a pad's rim, a town stamp or a spun crossing put a cell beside
+ ground from elsewhere, the copied blend pointed at a neighbour that was gone and the new one got
+ none, a hard stair-stepped edge: 16% of the class edges on Heartland Shield's and Twilight Flame's
+ maps against 6% and 3% on the shipped ones. So a neighbour is checked by its class against the one
+ the source cell had there, turned as the copy turned, and a corner any changed neighbour touches is
+ worked out again from the classes round it now, the way the exemplar lays them: a class goes over
+ another where the exemplar more often puts it over than under, and by its rank where the two never
+ meet. A cell whose neighbours all match keeps its blends byte for byte.
+
+ And the texture follows the final heights: a cell they made a cliff whose source is not a cliff
+ painted as one takes the class of the nearest that is, and flat ground copied from a cliff face
+ takes the class of the nearest flat ground (Exemplar::steepClass, openClass). Twilight Flame's maps
+ had 59% of their steep cells in dirt, sand and grass against the exemplar's 14%.
+
+ The faces of a cliff class get their mapping from the final heights (rmgCliffMapping). The
+ exemplar's own entries are no use to copy: Twilight Flame declares 7326 and no cell points at one,
+ its faces being shallow enough for the plane, and the pads and canyons laid here are not. */
Bool blendChunk( const Exemplar& src, Int W, Int H, const std::vector<Int>& syMap, const std::vector<Int>& sxMap,
- const std::vector<UnsignedByte>& turns, const Mask& cliff, std::vector<char>& out )
+ const std::vector<UnsignedByte>& turns, const Mask& cliff, const std::vector<Int>& heights, std::vector<char>& out )
{
- const Int SW = src.m.W;
+ const Int SW = src.m.W, SH = src.m.H, NC = (Int)src.classRank.size();
// the exemplar's shapes, then each turned one the copies need, in the order the cells ask for them
std::vector< std::pair< std::string, Int > > shapes = src.shapes;
std::map< std::pair<Int, Int>, Int > turned;
@@ -4488,26 +5069,152 @@ Bool blendChunk( const Exemplar& src, Int W, Int H, const std::vector<Int>& syMa
turned[key] = index;
return index;
};
- const Int nShapes = 8 * std::max( (Int)src.shapes.size(), 1 );
+ // and a shape worked out here, by its corners, its cut and the custom edge class of the blend it replaces
+ std::map< std::pair<Int, Int>, Int > made;
+ auto shapeFor = [&]( Int corners, Bool flipped, Int custom ) -> Int
+ {
+ std::pair<Int, Int> key( corners | ( flipped ? 16 : 0 ), custom );
+ std::map< std::pair<Int, Int>, Int >::const_iterator it = made.find( key );
+ if( it != made.end() ) return it->second;
+ char flags[6] = { 0, 0, 0, 0, (char)( flipped ? BLEND_FLIPPED_BIT : 0 ), 0 };
+ blendFlagsFor( corners, flags );
+ std::pair< std::string, Int > wanted( std::string( flags, 6 ), custom );
+ Int index = (Int)( std::find( shapes.begin(), shapes.end(), wanted ) - shapes.begin() );
+ if( index == (Int)shapes.size() ) shapes.push_back( wanted );
+ made[key] = index;
+ return index;
+ };
+ // whether the exemplar lays class k over class a
+ auto liesOver = [&]( Int k, Int a ) -> Bool
+ {
+ const Int up = src.blendOver[a * NC + k], down = src.blendOver[k * NC + a];
+ return up != down ? up > down : src.classRank[k] > src.classRank[a];
+ };
+
+ // each cell's class: its source cell's, unless the heights made it a cliff the source is not or the other way round
+ std::vector<Int> ground( W * H );
+ Mask moved( W * H, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ const Int o = syMap[i] * SW + sxMap[i];
+ Int c = src.cls[o];
+ const Bool rock = src.steep[o] && src.cliffTexture[c];
+ if( cliff[i] && !rock && src.steepClass[o] >= 0 ) c = src.steepClass[o];
+ else if( !cliff[i] && rock && src.openClass[o] >= 0 ) c = src.openClass[o];
+ ground[i] = c;
+ moved[i] = c != src.cls[o];
+ }
+
+ // the eight neighbours, and the corners each touches (0 (x, y), 1 (x + 1, y), 2 (x + 1, y + 1), 3 (x, y + 1))
+ static const Int theDY[8] = { -1, -1, -1, 0, 0, 1, 1, 1 }, theDX[8] = { -1, 0, 1, -1, 1, -1, 0, 1 };
+ static const Int theTouch[8] = { 0x1, 0x3, 0x2, 0x9, 0x6, 0x8, 0xC, 0x4 };
std::vector<Short> layer0( W * H );
- std::vector<Int> keys[2];
- for( Int l = 0; l < 2; l++ ) keys[l].resize( W * H );
+ std::vector<Int> tiles[2], shapeOf[2];
+ for( Int l = 0; l < 2; l++ )
+ {
+ tiles[l].assign( W * H, 0 );
+ shapeOf[l].assign( W * H, -1 );
+ }
for( Int y = 0; y < H; y++ )
{
for( Int x = 0; x < W; x++ )
{
- Int i = y * W + x, o = syMap[i] * SW + sxMap[i];
- layer0[i] = (Short)src.tileFor( src.cls[o], y, x );
+ const Int i = y * W + x, o = syMap[i] * SW + sxMap[i], mine = ground[i];
+ layer0[i] = (Short)src.tileFor( mine, y, x );
const Short entry[2] = { src.m.blends[o], src.m.extras[o] };
- for( Int l = 0; l < 2; l++ )
+
+ // the corners a changed neighbour touches: every corner of a cell whose own class changed
+ Int loose = moved[i] ? 0xF : 0;
+ for( Int d = 0; d < 8 && loose != 0xF; d++ )
+ {
+ const Int ny = y + theDY[d], nx = x + theDX[d];
+ if( ny < 0 || nx < 0 || ny >= H || nx >= W ) continue;
+ // the neighbour's offset on the source, the copy's turn undone (Copy::toSource)
+ Int sy = theDY[d], sx = theDX[d];
+ for( Int q = 0; q < ( turns[i] & 3 ); q++ ) { Int t = sy; sy = -sx; sx = t; }
+ if( turns[i] & 4 ) sx = -sx;
+ sy += syMap[i];
+ sx += sxMap[i];
+ if( sy < 0 || sx < 0 || sy >= SH || sx >= SW || src.cls[sy * SW + sx] != ground[ny * W + nx] )
+ loose |= theTouch[d];
+ }
+ if( loose == 0 )
+ {
+ for( Int l = 0; l < 2; l++ )
+ {
+ Int e = entry[l];
+ if( e <= 0 || e >= (Int)src.entries.size() ) continue;
+ tiles[l][i] = src.tileFor( src.blendClass[e], y, x );
+ shapeOf[l][i] = shapeTurned( src.blendShape[e], turns[i] );
+ }
+ continue;
+ }
+
+ // the copied blends on the corners that still hold, and on the others whatever the classes round them lay over this one
+ struct Layer { Int cls, corners, custom; };
+ Layer layer[10];
+ Int count = 0;
+ auto add = [&]( Int k, Int corners, Int custom )
+ {
+ if( k == mine || corners == 0 ) return;
+ for( Int n = 0; n < count; n++ )
+ if( layer[n].cls == k ) { layer[n].corners |= corners; return; }
+ layer[count].cls = k;
+ layer[count].corners = corners;
+ layer[count].custom = custom;
+ count++;
+ };
+ for( Int l = 0; l < 2 && !moved[i]; l++ )
{
Int e = entry[l];
- if( e <= 0 || e >= (Int)src.entries.size() ) { keys[l][i] = 0; continue; }
- Int tile = src.tileFor( src.blendClass[e], y, x );
- keys[l][i] = tile * nShapes + shapeTurned( src.blendShape[e], turns[i] ) + 1;
+ if( e <= 0 || e >= (Int)src.entries.size() ) continue;
+ const std::pair< std::string, Int >& shape = src.shapes[src.blendShape[e]];
+ char flags[6];
+ memcpy( flags, shape.first.data(), 6 );
+ add( src.blendClass[e], turnedCorners( blendCorners( flags ), turns[i] ) & ~loose, shape.second );
+ }
+ for( Int d = 0; d < 8; d++ )
+ {
+ const Int ny = y + theDY[d], nx = x + theDX[d];
+ if( ny < 0 || nx < 0 || ny >= H || nx >= W || !( theTouch[d] & loose ) ) continue;
+ const Int k = ground[ny * W + nx];
+ if( k != mine && liesOver( k, mine ) )
+ add( k, theTouch[d] & loose, -1 );
+ }
+
+ // lowest first, as the renderer stacks them; it has two, and keeps the classes on top
+ for( Int a = 1; a < count; a++ )
+ for( Int b = a; b > 0 && src.classRank[layer[b].cls] < src.classRank[layer[b - 1].cls]; b-- )
+ std::swap( layer[b], layer[b - 1] );
+ const Int first = std::max( count - 2, 0 );
+ Bool cutFlipped = FALSE;
+ for( Int n = first; n < count; n++ )
+ {
+ layer[n].corners = drawableCorners( layer[n].corners );
+ const Int c = layer[n].corners;
+ cutFlipped = cutFlipped || c == 0x1 || c == 0x4 || c == 0xB || c == 0xE;
+ }
+ // a side blend takes the cut of a diagonal it shares the cell with, as RMGLayout::buildBlends does
+ for( Int n = first; n < count; n++ )
+ {
+ const Int c = layer[n].corners;
+ if( c == 0 ) continue;
+ const Bool side = c == 0x3 || c == 0x6 || c == 0x9 || c == 0xC;
+ const Int l = n - first;
+ tiles[l][i] = src.tileFor( layer[n].cls, y, x );
+ shapeOf[l][i] = shapeFor( c, side && count - first == 2 && cutFlipped, layer[n].custom );
}
}
}
+ const Int nShapes = std::max( (Int)shapes.size(), 1 );
+ std::vector<Int> keys[2];
+ for( Int l = 0; l < 2; l++ )
+ {
+ keys[l].assign( W * H, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ if( shapeOf[l][i] >= 0 )
+ keys[l][i] = tiles[l][i] * nShapes + shapeOf[l][i] + 1;
+ }
std::vector<Int> table( 1, 0 );
table.insert( table.end(), keys[0].begin(), keys[0].end() );
table.insert( table.end(), keys[1].begin(), keys[1].end() );
@@ -4522,13 +5229,27 @@ Bool blendChunk( const Exemplar& src, Int W, Int H, const std::vector<Int>& syMa
for( Int i = 0; i < W * H; i++ )
layers[l][i] = (Short)( std::lower_bound( table.begin(), table.end(), keys[l][i] ) - table.begin() );
}
- std::vector<Short> zeroes( W * H, 0 );
+ // the heights as the file holds them, and the cells whose class is a cliff's
+ std::vector<Int> stored( W * H ), sheetFirst( W * H, -1 ), sheetWidth( W * H, 0 );
+ for( Int i = 0; i < W * H; i++ )
+ {
+ stored[i] = (UnsignedByte)heights[i];
+ if( src.cliffTexture[ground[i]] )
+ {
+ sheetFirst[i] = src.classFirst[ground[i]];
+ sheetWidth[i] = src.classWidth[ground[i]];
+ }
+ }
+ std::vector<Short> cliffIndex;
+ std::vector<RMGCliffInfo> cliffInfo;
+ rmgCliffMapping( stored, W, H, sheetFirst, sheetWidth, cliffIndex, cliffInfo );
+
out.clear();
putInt( out, W * H );
putBytes( out, &layer0[0], W * H * 2 );
putBytes( out, &layers[0][0], W * H * 2 );
putBytes( out, &layers[1][0], W * H * 2 );
- putBytes( out, &zeroes[0], W * H * 2 );
+ putBytes( out, &cliffIndex[0], W * H * 2 );
Int row = ( W + 7 ) / 8;
std::vector<UnsignedByte> bits( row * H, 0 );
for( Int y = 0; y < H; y++ )
@@ -4538,7 +5259,7 @@ Bool blendChunk( const Exemplar& src, Int W, Int H, const std::vector<Int>& syMa
putBytes( out, &bits[0], row * H );
putInt( out, src.bitmapTiles );
putInt( out, (Int)table.size() );
- putInt( out, 1 );
+ putInt( out, (Int)cliffInfo.size() );
putBytes( out, &src.tableHead[0], (Int)src.tableHead.size() );
for( size_t k = 1; k < table.size(); k++ )
{
@@ -4548,6 +5269,17 @@ Bool blendChunk( const Exemplar& src, Int W, Int H, const std::vector<Int>& syMa
putInt( out, shapes[shape].second );
putInt( out, 0x7ADA0000 );
}
+ for( size_t k = 1; k < cliffInfo.size(); k++ )
+ {
+ putInt( out, cliffInfo[k].m_tileIndex );
+ for( Int c = 0; c < 4; c++ )
+ {
+ putReal( out, cliffInfo[k].m_u[c] );
+ putReal( out, cliffInfo[k].m_v[c] );
+ }
+ putByte( out, cliffInfo[k].m_flip ? 1 : 0 );
+ putByte( out, 0 );
+ }
return TRUE;
}
@@ -4822,9 +5554,9 @@ void baseRegions( const Exemplar& src, std::vector<Field>& regions, std::vector<
}
}
-/** The exemplar's base round every start: of its starts and the eight ways a square turns over,
- the one that faces the middle as the start does, scaled down where the starts stand closer than
- the bases are wide. */
+/** The exemplar's base round every start: one of its starts for all of them, and of the eight ways a
+ square turns over the one that faces the middle as the start does, scaled down where the starts
+ stand closer than the bases are wide. */
void planPads( const Exemplar& src, const Levels& skel, Int W, Int H, Int seed, const std::vector<Field>& regions,
const std::vector<Real>& reaches, const std::vector<Real>& edges, const std::vector<UnsignedByte>& raised,
std::vector<Copy>& pads )
@@ -4841,40 +5573,86 @@ void planPads( const Exemplar& src, const Levels& skel, Int W, Int H, Int seed,
for( size_t j = i + 1; j < skel.startY.size(); j++ )
spacing = std::min( spacing, hypotr( (Real)( skel.startY[i] - skel.startY[j] ), (Real)( skel.startX[i] - skel.startX[j] ) ) );
const Real scale = clampr( PAD_SPACING * spacing / reachCells, PAD_SCALE_LEAST, 1.0f );
+ std::vector<Real> bearings;
for( size_t s = 0; s < skel.startY.size(); s++ )
+ bearings.push_back( ATan2( skel.startY[s] - skel.cy, skel.startX[s] - skel.cx ) );
+ auto facing = [&]( const Copy& c, Int t ) -> Real
{
- Real bearing = ATan2( skel.startY[s] - skel.cy, skel.startX[s] - skel.cx );
- Copy best;
- Real bestError = 1.0e9f;
- UnsignedInt bestTie = 0;
- for( size_t t = 0; t < src.lv.startY.size(); t++ )
- {
- if( anyRaised && !raised[t] ) continue;
- Real from = ATan2( src.lv.startY[t] - src.lv.cy, src.lv.startX[t] - src.lv.cx );
+ return c.angle( ATan2( src.lv.startY[t] - src.lv.cy, src.lv.startX[t] - src.lv.cx ) );
+ };
+ /* One base for every seat: two of Twilight Flame's stand over ground 27 bytes apart and keep their
+ docks 30 and 48 cells out, and seats that took them turn about stood that far apart. The base
+ whose turns face every seat best, the misses summed in whole milliradians; of those within
+ PAD_BEARING_SLACK a seat of the best, the one carrying a dock nearest its start, then the lowest. */
+ const Int SW = src.m.W, sb = src.m.border;
+ Int64 leastCost = -1;
+ std::vector<Int64> costs( src.lv.startY.size(), -1 );
+ std::vector<Int> dockCells( src.lv.startY.size(), 0x7fffffff );
+ for( size_t t = 0; t < src.lv.startY.size(); t++ )
+ {
+ if( anyRaised && !raised[t] ) continue;
+ Int64 cost = 0;
+ for( size_t s = 0; s < bearings.size(); s++ )
+ {
+ Real least = 1.0e9f;
for( Int d = 0; d < 8; d++ )
{
Copy c;
c.turn = d & 3;
c.mirror = d >= 4;
c.spinBy( 0.0f );
- Real error = turnBetween( c.angle( from ), bearing );
- UnsignedInt tie = synthHash( seed, 140 + (Int)s, (Int)t * 8 + d );
- if( error > bestError + 1.0e-3f || ( error > bestError - 1.0e-3f && tie >= bestTie ) )
- continue;
- best = c;
- best.source = yx( (Real)src.lv.startY[t], (Real)src.lv.startX[t] );
- best.region = &regions[t];
- best.radius = ( reaches[t] + COPY_FADE ) * scale + 1.0f;
- best.core = ( reaches[t] - PAD_MARGIN ) * scale + 1.0f;
- best.lift = skel.bowl - edges[t];
- // a plateau scaled down keeps its shape: lower by as much as it is narrower, so its
- // ramps climb no steeper than the exemplar's
- best.pivot = edges[t];
- best.heightScale = raised[t] ? scale : 1.0f;
- bestError = error;
- bestTie = tie;
+ least = std::min( least, turnBetween( facing( c, (Int)t ), bearings[s] ) );
}
+ cost += roundi( least * 1000.0f );
}
+ costs[t] = cost;
+ if( leastCost < 0 || cost < leastCost ) leastCost = cost;
+ for( size_t k = 0; k < src.m.supplies.size(); k++ )
+ {
+ const Int y = roundi( src.m.supplies[k].y + sb ), x = roundi( src.m.supplies[k].x + sb );
+ if( y < 0 || x < 0 || y >= src.m.H || x >= SW || regions[t][y * SW + x] < 0.9f ) continue;
+ dockCells[t] = std::min( dockCells[t], roundi( hypotr( (Real)( y - src.lv.startY[t] ), (Real)( x - src.lv.startX[t] ) ) ) );
+ }
+ }
+ Int chosen = -1;
+ const Int64 slack = (Int64)roundi( PAD_BEARING_SLACK * 1000.0f ) * (Int64)bearings.size();
+ for( size_t t = 0; t < costs.size(); t++ )
+ {
+ if( costs[t] < 0 || costs[t] > leastCost + slack ) continue;
+ if( chosen < 0 || dockCells[t] < dockCells[chosen] || ( dockCells[t] == dockCells[chosen] && costs[t] < costs[chosen] ) )
+ chosen = (Int)t;
+ }
+ if( chosen < 0 )
+ return;
+ const Int t = chosen;
+ for( size_t s = 0; s < bearings.size(); s++ )
+ {
+ Copy best;
+ Real bestError = 1.0e9f;
+ UnsignedInt bestTie = 0;
+ for( Int d = 0; d < 8; d++ )
+ {
+ Copy c;
+ c.turn = d & 3;
+ c.mirror = d >= 4;
+ c.spinBy( 0.0f );
+ Real error = turnBetween( facing( c, t ), bearings[s] );
+ UnsignedInt tie = synthHash( seed, 140 + (Int)s, t * 8 + d );
+ if( error > bestError + 1.0e-3f || ( error > bestError - 1.0e-3f && tie >= bestTie ) )
+ continue;
+ best = c;
+ bestError = error;
+ bestTie = tie;
+ }
+ best.source = yx( (Real)src.lv.startY[t], (Real)src.lv.startX[t] );
+ best.region = &regions[t];
+ best.radius = ( reaches[t] + COPY_FADE ) * scale + 1.0f;
+ best.core = ( reaches[t] - PAD_MARGIN ) * scale + 1.0f;
+ best.lift = skel.bowl - edges[t];
+ // a plateau scaled down keeps its shape: lower by as much as it is narrower, so its
+ // ramps climb no steeper than the exemplar's
+ best.pivot = edges[t];
+ best.heightScale = raised[t] ? scale : 1.0f;
best.target = yx( (Real)skel.startY[s], (Real)skel.startX[s] );
best.scale = scale;
best.regionW = src.m.W;
@@ -4906,14 +5684,71 @@ void planPads( const Exemplar& src, const Levels& skel, Int W, Int H, Int seed,
}
}
-/// The docks and derricks: the skeleton's off the pads, the exemplar's the pads carry.
-void carryMoney( const Exemplar& src, const std::vector<Copy>& pads, SynthMap& skm )
+/// 0 for a supply dock, 1 for an oil derrick, -1 for anything else: SynthMap::load's two kinds of money.
+Int moneyKind( const AsciiString& name )
+{
+ AsciiString lower = name;
+ lower.toLower();
+ if( strstr( lower.str(), "supplydock" ) ) return 0;
+ return lower == "techoilderrick" ? 1 : -1;
+}
+
+/** Where an object a pad carries lands (grid cells), or FALSE when it does not come. A rigid base on a
+ start nearer the edge than the exemplar's put its dock past the map: Twilight Flame's 50 cells
+ behind its start, a 140-cell map's start 24 from the edge. Such an object is pulled back along the
+ line to the start until it stands SITE_INNER inside the playable area, and dropped when that brings
+ it within PAD_SITE_LEAST of the start or onto the exemplar's cliff. carryMoney and the objects ask
+ this one question, so the money the reach is repaired to and the money written out agree. */
+Bool padSite( const Exemplar& src, const Copy& pad, Real sy, Real sx, const SynthMap& skm, YX& at )
+{
+ if( !pad.carries( sy, sx ) )
+ return FALSE;
+ at = pad.toTarget( sy, sx );
+ const Real from[2] = { pad.target.y, pad.target.x }, to[2] = { at.y, at.x };
+ const Real lo[2] = { skm.border + SITE_INNER, skm.border + SITE_INNER };
+ const Real hi[2] = { skm.border + skm.playY - SITE_INNER, skm.border + skm.playX - SITE_INNER };
+ Real k = 1.0f;
+ for( Int a = 0; a < 2; a++ )
+ {
+ if( to[a] >= lo[a] && to[a] <= hi[a] ) continue;
+ if( from[a] < lo[a] || from[a] > hi[a] ) return FALSE;
+ k = std::min( k, ( ( to[a] < lo[a] ? lo[a] : hi[a] ) - from[a] ) / ( to[a] - from[a] ) );
+ }
+ if( k >= 1.0f )
+ return TRUE;
+ at = yx( from[0] + ( to[0] - from[0] ) * k, from[1] + ( to[1] - from[1] ) * k );
+ if( hypotr( at.y - from[0], at.x - from[1] ) < PAD_SITE_LEAST )
+ return FALSE;
+ const YX s = pad.toSource( at.y, at.x );
+ for( Int dy = -1; dy <= 1; dy++ )
+ for( Int dx = -1; dx <= 1; dx++ )
+ if( src.m.cliff[clampi( roundi( s.y ) + dy, 0, src.m.H - 1 ) * src.m.W + clampi( roundi( s.x ) + dx, 0, src.m.W - 1 )] )
+ return FALSE;
+ return TRUE;
+}
+
+/** The docks and derricks: the skeleton's off the pads, the exemplar's the pads carry. A kind some pad
+ brings none of onto the map, Twilight Flame's derricks out in its bowl or an open base's docks past
+ its reach, keeps the skeleton's under every pad instead, so no seat loses its home dock or its
+ derricks to the copy; one pad short decides for all, so the seats stay alike. The skeleton's kept
+ under a pad are listed in levelled for a flat disc on the copied ground. */
+void carryMoney( const Exemplar& src, const std::vector<Copy>& pads, SynthMap& skm, Bool fellBack[2], std::vector<YX>& levelled )
{
const Int b = skm.border, sb = src.m.border;
std::vector<YX> *mine[2] = { &skm.supplies, &skm.derricks };
const std::vector<YX> *theirs[2] = { &src.m.supplies, &src.m.derricks };
for( Int kind = 0; kind < 2; kind++ )
{
+ Bool every = !pads.empty();
+ YX at;
+ for( size_t c = 0; c < pads.size() && every; c++ )
+ {
+ Bool any = FALSE;
+ for( size_t k = 0; k < theirs[kind]->size() && !any; k++ )
+ any = padSite( src, pads[c], ( *theirs[kind] )[k].y + sb, ( *theirs[kind] )[k].x + sb, skm, at );
+ every = any;
+ }
+ fellBack[kind] = !every;
std::vector<YX> kept;
for( size_t k = 0; k < mine[kind]->size(); k++ )
{
@@ -4921,16 +5756,16 @@ void carryMoney( const Exemplar& src, const std::vector<Copy>& pads, SynthMap& s
Bool covered = FALSE;
for( size_t c = 0; c < pads.size() && !covered; c++ )
covered = pads[c].weight( roundi( p.y + b ), roundi( p.x + b ), COPY_FADE ) > 0.0f;
- if( !covered ) kept.push_back( p );
+ if( !covered || fellBack[kind] ) kept.push_back( p );
+ if( covered && fellBack[kind] ) levelled.push_back( yx( p.y + b, p.x + b ) );
}
- for( size_t c = 0; c < pads.size(); c++ )
+ for( size_t c = 0; c < pads.size() && !fellBack[kind]; c++ )
{
for( size_t k = 0; k < theirs[kind]->size(); k++ )
{
const YX& p = ( *theirs[kind] )[k];
- if( !pads[c].carries( p.y + sb, p.x + sb ) ) continue;
- YX t = pads[c].toTarget( p.y + sb, p.x + sb );
- kept.push_back( yx( t.y - b, t.x - b ) );
+ if( padSite( src, pads[c], p.y + sb, p.x + sb, skm, at ) )
+ kept.push_back( yx( at.y - b, at.x - b ) );
}
}
mine[kind]->swap( kept );
@@ -5075,9 +5910,9 @@ void widenRamps( std::vector<Int>& heights, Int W, Int H, Int border, const Plan
}
/** Where a start, dock, derrick or tech building is cut off from the first start, a ramp along the
- cheapest way to the ground that start reaches: through a cliff at a price, never through water.
- Returns the ramps cut. */
-Int repairReach( std::vector<Int>& heights, Int W, Int H, const Plan& plan, const Mask& decks, Int firstStart,
+ cheapest way to the ground that start reaches: through a cliff at a price, never through water nor
+ the border, which the pathfinder does not walk. Returns the ramps cut. */
+Int repairReach( std::vector<Int>& heights, Int W, Int H, const Plan& plan, const Mask& decks, const Mask& play, Int firstStart,
const std::vector<YX>& targets )
{
const Int RAMP_HALF = 4, RAMP_BLEND = 3, CLIFF_COST = 6;
@@ -5097,7 +5932,7 @@ Int repairReach( std::vector<Int>& heights, Int W, Int H, const Plan& plan, cons
for( Int i = 0; i < W * H; i++ )
{
wet[i] = plan.wet[i] && heights[i] < plan.level[i] && !decks[i];
- passable[i] = ( walk[i] && !wet[i] ) || decks[i];
+ passable[i] = ( ( walk[i] && !wet[i] ) || decks[i] ) && play[i];
}
reach( passable, W, H, firstStart, reached );
stale = FALSE;
@@ -5127,7 +5962,7 @@ Int repairReach( std::vector<Int>& heights, Int W, Int H, const Plan& plan, cons
const Int n[4] = { x + 1 < W ? i + 1 : -1, x > 0 ? i - 1 : -1, y + 1 < H ? i + W : -1, y > 0 ? i - W : -1 };
for( Int j = 0; j < 4; j++ )
{
- if( n[j] < 0 || wet[n[j]] ) continue;
+ if( n[j] < 0 || wet[n[j]] || !play[n[j]] ) continue;
Int step = top.first + ( passable[n[j]] ? 1 : CLIFF_COST );
if( step >= cost[n[j]] ) continue;
cost[n[j]] = step;
@@ -5178,6 +6013,20 @@ Int repairReach( std::vector<Int>& heights, Int W, Int H, const Plan& plan, cons
} // namespace
+/** How much of the way up to the lower plateau a cell between two copied plateau bases is raised
+ (Composer::joinPlateaus). sum is the cell's two 3-4 chamfer distances added, pairLeast the least
+ such sum over the map: three times the real gap between the two bases, along the line between
+ them. Whether the pair is joined at all is decided on that gap, PAD_CORRIDOR; the fade over
+ JOIN_FADE only shapes the joined way's shoulders. Fading on the sum alone also filled a valley a
+ few cells wider than PAD_CORRIDOR part way across, half its height at a gap of 36 cells. */
+Real rmgJoinShare( Int pairLeast, Int sum )
+{
+ const Int inside = 3 * PAD_CORRIDOR, reachSum = 3 * ( PAD_CORRIDOR + JOIN_FADE );
+ if( pairLeast >= inside || sum >= reachSum )
+ return 0.0f;
+ return sum < inside ? 1.0f : fade( (Real)( reachSum - sum ) / ( 3 * JOIN_FADE ) );
+}
+
//-----------------------------------------------------------------------------
// The synthesis
//-----------------------------------------------------------------------------
@@ -5251,14 +6100,15 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
baseRegions( src, regions, reaches, edges, raised );
std::vector<Copy> basePads;
planPads( src, skel, W, H, seed, regions, reaches, edges, raised, basePads );
- carryMoney( src, basePads, skm );
+ Bool moneyFellBack[2];
+ std::vector<YX> levelledMoney;
+ carryMoney( src, basePads, skm, moneyFellBack, levelledMoney );
// the exemplar's large features first, then what of the skeleton keeps its own height
Composer composer( src, skm, skel, seed, basePads );
{
- Field keepBefore, padsBefore;
- protection( skm, skel, keepBefore, padsBefore );
- composer.keepBefore = keepBefore;
+ Field keepBefore;
+ protection( skm, skel, keepBefore, composer.padsBefore );
}
Field h = skel.h;
Plan plan = composer.compose( h );
@@ -5329,8 +6179,24 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
Real treesWanted = std::max( src.treeDensity * treeGround - inTowns, 0.0f );
Int64 treeRateQ16 = allowedCount ? (Int64)( treesWanted * 65536.0f / allowedCount ) : 0;
+ // the ground the quilt matches besides height: the water that will be water (plan.wet holds dry ground
+ // a pad's guard kept, so it is the composed height under the plane), its bank, and the roads' clearance.
+ // An exemplar with no water has no bed or bank to match, and a price every patch pays alike only moves the jitter.
+ Mask targetGround( W * H, 0 );
+ {
+ Mask wetSkel( W * H, 0 ), roads( W * H, 0 ), shore, clear;
+ if( src.hasWater )
+ for( Int i = 0; i < W * H; i++ ) wetSkel[i] = plan.wet[i] && skel.h[i] < plan.level[i];
+ maskGrow( wetSkel, W, H, SHORE_GROUND, shore );
+ for( size_t k = 0; k < plan.roads.size(); k++ )
+ for( size_t p = 0; p + 1 < plan.roads[k].points.size(); p++ )
+ lineCells( plan.roads[k].points[p], plan.roads[k].points[p + 1], W, H, roads );
+ maskGrow( roads, W, H, ROAD_CLEAR, clear );
+ for( Int i = 0; i < W * H; i++ )
+ targetGround[i] = ( wetSkel[i] ? GROUND_WET : 0 ) | ( shore[i] ? GROUND_SHORE : 0 ) | ( clear[i] ? GROUND_STRIP : 0 );
+ }
std::vector<Int> syMap, sxMap;
- Int patches = quilt( src, skm, skel, keep, seed, plan.stamps, plan.fixedSource, treesAllowed, treeRateQ16, syMap, sxMap );
+ Int patches = quilt( src, skm, skel, keep, seed, plan.stamps, plan.fixedSource, treesAllowed, treeRateQ16, targetGround, syMap, sxMap );
Mask stamped( W * H, 0 );
for( size_t s = 0; s < plan.stamps.size(); s++ )
for( Int y = plan.stamps[s].ty; y < plan.stamps[s].ty + plan.stamps[s].rows; y++ )
@@ -5370,14 +6236,18 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
heights[i] = clampi( roundi( value ), 0, 255 );
}
widenRamps( heights, W, H, b, plan, basePads, skel.bowl );
+ // the skeleton's money kept under a pad stands on the copy's ground, levelled as the skeleton levelled it
+ for( size_t k = 0; k < levelledMoney.size(); k++ )
+ levelDisc( heights, W, H, roundi( levelledMoney[k].y ), roundi( levelledMoney[k].x ), PILE_FLAT );
Mask cliff;
cliffOf( heights, W, H, cliff );
- // the skeleton's money and seats stay, its dressing goes, and on a copy all but its waypoints; the piles move
- auto underCopy = [&]( Real gy, Real gx ) -> Bool
+ // the skeleton's money and seats stay, its dressing goes, and on a copy all but its waypoints and the
+ // money a pad fell back on (carryMoney); the piles move
+ auto underCopy = [&]( Real gy, Real gx, Bool crossingsOnly ) -> Bool
{
for( size_t c = 0; c < plan.copies.size(); c++ )
- if( plan.copies[c].weight( roundi( gy ), roundi( gx ), COPY_FADE ) > 0.0f )
+ if( ( !crossingsOnly || plan.copies[c].radius <= 0.0f ) && plan.copies[c].weight( roundi( gy ), roundi( gx ), COPY_FADE ) > 0.0f )
return TRUE;
return FALSE;
};
@@ -5389,7 +6259,8 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
if( t.name.startsWith( "Tree" ) || t.name.startsWith( "Rocks" ) || t.name.startsWith( "RockCluster" ) ||
t.name.startsWith( "AmbientWaves" ) || ( t.flags & FLAG_ROAD_FLAGS ) || ( civilian && !t.waypointID && civilian( t.name.str() ) ) )
continue;
- if( !t.waypointID && underCopy( t.y + b, t.x + b ) )
+ const Int kind = moneyKind( t.name );
+ if( !t.waypointID && underCopy( t.y + b, t.x + b, kind >= 0 && moneyFellBack[kind] ) )
continue;
( t.name == "SupplyPileSmall" ? piles : kept ).push_back( chunk );
}
@@ -5401,7 +6272,8 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
maskGrow( lines, W, H, 1, decks );
Mask walk, passable( W * H ), reached, openGround( W * H );
walkable( cliff, W, H, walk );
- for( Int i = 0; i < W * H; i++ ) passable[i] = ( walk[i] && !levelWet[i] ) || decks[i];
+ // the border is no ground: the pathfinder keeps to the playable area
+ for( Int i = 0; i < W * H; i++ ) passable[i] = ( ( walk[i] && !levelWet[i] ) || decks[i] ) && f.play[i];
const Int firstStart = (Int)f.starts[0].y * W + (Int)f.starts[0].x;
reach( passable, W, H, firstStart, reached );
for( Int i = 0; i < W * H; i++ ) openGround[i] = passable[i] && reached[i] && !plan.keepout[i] && !levelWet[i];
@@ -5409,6 +6281,7 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
// the piles: where the exemplar keeps its own on high ground, a pair halfway to the next seat and a
// pair a third of the way, with what stands beside the exemplar's; otherwise where the skeleton put them
std::vector<YX> pileSites;
+ Bool everyGap = TRUE;
struct Added { AsciiString name; Real x, y, angle; };
std::vector<Added> added;
if( src.inv.pileCount && src.inv.pileDz >= HIGH_RISE )
@@ -5427,7 +6300,8 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
Real a = bearings[seats[k]];
Real gap = bearings[seats[( k + 1 ) % seats.size()]] - a;
gap = gap - 2.0f * PI_R * floorf( gap / ( 2.0f * PI_R ) );
- const Real shares[2] = { 0.5f, k % 2 == 0 ? 0.38f : 0.62f };
+ // halfway, and a pair nearer the seat the gap follows: one pair a seat and a half of two, whatever the count
+ const Real shares[2] = { 0.5f, 0.38f };
for( Int s = 0; s < 2; s++ )
{
Bool found = FALSE;
@@ -5439,7 +6313,11 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
angle = a + ( shares[s] + theNudges[n] ) * gap;
found = placeOnBearing( heights, g == 0 ? high : openGround, W, H, skel.cy, skel.cx, angle, 0.6f * f.seatRing, outer, &y, &x );
}
- if( !found ) continue;
+ if( !found )
+ {
+ everyGap = FALSE;
+ continue;
+ }
Real ty = Cos( angle ) * 4.0f, tx = -Sin( angle ) * 4.0f;
pileSites.push_back( yx( y + ty, x + tx ) );
pileSites.push_back( yx( y - ty, x - tx ) );
@@ -5455,17 +6333,17 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
}
}
}
- for( size_t k = 0; k < piles.size(); k++ )
+ /* A pile at every site, the skeleton's then dropped: moving the few the copies left fed only the
+ first gap or two, four piles by one seat and none by the rest. A gap with no room for its sites
+ keeps the skeleton's piles where they stood, so no gap goes bare while the next has four. */
+ Int serial = 0;
+ const Bool atSites = !pileSites.empty() && everyGap;
+ if( !atSites )
+ kept.insert( kept.end(), piles.begin(), piles.end() );
+ for( size_t k = 0; k < pileSites.size() && atSites; k++ )
{
- Chunk c = piles[k];
- if( k < pileSites.size() )
- {
- Real wx = ( pileSites[k].x - b ) * MAP_XY, wy = ( pileSites[k].y - b ) * MAP_XY;
- memcpy( &c.body[0], &wx, 4 );
- memcpy( &c.body[4], &wy, 4 );
- levelDisc( heights, W, H, (Int)pileSites[k].y, (Int)pileSites[k].x, PILE_FLAT );
- }
- kept.push_back( c );
+ neutralObject( skm.raw, "SupplyPileSmall", pileSites[k].x, pileSites[k].y, b, 0.0f, ++serial, kept );
+ levelDisc( heights, W, H, (Int)pileSites[k].y, (Int)pileSites[k].x, PILE_FLAT );
}
for( size_t k = 0; k < plan.tech.size(); k++ )
{
@@ -5483,13 +6361,13 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
for( size_t s = 0; s < skm.supplies.size(); s++ ) mustReach.push_back( yx( skm.supplies[s].y + b, skm.supplies[s].x + b ) );
for( size_t s = 0; s < skm.derricks.size(); s++ ) mustReach.push_back( yx( skm.derricks[s].y + b, skm.derricks[s].x + b ) );
for( size_t s = 0; s < plan.tech.size(); s++ ) mustReach.push_back( yx( (Real)plan.tech[s].y, (Real)plan.tech[s].x ) );
- const Int ramps = repairReach( heights, W, H, plan, decks, firstStart, mustReach );
+ const Int ramps = repairReach( heights, W, H, plan, decks, f.play, firstStart, mustReach );
// a waypoint or a pile the water, a new cliff or a pocket now holds goes to the nearest ground the starts share
cliffOf( heights, W, H, cliff );
walkable( cliff, W, H, walk );
for( Int i = 0; i < W * H; i++ ) levelWet[i] = plan.wet[i] && heights[i] < plan.level[i];
- for( Int i = 0; i < W * H; i++ ) passable[i] = ( walk[i] && !levelWet[i] ) || decks[i];
+ for( Int i = 0; i < W * H; i++ ) passable[i] = ( ( walk[i] && !levelWet[i] ) || decks[i] ) && f.play[i];
Mask ground, wetClear;
reach( passable, W, H, firstStart, ground );
maskGrow( levelWet, W, H, 3, wetClear );
@@ -5540,6 +6418,8 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
Int o = syMap[i] * SW + sxMap[i];
if( src.sceneryFirst[o] == src.sceneryFirst[o + 1] ) continue;
if( !f.play[i] || pads[i] >= 0.9f || keep[i] >= 0.95f || plan.keepout[i] || wetNear[i] || stamped[i] ) continue;
+ // nothing on a wall the new ground made where the exemplar's cell was not one
+ if( cliff[i] && !src.m.cliff[o] ) continue;
Bool near = FALSE;
for( size_t s = 0; s < taken.size() && !near; s++ )
near = fabsf( y - taken[s].y ) < 6.0f && fabsf( x - taken[s].x ) < 6.0f;
@@ -5565,7 +6445,7 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
for( Int i = 0; i < W * H; i++ ) standingCount += standing[i];
maskGrow( standing, W, H, 1, standingNear );
Mask freeGround( W * H );
- for( Int i = 0; i < W * H; i++ ) freeGround[i] = treesAllowed[i] && !standingNear[i];
+ for( Int i = 0; i < W * H; i++ ) freeGround[i] = treesAllowed[i] && !standingNear[i] && !cliff[i];
for( size_t s = 0; s < taken.size(); s++ )
for( Int y = std::max( (Int)taken[s].y - 6, 0 ); y < std::min( (Int)taken[s].y + 7, H ); y++ )
for( Int x = std::max( (Int)taken[s].x - 6, 0 ); x < std::min( (Int)taken[s].x + 7, W ); x++ )
@@ -5621,7 +6501,7 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
// every object goes in neutral; no tower, hut or tent where the new ground has a cliff
cliffOf( heights, W, H, cliff );
- Int serial = 0, trees = 0, scenery = 0;
+ Int trees = 0, scenery = 0;
for( size_t k = 0; k < added.size(); k++ )
{
const Added& a = added[k];
@@ -5668,17 +6548,99 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
if( one.flags == road->flags[0] && two.flags == road->flags[1] ) { pair = (Int)p; break; }
}
if( pair < 0 ) continue;
+ // both ends of a road say they join: where one meets a road of its own kind the renderer counts the
+ // shared point and ignores the flag, where it meets another kind it lays the blend between them, and in
+ // the open it fades the road out instead of cutting it square
const std::vector<YX>& points = plan.roads[k].points;
for( size_t s = 0; s + 1 < points.size(); s++ )
{
movedObject( src.m, pair, skm.raw, points[s].y, points[s].x, b, ++serial, kept );
movedObject( src.m, pair + 1, skm.raw, points[s + 1].y, points[s + 1].x, b, ++serial, kept );
+ for( Int e = 0; e < 2; e++ )
+ {
+ if( e == 0 ? s != 0 : s + 2 != points.size() ) continue;
+ Chunk& end = kept[kept.size() - 2 + e];
+ Int flags;
+ memcpy( &flags, &end.body[16], 4 );
+ flags |= FLAG_ROAD_JOIN;
+ memcpy( &end.body[16], &flags, 4 );
+ }
segments++;
}
}
- // the towns: every object of the exemplar inside each stamped box, moved with it; a road only with both ends inside
+ // A copy takes a road pair only with both ends on it, so an exemplar road that runs off a copy leaves the
+ // pairs it led to cut: a chain ending at the copy's edge, or a stub flagged to join a road that stayed
+ // behind. After each copy its road pairs are peeled from every such loose end back to a junction, and
+ // what is closed inside the copy stays. Shared ends are the exemplar's own points, compared exactly.
+ struct CopiedRoad { size_t at; Int thing; YX ends[2]; };
+ std::vector<CopiedRoad> copiedRoads;
+ std::vector<Int> cutRoads;
+ std::vector< std::pair<YX, YX> > emittedRoads;
+ for( size_t k = 0; k < plan.roads.size(); k++ )
+ for( size_t s = 0; s + 1 < plan.roads[k].points.size(); s++ )
+ emittedRoads.push_back( std::make_pair( plan.roads[k].points[s], plan.roads[k].points[s + 1] ) );
+ auto offRoad = []( const YX& e, const YX& a, const YX& z ) -> Real
+ {
+ Real dy = z.y - a.y, dx = z.x - a.x, span = dy * dy + dx * dx;
+ Real t = span > 0.0f ? clampr( ( ( e.y - a.y ) * dy + ( e.x - a.x ) * dx ) / span, 0.0f, 1.0f ) : 0.0f;
+ return hypotr( e.y - a.y - t * dy, e.x - a.x - t * dx );
+ };
+ auto sameSpot = [&]( Int i, Int j ) -> Bool
+ {
+ return src.m.things[i].x == src.m.things[j].x && src.m.things[i].y == src.m.things[j].y;
+ };
Int copied = 0;
+ auto peelCutRoads = [&]()
+ {
+ const size_t n = copiedRoads.size();
+ std::vector<Bool> loose( 2 * n, FALSE ), alive( n, TRUE );
+ for( size_t k = 0; k < n; k++ )
+ for( Int e = 0; e < 2; e++ )
+ {
+ const Int t = copiedRoads[k].thing + e;
+ for( size_t d = 0; d < cutRoads.size(); d++ )
+ loose[2 * k + e] = loose[2 * k + e] || sameSpot( t, cutRoads[d] ) || sameSpot( t, cutRoads[d] + 1 );
+ if( !( src.m.things[t].flags & FLAG_ROAD_JOIN ) ) continue;
+ Bool near = FALSE;
+ for( size_t j = 0; j < emittedRoads.size() && !near; j++ )
+ near = offRoad( copiedRoads[k].ends[e], emittedRoads[j].first, emittedRoads[j].second ) <= ROAD_STUB_REACH;
+ for( size_t j = 0; j < n && !near; j++ )
+ near = j != k && offRoad( copiedRoads[k].ends[e], copiedRoads[j].ends[0], copiedRoads[j].ends[1] ) <= ROAD_STUB_REACH;
+ loose[2 * k + e] = loose[2 * k + e] || !near;
+ }
+ for( Bool peeled = TRUE; peeled; )
+ {
+ peeled = FALSE;
+ for( size_t k = 0; k < n; k++ )
+ {
+ if( !alive[k] || !( loose[2 * k] || loose[2 * k + 1] ) ) continue;
+ // gone; the pair beyond its other end becomes the loose end, unless several meet there
+ const Int other = copiedRoads[k].thing + ( loose[2 * k] ? 1 : 0 );
+ Int meets = 0, beyond = -1;
+ for( size_t j = 0; j < n; j++ )
+ for( Int g = 0; g < 2; g++ )
+ if( j != k && alive[j] && sameSpot( other, copiedRoads[j].thing + g ) ) { meets++; beyond = 2 * (Int)j + g; }
+ alive[k] = FALSE;
+ if( meets == 1 ) loose[beyond] = TRUE;
+ peeled = TRUE;
+ }
+ }
+ for( size_t k = n; k-- > 0; )
+ {
+ if( alive[k] )
+ {
+ emittedRoads.push_back( std::make_pair( copiedRoads[k].ends[0], copiedRoads[k].ends[1] ) );
+ continue;
+ }
+ kept.erase( kept.begin() + copiedRoads[k].at, kept.begin() + copiedRoads[k].at + 2 );
+ copied -= 2;
+ }
+ copiedRoads.clear();
+ cutRoads.clear();
+ };
+
+ // the towns: every object of the exemplar inside each stamped box, moved with it; a road only with both ends inside
for( size_t s = 0; s < plan.stamps.size(); s++ )
{
const Stamp& st = plan.stamps[s];
@@ -5705,13 +6667,24 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
if( inside )
onCliff = onCliff || cliff[clampi( (Int)cys[g], 0, H - 1 ) * W + clampi( (Int)cxs[g], 0, W - 1 )];
}
- if( !inside || onCliff ) continue;
+ const Bool road = ( t.flags & FLAG_ROAD_POINT1 ) && group == 2;
+ if( !inside || onCliff )
+ {
+ if( road ) cutRoads.push_back( (Int)first );
+ continue;
+ }
+ if( road )
+ {
+ CopiedRoad one = { kept.size(), (Int)first, { yx( cys[0], cxs[0] ), yx( cys[1], cxs[1] ) } };
+ copiedRoads.push_back( one );
+ }
for( Int g = 0; g < group; g++ )
{
movedObject( src.m, (Int)( first + g ), skm.raw, cys[g], cxs[g], b, ++serial, kept );
copied++;
}
}
+ peelCutRoads();
}
// what stands on a copy goes with it, turned as it is: a pad brings its base's money and dressing (no
@@ -5735,20 +6708,53 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
continue;
if( pad && copy.scale < 1.0f && group == 1 && !money && civilian && civilian( t.name.str() ) )
continue;
+ // a kind of money the pads fell back on is the skeleton's (carryMoney)
+ const Int kind = moneyKind( t.name );
+ if( kind >= 0 && moneyFellBack[kind] )
+ continue;
+ // money where padSite puts it; the rest where it fell, if it fell on the map and not on a new wall
Bool inside = TRUE;
+ YX ats[2];
for( Int g = 0; g < group && inside; g++ )
- inside = copy.carries( src.m.things[first + g].y + sb, src.m.things[first + g].x + sb );
- if( !inside ) continue;
+ {
+ const MapThing&u = src.m.things[first + g];
+ if( pad && money )
+ {
+ inside = padSite( src, copy, u.y + sb, u.x + sb, skm, ats[g] );
+ continue;
+ }
+ inside = copy.carries( u.y + sb, u.x + sb );
+ ats[g] = copy.toTarget( u.y + sb, u.x + sb );
+ const Int ty = roundi( ats[g].y ), tx = roundi( ats[g].x );
+ inside = inside && ty >= 0 && tx >= 0 && ty < H && tx < W;
+ if( inside && pad && group == 1 )
+ {
+ const Int o = clampi( roundi( u.y + sb ), 0, src.m.H - 1 ) * src.m.W + clampi( roundi( u.x + sb ), 0, src.m.W - 1 );
+ inside = !cliff[ty * W + tx] || src.m.cliff[o];
+ }
+ }
+ const Bool road = ( t.flags & FLAG_ROAD_POINT1 ) && group == 2;
+ if( !inside )
+ {
+ if( road ) cutRoads.push_back( (Int)first );
+ continue;
+ }
+ if( road )
+ {
+ CopiedRoad one = { kept.size(), (Int)first, { ats[0], ats[1] } };
+ copiedRoads.push_back( one );
+ }
for( Int g = 0; g < group; g++ )
{
const MapThing&u = src.m.things[first + g];
- YX at = copy.toTarget( u.y + sb, u.x + sb );
+ const YX at = ats[g];
movedObject( src.m, (Int)( first + g ), skm.raw, at.y, at.x, b, ++serial, kept );
Real turned = copy.angle( u.angle );
memcpy( &kept.back().body[12], &turned, 4 );
copied++;
}
}
+ peelCutRoads();
}
// the chunks: heights, textures, objects, water, the exemplar's light and weather
@@ -5759,7 +6765,7 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
cliffOf( heights, W, H, cliff );
Chunk *blend = out.chunk( "BlendTileData" );
std::vector<char> blendBody;
- if( !blendChunk( src, W, H, syMap, sxMap, plan.fixedTurn, cliff, blendBody ) )
+ if( !blendChunk( src, W, H, syMap, sxMap, plan.fixedTurn, cliff, heights, blendBody ) )
{
DEBUG_LOG(( "random map: '%s' needs more blends than the renderer holds\n", clamped.m_template.str() ));
restoreFPMode( callersFPMode );
@@ -5799,7 +6805,7 @@ Bool rmgSynthesise( const RandomMapSettings& clamped, const std::vector<char>& e
// every start walks to every other, every dock, derrick and tech building, over the bridges and round the water
for( Int i = 0; i < W * H; i++ ) levelWet[i] = plan.wet[i] && heights[i] < plan.level[i];
walkable( cliff, W, H, walk );
- for( Int i = 0; i < W * H; i++ ) passable[i] = ( walk[i] && !levelWet[i] ) || decks[i];
+ for( Int i = 0; i < W * H; i++ ) passable[i] = ( ( walk[i] && !levelWet[i] ) || decks[i] ) && f.play[i];
reach( passable, W, H, firstStart, reached );
auto cutOff = [&]( Real py, Real px ) -> Bool
{
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 06a356548..8e4dddeba 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -1646,6 +1646,16 @@ TEST(are_music_files_on_cd_accepts_the_local_no_cd_layout)
{
CHECK( bootOnce() );
+ /* Run from GeneralsMD/Run the real archive is there. It is the game's proof of media, so it is
+ neither overwritten nor removed: a run that did left every headless match quitting silently
+ right after it loaded, with no HEADLESS lines and no crash. */
+ if (FILE *real = fopen( "genseczh.big", "rb" ))
+ {
+ fclose( real );
+ CHECK_EQ( TheFileSystem->areMusicFilesOnCD(), TRUE );
+ return;
+ }
+
/* No local big and the test's CD manager is the NULL stub: no media. */
CHECK_EQ( TheFileSystem->areMusicFilesOnCD(), FALSE );
@@ -10396,6 +10406,9 @@ struct RMGParse
AsciiString m_textureName;
std::vector<AsciiString> m_textureNames;
std::vector<Int> m_firstTiles;
+ std::vector<Int> m_classTiles, m_classWidths; ///< each class's tile count and sheet width
+ std::vector<Short> m_cliffIndexes; ///< per cell, into m_cliffInfos; 0 is the planar tiling
+ std::vector<RMGCliffInfo> m_cliffInfos; ///< the table, entry 0 the default the file never holds
std::vector<AsciiString> m_waypointNames;
std::vector<Coord3D> m_waypointPositions;
std::vector<AsciiString> m_pathWaypointNames; ///< the approach paths' waypoints, "Center2_from1_0"
@@ -10459,8 +10472,17 @@ static Bool RMGParseBlendTile( DataChunkInput &file, DataChunkInfo *info, void *
theRMGParse.m_extraBlendIndexes.resize( len );
file.readArrayOfBytes( (char *)&theRMGParse.m_extraBlendIndexes[0], len * sizeof(Short) );
- std::vector<Short> scratch( len );
- file.readArrayOfBytes( (char *)&scratch[0], len * sizeof(Short) ); // cliff info
+ theRMGParse.m_cliffIndexes.resize( len );
+ file.readArrayOfBytes( (char *)&theRMGParse.m_cliffIndexes[0], len * sizeof(Short) );
+
+ // a cliff bit a cell from version 7 on (version 7 itself wrote rows one byte short): without
+ // skipping them the counts below were read out of the bits and came out whatever they held
+ if( info->version >= 7 )
+ {
+ Int rowBytes = info->version == 7 ? ( theRMGParse.m_width + 1 ) / 8 : ( theRMGParse.m_width + 7 ) / 8;
+ std::vector<char> cliffBits( rowBytes * theRMGParse.m_height + 1 );
+ file.readArrayOfBytes( &cliffBits[0], rowBytes * theRMGParse.m_height );
+ }
theRMGParse.m_numBitmapTiles = file.readInt();
theRMGParse.m_numBlendedTiles = file.readInt();
@@ -10476,6 +10498,8 @@ static Bool RMGParseBlendTile( DataChunkInput &file, DataChunkInfo *info, void *
AsciiString name = file.readAsciiString();
theRMGParse.m_firstTiles.push_back( firstTile );
+ theRMGParse.m_classTiles.push_back( theRMGParse.m_numTiles );
+ theRMGParse.m_classWidths.push_back( theRMGParse.m_tileWidth );
theRMGParse.m_textureNames.push_back( name );
if( i == 0 )
@@ -10505,6 +10529,22 @@ static Bool RMGParseBlendTile( DataChunkInput &file, DataChunkInfo *info, void *
theRMGParse.m_blends.push_back( entry );
}
+ // and the cliff mappings after it, version 5 on, entry 0 again the default
+ theRMGParse.m_cliffInfos.assign( 1, RMGCliffInfo() );
+ for( Int cliff = 1; cliff < theRMGParse.m_numCliffInfo && info->version >= 5; cliff++ )
+ {
+ RMGCliffInfo entry;
+ entry.m_tileIndex = file.readInt();
+ for( Int k = 0; k < 4; k++ )
+ {
+ entry.m_u[k] = file.readReal();
+ entry.m_v[k] = file.readReal();
+ }
+ entry.m_flip = file.readByte() != 0;
+ file.readByte(); // mutant
+ theRMGParse.m_cliffInfos.push_back( entry );
+ }
+
theRMGParse.m_blendBytesLeftOver = file.atEndOfChunk() ? 0 : 1;
return TRUE;
}
@@ -10656,6 +10696,50 @@ static void parseGeneratedMap( std::vector<char>& bytes )
CHECK( input.parse( NULL ) == TRUE );
}
+/// The parsed map's texture class index of a tile index (BlendTileData's tile, or a blend entry's).
+static Int RMGClassOfTile( Int tile )
+{
+ Int best = 0;
+ for( Int c = 0; c < (Int)theRMGParse.m_firstTiles.size(); c++ )
+ if( theRMGParse.m_firstTiles[c] <= ( tile >> 2 ) && theRMGParse.m_firstTiles[c] >= theRMGParse.m_firstTiles[best] )
+ best = c;
+ return best;
+}
+
+/** The parsed map's cliff mapping against what the renderer can use: indexes past the table, entries
+ of another class than their cell's (getUVForTileIndex ignores those), coordinates outside the
+ class's block of the terrain texture (they draw a neighbouring class), and the cells mapped. */
+struct RMGCliffCensus
+{
+ Int badIndexes, foreignEntries, outsideSheet, mapped;
+};
+
+static RMGCliffCensus RMGCliffCount( void )
+{
+ RMGCliffCensus census = { 0, 0, 0, 0 };
+ for( Int i = 0; i < (Int)theRMGParse.m_cliffIndexes.size(); i++ )
+ {
+ const Int index = theRMGParse.m_cliffIndexes[i];
+ if( index == 0 )
+ continue;
+ if( index < 0 || index >= (Int)theRMGParse.m_cliffInfos.size() )
+ {
+ census.badIndexes++;
+ continue;
+ }
+ census.mapped++;
+ const RMGCliffInfo& entry = theRMGParse.m_cliffInfos[index];
+ const Int c = RMGClassOfTile( theRMGParse.m_tiles[i] );
+ if( RMGClassOfTile( entry.m_tileIndex ) != c )
+ census.foreignEntries++;
+ const Real extent = (Real)theRMGParse.m_classWidths[c] / 32.0f;
+ for( Int k = 0; k < 4; k++ )
+ if( entry.m_u[k] < 0.0f || entry.m_u[k] > extent || entry.m_v[k] > 0.0f || entry.m_v[k] < -extent )
+ census.outsideSheet++;
+ }
+ return census;
+}
+
//-------------------------------------------------------------------------------------------------
/** The whole point of generating a map from a seed instead of shipping a file: every machine in
the game has to build identical bytes, or the map CRC that guards the lobby is worthless.
@@ -10714,19 +10798,30 @@ TEST(a_generated_map_reads_back_through_the_engines_own_chunk_reader)
// ParseBlendTileData throws ERROR_CORRUPT_FILE_FORMAT unless these two agree.
CHECK_EQ( theRMGParse.m_blendDataSize, theRMGParse.m_dataSize );
+ // Each class as big as its image, as the shipped maps declare it: SandLargeType1 is six tiles by
+ // six, the other three two by two, one after another.
CHECK_EQ( theRMGParse.m_numTextureClasses, 4 );
CHECK_EQ( theRMGParse.m_firstTile, 0 );
+ CHECK_EQ( theRMGParse.m_classTiles[1], 36 );
+ CHECK_EQ( theRMGParse.m_classWidths[1], 6 );
CHECK_EQ( theRMGParse.m_numTiles, 4 );
CHECK_EQ( theRMGParse.m_tileWidth, 2 );
- CHECK_EQ( theRMGParse.m_numBitmapTiles, 4 * 4 ); // four classes of four tiles
+ CHECK_EQ( theRMGParse.m_numBitmapTiles, 4 + 36 + 4 + 4 );
CHECK( theRMGParse.m_numBlendedTiles > 1 ); // entry 0 is the default; the rest are real
- CHECK_EQ( theRMGParse.m_numCliffInfo, 1 ); // entry 0 is the default, no cliff faces
- CHECK_EQ( theRMGParse.m_blendBytesLeftOver, 0 ); // the blend table ends where the chunk does
+ CHECK( theRMGParse.m_numCliffInfo >= 1 ); // entry 0 is the default
+ CHECK( theRMGParse.m_numCliffInfo <= 32384 ); // NUM_CLIFF_INFO, or the reader throws
+ CHECK_EQ( theRMGParse.m_blendBytesLeftOver, 0 ); // the cliff table ends where the chunk does
CHECK_STR( theRMGParse.m_textureName.str(), "GrassType1" );
CHECK_STR( theRMGParse.m_textureNames[1].str(), "SandLargeType1" );
CHECK_STR( theRMGParse.m_textureNames[2].str(), "DirtType1" );
CHECK_STR( theRMGParse.m_textureNames[3].str(), "RocksType1" );
- CHECK_EQ( theRMGParse.m_firstTiles[3], 12 );
+ CHECK_EQ( theRMGParse.m_firstTiles[3], 44 );
+
+ // Every cliff index names an entry, of its cell's class, inside that class's block.
+ const RMGCliffCensus census = RMGCliffCount();
+ CHECK_EQ( census.badIndexes, 0 );
+ CHECK_EQ( census.foreignEntries, 0 );
+ CHECK_EQ( census.outsideSheet, 0 );
CHECK_EQ( theRMGParse.m_weather, 0 );
CHECK_EQ( theRMGParse.m_compression, 0 );
@@ -10771,6 +10866,83 @@ TEST(a_generated_map_reads_back_through_the_engines_own_chunk_reader)
CHECK( theRMGParse.m_terrainAmbient[TIME_OF_DAY_AFTERNOON - TIME_OF_DAY_FIRST][0] > 0.2f );
}
+//-------------------------------------------------------------------------------------------------
+/** The twilight style's rim rises about 29 height bytes a cell, which the planar tiling drew with
+ its rock stretched to twice its length down the face, out of a quarter of CliffLargeType10's
+ image. Its rock class is the whole 4 by 4 sheet now, and a rock cell that rises down its fall
+ takes a cliff entry: one the reader holds, of the rock's own class, inside its block of the
+ texture, drawn by height, so a face's texture runs as far as the face does. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_style_maps_cliff_faces_carry_a_cliff_mapping_of_their_own_rock)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 7;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = 300;
+ settings.m_style = 1;
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ CHECK_STR( theRMGParse.m_textureNames[3].str(), "CliffLargeType10" );
+ CHECK_EQ( theRMGParse.m_classTiles[3], 16 );
+ CHECK_EQ( theRMGParse.m_classWidths[3], 4 );
+ CHECK_EQ( theRMGParse.m_blendBytesLeftOver, 0 );
+
+ // No mapped edge is drawn more stretched than the plane drew it, past 1.6 times: an edge a cell's
+ // height mapping gives no length (a cell flat down one side of its fall) would be a smear of one texel.
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height;
+ Int steepRock = 0, worseThanThePlane = 0, planarPastTwo = 0, drawnPastTwo = 0;
+ for( Int y = 0; y + 1 < H; y++ )
+ {
+ for( Int x = 0; x + 1 < W; x++ )
+ {
+ const Int i = y * W + x;
+ const Int h[4] = { theRMGParse.m_heights[i], theRMGParse.m_heights[i + 1], theRMGParse.m_heights[i + W + 1], theRMGParse.m_heights[i + W] };
+ if( RMGClassOfTile( theRMGParse.m_tiles[i] ) != 3 )
+ continue;
+ const Int index = theRMGParse.m_cliffIndexes[i];
+ const Bool mapped = index > 0 && index < (Int)theRMGParse.m_cliffInfos.size();
+ Real planarWorst = 0.0f, drawnWorst = 0.0f;
+ for( Int k = 0; k < 4; k++ )
+ {
+ const Int n = ( k + 1 ) & 3;
+ // in cells: one across, a height byte a sixteenth of one up
+ const Real world = sqrtf( 1.0f + sqr( (Real)( h[k] - h[n] ) / 16.0f ) );
+ Real drawn = world;
+ if( mapped )
+ {
+ const RMGCliffInfo& entry = theRMGParse.m_cliffInfos[index];
+ const Real texture = sqrtf( sqr( entry.m_u[k] - entry.m_u[n] ) + sqr( entry.m_v[k] - entry.m_v[n] ) ) * 64.0f;
+ drawn = texture > 0.0f ? world / texture : 1000.0f;
+ if( drawn > std::max( world, 1.6f ) )
+ worseThanThePlane++;
+ }
+ planarWorst = std::max( planarWorst, world );
+ drawnWorst = std::max( drawnWorst, drawn );
+ }
+ if( planarWorst <= sqrtf( 1.0f + sqr( 12.0f / 16.0f ) ) )
+ continue;
+ steepRock++;
+ planarPastTwo += planarWorst > 2.0f;
+ drawnPastTwo += drawnWorst > 2.0f;
+ }
+ }
+ const RMGCliffCensus census = RMGCliffCount();
+ CHECK( steepRock > 1000 );
+ CHECK( census.mapped > steepRock / 2 );
+ CHECK_EQ( worseThanThePlane, 0 );
+ CHECK( planarPastTwo > steepRock / 5 );
+ CHECK( drawnPastTwo * 2 < planarPastTwo ); // 28.5% of the steep rock past twice its length, now 8.5%
+ CHECK_EQ( census.badIndexes, 0 );
+ CHECK_EQ( census.foreignEntries, 0 );
+ CHECK_EQ( census.outsideSheet, 0 );
+ CHECK_EQ( (Int)theRMGParse.m_cliffInfos.size(), theRMGParse.m_numCliffInfo );
+}
+
//-------------------------------------------------------------------------------------------------
/** The seed rolls the hour as well as the ground: all four come up, each lit as itself, and a
winter map snows - snowed roofs from the WorldInfo weather, falling snow from a map.ini the
@@ -10883,7 +11055,7 @@ TEST(every_generated_tile_index_names_a_tile_the_map_declared)
}
CHECK( worstSource >= 0 );
- CHECK( worstSource < theRMGParse.m_numTextureClasses * theRMGParse.m_numTiles );
+ CHECK( worstSource < theRMGParse.m_numBitmapTiles );
CHECK_EQ( quadrantsSeen, 0xf ); // all four quadrants of the sheet get used
}
@@ -11145,6 +11317,25 @@ TEST(start_positions_land_inside_the_map_with_room_between_them)
}
}
}
+
+ /* A lake map with water on three sides of the seats: a thin pool of dry flats used to run the
+ ring search out of seats or stack two bases. Every seat, and two base discs and a gap apart. */
+ settings.m_seed = 121;
+ settings.m_numPlayers = 8;
+ settings.m_playableCells = 280;
+ std::vector<char> lakeBytes;
+ RandomMapGenerator::generate( settings, lakeBytes );
+ parseGeneratedMap( lakeBytes );
+ CHECK_EQ( (Int)theRMGParse.m_waypointPositions.size(), 8 );
+ Real closest = 1.0e9f;
+ for( size_t i = 0; i < theRMGParse.m_waypointPositions.size(); i++ )
+ for( size_t j = i + 1; j < theRMGParse.m_waypointPositions.size(); j++ )
+ {
+ Real dx = theRMGParse.m_waypointPositions[i].x - theRMGParse.m_waypointPositions[j].x;
+ Real dy = theRMGParse.m_waypointPositions[i].y - theRMGParse.m_waypointPositions[j].y;
+ closest = std::min( closest, sqrtf( dx * dx + dy * dy ) );
+ }
+ CHECK( closest >= ( 2.0f * 13.0f + 6.0f ) * MAP_XY_FACTOR );
}
//-------------------------------------------------------------------------------------------------
@@ -11291,7 +11482,7 @@ TEST(every_texture_boundary_is_blended_rather_than_cut)
std::vector<Int> ground( width * height );
for( i = 0; i < width * height; i++ )
- ground[i] = (theRMGParse.m_tiles[i] >> 2) / 4;
+ ground[i] = RMGClassOfTile( theRMGParse.m_tiles[i] );
Int boundaries = 0;
Int extraLayers = 0;
@@ -11347,7 +11538,7 @@ TEST(every_texture_boundary_is_blended_rather_than_cut)
extraLayers++;
const RMGBlendEntry& entry = theRMGParse.m_blends[layers[layer] - 1];
- Int layerClass = (entry.m_blendTileIndex >> 2) / 4;
+ Int layerClass = RMGClassOfTile( entry.m_blendTileIndex );
if( layerClass <= previousClass )
badIndexes++; // a layer has to be a higher ground than what it covers
previousClass = layerClass;
@@ -11774,6 +11965,295 @@ TEST(a_generated_lake_follows_the_valley)
CHECK( elongated > 0 );
}
+//-------------------------------------------------------------------------------------------------
+/** A base levelled beside a lake used to level the lake bed with it: the water polygon stayed where
+ the lake was carved and dry ground stood up through it, the start's height under the water's.
+ Seed 206 at two seats had over a hundred such cells, all in the ring round one base. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_base_beside_a_lake_leaves_the_lake_bed_under_the_water)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 206;
+ settings.m_numPlayers = 2;
+ settings.m_playableCells = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 2 );
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+ CHECK( !theRMGParse.m_waterPolygons.empty() );
+ if( theRMGParse.m_waterPolygons.empty() )
+ return;
+
+ // two cells inside the polygon every way: the bank itself slopes through the waterline
+ const Real waterZ = theRMGParse.m_waterPolygons[0][0].z;
+ const Real two = 2.0f * MAP_XY_FACTOR;
+ Int deep = 0, raised = 0;
+ for( Int y = theRMGParse.m_border; y < theRMGParse.m_height - theRMGParse.m_border; y++ )
+ {
+ for( Int x = theRMGParse.m_border; x < theRMGParse.m_width - theRMGParse.m_border; x++ )
+ {
+ Real worldX = (Real)(x - theRMGParse.m_border) * MAP_XY_FACTOR;
+ Real worldY = (Real)(y - theRMGParse.m_border) * MAP_XY_FACTOR;
+ if( !insideAWaterArea( worldX, worldY ) || !insideAWaterArea( worldX + two, worldY ) ||
+ !insideAWaterArea( worldX - two, worldY ) || !insideAWaterArea( worldX, worldY + two ) ||
+ !insideAWaterArea( worldX, worldY - two ) )
+ continue;
+ deep++;
+ if( (Real)theRMGParse.m_heights[y * theRMGParse.m_width + x] * MAP_HEIGHT_SCALE > waterZ )
+ raised++;
+ }
+ }
+ CHECK( deep > 0 );
+ CHECK_EQ( raised, 0 );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A style's bowl skips the soft floor the plain maps are eased onto, so its deepest pits went below
+ nought before the height was stored as a byte. That conversion is undefined; x64 wrapped -3 to 253
+ and left a field of cliff spikes in the pit, and another compiler or CPU may store something else
+ under the same map name. No stored height is ever 0 or 255, so either one is a wrapped pit. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_style_maps_deepest_pit_is_ground_not_a_wrapped_spike)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 11;
+ settings.m_numPlayers = 6;
+ settings.m_playableCells = 383;
+ settings.m_style = 1;
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ Int wrapped = 0;
+ for( size_t c = 0; c < theRMGParse.m_heights.size(); c++ )
+ {
+ if( theRMGParse.m_heights[c] == 0 || theRMGParse.m_heights[c] == 255 )
+ wrapped++;
+ }
+ CHECK( !theRMGParse.m_heights.empty() );
+ CHECK_EQ( wrapped, 0 );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Each seat places one contested dock, toward the next seat round the map, and it stands on the
+ placer's side as the crow flies. The four-way walk the docks were placed by, and the lowest
+ index winning a tie between two ring neighbours, gave seed 22 two contested docks by seat 0 and
+ none by seat 3. Counted as the crow flies, every seat is nearest its home dock and one other. */
+//-------------------------------------------------------------------------------------------------
+TEST(every_gap_between_two_seats_gets_one_contested_dock)
+{
+ CHECK( bootOnce() );
+
+ static const Int theMaps[][3] = { { 22, 4, 304 }, { 13, 3, 260 }, { 5, 4, 280 } };
+ for( Int s = 0; s < 3; s++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theMaps[s][0];
+ settings.m_numPlayers = theMaps[s][1];
+ settings.m_playableCells = theMaps[s][2];
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ const Int players = (Int)theRMGParse.m_waypointPositions.size();
+ CHECK_EQ( players, settings.m_numPlayers );
+ std::vector<Int> nearestTo( players, 0 );
+ for( Int k = 0; k < (Int)theRMGParse.m_objectNames.size(); k++ )
+ {
+ if( theRMGParse.m_objectNames[k].compare( "SupplyDock" ) != 0 )
+ continue;
+ // octile, as the pathfinder counts a straight run: a straight line can differ by a cell
+ Int best = 0;
+ Real bestDistance = 1.0e9f;
+ for( Int i = 0; i < players; i++ )
+ {
+ Real dx = fabsf( theRMGParse.m_objectPositions[k].x - theRMGParse.m_waypointPositions[i].x );
+ Real dy = fabsf( theRMGParse.m_objectPositions[k].y - theRMGParse.m_waypointPositions[i].y );
+ Real d = std::max( dx, dy ) + 0.4f * std::min( dx, dy );
+ if( d < bestDistance )
+ {
+ bestDistance = d;
+ best = i;
+ }
+ }
+ nearestTo[best]++;
+ }
+ for( Int i = 0; i < players; i++ )
+ {
+ if( nearestTo[i] != 2 )
+ printf( " seed %d: seat %d is nearest %d docks\n", settings.m_seed, i, nearestTo[i] );
+ CHECK_EQ( nearestTo[i], 2 );
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The woods used to be planted at every second cell in a solid grid: the chance a cell was taken
+ was read off eight bits of a hash as a per-mille, which never came to more than a quarter, so any
+ chance past that planted every cell. A wood thins towards its edge now, and a tree with six of its
+ eight neighbours on the planting grid taken - a third of the trees on seed 44 - is the exception. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_wood_is_planted_thick_and_thin_not_as_a_solid_grid)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 44;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 4 );
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ std::set< std::pair<Int, Int> > trees;
+ for( Int k = 0; k < (Int)theRMGParse.m_objectNames.size(); k++ )
+ {
+ if( !theRMGParse.m_objectNames[k].startsWith( "Tree" ) )
+ continue;
+ trees.insert( std::make_pair( (Int)floorf( theRMGParse.m_objectPositions[k].x / MAP_XY_FACTOR + 0.5f ),
+ (Int)floorf( theRMGParse.m_objectPositions[k].y / MAP_XY_FACTOR + 0.5f ) ) );
+ }
+ Int packed = 0;
+ for( std::set< std::pair<Int, Int> >::const_iterator it = trees.begin(); it != trees.end(); ++it )
+ {
+ Int neighbours = 0;
+ for( Int dy = -2; dy <= 2; dy += 2 )
+ {
+ for( Int dx = -2; dx <= 2; dx += 2 )
+ {
+ if( ( dx || dy ) && trees.count( std::make_pair( it->first + dx, it->second + dy ) ) )
+ neighbours++;
+ }
+ }
+ if( neighbours >= 6 )
+ packed++;
+ }
+ printf( " %d trees, %d with six of eight neighbours\n", (Int)trees.size(), packed );
+ CHECK( trees.size() > 200 );
+ CHECK( packed * 100 < (Int)trees.size() * 15 );
+
+ /* A black forest plants up to its tree count. Its chances were tuned against the old per-mille
+ test, which planted four times what they read as; read straight they left this map's woods at
+ 84% of the count and others at a third. 1520 is the count the map type, biome and seed give
+ (area / RMG_TREE_CELLS_EACH times the wooded share); about 22 trees a seat stand off the field. */
+ RandomMapSettings forest;
+ forest.m_seed = 27;
+ forest.m_numPlayers = 8;
+ forest.m_playableCells = 330;
+ std::vector<char> forestBytes;
+ RandomMapGenerator::generate( forest, forestBytes );
+ parseGeneratedMap( forestBytes );
+ Int forestTrees = 0;
+ for( Int k = 0; k < (Int)theRMGParse.m_objectNames.size(); k++ )
+ forestTrees += theRMGParse.m_objectNames[k].startsWith( "Tree" ) ? 1 : 0;
+ printf( " black forest: %d trees, %d off the field, against a count of 1520\n", forestTrees, forestTrees - 22 * 8 );
+ CHECK( ( forestTrees - 22 * 8 ) * 100 >= 1520 * 95 );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A river stretch cut off between a ford and the river's end, or between two fords, was left as a
+ square pond capping the line: seed 77 had one at each end of its river and seed 120 one between
+ two fords. The stretch goes dry with its ford now, so every water area on those maps is river. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_ford_takes_the_short_stretch_beside_it_rather_than_leave_a_pond)
+{
+ CHECK( bootOnce() );
+
+ static const Int theSeeds[] = { 77, 120 };
+ for( Int s = 0; s < 2; s++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theSeeds[s];
+ 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( !theRMGParse.m_waterPolygons.empty() );
+
+ // the stubs came out at 270 to 380 square cells; the shortest real stretch here is over 1500
+ for( Int area = 0; area < (Int)theRMGParse.m_waterPolygons.size(); area++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[area];
+ Real twice = 0.0f;
+ for( Int p = 0, last = (Int)polygon.size() - 1; p < (Int)polygon.size(); last = p++ )
+ twice += polygon[last].x * polygon[p].y - polygon[p].x * polygon[last].y;
+ Real cells = fabsf( twice ) * 0.5f / ( MAP_XY_FACTOR * MAP_XY_FACTOR );
+ if( cells < 800.0f )
+ printf( " seed %d: a water area of %.0f cells\n", settings.m_seed, cells );
+ CHECK( cells >= 800.0f );
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A town's radius is what keeps it off the map's edge, the money and the bases, and it used to be
+ half the longer side of the grid, so the corner plots stood past it: on a pile, a derrick, outside
+ the playable area. And a plan that found no room was never made smaller, so seed 122 at four seats
+ ended with no town at all though a small one had room. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_town_keeps_its_buildings_inside_its_own_clearance_and_always_finds_room)
+{
+ CHECK( bootOnce() );
+
+ // 122 had no town, 100 a building fourteen cells from a start, 126 one four cells from a derrick
+ static const Int theMaps[][3] = { { 122, 4, 304 }, { 100, 4, 304 }, { 126, 6, 240 } };
+ for( Int m = 0; m < 3; m++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theMaps[m][0];
+ settings.m_numPlayers = theMaps[m][1];
+ settings.m_playableCells = theMaps[m][2];
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ const Real edge = (Real)settings.m_playableCells * MAP_XY_FACTOR;
+ Int buildings = 0;
+ Real nearestStart = 1.0e9f, nearestMoney = 1.0e9f, nearestEdge = 1.0e9f;
+ for( Int k = 0; k < (Int)theRMGParse.m_objectNames.size(); k++ )
+ {
+ const AsciiString& name = theRMGParse.m_objectNames[k];
+ if( !name.startsWith( "Stan" ) && !name.startsWith( "Asian" ) && !name.startsWith( "CivilianHighrise" ) )
+ continue;
+ buildings++;
+ const Coord3D& at = theRMGParse.m_objectPositions[k];
+ nearestEdge = std::min( nearestEdge, std::min( std::min( at.x, at.y ), std::min( edge - at.x, edge - at.y ) ) );
+ for( Int i = 0; i < (Int)theRMGParse.m_waypointPositions.size(); i++ )
+ {
+ Real dx = at.x - theRMGParse.m_waypointPositions[i].x;
+ Real dy = at.y - theRMGParse.m_waypointPositions[i].y;
+ nearestStart = std::min( nearestStart, sqrtf( dx * dx + dy * dy ) );
+ }
+ for( Int j = 0; j < (Int)theRMGParse.m_objectNames.size(); j++ )
+ {
+ const AsciiString& money = theRMGParse.m_objectNames[j];
+ if( money.compare( "SupplyDock" ) != 0 && money.compare( "TechOilDerrick" ) != 0 &&
+ money.compare( "SupplyPileSmall" ) != 0 )
+ continue;
+ Real dx = at.x - theRMGParse.m_objectPositions[j].x;
+ Real dy = at.y - theRMGParse.m_objectPositions[j].y;
+ nearestMoney = std::min( nearestMoney, sqrtf( dx * dx + dy * dy ) );
+ }
+ }
+ printf( " seed %d: %d buildings, nearest a start %.1f, money %.1f, the edge %.1f cells\n", settings.m_seed,
+ buildings, nearestStart / MAP_XY_FACTOR, nearestMoney / MAP_XY_FACTOR, nearestEdge / MAP_XY_FACTOR );
+ CHECK( buildings > 0 );
+ CHECK( nearestStart >= 26.0f * MAP_XY_FACTOR ); // RMG_BLEND_RADIUS: out of every base's ring
+ CHECK( nearestMoney >= 4.0f * MAP_XY_FACTOR ); // RMG_PILE_CLEARANCE, the smallest money keeps
+ CHECK( nearestEdge >= 4.0f * MAP_XY_FACTOR );
+ }
+}
+
//-------------------------------------------------------------------------------------------------
/** Two towns on one map are two towns, not the same grid stamped twice. Each rolls its own street
count, block spacing and rotation out of the seed, so what says the towns are generated rather
@@ -12512,15 +12992,15 @@ TEST(the_generator_still_turns_a_seed_into_the_bytes_it_used_to)
{
CHECK( bootOnce() );
- CHECK_EQ( RANDOM_MAP_GENERATOR_VERSION, 17 );
+ CHECK_EQ( RANDOM_MAP_GENERATOR_VERSION, 18 );
struct RMGFingerprint { Int m_seed, m_players, m_cells, m_style; UnsignedInt m_crc; };
static const RMGFingerprint theFingerprints[] =
{
- { 0, 2, 64, 0, 0x47856863 },
- { 12345, 4, 96, 0, 0x2863C7F9 },
- { 7, 8, 128, 0, 0x357288D3 },
- { 7, 4, 200, 1, 0x100AD67B },
+ { 0, 2, 64, 0, 0x1BF70484 },
+ { 12345, 4, 96, 0, 0x114BBAEA },
+ { 7, 8, 128, 0, 0xFB27A0BB },
+ { 7, 4, 200, 1, 0x1F261D65 },
};
const Int numFingerprints = sizeof(theFingerprints) / sizeof(theFingerprints[0]);
@@ -12556,6 +13036,8 @@ TEST(the_generator_still_turns_a_seed_into_the_bytes_it_used_to)
UnsignedInt inADriversMode = RandomMapGenerator::fingerprint( settings );
_controlfp( entry, _MCW_PC | _MCW_RC );
+ if( inADriversMode != theFingerprints[0].m_crc )
+ printf( " in a driver's FPU mode the first is 0x%08X\n", inADriversMode );
CHECK( inADriversMode == theFingerprints[0].m_crc );
// and the caller's mode is handed back rather than left at the simulation's
@@ -12763,7 +13245,7 @@ TEST(a_template_map_comes_out_the_same_twice_and_every_start_walks_to_every_othe
RandomMapGenerator::generate( exemplarSettings, exemplar );
// the bytes themselves, pinned like the generator's: a change here is a change to every template map's name
- static const UnsignedInt theTemplateFingerprints[2] = { 0xF9D5107Cu, 0x4035FBF7u };
+ static const UnsignedInt theTemplateFingerprints[2] = { 0x26A63ABEu, 0x6D469E48u };
for( Int players = 2; players <= 8; players += 6 )
{
RandomMapSettings settings;
@@ -12824,63 +13306,1509 @@ TEST(a_template_map_comes_out_the_same_twice_and_every_start_walks_to_every_othe
CHECK_EQ( missing.m_templateCRC, 0u );
}
-//-------------------------------------------------------------------------------------------------
-/** Not a check: with RMG_TEMPLATE_DUMP set to "<dir> <exemplar.map> <seed>,<players>,<cells> ..." it
- synthesises each map from the exemplar (a .map taken out of the game's archive, packed or not) and
- writes it and its preview into dir, with the report and the time it took. RMG_TEMPLATE_CIVILIANS
- names a file of town building names, one a line, standing in for the object INI. Run as
- test_gameengine.exe write_the_maps_RMG_TEMPLATE_DUMP_names. */
-//-------------------------------------------------------------------------------------------------
-TEST(write_the_maps_RMG_TEMPLATE_DUMP_names)
-{
- const char *dump = getenv( "RMG_TEMPLATE_DUMP" );
- if( dump == NULL )
- return;
- CHECK( bootOnce() );
+struct RMGAddedObject { Real x, y; Int flags; const char *name; };
- const char *civilians = getenv( "RMG_TEMPLATE_CIVILIANS" );
- if( civilians )
+/// Objects appended to a raw map's ObjectsList, each with an empty dict, the chunk sizes grown to match.
+static Bool RMGAddObjects( std::vector<char>& map, const std::vector<RMGAddedObject>& added )
+{
+ if( map.size() < 8 || memcmp( &map[0], "CkMp", 4 ) != 0 )
+ return FALSE;
+ Int count, pos = 8;
+ memcpy( &count, &map[4], 4 );
+ UnsignedInt listId = 0, objectId = 0;
+ for( Int i = 0; i < count; i++ )
{
- std::vector<char> list;
- CHECK( readWholeFile( civilians, list ) );
- std::string all( list.begin(), list.end() );
- size_t from = 0;
- while( from < all.size() )
+ Int length = (UnsignedByte)map[pos];
+ std::string name( &map[pos + 1], length );
+ UnsignedInt id;
+ memcpy( &id, &map[pos + 1 + length], 4 );
+ pos += 1 + length + 4;
+ if( name == "ObjectsList" ) listId = id;
+ if( name == "Object" ) objectId = id;
+ }
+ while( pos + 10 <= (Int)map.size() )
+ {
+ UnsignedInt id;
+ Int size;
+ memcpy( &id, &map[pos], 4 );
+ memcpy( &size, &map[pos + 6], 4 );
+ if( id != listId )
{
- size_t end = all.find_first_of( "\r\n", from );
- if( end == std::string::npos ) end = all.size();
- if( end > from )
- theTestCivilians.push_back( AsciiString( all.substr( from, end - from ).c_str() ) );
- from = end + 1;
+ pos += 10 + size;
+ continue;
+ }
+ Short version;
+ memcpy( &version, &map[pos + 14], 2 ); // the first object's
+ std::vector<char> body;
+ for( size_t k = 0; k < added.size(); k++ )
+ {
+ std::vector<char> one( 16 + 4 + 2 + strlen( added[k].name ) + 2, 0 );
+ const Real at[4] = { added[k].x, added[k].y, 0.0f, 0.0f };
+ memcpy( &one[0], at, 16 );
+ memcpy( &one[16], &added[k].flags, 4 );
+ UnsignedShort nameLength = (UnsignedShort)strlen( added[k].name );
+ memcpy( &one[20], &nameLength, 2 );
+ memcpy( &one[22], added[k].name, nameLength );
+ char head[10];
+ Int oneSize = (Int)one.size();
+ memcpy( head, &objectId, 4 );
+ memcpy( head + 4, &version, 2 );
+ memcpy( head + 6, &oneSize, 4 );
+ body.insert( body.end(), head, head + 10 );
+ body.insert( body.end(), one.begin(), one.end() );
}
+ size += (Int)body.size();
+ memcpy( &map[pos + 6], &size, 4 );
+ map.insert( map.begin() + pos + 10 + size - (Int)body.size(), body.begin(), body.end() );
+ return TRUE;
}
+ return FALSE;
+}
- char dir[MAX_PATH], source[MAX_PATH];
- Int read = 0;
- CHECK( sscanf( dump, "%259s %259s%n", dir, source, &read ) == 2 );
- std::vector<char> exemplar;
- CHECK( readWholeFile( source, exemplar ) );
- const char *next = dump + read;
- // the pool the game starts, so the time is the one a player waits
- JobSystem::init();
- RandomMapSettings settings;
- while( sscanf( next, " %d,%d,%d%n", &settings.m_seed, &settings.m_numPlayers, &settings.m_playableCells, &read ) == 3 )
- {
- next += read;
- RandomMapGenerator::clampSettings( settings );
- std::vector<char> map, preview;
- RMGTemplateReport report;
- LARGE_INTEGER frequency, before, after;
- QueryPerformanceFrequency( &frequency );
- QueryPerformanceCounter( &before );
- Bool built = rmgSynthesise( settings, exemplar, civilians ? isListedCivilian : NULL, map, &preview, &report );
- QueryPerformanceCounter( &after );
- CHECK( built );
- if( !built )
- continue;
+/// A water area added to a raw map: corners in playable cells (x, y), its surface in height bytes.
+struct RMGAddedWater { std::vector<Coord2D> corners; Real surfaceBytes; };
- char name[MAX_PATH];
- snprintf( name, sizeof(name), "%s\\synth_%d_%dp_%dc", dir, settings.m_seed, settings.m_numPlayers, settings.m_playableCells );
+/** A generated map turned into another kind of exemplar, the one way a test has a sea or a river's
+ branch without the game's archives: reshape( heights, W, H, border ) changes the heights in place,
+ and the water areas are appended to PolygonTriggers, the chunk sizes grown to match. */
+template <class Reshape>
+static Bool RMGReshapeMap( std::vector<char>& map, Reshape reshape, const std::vector<RMGAddedWater>& water )
+{
+ if( map.size() < 8 || memcmp( &map[0], "CkMp", 4 ) != 0 )
+ return FALSE;
+ Int count, pos = 8;
+ memcpy( &count, &map[4], 4 );
+ UnsignedInt heightsId = 0, triggersId = 0;
+ for( Int i = 0; i < count; i++ )
+ {
+ Int length = (UnsignedByte)map[pos];
+ std::string name( &map[pos + 1], length );
+ UnsignedInt id;
+ memcpy( &id, &map[pos + 1 + length], 4 );
+ pos += 1 + length + 4;
+ if( name == "HeightMapData" ) heightsId = id;
+ if( name == "PolygonTriggers" ) triggersId = id;
+ }
+ Bool reshaped = FALSE, watered = water.empty();
+ while( pos + 10 <= (Int)map.size() )
+ {
+ UnsignedInt id;
+ Short version;
+ Int size;
+ memcpy( &id, &map[pos], 4 );
+ memcpy( &version, &map[pos + 4], 2 );
+ memcpy( &size, &map[pos + 6], 4 );
+ if( id == heightsId )
+ {
+ Int head[4];
+ memcpy( head, &map[pos + 10], sizeof(head) ); // width, height, border, boundaries
+ Int at = pos + 10 + 16 + 8 * head[3];
+ Int cells;
+ memcpy( &cells, &map[at], 4 );
+ std::vector<UnsignedByte> heights( (UnsignedByte *)&map[at + 4], (UnsignedByte *)&map[at + 4] + cells );
+ reshape( heights, head[0], head[1], head[2] );
+ memcpy( &map[at + 4], &heights[0], cells );
+ reshaped = TRUE;
+ }
+ else if( id == triggersId && !water.empty() )
+ {
+ std::vector<char> body;
+ auto putInt = [&]( Int v ) { body.insert( body.end(), (char *)&v, (char *)&v + 4 ); };
+ for( size_t k = 0; k < water.size(); k++ )
+ {
+ char name[32];
+ snprintf( name, sizeof(name), "TestWater%d", (Int)k + 1 );
+ UnsignedShort nameLength = (UnsignedShort)strlen( name ), none = 0;
+ body.insert( body.end(), (char *)&nameLength, (char *)&nameLength + 2 );
+ body.insert( body.end(), name, name + nameLength );
+ if( version >= 4 )
+ body.insert( body.end(), (char *)&none, (char *)&none + 2 );
+ putInt( 9000 + (Int)k );
+ if( version >= 2 )
+ body.push_back( 1 );
+ if( version >= 3 )
+ {
+ body.push_back( 0 );
+ putInt( 0 );
+ }
+ putInt( (Int)water[k].corners.size() );
+ for( size_t p = 0; p < water[k].corners.size(); p++ )
+ {
+ putInt( (Int)( water[k].corners[p].x * MAP_XY_FACTOR ) );
+ putInt( (Int)( water[k].corners[p].y * MAP_XY_FACTOR ) );
+ putInt( (Int)( water[k].surfaceBytes * MAP_HEIGHT_SCALE + 0.5f ) );
+ }
+ }
+ Int areas;
+ memcpy( &areas, &map[pos + 10], 4 );
+ areas += (Int)water.size();
+ memcpy( &map[pos + 10], &areas, 4 );
+ Int grown = size + (Int)body.size();
+ memcpy( &map[pos + 6], &grown, 4 );
+ map.insert( map.begin() + pos + 10 + size, body.begin(), body.end() );
+ size = grown;
+ watered = TRUE;
+ }
+ pos += 10 + size;
+ }
+ return reshaped && watered;
+}
+
+static Bool isTestRiverHouse( const char *name )
+{
+ return strcmp( name, "TestRiverHouse" ) == 0;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A town that stands on its river comes over as a crossing, the river's piece of the exemplar cut
+ down to fit. Heartland Shield's came over with a bridge whose end stood on the cut's fading edge,
+ where the generated riverbed shows through, so the deck dived into the water; and the houses the
+ cut left were gone without a word. The exemplar is a generated river map with a town and a
+ bridge laid across its river, the one way a test has a river town without the game's archives. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_river_town_crossing_keeps_its_bridge_ends_dry_and_says_what_it_left)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings exemplarSettings;
+ exemplarSettings.m_seed = 2;
+ exemplarSettings.m_numPlayers = 4;
+ exemplarSettings.m_playableCells = 304;
+ RandomMapGenerator::clampSettings( exemplarSettings );
+ std::vector<char> exemplar;
+ RandomMapGenerator::generate( exemplarSettings, exemplar );
+ parseGeneratedMap( exemplar );
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ auto wetAt = [&]( Int x, Int y ) -> Bool
+ {
+ return insideAWaterArea( (Real)( x - B ) * MAP_XY_FACTOR, (Real)( y - B ) * MAP_XY_FACTOR );
+ };
+
+ // the run of river across a row or a column nearest the middle with dry banks either side: the
+ // bridge's place; the rest of the test works in that row or column's frame, u across, v along
+ Int siteV = -1, siteU0 = 0, siteU1 = 0, siteAxis = 0;
+ Real nearest = 1.0e9f;
+ for( Int axis = 0; axis < 2; axis++ )
+ {
+ auto wet = [&]( Int u, Int v ) -> Bool { return axis ? wetAt( v, u ) : wetAt( u, v ); };
+ for( Int v = B + 40; v < H - B - 40; v += 2 )
+ {
+ Int run = -1;
+ for( Int u = B + 30; u < W - B - 30; u++ )
+ {
+ Bool here = wet( u, v );
+ if( here && run < 0 ) run = u;
+ if( here || run < 0 ) continue;
+ Int length = u - run;
+ Bool banks = length >= 6 && length <= 24;
+ for( Int d = 1; d <= 20 && banks; d++ )
+ banks = !wet( run - d, v ) && !wet( u - 1 + d, v );
+ Real centre = hypotf( (Real)( v - H / 2 ), (Real)( run + length / 2 - W / 2 ) );
+ if( banks && centre < nearest )
+ {
+ nearest = centre;
+ siteV = v; siteU0 = run; siteU1 = u; siteAxis = axis;
+ }
+ run = -1;
+ }
+ }
+ }
+ CHECK( siteV >= 0 );
+ if( siteV < 0 )
+ return;
+ auto wetUV = [&]( Int u, Int v ) -> Bool { return siteAxis ? wetAt( v, u ) : wetAt( u, v ); };
+ auto worldUV = [&]( Int u, Int v, Int flags, const char *name ) -> RMGAddedObject
+ {
+ RMGAddedObject o = { (Real)( ( siteAxis ? v : u ) - B ) * MAP_XY_FACTOR, (Real)( ( siteAxis ? u : v ) - B ) * MAP_XY_FACTOR, flags, name };
+ return o;
+ };
+
+ // a bridge across it and a town of houses on both banks round the bridge
+ std::vector<RMGAddedObject> added;
+ const Int TOWN_HALF = 24, HOUSE_STEP = 6;
+ Int houses = 0;
+ const Int siteU = ( siteU0 + siteU1 ) / 2, halfRiver = ( siteU1 - siteU0 ) / 2;
+ for( Int dv = -TOWN_HALF; dv <= TOWN_HALF; dv += HOUSE_STEP )
+ for( Int du = -TOWN_HALF - halfRiver; du <= TOWN_HALF + halfRiver; du += HOUSE_STEP )
+ {
+ Bool dry = TRUE;
+ for( Int nv = -3; nv <= 3 && dry; nv++ )
+ for( Int nu = -3; nu <= 3 && dry; nu++ )
+ dry = !wetUV( siteU + du + nu, siteV + dv + nv );
+ if( !dry || ( dv == 0 && abs( du ) < halfRiver + 6 ) )
+ continue;
+ added.push_back( worldUV( siteU + du, siteV + dv, 0, "TestRiverHouse" ) );
+ houses++;
+ }
+ added.push_back( worldUV( siteU0 - 3, siteV, FLAG_BRIDGE_POINT1, "TestRiverBridge" ) );
+ added.push_back( worldUV( siteU1 + 2, siteV, FLAG_BRIDGE_POINT2, "TestRiverBridge" ) );
+ CHECK( RMGAddObjects( exemplar, added ) );
+
+ Int crossings = 0;
+ for( Int trial = 0; trial < 2; trial++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = trial ? 6 : 7;
+ settings.m_numPlayers = 2;
+ settings.m_playableCells = trial ? 256 : 208;
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, isTestRiverHouse, map, NULL, &report ) );
+ if( map.empty() )
+ continue;
+ parseGeneratedMap( map );
+ const Int w = theRMGParse.m_width, b = theRMGParse.m_border;
+
+ Int carried = 0, bridgeEnds = 0;
+ for( Int i = 0; i < theRMGParse.m_numObjects; i++ )
+ {
+ if( theRMGParse.m_objectNames[i] == "TestRiverHouse" )
+ carried++;
+ if( theRMGParse.m_objectNames[i] == "TestRiverBridge" )
+ bridgeEnds++;
+ if( !( theRMGParse.m_objectFlags[i] & FLAG_BRIDGE_FLAGS ) )
+ continue;
+ // a bridge end stands above every water polygon round it
+ const Coord3D& end = theRMGParse.m_objectPositions[i];
+ Int cx = (Int)( end.x / MAP_XY_FACTOR + 0.5f ) + b, cy = (Int)( end.y / MAP_XY_FACTOR + 0.5f ) + b;
+ Real ground = theRMGParse.m_heights[cy * w + cx] * MAP_HEIGHT_SCALE;
+ for( size_t area = 0; area < theRMGParse.m_waterPolygons.size(); area++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[area];
+ Bool inside = FALSE;
+ for( size_t p = 0, last = polygon.size() - 1; p < polygon.size(); last = p++ )
+ if( ( polygon[p].y > end.y ) != ( polygon[last].y > end.y ) &&
+ end.x < polygon[p].x + ( end.y - polygon[p].y ) * ( polygon[last].x - polygon[p].x ) / ( polygon[last].y - polygon[p].y ) )
+ inside = !inside;
+ if( inside && ground < polygon[0].z )
+ printf( " seed %d: %s end at (%d, %d) %.1f under the water at %.1f\n", settings.m_seed,
+ theRMGParse.m_objectNames[i].str(), cx, cy, ground, polygon[0].z );
+ CHECK( !inside || ground >= polygon[0].z );
+ }
+ }
+ crossings += carried > 0;
+ /* The crossing keeps its bridge however small a cut of it fitted: a cut too small to hold it
+ grows over it, rather than hand it back to a river with no room left for it. */
+ if( carried > 0 && bridgeEnds < 2 )
+ printf( " seed %d: crossing laid with %d bridge ends, notes:\n%s", settings.m_seed, bridgeEnds, report.m_notes.str() );
+ CHECK( carried == 0 || bridgeEnds >= 2 );
+ // a town the crossing cut short is in the notes with what it carried
+ if( carried > 0 && carried < houses )
+ {
+ if( strstr( report.m_notes.str(), "on the crossing)" ) == NULL )
+ printf( " seed %d: %d of %d houses on the crossing, notes:\n%s", settings.m_seed, carried, houses, report.m_notes.str() );
+ CHECK( strstr( report.m_notes.str(), "on the crossing)" ) != NULL );
+ }
+ }
+ // the test is about a crossing: one was laid
+ CHECK( crossings > 0 );
+}
+
+/// The generated exemplar the sea tests reshape: seed 31's four seats, its starts and money in grid cells.
+static void RMGSeaExemplar( std::vector<char>& exemplar, std::vector<Coord2D>& starts, std::vector<Coord2D>& money )
+{
+ RandomMapSettings exemplarSettings;
+ exemplarSettings.m_seed = 31;
+ exemplarSettings.m_numPlayers = 4;
+ exemplarSettings.m_style = 1;
+ RandomMapGenerator::clampSettings( exemplarSettings );
+ RandomMapGenerator::generate( exemplarSettings, exemplar );
+ parseGeneratedMap( exemplar );
+ starts.clear();
+ money.clear();
+ for( size_t i = 0; i < theRMGParse.m_waypointNames.size(); i++ )
+ if( theRMGParse.m_waypointNames[i].startsWith( "Player_" ) )
+ {
+ Coord2D p = { theRMGParse.m_waypointPositions[i].x / MAP_XY_FACTOR, theRMGParse.m_waypointPositions[i].y / MAP_XY_FACTOR };
+ starts.push_back( p );
+ }
+ for( Int i = 0; i < theRMGParse.m_numObjects; i++ )
+ if( strstr( theRMGParse.m_objectNames[i].str(), "SupplyDock" ) || theRMGParse.m_objectNames[i] == "TechOilDerrick" )
+ {
+ Coord2D p = { theRMGParse.m_objectPositions[i].x / MAP_XY_FACTOR, theRMGParse.m_objectPositions[i].y / MAP_XY_FACTOR };
+ money.push_back( p );
+ }
+}
+
+/** The parsed map's sea, the water area with the widest box: its surface in bytes, the share of play
+ under any water, and of the land the share standing 0-3 bytes over the sea. */
+static Real RMGSeaShare( Real *surfaceBytes, Real *lowLandShare )
+{
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ Real surface = -1.0f, widest = -1.0f;
+ for( size_t a = 0; a < theRMGParse.m_waterPolygons.size(); a++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[a];
+ Real x0 = 1.0e9f, x1 = -1.0e9f, y0 = 1.0e9f, y1 = -1.0e9f;
+ for( size_t p = 0; p < polygon.size(); p++ )
+ {
+ x0 = std::min( x0, polygon[p].x ); x1 = std::max( x1, polygon[p].x );
+ y0 = std::min( y0, polygon[p].y ); y1 = std::max( y1, polygon[p].y );
+ }
+ if( ( x1 - x0 ) * ( y1 - y0 ) > widest )
+ {
+ widest = ( x1 - x0 ) * ( y1 - y0 );
+ surface = polygon[0].z / MAP_HEIGHT_SCALE;
+ }
+ }
+ Int play = 0, wet = 0, land = 0, low = 0;
+ for( Int y = B; y < H - B; y++ )
+ for( Int x = B; x < W - B; x++ )
+ {
+ play++;
+ const Real wx = (Real)( x - B ) * MAP_XY_FACTOR, wy = (Real)( y - B ) * MAP_XY_FACTOR;
+ Bool under = FALSE;
+ for( size_t a = 0; a < theRMGParse.m_waterPolygons.size() && !under; a++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[a];
+ Bool inside = FALSE;
+ for( size_t p = 0, last = polygon.size() - 1; p < polygon.size(); last = p++ )
+ if( ( polygon[p].y > wy ) != ( polygon[last].y > wy ) &&
+ wx < polygon[p].x + ( wy - polygon[p].y ) * ( polygon[last].x - polygon[p].x ) / ( polygon[last].y - polygon[p].y ) )
+ inside = !inside;
+ under = inside && theRMGParse.m_heights[y * W + x] * MAP_HEIGHT_SCALE < polygon[0].z;
+ }
+ if( under ) { wet++; continue; }
+ land++;
+ Real over = theRMGParse.m_heights[y * W + x] - surface;
+ low += over >= 0.0f && over <= 3.0f;
+ }
+ *surfaceBytes = surface;
+ *lowLandShare = land ? (Real)low / land : 0.0f;
+ return play ? (Real)wet / play : 0.0f;
+}
+
+//-------------------------------------------------------------------------------------------------
+/** An island exemplar, Tournament Island's kind: land round each start, its money and the middle,
+ a causeway from each start in, sea bed everywhere else. Its template maps put a dock out of reach
+ in the sea, sat the coast a byte or two over the water, and lost a third of the sea once the
+ players filled the seats on a small map. The exemplar is the generated Twilight-style one with
+ its ground cut down to that shape. */
+//-------------------------------------------------------------------------------------------------
+TEST(an_island_template_keeps_its_money_on_land_its_coast_over_the_water_and_its_sea)
+{
+ CHECK( bootOnce() );
+
+ std::vector<char> exemplar;
+ std::vector<Coord2D> starts, money;
+ RMGSeaExemplar( exemplar, starts, money );
+ const Real SEA_SURFACE = 16.0f;
+ const Int playable = theRMGParse.m_boundaryX;
+ Coord2D middle = { playable * 0.5f, theRMGParse.m_boundaryY * 0.5f };
+ auto island = [&]( std::vector<UnsignedByte>& h, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ Real px = (Real)( x - border ), py = (Real)( y - border );
+ Bool land = hypotf( px - middle.x, py - middle.y ) < 0.15f * playable;
+ for( size_t s = 0; s < starts.size(); s++ )
+ {
+ land = land || hypotf( px - starts[s].x, py - starts[s].y ) < 0.18f * playable;
+ // a causeway in: the start to middle segment, eight cells wide
+ Real dx = middle.x - starts[s].x, dy = middle.y - starts[s].y;
+ Real t = std::max( 0.0f, std::min( 1.0f, ( ( px - starts[s].x ) * dx + ( py - starts[s].y ) * dy ) / ( dx * dx + dy * dy ) ) );
+ land = land || hypotf( px - starts[s].x - t * dx, py - starts[s].y - t * dy ) < 4.0f;
+ }
+ for( size_t m = 0; m < money.size(); m++ )
+ land = land || hypotf( px - money[m].x, py - money[m].y ) < 14.0f;
+ UnsignedByte& cell = h[y * W + x];
+ cell = land ? (UnsignedByte)( SEA_SURFACE + 8.0f + cell / 16 ) : 0;
+ }
+ };
+ std::vector<RMGAddedWater> water( 1 );
+ const Real outer = (Real)( playable + 40 );
+ Coord2D box[4] = { { -40.0f, -40.0f }, { outer, -40.0f }, { outer, outer }, { -40.0f, outer } };
+ water[0].corners.assign( box, box + 4 );
+ water[0].surfaceBytes = SEA_SURFACE;
+ CHECK( RMGReshapeMap( exemplar, island, water ) );
+ parseGeneratedMap( exemplar );
+ Real exemplarSurface, exemplarLow;
+ Real exemplarShare = RMGSeaShare( &exemplarSurface, &exemplarLow );
+
+ static const Int theCells[] = { 204, 304 };
+ for( Int k = 0; k < 2; k++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = 405;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = theCells[k];
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ continue;
+ parseGeneratedMap( map );
+ Real surface, low;
+ Real share = RMGSeaShare( &surface, &low );
+ if( report.m_cutOffStarts || report.m_cutOffSites || low > 0.1f || share < 0.2f )
+ printf( " %d cells: sea %.2f (exemplar %.2f) at %.1f, land 0-3 bytes over it %.2f (exemplar %.2f), cut off %d starts %d sites\n%s",
+ theCells[k], share, exemplarShare, surface, low, exemplarLow, report.m_cutOffStarts, report.m_cutOffSites, report.m_notes.str() );
+ // a dock far from the middle and from its start had only its own disc of land: 1 cut off at 304
+ CHECK_EQ( report.m_cutOffStarts, 0 );
+ CHECK_EQ( report.m_cutOffSites, 0 );
+ // the sea set from a bowl half sea bed: 13% of the land 0-3 bytes over it at 204, the exemplar's none
+ CHECK( low <= 0.1f );
+ // the land floors in cells, not shares: 17% sea at 204 against the exemplar's half
+ CHECK( share >= 0.2f );
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A coast exemplar, Bombardment Beach's kind: sea along one edge. The skeleton puts a start near
+ every edge, and a coast stopped short of the nearest guarded cell anywhere along it came out as
+ no sea at all at four players. The coast bends round the sites instead. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_coast_template_lays_its_sea_whatever_edge_the_starts_stand_near)
+{
+ CHECK( bootOnce() );
+
+ std::vector<char> exemplar;
+ std::vector<Coord2D> starts, money;
+ RMGSeaExemplar( exemplar, starts, money );
+ const Real SEA_SURFACE = 16.0f;
+ const Int playable = theRMGParse.m_boundaryX;
+ const Real coast = 0.12f * playable;
+ auto beach = [&]( std::vector<UnsignedByte>& h, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ UnsignedByte& cell = h[y * W + x];
+ cell = x - border < coast ? 0 : (UnsignedByte)( SEA_SURFACE + 8.0f + cell / 16 );
+ }
+ };
+ std::vector<RMGAddedWater> water( 1 );
+ const Real outer = (Real)( playable + 40 );
+ Coord2D box[4] = { { -40.0f, -40.0f }, { coast + 3.0f, -40.0f }, { coast + 3.0f, outer }, { -40.0f, outer } };
+ water[0].corners.assign( box, box + 4 );
+ water[0].surfaceBytes = SEA_SURFACE;
+ CHECK( RMGReshapeMap( exemplar, beach, water ) );
+ parseGeneratedMap( exemplar );
+ Real surface, low;
+ Real exemplarShare = RMGSeaShare( &surface, &low );
+
+ RandomMapSettings settings;
+ settings.m_seed = 6;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = 304;
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ return;
+ parseGeneratedMap( map );
+ Real share = RMGSeaShare( &surface, &low );
+ if( share < 0.8f * exemplarShare || report.m_cutOffStarts || report.m_cutOffSites )
+ printf( " sea %.2f against the exemplar's %.2f, cut off %d starts %d sites\n%s", share, exemplarShare,
+ report.m_cutOffStarts, report.m_cutOffSites, report.m_notes.str() );
+ CHECK( strstr( report.m_notes.str(), "no coast clear" ) == NULL );
+ CHECK( share >= 0.8f * exemplarShare );
+ CHECK_EQ( report.m_cutOffStarts, 0 );
+ CHECK_EQ( report.m_cutOffSites, 0 );
+}
+
+/** A raw map's tiles repainted: paint( tiles, W, H, border ) changes BlendTileData's tile a cell in
+ place, W, H and border the map's own. The template reads a cell's texture class off its tile alone. */
+template <class Paint>
+static Bool RMGPaintTiles( std::vector<char>& map, Int W, Int H, Int border, Paint paint )
+{
+ if( map.size() < 8 || memcmp( &map[0], "CkMp", 4 ) != 0 )
+ return FALSE;
+ Int count, pos = 8;
+ memcpy( &count, &map[4], 4 );
+ UnsignedInt blendId = 0;
+ for( Int i = 0; i < count; i++ )
+ {
+ Int length = (UnsignedByte)map[pos];
+ std::string name( &map[pos + 1], length );
+ UnsignedInt id;
+ memcpy( &id, &map[pos + 1 + length], 4 );
+ pos += 1 + length + 4;
+ if( name == "BlendTileData" ) blendId = id;
+ }
+ while( pos + 10 <= (Int)map.size() )
+ {
+ UnsignedInt id;
+ Int size;
+ memcpy( &id, &map[pos], 4 );
+ memcpy( &size, &map[pos + 6], 4 );
+ if( id == blendId )
+ {
+ Int cells;
+ memcpy( &cells, &map[pos + 10], 4 );
+ if( cells != W * H )
+ return FALSE;
+ std::vector<Short> tiles( cells );
+ memcpy( &tiles[0], &map[pos + 14], cells * sizeof(Short) );
+ paint( tiles, W, H, border );
+ memcpy( &map[pos + 14], &tiles[0], cells * sizeof(Short) );
+ return TRUE;
+ }
+ pos += 10 + size;
+ }
+ return FALSE;
+}
+
+/// The parsed map's texture class name at a cell, by its tile.
+static const AsciiString& RMGClassAt( Int cell )
+{
+ Int tile = theRMGParse.m_tiles[cell] >> 2, best = 0;
+ for( Int c = 0; c < (Int)theRMGParse.m_firstTiles.size(); c++ )
+ if( theRMGParse.m_firstTiles[c] <= tile && theRMGParse.m_firstTiles[c] >= theRMGParse.m_firstTiles[best] )
+ best = c;
+ return theRMGParse.m_textureNames[best];
+}
+
+/// The parsed map's cells under a water area's plane, a byte a cell.
+static void RMGWetCells( std::vector<UnsignedByte>& wet )
+{
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ wet.assign( W * H, 0 );
+ for( Int y = B; y < H - B; y++ )
+ for( Int x = B; x < W - B; x++ )
+ {
+ const Real wx = (Real)( x - B ) * MAP_XY_FACTOR, wy = (Real)( y - B ) * MAP_XY_FACTOR;
+ for( size_t a = 0; a < theRMGParse.m_waterPolygons.size() && !wet[y * W + x]; a++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[a];
+ Bool inside = FALSE;
+ for( size_t p = 0, last = polygon.size() - 1; p < polygon.size(); last = p++ )
+ if( ( polygon[p].y > wy ) != ( polygon[last].y > wy ) &&
+ wx < polygon[p].x + ( wy - polygon[p].y ) * ( polygon[last].x - polygon[p].x ) / ( polygon[last].y - polygon[p].y ) )
+ inside = !inside;
+ wet[y * W + x] = inside && theRMGParse.m_heights[y * W + x] * MAP_HEIGHT_SCALE < polygon[0].z;
+ }
+ }
+}
+
+/** What the parsed map draws badly in its playable area: the class edges between two cells that
+ neither cell blends across (no layer of the other's class on a corner they share, read as
+ getAlphaUVData reads it), the steep cells painted with no cliff texture, and how many steep cells
+ there are. */
+static void RMGTextureFaults( Int *edges, Int *hard, Int *steep, Int *steepOpen )
+{
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ std::vector<Int> cls( W * H ), cover[2], coverClass[2];
+ for( Int i = 0; i < W * H; i++ )
+ cls[i] = RMGClassOfTile( theRMGParse.m_tiles[i] );
+ for( Int l = 0; l < 2; l++ )
+ {
+ cover[l].assign( W * H, 0 );
+ coverClass[l].assign( W * H, -1 );
+ const std::vector<Short>& index = l == 0 ? theRMGParse.m_blendIndexes : theRMGParse.m_extraBlendIndexes;
+ for( Int i = 0; i < W * H; i++ )
+ {
+ if( index[i] <= 0 || index[i] > (Int)theRMGParse.m_blends.size() )
+ continue;
+ const RMGBlendEntry& entry = theRMGParse.m_blends[index[i] - 1];
+ Bool alpha[4], flip;
+ RMGBlendCorners( entry, alpha, &flip );
+ for( Int c = 0; c < 4; c++ )
+ cover[l][i] |= alpha[c] ? 1 << c : 0;
+ coverClass[l][i] = RMGClassOfTile( entry.m_blendTileIndex );
+ }
+ }
+ // the corners of a cell a class covers
+ auto covers = [&]( Int i, Int k ) -> Int
+ {
+ return ( coverClass[0][i] == k ? cover[0][i] : 0 ) | ( coverClass[1][i] == k ? cover[1][i] : 0 );
+ };
+ *edges = *hard = *steep = *steepOpen = 0;
+ for( Int y = B; y < H - B - 1; y++ )
+ {
+ for( Int x = B; x < W - B - 1; x++ )
+ {
+ const Int i = y * W + x;
+ // east: this cell's corners 1 and 2 against its neighbour's 0 and 3; south: 2 and 3 against 1 and 0
+ const Int next[2] = { i + 1, i + W }, mine[2] = { 0x6, 0xC }, theirs[2] = { 0x9, 0x3 };
+ for( Int d = 0; d < 2; d++ )
+ {
+ const Int n = next[d];
+ if( cls[n] == cls[i] )
+ continue;
+ ( *edges )++;
+ if( !( covers( i, cls[n] ) & mine[d] ) && !( covers( n, cls[i] ) & theirs[d] ) )
+ ( *hard )++;
+ }
+ const Int a = theRMGParse.m_heights[i], b = theRMGParse.m_heights[i + 1];
+ const Int c = theRMGParse.m_heights[i + W], e = theRMGParse.m_heights[i + W + 1];
+ const Int span = std::max( std::max( a, b ), std::max( c, e ) ) - std::min( std::min( a, b ), std::min( c, e ) );
+ if( span * MAP_HEIGHT_SCALE > 9.8f ) // a cliff, WorldHeightMapData::initCliffFlagsFromHeights
+ {
+ ( *steep )++;
+ AsciiString name = theRMGParse.m_textureNames[cls[i]];
+ name.toLower();
+ if( strstr( name.str(), "cliff" ) == NULL )
+ ( *steepOpen )++;
+ }
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A template map's texture comes cell by cell from the exemplar, and each cell's blends were drawn
+ for the exemplar's neighbours. Where the quilt, a pad's rim or a town stamp put a cell beside ground
+ from somewhere else, the copied blend pointed at a neighbour that was gone and the new neighbour got
+ none: Heartland Shield's 4-player map had 16.4% of its class edges cut hard against 5.9% on the
+ shipped map, Twilight Flame's 8-player 16.6% against 2.6%. And a cell the heights made a cliff
+ kept the flat ground it was copied from: 61% of Twilight's steep cells were dirt, sand or grass
+ against the exemplar's 14%. The exemplar is the generated Twilight-style one, its blends whole. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_maps_texture_edges_are_blended_and_its_cliffs_are_rock)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings exemplarSettings;
+ exemplarSettings.m_seed = 31;
+ exemplarSettings.m_numPlayers = 4;
+ exemplarSettings.m_style = 1;
+ RandomMapGenerator::clampSettings( exemplarSettings );
+ std::vector<char> exemplar;
+ RandomMapGenerator::generate( exemplarSettings, exemplar );
+ parseGeneratedMap( exemplar );
+ Int edges0, hard0, steep0, steepOpen0;
+ RMGTextureFaults( &edges0, &hard0, &steep0, &steepOpen0 );
+
+ RandomMapSettings settings;
+ settings.m_seed = 904;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 4 );
+ std::vector<char> map;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, NULL ) );
+ if( map.empty() )
+ return;
+ parseGeneratedMap( map );
+ CHECK( theRMGParse.m_numBlendedTiles <= 16192 ); // NUM_BLEND_TILES
+ Int edges, hard, steep, steepOpen;
+ RMGTextureFaults( &edges, &hard, &steep, &steepOpen );
+ // copied blends alone: 1347 of 11646 edges hard and 3053 of 6520 steep cells dirt or sand; worked out again, 2 and 0
+ if( hard * 50 > edges || steepOpen * 10 > steep )
+ {
+ printf( " exemplar: %d of %d class edges hard, %d of %d steep cells not cliff\n", hard0, edges0, steepOpen0, steep0 );
+ printf( " template: %d of %d class edges hard, %d of %d steep cells not cliff\n", hard, edges, steepOpen, steep );
+ }
+ CHECK( edges > 0 && steep > 0 );
+ CHECK( hard * 50 <= edges );
+ CHECK( steepOpen * 10 <= steep );
+
+ // and its rock faces carry a cliff mapping the reader can use (rmgCliffMapping): the template
+ // wrote every index 0 and declared one entry
+ const RMGCliffCensus census = RMGCliffCount();
+ CHECK( census.mapped * 4 > steep );
+ CHECK_EQ( census.badIndexes, 0 );
+ CHECK_EQ( census.foreignEntries, 0 );
+ CHECK_EQ( census.outsideSheet, 0 );
+ CHECK_EQ( theRMGParse.m_blendBytesLeftOver, 0 );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The quilt copies ground by its height alone, so it put what the exemplar has only in one place
+ anywhere else. Bombardment Beach's sea bed came out 57% base dirt, Heartland Shield's bank sand
+ lay in columns 25 cells from any water, its road strips (worn grass, red dirt) ran through open
+ fields with no road on them, and Bombardment's flat start pads, the flattest ground there is and
+ so the best fit for a flat map, were tiled over 43% of it against 12% on the template. The
+ exemplar is the coast one with its relief kept low, its bases levelled and its sea bed, its bank,
+ its start discs and its roads each painted a class of their own, so a class out of place shows. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_quilts_sea_bed_banks_road_strips_and_bases_only_where_they_belong)
+{
+ CHECK( bootOnce() );
+
+ std::vector<char> coastMap;
+ std::vector<Coord2D> starts, money;
+ RMGSeaExemplar( coastMap, starts, money );
+ CHECK_EQ( (Int)starts.size(), 4 );
+ if( starts.size() != 4 || theRMGParse.m_textureNames.size() < 4 )
+ return;
+ // PAD_OUTER_CELLS: a pad's reach on open ground and its fade, past which its ground is the quilt's
+ const Real SEA_SURFACE = 16.0f, SEA_BED = 12.0f, BASE_LEVEL = 30.0f, BASE_DISC = 20.0f, PAD_OUTER_CELLS = 50.0f;
+ const Int BANK_CELLS = 5;
+ const Int playable = theRMGParse.m_boundaryX;
+ const Int exemplarW = theRMGParse.m_width, exemplarH = theRMGParse.m_height, exemplarBorder = theRMGParse.m_border;
+ // wider than a patch, so a patch can be all sea, and short of the starts
+ const Real coast = 0.14f * playable;
+ auto nearStart = [&]( Real px, Real py ) -> Bool
+ {
+ for( size_t s = 0; s < starts.size(); s++ )
+ if( hypotf( px - starts[s].x, py - starts[s].y ) <= BASE_DISC )
+ return TRUE;
+ return FALSE;
+ };
+ // low rolling land, a shallow sea bed and every base levelled: Bombardment's start pads at the map's
+ // median, the one ground as flat as a flat map
+ auto beach = [&]( std::vector<UnsignedByte>& h, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ Real px = (Real)( x - border ), py = (Real)( y - border );
+ UnsignedByte& cell = h[y * W + x];
+ Real roll = 6.0f * sinf( px / 5.0f ) * cosf( py / 5.0f );
+ cell = px < coast ? (UnsignedByte)SEA_BED : nearStart( px, py ) ? (UnsignedByte)BASE_LEVEL : (UnsignedByte)( 22.0f + cell / 8 + roll );
+ }
+ };
+ std::vector<RMGAddedWater> water( 1 );
+ const Real outer = (Real)( playable + 40 );
+ Coord2D box[4] = { { -40.0f, -40.0f }, { coast + 3.0f, -40.0f }, { coast + 3.0f, outer }, { -40.0f, outer } };
+ water[0].corners.assign( box, box + 4 );
+ water[0].surfaceBytes = SEA_SURFACE;
+ CHECK( RMGReshapeMap( coastMap, beach, water ) );
+ std::vector<AsciiString> names( theRMGParse.m_textureNames.begin(), theRMGParse.m_textureNames.begin() + 4 );
+ std::vector<Int> firstTiles( theRMGParse.m_firstTiles.begin(), theRMGParse.m_firstTiles.begin() + 4 );
+ enum { PLAIN, SEA, BANK, BASE };
+ // the parsed map's pads are copies of the exemplar's bases, whatever ground they hold: the quilt's is the rest
+ auto onAPad = [&]( Int px, Int py ) -> Bool
+ {
+ for( size_t i = 0; i < theRMGParse.m_waypointNames.size(); i++ )
+ if( theRMGParse.m_waypointNames[i].startsWith( "Player_" ) &&
+ hypotf( px - theRMGParse.m_waypointPositions[i].x / MAP_XY_FACTOR, py - theRMGParse.m_waypointPositions[i].y / MAP_XY_FACTOR ) <= PAD_OUTER_CELLS )
+ return TRUE;
+ return FALSE;
+ };
+
+ // one: the sea bed, the bank beside it and the start discs
+ {
+ std::vector<char> exemplar = coastMap;
+ auto paint = [&]( std::vector<Short>& tiles, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ Real px = (Real)( x - border ), py = (Real)( y - border );
+ Int c = px < coast ? SEA : px < coast + BANK_CELLS ? BANK : nearStart( px, py ) ? BASE : PLAIN;
+ tiles[y * W + x] = (Short)( firstTiles[c] << 2 );
+ }
+ };
+ CHECK( RMGPaintTiles( exemplar, exemplarW, exemplarH, exemplarBorder, paint ) );
+
+ RandomMapSettings settings;
+ settings.m_seed = 6;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = 304;
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ return;
+ parseGeneratedMap( map );
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ std::vector<UnsignedByte> wet;
+ RMGWetCells( wet );
+ Int wetCells = 0, wetSea = 0, bankCells = 0, bankFar = 0, play = 0, baseFar = 0;
+ for( Int y = B; y < H - B; y++ )
+ for( Int x = B; x < W - B; x++ )
+ {
+ const Int i = y * W + x;
+ const AsciiString& name = RMGClassAt( i );
+ play++;
+ if( onAPad( x - B, y - B ) )
+ continue;
+ if( wet[i] )
+ {
+ wetCells++;
+ wetSea += name == names[SEA];
+ }
+ if( name == names[BANK] )
+ {
+ bankCells++;
+ Bool byWater = FALSE;
+ for( Int yy = std::max( y - 6, 0 ); yy <= std::min( y + 6, H - 1 ) && !byWater; yy++ )
+ for( Int xx = std::max( x - 6, 0 ); xx <= std::min( x + 6, W - 1 ) && !byWater; xx++ )
+ byWater = wet[yy * W + xx] != 0;
+ bankFar += !byWater;
+ }
+ baseFar += name == names[BASE];
+ }
+ printf( " off the pads: sea bed %d of %d wet cells, bank %d of %d cells more than 6 off the water, base ground %d of %d cells\n",
+ wetSea, wetCells, bankFar, bankCells, baseFar, play );
+ CHECK( wetCells > 0 );
+ // the sea takes the exemplar's sea bed, not whatever land matched its height: 67% before, 84% since
+ CHECK( wetSea * 4 >= wetCells * 3 );
+ // a bank stays by the water: 15% of it more than 6 cells off before, 6% since
+ CHECK( bankFar * 10 <= bankCells );
+ // a flat base's ground comes only with its pad: 2% of the map before, none since
+ CHECK( baseFar * 100 <= play );
+ }
+
+ // two: a ring road through the starts, the ground along it painted a strip of its own
+ {
+ std::vector<char> exemplar = coastMap;
+ const Real ROAD_STEP = 20.0f, STRIP_CELLS = 1.5f, OFF_ROAD = 4.0f;
+ std::vector<RMGAddedObject> added;
+ std::vector<Coord2D> ends;
+ for( Int s = 0; s < 4; s++ )
+ {
+ const Coord2D& a = starts[s];
+ const Coord2D& z = starts[( s + 1 ) % 4];
+ const Int pieces = std::max( (Int)( hypotf( z.x - a.x, z.y - a.y ) / ROAD_STEP ), 1 );
+ for( Int q = 0; q < pieces; q++ )
+ {
+ Coord2D one = { a.x + ( z.x - a.x ) * q / pieces, a.y + ( z.y - a.y ) * q / pieces };
+ Coord2D two = { a.x + ( z.x - a.x ) * ( q + 1 ) / pieces, a.y + ( z.y - a.y ) * ( q + 1 ) / pieces };
+ RMGAddedObject first = { one.x * MAP_XY_FACTOR, one.y * MAP_XY_FACTOR, FLAG_ROAD_POINT1, "TestRoad" };
+ RMGAddedObject second = { two.x * MAP_XY_FACTOR, two.y * MAP_XY_FACTOR, FLAG_ROAD_POINT2, "TestRoad" };
+ added.push_back( first );
+ added.push_back( second );
+ ends.push_back( one );
+ ends.push_back( two );
+ }
+ }
+ CHECK( RMGAddObjects( exemplar, added ) );
+ // a cell's distance from the nearest of a list of segments, in cells
+ auto roadDistance = [&]( const std::vector<Coord2D>& segments, Real px, Real py ) -> Real
+ {
+ Real best = 1.0e9f;
+ for( size_t k = 0; k + 1 < segments.size(); k += 2 )
+ {
+ const Coord2D& a = segments[k];
+ const Coord2D& z = segments[k + 1];
+ Real dx = z.x - a.x, dy = z.y - a.y, length = dx * dx + dy * dy;
+ Real t = length > 0.0f ? std::max( 0.0f, std::min( 1.0f, ( ( px - a.x ) * dx + ( py - a.y ) * dy ) / length ) ) : 0.0f;
+ best = std::min( best, hypotf( px - a.x - t * dx, py - a.y - t * dy ) );
+ }
+ return best;
+ };
+ auto paint = [&]( std::vector<Short>& tiles, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ tiles[y * W + x] = (Short)( firstTiles[roadDistance( ends, (Real)( x - border ), (Real)( y - border ) ) <= STRIP_CELLS ? SEA : PLAIN] << 2 );
+ };
+ CHECK( RMGPaintTiles( exemplar, exemplarW, exemplarH, exemplarBorder, paint ) );
+
+ RandomMapSettings settings;
+ settings.m_seed = 6;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = 304;
+ std::vector<char> map;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, NULL ) );
+ if( map.empty() )
+ return;
+ parseGeneratedMap( map );
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ std::vector<Coord2D> roads;
+ for( Int i = 0; i + 1 < theRMGParse.m_numObjects; i++ )
+ {
+ if( !( theRMGParse.m_objectFlags[i] & FLAG_ROAD_POINT1 ) || !( theRMGParse.m_objectFlags[i + 1] & FLAG_ROAD_POINT2 ) )
+ continue;
+ for( Int e = 0; e < 2; e++ )
+ {
+ Coord2D p = { theRMGParse.m_objectPositions[i + e].x / MAP_XY_FACTOR, theRMGParse.m_objectPositions[i + e].y / MAP_XY_FACTOR };
+ roads.push_back( p );
+ }
+ }
+ Int strips = 0, offRoad = 0;
+ for( Int y = B; y < H - B; y++ )
+ for( Int x = B; x < W - B; x++ )
+ {
+ if( !( RMGClassAt( y * W + x ) == names[SEA] ) || onAPad( x - B, y - B ) )
+ continue;
+ strips++;
+ offRoad += roadDistance( roads, (Real)( x - B ), (Real)( y - B ) ) > OFF_ROAD;
+ }
+ printf( " %d road segments, off the pads road strip %d of %d cells more than 4 off a road\n", (Int)roads.size() / 2, offRoad, strips );
+ CHECK( !roads.empty() );
+ // a road's worn ground goes where a road goes: 1168 of 1366 cells more than 4 off one before, none since
+ CHECK( offRoad * 2 <= strips );
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A river exemplar with a branch and two bridges, Winding River's kind. A branch carved after the
+ main river's bridges cut through one's end and sank its deck; a dock or derrick on the line held
+ its ground and dammed the river right across, two pools under one plane; and low ground beside
+ the river sat under its plane outside the polygon, the water hanging over it. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_river_template_keeps_its_bridges_its_river_whole_and_its_banks_over_the_water)
+{
+ CHECK( bootOnce() );
+
+ std::vector<char> exemplar;
+ std::vector<Coord2D> starts, money;
+ RMGSeaExemplar( exemplar, starts, money );
+ const Real SURFACE = 30.0f, BED = 5.0f;
+ const Int playable = theRMGParse.m_boundaryX;
+ const Real HALF = 8.0f, BRANCH_HALF = 5.0f, BANK = 6.0f, branchX = 0.6f * playable;
+ auto riverY = [&]( Real x ) -> Real { return 0.5f * playable + 0.06f * playable * sinf( 6.2832f * x / ( 0.5f * playable ) ); };
+ auto river = [&]( std::vector<UnsignedByte>& h, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ Real px = (Real)( x - border ), py = (Real)( y - border );
+ // across the main river, and along the branch running off it to the top edge
+ Real d = fabsf( py - riverY( px ) ) - HALF;
+ if( py < riverY( branchX ) )
+ d = std::min( d, fabsf( px - branchX ) - BRANCH_HALF );
+ UnsignedByte& cell = h[y * W + x];
+ Real land = 40.0f + cell / 8;
+ cell = (UnsignedByte)( d <= 0.0f ? BED : d < BANK ? BED + ( land - BED ) * d / BANK : land );
+ }
+ };
+ std::vector<RMGAddedWater> water( 2 );
+ const Real reach = HALF + 3.0f, branchReach = BRANCH_HALF + 3.0f;
+ for( Int x = -8; x <= playable + 8; x += 8 )
+ water[0].corners.push_back( Coord2D() ), water[0].corners.back().x = (Real)x, water[0].corners.back().y = riverY( (Real)x ) - reach;
+ for( Int x = playable + 8; x >= -8; x -= 8 )
+ water[0].corners.push_back( Coord2D() ), water[0].corners.back().x = (Real)x, water[0].corners.back().y = riverY( (Real)x ) + reach;
+ Coord2D branchBox[4] = { { branchX - branchReach, -8.0f }, { branchX + branchReach, -8.0f },
+ { branchX + branchReach, riverY( branchX ) }, { branchX - branchReach, riverY( branchX ) } };
+ water[1].corners.assign( branchBox, branchBox + 4 );
+ water[0].surfaceBytes = water[1].surfaceBytes = SURFACE;
+ CHECK( RMGReshapeMap( exemplar, river, water ) );
+ std::vector<RMGAddedObject> bridges;
+ for( Int k = 0; k < 2; k++ )
+ {
+ Real x = ( k ? 0.85f : 0.3f ) * playable, y = riverY( x );
+ RMGAddedObject a = { x * MAP_XY_FACTOR, ( y - HALF - BANK ) * MAP_XY_FACTOR, FLAG_BRIDGE_POINT1, "TestRiverBridge" };
+ RMGAddedObject z = { x * MAP_XY_FACTOR, ( y + HALF + BANK ) * MAP_XY_FACTOR, FLAG_BRIDGE_POINT2, "TestRiverBridge" };
+ bridges.push_back( a );
+ bridges.push_back( z );
+ }
+ CHECK( RMGAddObjects( exemplar, bridges ) );
+
+ static const Int theSizes[][3] = { { 5, 4, 304 }, { 5, 2, 140 } };
+ for( Int k = 0; k < 2; k++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theSizes[k][0];
+ settings.m_numPlayers = theSizes[k][1];
+ settings.m_playableCells = theSizes[k][2];
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ continue;
+ parseGeneratedMap( map );
+ const Int W = theRMGParse.m_width, H = theRMGParse.m_height, B = theRMGParse.m_border;
+ // each cell's water: the plane over it, -1 outside every polygon
+ std::vector<Real> plane( W * H, -1.0f );
+ for( size_t a = 0; a < theRMGParse.m_waterPolygons.size(); a++ )
+ {
+ const std::vector<Coord3D>& polygon = theRMGParse.m_waterPolygons[a];
+ for( Int y = B; y < H - B; y++ )
+ for( Int x = B; x < W - B; x++ )
+ {
+ const Real wx = (Real)( x - B ) * MAP_XY_FACTOR, wy = (Real)( y - B ) * MAP_XY_FACTOR;
+ Bool inside = FALSE;
+ for( size_t p = 0, last = polygon.size() - 1; p < polygon.size(); last = p++ )
+ if( ( polygon[p].y > wy ) != ( polygon[last].y > wy ) &&
+ wx < polygon[p].x + ( wy - polygon[p].y ) * ( polygon[last].x - polygon[p].x ) / ( polygon[last].y - polygon[p].y ) )
+ inside = !inside;
+ if( inside ) plane[y * W + x] = std::max( plane[y * W + x], polygon[0].z );
+ }
+ }
+ Int drowned = 0, pits = 0;
+ for( Int i = 0; i < theRMGParse.m_numObjects; i++ )
+ {
+ Int cx, cy;
+ RMGWorldToCell( theRMGParse.m_objectPositions[i], &cx, &cy );
+ if( ( theRMGParse.m_objectFlags[i] & FLAG_BRIDGE_FLAGS ) && cx >= 0 && cy >= 0 && cx < W && cy < H )
+ drowned += theRMGParse.m_heights[cy * W + cx] * MAP_HEIGHT_SCALE < plane[cy * W + cx];
+ }
+ // dry ground just outside a polygon under the plane of the water beside it
+ for( Int y = B + 2; y < H - B - 2; y++ )
+ for( Int x = B + 2; x < W - B - 2; x++ )
+ {
+ if( plane[y * W + x] >= 0.0f ) continue;
+ Real over = -1.0f;
+ for( Int dy = -2; dy <= 2; dy++ )
+ for( Int dx = -2; dx <= 2; dx++ )
+ over = std::max( over, plane[( y + dy ) * W + x + dx] );
+ pits += over >= 0.0f && theRMGParse.m_heights[y * W + x] * MAP_HEIGHT_SCALE < over;
+ }
+ // pieces of water: a river dammed across is two
+ std::vector<char> seen( W * H, 0 );
+ Int pieces = 0;
+ for( Int start = 0; start < W * H; start++ )
+ {
+ auto wet = [&]( Int i ) { return plane[i] >= 0.0f && theRMGParse.m_heights[i] * MAP_HEIGHT_SCALE < plane[i]; };
+ if( seen[start] || !wet( start ) ) continue;
+ std::vector<Int> stack( 1, start );
+ seen[start] = 1;
+ Int size = 0;
+ while( !stack.empty() )
+ {
+ Int i = stack.back();
+ stack.pop_back();
+ size++;
+ const Int next[4] = { i - 1, i + 1, i - W, i + W };
+ for( Int n = 0; n < 4; n++ )
+ if( next[n] >= 0 && next[n] < W * H && !seen[next[n]] && wet( next[n] ) )
+ {
+ seen[next[n]] = 1;
+ stack.push_back( next[n] );
+ }
+ }
+ pieces += size >= 20;
+ }
+ const Bool first = k == 0;
+ if( drowned || ( first && ( pieces != 1 || pits >= 40 ) ) || report.m_cutOffStarts )
+ printf( " seed %d %dp %dc: %d bridge ends under water, %d pits by the water, %d pieces, %d rivers %d bridges\n%s",
+ settings.m_seed, settings.m_numPlayers, settings.m_playableCells, drowned, pits, pieces, report.m_rivers,
+ report.m_bridges, report.m_notes.str() );
+ CHECK_EQ( drowned, 0 );
+ CHECK_EQ( report.m_cutOffStarts, 0 );
+ if( first )
+ {
+ // the river ranked off the money stays whole: dammed by a dock it was three pools, 620 dry bed cells
+ CHECK_EQ( pieces, 1 );
+ // and its banks stay over its plane: 88 cells under it beside the polygon before the bank's floor
+ CHECK( pits < 40 );
+ }
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The size buttons never go under a template's Tiny, but a typed cell count or a name read back
+ could, and eight seats on a 64-cell Bitter Winter came out as eight pads in a heap with a quarter
+ of the objects outside play. A template map is clamped to its Tiny, and no size at all takes the
+ template's own Normal, not the plain table's. The template is installed as a loose file in a
+ folder of the test's own, the one way a test has to put a map under maps\. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_map_never_comes_smaller_than_its_tiny_size)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings exemplarSettings;
+ exemplarSettings.m_seed = 31;
+ exemplarSettings.m_numPlayers = 4;
+ exemplarSettings.m_style = 1;
+ RandomMapGenerator::clampSettings( exemplarSettings );
+ std::vector<char> exemplar;
+ RandomMapGenerator::generate( exemplarSettings, exemplar );
+ CHECK( !exemplar.empty() );
+
+ const std::filesystem::path home = std::filesystem::current_path();
+ const std::filesystem::path dir = std::filesystem::temp_directory_path() / "zh_rmg_template_floor";
+ std::error_code ec;
+ std::filesystem::remove_all( dir, ec );
+ std::filesystem::create_directories( dir / "maps" / "rmg floor test", ec );
+ FILE *out = fopen( ( dir / "maps" / "rmg floor test" / "rmg floor test.map" ).string().c_str(), "wb" );
+ CHECK( out != NULL );
+ if( out == NULL )
+ return;
+ fwrite( &exemplar[0], 1, exemplar.size(), out );
+ fclose( out );
+ std::filesystem::current_path( dir );
+
+ const AsciiString path( "maps\\rmg floor test\\rmg floor test.map" );
+ RandomMapSettings typed;
+ typed.m_seed = 5;
+ typed.m_numPlayers = 8;
+ typed.m_playableCells = 64;
+ typed.m_template = path;
+ RandomMapGenerator::clampSettings( typed );
+ const Int tiny = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_TINY, 8, path );
+ CHECK( !typed.m_template.isEmpty() );
+ CHECK( tiny > 64 );
+ CHECK_EQ( typed.m_playableCells, tiny );
+
+ RandomMapSettings unsized;
+ unsized.m_numPlayers = 2;
+ unsized.m_template = path;
+ RandomMapGenerator::clampSettings( unsized );
+ CHECK_EQ( unsized.m_playableCells, RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 2, path ) );
+ CHECK( unsized.m_playableCells != RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 2 ) );
+
+ std::filesystem::current_path( home );
+ std::filesystem::remove_all( dir, ec );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A template map's roads came out as pieces that stopped three cells short of the road they ran
+ into, every end cut square, in the 0- and 45-degree doglegs of a grid path and in pieces shorter
+ than the exemplar's, and a pad brought along a stub flagged to join a road the pad left behind.
+ Heartland Shield at 4 seats had no tee, 44 ends in the open, none of them flagged to join, and 60%
+ of its segments on the grid's bearings. The exemplar is the generated one with a ring road laid
+ through its starts and that stub off the first start, the one way a test has roads without the
+ game's archives. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_maps_roads_meet_the_roads_they_run_into_and_leave_no_stub)
+{
+ CHECK( bootOnce() );
+
+ std::vector<char> exemplar;
+ std::vector<Coord2D> starts, money;
+ RMGSeaExemplar( exemplar, starts, money );
+ CHECK_EQ( (Int)starts.size(), 4 );
+ if( starts.size() != 4 )
+ return;
+ const Real ROAD_STEP = 20.0f, STUB_FROM = 8.0f, STUB_TO = 14.0f;
+ std::vector<RMGAddedObject> added;
+ auto addRoad = [&]( Real ax, Real ay, Real zx, Real zy, Int joinFirst, const char *name )
+ {
+ RMGAddedObject one = { ax * MAP_XY_FACTOR, ay * MAP_XY_FACTOR, FLAG_ROAD_POINT1 | joinFirst, name };
+ RMGAddedObject two = { zx * MAP_XY_FACTOR, zy * MAP_XY_FACTOR, FLAG_ROAD_POINT2, name };
+ added.push_back( one );
+ added.push_back( two );
+ };
+ for( Int s = 0; s < 4; s++ )
+ {
+ const Coord2D& a = starts[s];
+ const Coord2D& z = starts[( s + 1 ) % 4];
+ const Int pieces = std::max( (Int)( hypotf( z.x - a.x, z.y - a.y ) / ROAD_STEP ), 1 );
+ for( Int q = 0; q < pieces; q++ )
+ addRoad( a.x + ( z.x - a.x ) * q / pieces, a.y + ( z.y - a.y ) * q / pieces,
+ a.x + ( z.x - a.x ) * ( q + 1 ) / pieces, a.y + ( z.y - a.y ) * ( q + 1 ) / pieces, 0, "TestRoad" );
+ }
+ // a road off each side of the map, so the new map has ways off it whose roads run into the ring's
+ const Real playX = (Real)( theRMGParse.m_width - 2 * theRMGParse.m_border ), playY = (Real)( theRMGParse.m_height - 2 * theRMGParse.m_border );
+ addRoad( 2.0f, playY / 2, 2.0f + ROAD_STEP, playY / 2, 0, "TestRoad" );
+ addRoad( playX - 3.0f, playY / 2, playX - 3.0f - ROAD_STEP, playY / 2, 0, "TestRoad" );
+ addRoad( playX / 2, 2.0f, playX / 2, 2.0f + ROAD_STEP, 0, "TestRoad" );
+ addRoad( playX / 2, playY - 3.0f, playX / 2, playY - 3.0f - ROAD_STEP, 0, "TestRoad" );
+ // the stub points away from both legs of the ring at the first start, so no road comes near its end
+ Real awayX = 0.0f, awayY = 0.0f;
+ for( Int s = 1; s <= 3; s += 2 )
+ {
+ Real dx = starts[s].x - starts[0].x, dy = starts[s].y - starts[0].y, length = hypotf( dx, dy );
+ awayX -= dx / length;
+ awayY -= dy / length;
+ }
+ const Real away = hypotf( awayX, awayY );
+ awayX /= away;
+ awayY /= away;
+ addRoad( starts[0].x + awayX * STUB_TO, starts[0].y + awayY * STUB_TO, starts[0].x + awayX * STUB_FROM, starts[0].y + awayY * STUB_FROM,
+ FLAG_ROAD_JOIN, "TestStub" );
+ CHECK( RMGAddObjects( exemplar, added ) );
+
+ RandomMapSettings settings;
+ settings.m_seed = 905;
+ settings.m_numPlayers = 4;
+ settings.m_playableCells = RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, 4 );
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ return;
+ parseGeneratedMap( map );
+
+ // every road pair's ends, counted by exact point: the renderer joins two roads only where they share one
+ std::map< std::pair<Real, Real>, Int > ends, joins;
+ Int pairs = 0, stubs = 0, gridBearing = 0;
+ for( Int i = 0; i + 1 < theRMGParse.m_numObjects; i++ )
+ {
+ if( !( theRMGParse.m_objectFlags[i] & FLAG_ROAD_POINT1 ) || !( theRMGParse.m_objectFlags[i + 1] & FLAG_ROAD_POINT2 ) )
+ continue;
+ pairs++;
+ stubs += theRMGParse.m_objectNames[i] == "TestStub";
+ for( Int e = 0; e < 2; e++ )
+ {
+ std::pair<Real, Real> at( theRMGParse.m_objectPositions[i + e].x, theRMGParse.m_objectPositions[i + e].y );
+ ends[at]++;
+ joins[at] |= ( theRMGParse.m_objectFlags[i + e] & FLAG_ROAD_JOIN ) != 0;
+ }
+ Real degrees = atan2f( theRMGParse.m_objectPositions[i + 1].y - theRMGParse.m_objectPositions[i].y,
+ theRMGParse.m_objectPositions[i + 1].x - theRMGParse.m_objectPositions[i].x ) * 180.0f / PI;
+ degrees = fmodf( degrees + 360.0f, 45.0f );
+ gridBearing += std::min( degrees, 45.0f - degrees ) < 3.0f;
+ }
+ Int tees = 0, bare = 0;
+ for( std::map< std::pair<Real, Real>, Int >::iterator it = ends.begin(); it != ends.end(); ++it )
+ {
+ tees += it->second >= 3;
+ bare += it->second == 1 && !joins[it->first];
+ }
+ printf( " %d road pairs, %d tees, %d ends cut square, %d on the grid's bearings, %d stubs\n", pairs, tees, bare, gridBearing, stubs );
+ CHECK( pairs > 0 );
+ // a road that runs into another ends on it
+ CHECK( tees > 0 );
+ // an end in the open fades out
+ CHECK_EQ( bare, 0 );
+ // a grid path pulled straight: at most a third of the segments on 0 or 45 degrees
+ CHECK( gridBearing * 3 <= pairs );
+ // a stub whose road stayed behind stays behind too
+ CHECK_EQ( stubs, 0 );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Every seat of a template map gets the same base: Twilight Flame's eight seats came out on two of
+ its bases taken turn about, 26 bytes apart in height and their docks 30 and 48 cells out. The
+ money a base carries stays on the map (a 140-cell Twilight Flame put both docks past the grid), a
+ kind the bases carry none of is the skeleton's, and the high piles go one to a site, as many
+ between every two seats. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_map_gives_every_seat_the_same_base_and_keeps_its_money_on_the_map)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings exemplarSettings;
+ exemplarSettings.m_seed = 31;
+ exemplarSettings.m_numPlayers = 4;
+ exemplarSettings.m_style = 1;
+ RandomMapGenerator::clampSettings( exemplarSettings );
+ std::vector<char> exemplar;
+ RandomMapGenerator::generate( exemplarSettings, exemplar );
+ CHECK( !exemplar.empty() );
+
+ /* An uneven exemplar as well, Twilight Flame's kind: every base a plateau with its money on it and
+ slopes a tank climbs down off it, the west ones over ground 30 bytes lower than the east ones,
+ so they stand that much higher over what they fall to, and the piles on knolls well over the
+ starts. */
+ std::vector<char> uneven( exemplar );
+ parseGeneratedMap( uneven );
+ std::vector<Coord2D> knolls, bases;
+ for( Int k = 0; k < theRMGParse.m_numObjects; k++ )
+ {
+ Coord2D at = { theRMGParse.m_objectPositions[k].x / MAP_XY_FACTOR, theRMGParse.m_objectPositions[k].y / MAP_XY_FACTOR };
+ if( theRMGParse.m_objectNames[k] == "SupplyPileSmall" )
+ knolls.push_back( at );
+ }
+ for( size_t k = 0; k < theRMGParse.m_waypointNames.size(); k++ )
+ if( theRMGParse.m_waypointNames[k].startsWith( "Player_" ) )
+ {
+ Coord2D at = { theRMGParse.m_waypointPositions[k].x / MAP_XY_FACTOR, theRMGParse.m_waypointPositions[k].y / MAP_XY_FACTOR };
+ bases.push_back( at );
+ }
+ auto plateaus = [&]( std::vector<UnsignedByte>& h, Int W, Int H, Int border )
+ {
+ for( Int y = 0; y < H; y++ )
+ for( Int x = 0; x < W; x++ )
+ {
+ UnsignedByte& cell = h[y * W + x];
+ const Real ground = x < W / 2 ? 60.0f : 90.0f;
+ Real high = ground;
+ for( size_t k = 0; k < bases.size(); k++ )
+ {
+ // level to 45 cells out, then a slope down a tank climbs
+ const Real out = hypotf( x - border - bases[k].x, y - border - bases[k].y ) - 45.0f;
+ high = std::max( high, 170.0f - std::max( out, 0.0f ) * 4.0f );
+ }
+ cell = (UnsignedByte)high;
+ for( size_t k = 0; k < knolls.size(); k++ )
+ if( hypotf( x - border - knolls[k].x, y - border - knolls[k].y ) < 5.0f )
+ cell = 230;
+ }
+ };
+ CHECK( RMGReshapeMap( uneven, plateaus, std::vector<RMGAddedWater>() ) );
+
+ struct Case { Int seed, players, cells; Bool uneven; };
+ static const Case theCases[] = { { 7, 8, 0, TRUE }, { 2, 2, 140, FALSE }, { 5, 3, 0, TRUE } };
+ for( Int c = 0; c < 3; c++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theCases[c].seed;
+ settings.m_numPlayers = theCases[c].players;
+ settings.m_playableCells = theCases[c].cells ? theCases[c].cells : RandomMapGenerator::cellsFor( RANDOM_MAP_SIZE_NORMAL, theCases[c].players );
+ std::vector<char> map;
+ RMGTemplateReport report;
+ CHECK( rmgSynthesise( settings, theCases[c].uneven ? uneven : exemplar, NULL, map, NULL, &report ) );
+ if( map.empty() )
+ continue;
+ parseGeneratedMap( map );
+ const Int W = theRMGParse.m_width, b = theRMGParse.m_border, px = theRMGParse.m_boundaryX, py = theRMGParse.m_boundaryY;
+ std::vector<Coord3D> starts;
+ std::vector<Int> tops;
+ for( size_t k = 0; k < theRMGParse.m_waypointNames.size(); k++ )
+ {
+ if( !theRMGParse.m_waypointNames[k].startsWith( "Player_" ) ) continue;
+ const Coord3D& at = theRMGParse.m_waypointPositions[k];
+ starts.push_back( at );
+ tops.push_back( theRMGParse.m_heights[( (Int)( at.y / MAP_XY_FACTOR ) + b ) * W + (Int)( at.x / MAP_XY_FACTOR ) + b] );
+ }
+ Int outside = 0, docks = 0, derricks = 0, treesOnCliffs = 0;
+ std::vector<Int> piles( starts.size(), 0 );
+ for( Int k = 0; k < theRMGParse.m_numObjects; k++ )
+ {
+ const AsciiString& name = theRMGParse.m_objectNames[k];
+ const Real x = theRMGParse.m_objectPositions[k].x / MAP_XY_FACTOR, y = theRMGParse.m_objectPositions[k].y / MAP_XY_FACTOR;
+ const Bool dock = name == "SupplyDock", derrick = name == "TechOilDerrick";
+ docks += dock;
+ derricks += derrick;
+ const Int cx = (Int)x + b, cy = (Int)y + b;
+ if( name.startsWith( "Tree" ) && cx >= 0 && cy >= 0 && cx + 1 < W && cy + 1 < theRMGParse.m_height && RMGCellSpan( cx, cy ) > 9.8f )
+ treesOnCliffs++;
+ if( ( dock || derrick ) && !( x >= 0.0f && y >= 0.0f && x < px && y < py ) )
+ outside++;
+ // a pile counts to the gap between the two seats either side of it round the middle
+ if( name == "SupplyPileSmall" && !starts.empty() )
+ {
+ const Real mine = atan2f( y - 0.5f * py, x - 0.5f * px );
+ size_t gap = 0;
+ Real least = 1.0e9f;
+ for( size_t s = 0; s < starts.size(); s++ )
+ {
+ Real behind = mine - atan2f( starts[s].y / MAP_XY_FACTOR - 0.5f * py, starts[s].x / MAP_XY_FACTOR - 0.5f * px );
+ while( behind < 0.0f ) behind += 2.0f * PI;
+ if( behind < least ) { least = behind; gap = s; }
+ }
+ piles[gap]++;
+ }
+ }
+ Real steepest = 0.0f;
+ for( Int y = b; y + 1 < theRMGParse.m_height - b; y++ )
+ for( Int x = b; x + 1 < W - b; x++ )
+ steepest = std::max( steepest, RMGCellSpan( x, y ) );
+ Bool even = TRUE;
+ for( size_t s = 1; s < tops.size(); s++ ) even = even && tops[s] == tops[0];
+ for( size_t s = 0; s < piles.size() && theCases[c].uneven; s++ ) even = even && piles[s] == 4;
+ if( !even || outside || report.m_cutOffSites || derricks < theCases[c].players || treesOnCliffs || steepest > 40.0f )
+ {
+ printf( " %dp %dc: tops", theCases[c].players, settings.m_playableCells );
+ for( size_t s = 0; s < tops.size(); s++ ) printf( " %d", tops[s] );
+ printf( "; docks %d derricks %d outside %d; piles", docks, derricks, outside );
+ for( size_t s = 0; s < piles.size(); s++ ) printf( " %d", piles[s] );
+ printf( "; cut off %d starts %d sites; %d trees on cliffs, steepest cell %.1f\n", report.m_cutOffStarts, report.m_cutOffSites,
+ treesOnCliffs, steepest );
+ }
+ CHECK_EQ( (Int)starts.size(), theCases[c].players );
+ // one base for every seat, not an east and a west one taken turn about, 20 to 30 bytes apart
+ for( size_t s = 1; s < tops.size(); s++ )
+ CHECK_EQ( tops[s], tops[0] );
+ // a dock the 140-cell map put past the edge is pulled back in, and the report no longer walks the border to it
+ CHECK_EQ( outside, 0 );
+ CHECK_EQ( report.m_cutOffSites, 0 );
+ CHECK( docks >= theCases[c].players );
+ // the exemplar's derricks stand out in its bowl, past every base: the skeleton's stay, none before
+ CHECK( derricks >= theCases[c].players );
+ // four piles between every two seats, not the few the copies left in the first gap
+ if( theCases[c].uneven )
+ for( size_t s = 0; s < piles.size(); s++ )
+ CHECK_EQ( piles[s], 4 );
+ // the way joining two plateaus falls back to the ground over cells, not in one: 85 world units a
+ // cell at 2p and 43 at 8p with a hard edge, 33 and 28 faded
+ CHECK( steepest <= 40.0f );
+ // no tree on a wall the copy's ramps or levelled discs made (11 at 2p, the exemplar's own cliffs excepted)
+ CHECK_EQ( treesOnCliffs, 0 );
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Two copied plateau bases closer than a corridor are joined into one stretch of high ground; two
+ further apart keep the valley between them. The distances are a 3-4 chamfer, so a gap of n cells
+ sums to 3n on the line between the bases. Fading on that sum alone half filled the valley between
+ two bases 36 cells apart. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_template_joins_two_plateau_bases_across_a_corridor_not_a_valley)
+{
+ // 20 cells apart: the way between is raised whole, and its shoulders fall back over the fade
+ CHECK( rmgJoinShare( 3 * 20, 3 * 20 ) == 1.0f );
+ const Real shoulder = rmgJoinShare( 3 * 20, 3 * 36 );
+ CHECK( shoulder > 0.0f && shoulder < 1.0f );
+ CHECK( rmgJoinShare( 3 * 20, 3 * 60 ) == 0.0f );
+ // 30 and 36 cells apart: a valley, the floor on the line between them untouched
+ CHECK( rmgJoinShare( 3 * 30, 3 * 30 ) == 0.0f );
+ CHECK( rmgJoinShare( 3 * 36, 3 * 36 ) == 0.0f );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** A LAN game names a template map by four letters of its folder's name, and a machine binds the
+ first folder under maps\ whose letters match, so two shipped maps sharing four letters would put
+ the later one out of LAN games without a word. Every map folder Zero Hour and Generals ship, read
+ out of MapsZH.big and Maps.big, has letters of its own; the day one does not, the wire takes a
+ fifth letter. */
+//-------------------------------------------------------------------------------------------------
+TEST(every_shipped_map_has_wire_letters_of_its_own)
+{
+ static const char *const theShippedMaps[] =
+ {
+ "_art review new units", "allbuildingsallsidesunittest_save", "alpine assault", "armored fury",
+ "barrenbadlands", "bear town beatdown", "bitter winter", "bombardment beach", "bridge busters",
+ "bug_savedgameandenabledfolders", "cairo commandos", "chi01", "chi02", "chi03", "chi04", "chi05",
+ "chi06", "chi07", "chi08", "chifinal", "cliff", "dark mountain", "dark night", "death valley",
+ "defcon6", "desert fury", "destruction station", "dogsofwar", "dust devil", "eastern everglades",
+ "el scorcho", "fallen empire", "final crusade", "flash effect", "flash fire", "floodedplains",
+ "forgottenforestzh", "fortress avalanche", "free fire zone", "gc_airgeneral", "gc_chemgeneral",
+ "gc_chinaboss", "gc_demolitiongeneral", "gc_lasergeneral", "gc_nukegeneral", "gc_stealth",
+ "gc_superweaponsgeneral", "gc_tankgeneral", "gla01", "gla02", "gla04", "gla05", "gla06", "gla07",
+ "gla08", "golden oasis", "green pastures", "heartland shield", "homeland alliance", "hostile dawn",
+ "hovercraft", "iron dragon", "killing fields", "leipzig lowlands", "lights out", "lone eagle",
+ "manic aggression", "md_chi01", "md_chi02", "md_chi03", "md_chi04", "md_chi05", "md_chi05_end",
+ "md_chi05_intro", "md_gla01", "md_gla02", "md_gla02_cine", "md_gla03", "md_gla03_cine",
+ "md_gla03_end", "md_gla04", "md_gla04_intro", "md_gla04_sound", "md_gla05", "md_gla05_end",
+ "md_gla05_intro", "md_shellmap", "md_usa01", "md_usa01_cine", "md_usa02", "md_usa02_intro",
+ "md_usa02_intro_ns", "md_usa03", "md_usa03_cine", "md_usa03_end", "md_usa03_end1", "md_usa03_intro",
+ "md_usa03_mid_cine", "md_usa04", "md_usa04_cine", "md_usa04_intro", "md_usa05", "md_usa06_intro",
+ "mountain fox", "mountain guns", "mountainfox", "northamerica", "overland", "red rock",
+ "rocky rampage", "rogue agent", "sand serpent", "scorched earth", "seaside mutiny", "shellmap1",
+ "shellmap1low", "shellmapmd", "silent river", "swissmp", "thefrontline", "tournament city",
+ "tournament continent", "tournament desert", "tournament island", "tournament lake",
+ "tournament plains", "tournament tundra", "tournament urban", "tournamenta", "tournamentb",
+ "training01", "twilight flame", "usa01", "usa02", "usa03", "usa04", "usa05", "usa05_endsconflict",
+ "usa05_endsconflict_intro", "usa05_endsconflict_intro_n", "usa06", "usa07", "usa07-taskforces",
+ "usa08", "victory valley", "wasteland warlords", "whiteout", "winding river", "winter wolf",
+ "woodcrest circle"
+ };
+ const Int numShippedMaps = sizeof(theShippedMaps) / sizeof(theShippedMaps[0]);
+
+ std::map<std::string, const char *> seen;
+ for( Int i = 0; i < numShippedMaps; i++ )
+ {
+ AsciiString folder, wire;
+ folder.format( "rmg_v17_1_2p_200c_t00000001_%s", theShippedMaps[i] );
+ CHECK( generatedMapWireName( folder, wire ) );
+ const char *letters = strrchr( wire.str(), '~' );
+ CHECK( letters != NULL && letters != wire.str() );
+ if( letters == NULL )
+ continue;
+ std::map<std::string, const char *>::const_iterator twin = seen.find( letters );
+ if( twin != seen.end() )
+ printf( " '%s' and '%s' both go as %s\n", twin->second, theShippedMaps[i], letters );
+ CHECK( twin == seen.end() );
+ seen[letters] = theShippedMaps[i];
+ }
+ CHECK_EQ( (Int)seen.size(), numShippedMaps );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Not a check: with RMG_TEMPLATE_DUMP set to "<dir> <exemplar.map> <seed>,<players>,<cells> ..." it
+ synthesises each map from the exemplar (a .map taken out of the game's archive, packed or not) and
+ writes it and its preview into dir, with the report and the time it took. RMG_TEMPLATE_CIVILIANS
+ names a file of town building names, one a line, standing in for the object INI. Run as
+ test_gameengine.exe write_the_maps_RMG_TEMPLATE_DUMP_names. */
+//-------------------------------------------------------------------------------------------------
+TEST(write_the_maps_RMG_TEMPLATE_DUMP_names)
+{
+ const char *dump = getenv( "RMG_TEMPLATE_DUMP" );
+ if( dump == NULL )
+ return;
+ CHECK( bootOnce() );
+
+ const char *civilians = getenv( "RMG_TEMPLATE_CIVILIANS" );
+ if( civilians )
+ {
+ std::vector<char> list;
+ CHECK( readWholeFile( civilians, list ) );
+ std::string all( list.begin(), list.end() );
+ size_t from = 0;
+ while( from < all.size() )
+ {
+ size_t end = all.find_first_of( "\r\n", from );
+ if( end == std::string::npos ) end = all.size();
+ if( end > from )
+ theTestCivilians.push_back( AsciiString( all.substr( from, end - from ).c_str() ) );
+ from = end + 1;
+ }
+ }
+
+ char dir[MAX_PATH], source[MAX_PATH];
+ Int read = 0;
+ CHECK( sscanf( dump, "%259s %259s%n", dir, source, &read ) == 2 );
+ std::vector<char> exemplar;
+ CHECK( readWholeFile( source, exemplar ) );
+ const char *next = dump + read;
+ // the pool the game starts, so the time is the one a player waits
+ JobSystem::init();
+ RandomMapSettings settings;
+ while( sscanf( next, " %d,%d,%d%n", &settings.m_seed, &settings.m_numPlayers, &settings.m_playableCells, &read ) == 3 )
+ {
+ next += read;
+ RandomMapGenerator::clampSettings( settings );
+ std::vector<char> map, preview;
+ RMGTemplateReport report;
+ LARGE_INTEGER frequency, before, after;
+ QueryPerformanceFrequency( &frequency );
+ QueryPerformanceCounter( &before );
+ Bool built = rmgSynthesise( settings, exemplar, civilians ? isListedCivilian : NULL, map, &preview, &report );
+ QueryPerformanceCounter( &after );
+ CHECK( built );
+ if( !built )
+ continue;
+
+ char name[MAX_PATH];
+ snprintf( name, sizeof(name), "%s\\synth_%d_%dp_%dc", dir, settings.m_seed, settings.m_numPlayers, settings.m_playableCells );
AsciiString file;
file.format( "%s.map", name );
FILE *out = fopen( file.str(), "wb" );
@@ -13023,7 +14951,8 @@ TEST(the_ground_is_textured_by_what_the_ground_is_doing)
for( Int i = 0; i < (Int)theRMGParse.m_tiles.size(); i++ )
{
Int source = theRMGParse.m_tiles[i] >> 2;
- Int terrainClass = source / 4;
+ Int terrainClass = RMGClassOfTile( theRMGParse.m_tiles[i] );
+ CHECK( source >= 0 && source < theRMGParse.m_numBitmapTiles );
CHECK( terrainClass >= 0 && terrainClass < 4 );
cellsPerClass[terrainClass]++;
}
@@ -21079,44 +23008,6 @@ TEST(ai_persona_rides_the_slot_entry_and_normal_leaves_it_unchanged)
TheWritableGlobalData = saved;
}
-// The debug log's cap: the head and the last whole lines survive, in one file still open for writing.
-TEST(debug_log_cut_keeps_the_head_and_the_last_whole_lines)
-{
- const std::string path = (std::filesystem::temp_directory_path() / "zh_logcut_test.txt").string();
- FILE *log = fopen( path.c_str(), "w" ); // text mode, as the game opens it
- fputs( "head one\nhead two\n", log );
- fflush( log );
- const long headEnd = ftell( log );
- char line[ 32 ];
- for( Int i = 0; i < 1000; ++i )
- {
- snprintf( line, sizeof( line ), "line %04d\n", i );
- fputs( line, log );
- }
- const long before = ftell( log );
- const long after = DebugCutLogFile( log, path.c_str(), headEnd, 100 );
- fputs( "written after the cut\n", log );
- fclose( log );
-
- FILE *in = fopen( path.c_str(), "r" );
- std::string text;
- char buffer[ 4096 ];
- size_t got;
- while( (got = fread( buffer, 1, sizeof( buffer ), in )) > 0 )
- text.append( buffer, got );
- fclose( in );
- std::filesystem::remove( path );
-
- CHECK( after < before );
- CHECK( text.compare( 0, 18, "head one\nhead two\n" ) == 0 );
- CHECK( text.find( "cut here" ) != std::string::npos );
- CHECK( text.find( "line 0989" ) == std::string::npos );
- CHECK( text.find( "\nline 0991\n" ) != std::string::npos ); // a whole line, never half of one
- CHECK( text.find( '\r' ) == std::string::npos ); // no \r\r\n from the text-mode rewrite
- const std::string ending = "line 0999\nwritten after the cut\n";
- CHECK( text.compare( text.size() - ending.size(), ending.size(), ending ) == 0 );
-}
-
#include "Common/MultiplayerSettings.h"
#include "GameNetwork/LANAPICallbacks.h"
@@ -21288,6 +23179,44 @@ TEST(handicap_rides_the_slot_entry_and_full_health_leaves_the_string_unchanged)
TheWritableGlobalData = savedData;
}
+// The debug log's cap: the head and the last whole lines survive, in one file still open for writing.
+TEST(debug_log_cut_keeps_the_head_and_the_last_whole_lines)
+{
+ const std::string path = (std::filesystem::temp_directory_path() / "zh_logcut_test.txt").string();
+ FILE *log = fopen( path.c_str(), "w" ); // text mode, as the game opens it
+ fputs( "head one\nhead two\n", log );
+ fflush( log );
+ const long headEnd = ftell( log );
+ char line[ 32 ];
+ for( Int i = 0; i < 1000; ++i )
+ {
+ snprintf( line, sizeof( line ), "line %04d\n", i );
+ fputs( line, log );
+ }
+ const long before = ftell( log );
+ const long after = DebugCutLogFile( log, path.c_str(), headEnd, 100 );
+ fputs( "written after the cut\n", log );
+ fclose( log );
+
+ FILE *in = fopen( path.c_str(), "r" );
+ std::string text;
+ char buffer[ 4096 ];
+ size_t got;
+ while( (got = fread( buffer, 1, sizeof( buffer ), in )) > 0 )
+ text.append( buffer, got );
+ fclose( in );
+ std::filesystem::remove( path );
+
+ CHECK( after < before );
+ CHECK( text.compare( 0, 18, "head one\nhead two\n" ) == 0 );
+ CHECK( text.find( "cut here" ) != std::string::npos );
+ CHECK( text.find( "line 0989" ) == std::string::npos );
+ CHECK( text.find( "\nline 0991\n" ) != std::string::npos ); // a whole line, never half of one
+ CHECK( text.find( '\r' ) == std::string::npos ); // no \r\r\n from the text-mode rewrite
+ const std::string ending = "line 0999\nwritten after the cut\n";
+ CHECK( text.compare( text.size() - ending.size(), ending.size(), ending ) == 0 );
+}
+
// The replay's writer: appends and header patches through the queue leave the bytes the same calls
// made straight on the FILE did, the way RecorderClass makes them.
TEST(file_write_queue_writes_what_the_file_calls_wrote)
diff --git a/Tools/RandomMapLab/synthmap.py b/Tools/RandomMapLab/synthmap.py
index 98589b5f6..f855ef65c 100644
--- a/Tools/RandomMapLab/synthmap.py
+++ b/Tools/RandomMapLab/synthmap.py
@@ -942,7 +942,8 @@ def lay_sea(h, skel, f, plan, src, sea, inland, boxes):
"""The sea where inland (cells from the coastline, under 0 at sea) is under 0: its bed, a beach
up from the waterline, higher ground cut back to a walkable slope, ground the plane would flood
inside its areas raised to the beach, and the areas themselves."""
- surface = max(skel.bowl + sea["surface_bytes"] - src.bowl, SEA_FLOOR)
+ # src.bowl on an island map is half sea bed; the exemplar's bank over its water bounds the surface
+ surface = max(min(skel.bowl + sea["surface_bytes"] - src.bowl, skel.bowl - max(sea["bank_bytes"], 4.0)), SEA_FLOOR)
bed = max(surface - max(sea["depth_bytes"], 6.0), 0.0)
target = np.where(inland < 0.0, surface - (surface - bed) * fade(-inland / SHORE_CELLS),
surface + 2.0 + RIVER_SLOPE * np.maximum(inland - 2.0, 0.0))