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): symmetric random maps with ridges, water and a reroll

Olcay Seygan751735768261
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b4dcd8a58..7581a771a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1002,9 +1002,25 @@ found and fixed — EA's own, not port damage.**
---
-## Not there yet
+## A new map whenever you want one
+
+- The skirmish map list ends with a random map. Pick it and the game builds one, then starts the
+ match on it; pick it again and you get a different one. There is nothing to install and nothing
+ to download, and the map shows up in the list with a picture like any other.
+- Every player gets the same ground. The layout is drawn once and turned into each player's corner,
+ so nobody starts on the hill while somebody else starts in the hollow - the buildable ground
+ around each base and the walk to each player's supply are identical, cell for cell.
+- It is a map, not a field. A ridge runs between one player and the next, too steep to drive up,
+ with one crossing cut through it that both of them have to use. There are lakes off to the side
+ of the lanes, sand where the ground drops, rock where it turns steep, trees and boulders in
+ drifts across the open ground, and neutral buildings to fight over: an oil derrick on every
+ crossing, a pair of civilian blocks in each corner and a hospital in the middle of a big map.
+- The number that made the map is in its name, so the same number always makes the same map, on
+ every machine. Two people who type it get the same ground, and a map worth keeping can be found
+ again.
+
+---
-- Random maps generate and can be played — a number picks the map and the match starts on it —
- but there is still no menu entry and no reroll button.
+## Not there yet
- Online and LAN play are untested.
- You need to own the game; no game data ships here.
diff --git a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h
index 73e8217a0..eef9cee5e 100644
--- a/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h
+++ b/GeneralsMD/Code/GameEngine/Include/Common/RandomMapGenerator.h
@@ -31,8 +31,10 @@
/** Version of the generated bytes. Bump it whenever the generator's output
changes for unchanged settings: it travels with the seed in multiplayer, so
a build that generates a different map is caught before the match starts
- rather than desyncing partway through it. */
-#define RANDOM_MAP_GENERATOR_VERSION 1
+ 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 2
/** Everything the generator is allowed to read. Two machines handed the same
settings must produce byte-identical maps, so nothing else - no clock, no
@@ -51,11 +53,28 @@ class RandomMapGenerator
public:
enum { MIN_PLAYERS = 2, MAX_PLAYERS = 8 };
enum { MIN_CELLS = 64, MAX_CELLS = 512 };
+ enum { PREVIEW_PIXELS = 128 }; ///< what getMapPreviewImage expects of the tga
/// Build an uncompressed CkMp map image. Deterministic in the settings alone.
static void generate( const RandomMapSettings& settings, std::vector<char>& mapBytes );
+
+ /// A 128x128 24-bit tga of the same layout, for the map list entry.
+ static void generatePreview( const RandomMapSettings& settings, std::vector<char>& tgaBytes );
+
+ /** CRC of the generated bytes with the generator version folded in. Two
+ builds that agree on this agree on the map; the test suite pins it. */
+ static UnsignedInt fingerprint( const RandomMapSettings& settings );
+
+ /// Settings clamped the way generate() clamps them, so callers can report the truth.
+ static void clampSettings( RandomMapSettings& settings );
};
+/** Generate the map and its preview and write both into the user map directory,
+ under a name that carries the generator version and the settings, so two
+ different maps never land on one file. Returns false when the file could not
+ be written; on success mapPathOut is what -map wants. */
+extern Bool writeRandomMap( const RandomMapSettings& settings, AsciiString& mapPathOut );
+
/** 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/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
index 7ba230692..f024a6d49 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp
@@ -444,7 +444,10 @@ Int parseMapName(char *args[], int num)
// parseRandomMap =============================================================
/** -randommap <seed> [players] [cells]: generate a skirmish map from the seed and write it into
- the user map directory as "RMG_<seed>", then point -map at it. Nothing downstream has to know
+ the user map directory as "RMG_v<generator version>_<seed>_<players>p_<cells>c", then point
+ -map at it. The version is in the name because it is in the bytes: a build that generates a
+ different map from the same seed writes a different file rather than a confusing one.
+ Nothing downstream has to know
it was generated: the map cache walks that directory on startup, so it shows up in the skirmish
map list like any hand-made map, and -autoskirmish starts on it. The same seed gives the same
map on every machine, so both sides of a network game can be handed the same command line. */
@@ -467,29 +470,11 @@ Int parseRandomMap(char *args[], int num)
if (num > eaten && isdigit((UnsignedByte)args[eaten][0]))
settings.m_playableCells = atoi( args[eaten++] );
- std::vector<char> mapBytes;
- RandomMapGenerator::generate( settings, mapBytes );
-
- // The map cache expects "<user maps>\<name>\<name>.map" - the directory carries the name.
- AsciiString mapsDir, dir, path;
- mapsDir.format( "%sMaps", TheGlobalData->getPath_UserData().str() );
- dir.format( "%s\\RMG_%d", mapsDir.str(), settings.m_seed );
- path.format( "%s\\RMG_%d.map", dir.str(), settings.m_seed );
- TheFileSystem->createDirectory( mapsDir ); // createDirectory is one level at a time
- TheFileSystem->createDirectory( dir );
-
- FILE *fp = fopen( path.str(), "wb" );
- if (fp == NULL)
- {
- DEBUG_LOG(("-randommap: could not write '%s'\n", path.str()));
+ AsciiString path;
+ if (!writeRandomMap( settings, path ))
return eaten;
- }
- fwrite( &mapBytes[0], 1, mapBytes.size(), fp );
- fclose( fp );
TheWritableGlobalData->m_mapName = path;
- DEBUG_LOG(("-randommap: wrote '%s' - %d players, %d cells, %d bytes\n",
- path.str(), settings.m_numPlayers, settings.m_playableCells, mapBytes.size()));
return eaten;
}
diff --git a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
index 6f84e65db..07f8ee9e3 100644
--- a/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/Common/RandomMapGenerator.cpp
@@ -20,17 +20,26 @@
// Writes a .map image straight into memory: the same CkMp chunk stream
// WorldBuilder saves (see WHeightMapEdit::saveToFile), minus everything a
// skirmish map does not need.
+//
+// The layout is built in one canonical sector and rotated into the others, so
+// every player gets the same ground in their own frame and a win rate measured
+// over these maps is not measuring the terrain.
#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
#include <math.h>
+#include <float.h>
#include "Common/RandomMapGenerator.h"
#include "Lib/Trig.h"
+#include "Common/crc.h"
#include "Common/DataChunk.h"
+#include "Common/FileSystem.h"
+#include "Common/GlobalData.h"
#include "Common/Dict.h"
#include "Common/MapObject.h"
#include "Common/MapReaderWriterInfo.h"
+#include "GameLogic/FPUControl.h"
// Chunk versions the writers of these chunks use. They live in the .cpp files
// that write them (SidesList.cpp, Scripts.cpp), not in MapReaderWriterInfo.h.
@@ -46,21 +55,29 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
// edges, so it is scenery, not play space.
#define RMG_BORDER_CELLS 20
-// One texture class, the four tiles of a 2x2 grass sheet. Named the way
-// Terrain.ini names it, since the reader looks the texture up by that name.
-#define RMG_TEXTURE_NAME "GrassType1"
-#define RMG_TEXTURE_TILES 4
-#define RMG_TEXTURE_WIDTH 2
+// Four texture classes, each read as the four tiles of a 2x2 sheet. Named the
+// way Terrain.ini names them, since the reader looks the texture up by name.
+#define RMG_TILES_PER_CLASS 4
+#define RMG_TILE_SHEET_WIDTH 2
// Height field, in height map bytes (a byte is MAP_HEIGHT_SCALE world units).
#define RMG_BASE_HEIGHT 40.0f
-#define RMG_AMPLITUDE 22.0f
+#define RMG_AMPLITUDE 20.0f
#define RMG_OCTAVES 4
#define RMG_FEATURES_PER_MAP 4.0f
// A start position gets a flat disc to build on, easing back into the terrain.
+// Eight players on a small map sit close enough together that the full-size
+// discs would overlap and flatten the whole map, so both radii are capped by
+// the spacing between neighbouring starts as well.
#define RMG_FLAT_RADIUS 14.0f
#define RMG_BLEND_RADIUS 30.0f
+#define RMG_FLAT_OF_SPACING 0.35f
+#define RMG_BLEND_OF_SPACING 0.75f
+
+// No ridge comes closer than this to a start, whatever the player count does to
+// the geometry. A base has to fit, and the pathfinder has to be able to leave.
+#define RMG_BASE_CLEARANCE 20.0f
// Where the start positions sit, as a fraction of the playable size.
#define RMG_START_RING 0.34f
@@ -68,6 +85,44 @@ static const Int K_SCRIPT_LIST_DATA_VERSION_1 = 1;
#define RMG_SUPPLY_PER_PLAYER 2
#define RMG_SUPPLY_DISTANCE 20.0f
+// The ridge that separates one player's ground from the next. It runs along the
+// sector boundary, is raised in one step so both of its sides read as cliff to
+// the pathfinder, and is cut by one gap - the chokepoint every crossing between
+// two neighbours has to use.
+#define RMG_RIDGE_RISE 34.0f ///< height bytes; a cliff needs more than 15.7
+#define RMG_RIDGE_HALF_WIDTH 2.5f ///< cells to either side of the boundary
+#define RMG_RIDGE_INNER 0.12f ///< fraction of the playable size
+#define RMG_RIDGE_OUTER 0.46f
+#define RMG_GAP_RADIUS 0.30f ///< where the chokepoint sits along the ridge
+#define RMG_GAP_HALF 0.05f ///< half the gap, as a fraction of the playable size
+#define RMG_GAP_WIDEN_STEP 1.4f ///< how much a failed connectivity check widens it
+#define RMG_LAYOUT_ATTEMPTS 5
+
+// One lake per player, off to the side of the lane rather than across it.
+#define RMG_LAKE_MIN_CELLS 96
+#define RMG_LAKE_RADIUS 0.045f ///< fraction of the playable size
+#define RMG_LAKE_DOCK_CLEARANCE 8.0f ///< cells of dry land kept around a supply dock
+#define RMG_LAKE_OF_SPACING 0.16f ///< and no wider than this much of the start spacing
+#define RMG_LAKE_SHORE 4.0f ///< cells of shore the basin eases out over
+#define RMG_LAKE_DEPTH 16.0f ///< height bytes below the water surface
+#define RMG_WATER_DROP 7.0f ///< height bytes: water surface below the base height
+
+// Scenery. The cap is per sector, so the map keeps the same object count per
+// player whatever the seed does.
+#define RMG_PROPS_PER_SECTOR 44
+#define RMG_PROP_STEP 3 ///< cells between placement candidates
+#define RMG_PROP_CLEARANCE 4.0f ///< cells kept clear beyond a start's blend radius
+#define RMG_SUPPLY_CLEARANCE 12.0f ///< cells kept clear around a supply dock
+#define RMG_GAP_CLEARANCE 9.0f ///< cells kept clear around the chokepoint
+#define RMG_CIVILIANS_PER_SECTOR 2
+#define RMG_CIVILIAN_RING 0.24f
+#define RMG_CIVILIAN_SPREAD 6.0f ///< cells between the two buildings of a cluster
+#define RMG_HOSPITAL_MIN_CELLS 128
+
+// What counts as a cliff. WorldHeightMap marks a cell impassable when its four
+// corners span more than this many world units (PATHFIND_CLIFF_SLOPE_LIMIT_F).
+#define RMG_CLIFF_WORLD_SPAN 9.8f
+
//-----------------------------------------------------------------------------
// Chunk writer
//-----------------------------------------------------------------------------
@@ -311,18 +366,40 @@ static Real fractalNoise( const UnsignedByte perm[512], Real x, Real y )
return total / range;
}
+/// Repeatable per-cell randomness, for scattering that must not depend on order.
+static UnsignedInt hashCell( Int seed, Int x, Int y )
+{
+ UnsignedInt h = (UnsignedInt)seed * 374761393U;
+ h += (UnsignedInt)x * 668265263U;
+ h ^= h >> 13;
+ h += (UnsignedInt)y * 2246822519U;
+ h ^= h >> 16;
+ h *= 2654435761U;
+ return h ^ (h >> 15);
+}
+
//-----------------------------------------------------------------------------
-// Map pieces
+// Layout
//-----------------------------------------------------------------------------
-/** The tile index WorldBuilder computes for a cell: four quadrants packed into
- each source tile, the source tile picked by tiling the class across the map. */
-static Short tileIndexForCell( Int x, Int y, Int firstTile, Int width )
+enum RMGTerrainClass
{
- Int ndx = firstTile + ((x / 2) % width) + width * ((y / 2) % width);
- ndx = (ndx << 2) + 2 * (y & 1) + (x & 1);
- return (Short)ndx;
-}
+ RMG_TERRAIN_GRASS = 0,
+ RMG_TERRAIN_DIRT,
+ RMG_TERRAIN_ROCK,
+ RMG_TERRAIN_SAND,
+
+ RMG_TERRAIN_COUNT
+};
+
+/// Index order matches RMGTerrainClass; the names are Terrain.ini's.
+static const char *theTerrainClassNames[RMG_TERRAIN_COUNT] =
+{
+ "GrassType1",
+ "DirtType1",
+ "RocksType1",
+ "SandLargeType1"
+};
struct RMGStart
{
@@ -331,91 +408,779 @@ struct RMGStart
Real m_angle; ///< direction from the middle of the map outwards
};
-static void computeStarts( const RandomMapSettings& settings, RMGStart *starts )
+/// Where a point sits relative to the sector its player owns.
+struct RMGPolar
{
- Real playable = (Real)settings.m_playableCells;
- Real center = playable * 0.5f;
+ Real m_radius; ///< cells from the middle of the playable area
+ Real m_offsetAngle; ///< radians from the sector's own start bearing, in [-half, +half)
+ Int m_sector; ///< which player's sector the point fell in
+};
+
+struct RMGObject
+{
+ AsciiString m_templateName;
+ AsciiString m_uniqueID;
+ Real m_worldX;
+ Real m_worldY;
+ Real m_angle;
+ Int m_waypointID; ///< 0 for anything that is not a waypoint
+};
+
+struct RMGLake
+{
+ Real m_cellX;
+ Real m_cellY;
+ Real m_radius;
+};
+
+/** Everything derived from the settings, in one place, so the map bytes and the
+ preview tga are two views of the same layout rather than two guesses at it. */
+class RMGLayout
+{
+public:
+ void build( const RandomMapSettings& settings );
+
+ Int cellIndex( Int x, Int y ) const { return y * m_width + x; }
+ UnsignedByte heightAtCell( Int x, Int y ) const { return m_heights[cellIndex( x, y )]; }
+ UnsignedByte terrainAtCell( Int x, Int y ) const { return m_terrain[cellIndex( x, y )]; }
+ Bool passableAtCell( Int x, Int y ) const { return m_passable[cellIndex( x, y )] != 0; }
+
+ /// True when the point is inside a lake outline; the distance is to the nearest shore.
+ Bool insideLake( Real cellX, Real cellY, Real *distanceOut ) const;
+
+ RandomMapSettings m_settings;
+ Int m_width; ///< map cells per side, border included
+ Int m_height;
+ Real m_baseAngle; ///< bearing of player one, from the middle
+ Real m_sectorAngle; ///< 2 pi / players
+ Real m_gapHalfCells; ///< half the chokepoint, after any widening
+ Real m_flatRadius; ///< the disc a base is laid out on
+ Real m_blendRadius; ///< where that disc has eased back into the terrain
+ Real m_waterHeight; ///< height bytes; the surface of every lake
+ RMGStart m_starts[RandomMapGenerator::MAX_PLAYERS];
+ std::vector<UnsignedByte> m_heights;
+ std::vector<UnsignedByte> m_terrain;
+ std::vector<char> m_passable;
+ std::vector<RMGLake> m_lakes;
+ std::vector<RMGObject> m_objects;
+
+private:
+ void computeStarts( void );
+ void placeLakes( void );
+ void buildHeights( const UnsignedByte perm[512] );
+ void buildTerrainClasses( void );
+ void buildPassability( void );
+ Bool everyStartReachable( void ) const;
+ void buildObjects( const UnsignedByte perm[512] );
+ void addProps( const UnsignedByte perm[512] );
+ void addTechAndCivilians( void );
+ void addRotatedCopies( const char *templateName, const char *idPrefix, Real cellX, Real cellY,
+ Real angle, Int& runningID );
+
+ RMGPolar toPolar( Real cellX, Real cellY ) const;
+ Real distanceToNearestStart( Real cellX, Real cellY ) const;
+ Real ridgeAndLakeHeight( const UnsignedByte perm[512], Real cellX, Real cellY ) const;
+ Real cellSpanWorld( Int x, Int y ) const;
+ void rotateAboutCentre( Real cellX, Real cellY, Real angle, Real *outX, Real *outY ) const;
+};
+
+RMGPolar RMGLayout::toPolar( Real cellX, Real cellY ) const
+{
+ Real centre = (Real)m_settings.m_playableCells * 0.5f;
+ Real dx = cellX - centre;
+ Real dy = cellY - centre;
+
+ RMGPolar polar;
+ polar.m_radius = sqrtf( dx * dx + dy * dy );
+
+ // ATan2, not atan2f: the simulation takes its trigonometry from Lib/Trig.h so
+ // every machine gets the same answer, and a generated map is simulation input.
+ Real angle = ATan2( dy, dx ) - m_baseAngle + m_sectorAngle * 0.5f;
+ Real turns = angle / (2.0f * PI);
+ angle -= floorf( turns ) * 2.0f * PI; // into [0, 2 pi)
+
+ Real sector = floorf( angle / m_sectorAngle );
+ if( sector >= (Real)m_settings.m_numPlayers )
+ sector = (Real)(m_settings.m_numPlayers - 1);
+
+ polar.m_sector = (Int)sector;
+ polar.m_offsetAngle = angle - sector * m_sectorAngle - m_sectorAngle * 0.5f;
+ return polar;
+}
+
+void RMGLayout::rotateAboutCentre( Real cellX, Real cellY, Real angle, Real *outX, Real *outY ) const
+{
+ Real centre = (Real)m_settings.m_playableCells * 0.5f;
+ Real dx = cellX - centre;
+ Real dy = cellY - centre;
+ Real c = Cos( angle );
+ Real s = Sin( angle );
+
+ *outX = centre + dx * c - dy * s;
+ *outY = centre + dx * s + dy * c;
+}
+
+void RMGLayout::computeStarts( void )
+{
+ Real playable = (Real)m_settings.m_playableCells;
+ Real centre = playable * 0.5f;
Real ring = playable * RMG_START_RING;
// One of 1024 rotations, so different seeds do not all put player one in
// the same corner.
- UnsignedInt state = (UnsignedInt)settings.m_seed * 2654435761U + 12345U;
+ UnsignedInt state = (UnsignedInt)m_settings.m_seed * 2654435761U + 12345U;
state ^= state >> 15;
- Real baseAngle = (Real)(state % 1024U) * (2.0f * PI / 1024.0f);
+ m_baseAngle = (Real)(state % 1024U) * (2.0f * PI / 1024.0f);
+ m_sectorAngle = 2.0f * PI / (Real)m_settings.m_numPlayers;
- for( Int i = 0; i < settings.m_numPlayers; i++ )
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
{
- Real angle = baseAngle + (2.0f * PI * (Real)i) / (Real)settings.m_numPlayers;
- starts[i].m_cellX = center + ring * Cos( angle );
- starts[i].m_cellY = center + ring * Sin( angle );
- starts[i].m_angle = angle;
+ Real angle = m_baseAngle + m_sectorAngle * (Real)i;
+ m_starts[i].m_cellX = centre + ring * Cos( angle );
+ m_starts[i].m_cellY = centre + ring * Sin( angle );
+ m_starts[i].m_angle = angle;
}
}
-/** Height map bytes for the whole map, border included. Playable cell (0,0) is
- map cell (border,border), which is world (0,0). */
-static void buildHeights( const RandomMapSettings& settings, const RMGStart *starts,
- Int width, Int height, std::vector<UnsignedByte>& data )
+/** One lake per sector, off the lane rather than across it. The first candidate that clears the
+ start it belongs to, and both of that start's supply docks, wins; a dock standing in water is
+ not a dock anybody can use. If none of them is clear the map simply has no lakes. */
+void RMGLayout::placeLakes( void )
{
- UnsignedByte perm[512];
- seedPermutation( settings.m_seed, perm );
+ m_lakes.clear();
+
+ if( m_settings.m_playableCells < RMG_LAKE_MIN_CELLS )
+ return;
+
+ Real playable = (Real)m_settings.m_playableCells;
+ Real centre = playable * 0.5f;
+
+ // A lake is sized by the sector it has to fit in as well as by the map: eight players leave
+ // each other a wedge, and a lake that does not fit in the wedge is not placed at all.
+ Real spacing = 2.0f * PI * playable * RMG_START_RING / (Real)m_settings.m_numPlayers;
+ Real radius = playable * RMG_LAKE_RADIUS;
+ if( radius > spacing * RMG_LAKE_OF_SPACING )
+ radius = spacing * RMG_LAKE_OF_SPACING;
+
+ // Where the docks of the first player sit, which is where every player's sit once the layout
+ // is turned into their sector.
+ Real dockX[RMG_SUPPLY_PER_PLAYER];
+ Real dockY[RMG_SUPPLY_PER_PLAYER];
+ for( Int k = 0; k < RMG_SUPPLY_PER_PLAYER; k++ )
+ {
+ Real side = (k == 0) ? (PI * 0.5f) : (-PI * 0.5f);
+ Real angle = m_starts[0].m_angle + side;
+ dockX[k] = m_starts[0].m_cellX + RMG_SUPPLY_DISTANCE * Cos( angle );
+ dockY[k] = m_starts[0].m_cellY + RMG_SUPPLY_DISTANCE * Sin( angle );
+ }
+
+ Real edge = radius + RMG_LAKE_SHORE;
+ Real startClearance = edge + m_flatRadius;
+ Real dockClearance = edge + RMG_LAKE_DOCK_CLEARANCE;
- Real scale = RMG_FEATURES_PER_MAP / (Real)settings.m_playableCells;
+ /* Walk the sector out from the middle rather than trying a handful of named spots: on a small
+ map with eight players there is very little room that is not somebody's base, somebody's
+ dock or the ridge, and a fixed list either misses it or drops a lake on a dock. */
+ // Outward first: a lake in the quiet part of a sector is better than one beside the middle of
+ // the map, and the inner radii are what a cramped layout falls back on.
+ for( Int radiusStep = 48; radiusStep >= 12; radiusStep -= 2 )
+ {
+ for( Int angleStep = 9; angleStep >= -9; angleStep-- )
+ {
+ Real lakeAngle = m_baseAngle + m_sectorAngle * 0.5f * (Real)angleStep * 0.1f;
+ Real lakeRing = playable * (Real)radiusStep * 0.01f;
+ Real x = centre + lakeRing * Cos( lakeAngle );
+ Real y = centre + lakeRing * Sin( lakeAngle );
- data.resize( width * height );
+ if( distanceToNearestStart( x, y ) < startClearance )
+ continue;
- // The flat disc under each start takes the height the noise gives at that
- // spot, so the discs sit in the landscape instead of on top of it.
- Real startHeight[RandomMapGenerator::MAX_PLAYERS];
- Int i;
- for( i = 0; i < settings.m_numPlayers; i++ )
+ // The ridge and its chokepoint stay out of the water.
+ Real arcToBoundary = (m_sectorAngle * 0.5f
+ - fabsf( m_sectorAngle * 0.5f * (Real)angleStep * 0.1f )) * lakeRing;
+ if( arcToBoundary < edge + RMG_RIDGE_HALF_WIDTH )
+ continue;
+
+ Bool clear = TRUE;
+ for( Int k = 0; k < RMG_SUPPLY_PER_PLAYER; k++ )
+ {
+ Real dx = x - dockX[k];
+ Real dy = y - dockY[k];
+ if( sqrtf( dx * dx + dy * dy ) < dockClearance )
+ clear = FALSE;
+ }
+ if( !clear )
+ continue;
+
+ // The lake also has to stay inside the playable area, shore and all.
+ if( x - edge < 0.0f || y - edge < 0.0f || x + edge > playable || y + edge > playable )
+ continue;
+
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
+ {
+ RMGLake lake;
+ rotateAboutCentre( x, y, m_sectorAngle * (Real)i, &lake.m_cellX, &lake.m_cellY );
+ lake.m_radius = radius;
+ m_lakes.push_back( lake );
+ }
+ return;
+ }
+ }
+}
+
+Real RMGLayout::distanceToNearestStart( Real cellX, Real cellY ) const
+{
+ Real nearest = 1.0e9f;
+
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
+ {
+ Real dx = cellX - m_starts[i].m_cellX;
+ Real dy = cellY - m_starts[i].m_cellY;
+ Real distance = sqrtf( dx * dx + dy * dy );
+ if( distance < nearest )
+ nearest = distance;
+ }
+
+ return nearest;
+}
+
+Bool RMGLayout::insideLake( Real cellX, Real cellY, Real *distanceOut ) const
+{
+ Bool inside = FALSE;
+ Real nearest = 1.0e9f;
+
+ for( UnsignedInt i = 0; i < m_lakes.size(); i++ )
+ {
+ Real dx = cellX - m_lakes[i].m_cellX;
+ Real dy = cellY - m_lakes[i].m_cellY;
+ Real dist = sqrtf( dx * dx + dy * dy ) - m_lakes[i].m_radius;
+ if( dist < nearest )
+ nearest = dist;
+ if( dist < 0.0f )
+ inside = TRUE;
+ }
+
+ if( distanceOut )
+ *distanceOut = nearest;
+
+ return inside;
+}
+
+/** The parts of the height field that come from the layout rather than the
+ noise: the ridge between two players and the basin under a lake. Both are
+ written in sector-local terms, so they appear identically in every sector. */
+Real RMGLayout::ridgeAndLakeHeight( const UnsignedByte perm[512], Real cellX, Real cellY ) const
+{
+ Real playable = (Real)m_settings.m_playableCells;
+ Real scale = RMG_FEATURES_PER_MAP / playable;
+
+ RMGPolar polar = toPolar( cellX, cellY );
+
+ // Sample the noise at the sector-zero image of this point, which is what
+ // makes two players' ground the same ground.
+ Real canonicalAngle = m_baseAngle + polar.m_offsetAngle;
+ Real centre = playable * 0.5f;
+ Real nx = centre + polar.m_radius * Cos( canonicalAngle );
+ Real ny = centre + polar.m_radius * Sin( canonicalAngle );
+
+ Real height = RMG_BASE_HEIGHT + RMG_AMPLITUDE * fractalNoise( perm, nx * scale, ny * scale );
+
+ // The ridge, along the boundary the sector shares with its neighbour.
+ Real halfSector = m_sectorAngle * 0.5f;
+ Real arcToBoundary = (halfSector - fabsf( polar.m_offsetAngle )) * polar.m_radius;
+ Real gapCentre = playable * RMG_GAP_RADIUS;
+ Bool insideGap = fabsf( polar.m_radius - gapCentre ) < m_gapHalfCells;
+
+ if( arcToBoundary < RMG_RIDGE_HALF_WIDTH &&
+ polar.m_radius > playable * RMG_RIDGE_INNER &&
+ polar.m_radius < playable * RMG_RIDGE_OUTER &&
+ !insideGap &&
+ distanceToNearestStart( cellX, cellY ) > RMG_BASE_CLEARANCE )
+ {
+ height += RMG_RIDGE_RISE;
+ }
+
+ // The lake basin. Inside the shore it drops to a flat floor, so the water
+ // surface has something to sit on.
+ Real distanceToShore;
+ if( insideLake( cellX, cellY, &distanceToShore ) || distanceToShore < RMG_LAKE_SHORE )
{
- Real n = fractalNoise( perm, starts[i].m_cellX * scale, starts[i].m_cellY * scale );
- startHeight[i] = RMG_BASE_HEIGHT + RMG_AMPLITUDE * n;
+ Real floorHeight = RMG_BASE_HEIGHT - RMG_WATER_DROP - RMG_LAKE_DEPTH;
+ Real t = 0.0f;
+ if( distanceToShore > 0.0f )
+ t = distanceToShore / RMG_LAKE_SHORE;
+
+ height = lerpReal( floorHeight, height, fadeCurve( t ) );
}
- for( Int y = 0; y < height; y++ )
+ return height;
+}
+
+void RMGLayout::buildHeights( const UnsignedByte perm[512] )
+{
+ m_heights.resize( m_width * m_height );
+
+ // The flat disc under each start takes the height the terrain has at that
+ // spot, so the discs sit in the landscape instead of on top of it. Every
+ // start has the same one, because the sampled point is the same point.
+ Real startHeight = ridgeAndLakeHeight( perm, m_starts[0].m_cellX, m_starts[0].m_cellY );
+
+ for( Int y = 0; y < m_height; y++ )
{
- for( Int x = 0; x < width; x++ )
+ for( Int x = 0; x < m_width; x++ )
{
Real px = (Real)(x - RMG_BORDER_CELLS);
Real py = (Real)(y - RMG_BORDER_CELLS);
- Real h = RMG_BASE_HEIGHT + RMG_AMPLITUDE * fractalNoise( perm, px * scale, py * scale );
+ Real h = ridgeAndLakeHeight( perm, px, py );
- for( i = 0; i < settings.m_numPlayers; i++ )
+ // The nearest start only. Blending against every start in turn lets
+ // two overlapping discs flatten ground that belongs to neither.
+ Real dist = distanceToNearestStart( px, py );
+ if( dist < m_blendRadius )
{
- Real dx = px - starts[i].m_cellX;
- Real dy = py - starts[i].m_cellY;
- Real dist = sqrtf( dx * dx + dy * dy );
- if( dist >= RMG_BLEND_RADIUS )
- continue;
-
Real t = 0.0f;
- if( dist > RMG_FLAT_RADIUS )
- t = (dist - RMG_FLAT_RADIUS) / (RMG_BLEND_RADIUS - RMG_FLAT_RADIUS);
+ if( dist > m_flatRadius )
+ t = (dist - m_flatRadius) / (m_blendRadius - m_flatRadius);
- h = lerpReal( startHeight[i], h, fadeCurve( t ) );
+ h = lerpReal( startHeight, h, fadeCurve( t ) );
}
if( h < 1.0f ) h = 1.0f;
if( h > 254.0f ) h = 254.0f;
- data[y * width + x] = (UnsignedByte)(h + 0.5f);
+ m_heights[cellIndex( x, y )] = (UnsignedByte)(h + 0.5f);
+ }
+ }
+}
+
+Real RMGLayout::cellSpanWorld( Int x, Int y ) const
+{
+ Int a = m_heights[cellIndex( x, y )];
+ Int b = m_heights[cellIndex( x + 1, y )];
+ Int c = m_heights[cellIndex( x, y + 1 )];
+ Int d = m_heights[cellIndex( x + 1, y + 1 )];
+
+ Int lo = a, hi = a;
+ if( b < lo ) lo = b;
+ if( b > hi ) hi = b;
+ if( c < lo ) lo = c;
+ if( c > hi ) hi = c;
+ if( d < lo ) lo = d;
+ if( d > hi ) hi = d;
+
+ return (Real)(hi - lo) * MAP_HEIGHT_SCALE;
+}
+
+void RMGLayout::buildTerrainClasses( void )
+{
+ m_terrain.resize( m_width * m_height );
+
+ for( Int y = 0; y < m_height; y++ )
+ {
+ for( Int x = 0; x < m_width; x++ )
+ {
+ Real px = (Real)(x - RMG_BORDER_CELLS);
+ Real py = (Real)(y - RMG_BORDER_CELLS);
+ Real height = (Real)m_heights[cellIndex( x, y )];
+
+ Real span = 0.0f;
+ if( x + 1 < m_width && y + 1 < m_height )
+ span = cellSpanWorld( x, y );
+
+ UnsignedByte terrainClass = RMG_TERRAIN_GRASS;
+
+ Real distanceToShore;
+ insideLake( px, py, &distanceToShore );
+
+ // Sand is the low ground, whether the low ground is a lake bed or just the bottom of
+ // a hollow. A map with no room for a lake still gets its shores.
+ if( height < m_waterHeight + 2.0f || distanceToShore < RMG_LAKE_SHORE )
+ terrainClass = RMG_TERRAIN_SAND;
+ else if( span > RMG_CLIFF_WORLD_SPAN * 0.55f )
+ terrainClass = RMG_TERRAIN_ROCK;
+ else if( height > RMG_BASE_HEIGHT + RMG_AMPLITUDE * 0.45f )
+ terrainClass = RMG_TERRAIN_DIRT;
+
+ m_terrain[cellIndex( x, y )] = terrainClass;
+ }
+ }
+}
+
+void RMGLayout::buildPassability( void )
+{
+ m_passable.resize( m_width * m_height, 0 );
+
+ for( Int y = 0; y < m_height - 1; y++ )
+ {
+ for( Int x = 0; x < m_width - 1; x++ )
+ {
+ Bool passable = cellSpanWorld( x, y ) <= RMG_CLIFF_WORLD_SPAN;
+
+ if( passable )
+ {
+ Real px = (Real)(x - RMG_BORDER_CELLS);
+ Real py = (Real)(y - RMG_BORDER_CELLS);
+ if( insideLake( px, py, NULL ) && (Real)m_heights[cellIndex( x, y )] < m_waterHeight )
+ passable = FALSE;
+ }
+
+ m_passable[cellIndex( x, y )] = passable ? 1 : 0;
+ }
+ }
+}
+
+/** A map nobody can cross is not a map. Flood fill from player one's build
+ area and demand that every other start, and every supply dock, comes back.
+ The ridge is the only thing that can break this, so a failure widens its gap
+ and the whole layout is built again. */
+Bool RMGLayout::everyStartReachable( void ) const
+{
+ std::vector<char> seen( m_width * m_height, 0 );
+ std::vector<Int> stack;
+
+ Int startX = (Int)(m_starts[0].m_cellX + 0.5f) + RMG_BORDER_CELLS;
+ Int startY = (Int)(m_starts[0].m_cellY + 0.5f) + RMG_BORDER_CELLS;
+ Int startIndex = cellIndex( startX, startY );
+ if( m_passable[startIndex] == 0 )
+ return FALSE;
+
+ seen[startIndex] = 1;
+ stack.push_back( startIndex );
+
+ while( !stack.empty() )
+ {
+ Int index = stack.back();
+ stack.pop_back();
+
+ Int x = index % m_width;
+ Int y = index / m_width;
+
+ static const Int offsetX[4] = { 1, -1, 0, 0 };
+ static const Int offsetY[4] = { 0, 0, 1, -1 };
+
+ for( Int i = 0; i < 4; i++ )
+ {
+ Int nx = x + offsetX[i];
+ Int ny = y + offsetY[i];
+ if( nx < 0 || ny < 0 || nx >= m_width - 1 || ny >= m_height - 1 )
+ continue;
+
+ Int next = cellIndex( nx, ny );
+ if( seen[next] || m_passable[next] == 0 )
+ continue;
+
+ seen[next] = 1;
+ stack.push_back( next );
+ }
+ }
+
+ for( Int i = 1; i < m_settings.m_numPlayers; i++ )
+ {
+ Int x = (Int)(m_starts[i].m_cellX + 0.5f) + RMG_BORDER_CELLS;
+ Int y = (Int)(m_starts[i].m_cellY + 0.5f) + RMG_BORDER_CELLS;
+ if( !seen[cellIndex( x, y )] )
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+void RMGLayout::addRotatedCopies( const char *templateName, const char *idPrefix, Real cellX,
+ Real cellY, Real angle, Int& runningID )
+{
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
+ {
+ Real rotatedX, rotatedY;
+ rotateAboutCentre( cellX, cellY, m_sectorAngle * (Real)i, &rotatedX, &rotatedY );
+
+ RMGObject object;
+ object.m_templateName = templateName;
+ object.m_uniqueID.format( "%s %d", idPrefix, runningID++ );
+ object.m_worldX = rotatedX * MAP_XY_FACTOR;
+ object.m_worldY = rotatedY * MAP_XY_FACTOR;
+ object.m_angle = angle + m_sectorAngle * (Real)i;
+ object.m_waypointID = 0;
+
+ m_objects.push_back( object );
+ }
+}
+
+void RMGLayout::addProps( const UnsignedByte perm[512] )
+{
+ Real playable = (Real)m_settings.m_playableCells;
+ Real scale = RMG_FEATURES_PER_MAP * 2.0f / playable;
+ Real gapCentre = playable * RMG_GAP_RADIUS;
+
+ // One name per slot of the hash, so a patch of forest is trees and a patch
+ // of scree is rocks rather than both being one repeated model.
+ static const char *theTreeNames[] = { "TreeDogwood1", "TreeFir01B", "TreeCherryBlossom01",
+ "TreeCherryBlossom02" };
+ static const char *theRockNames[] = { "Rocks1", "Rocks2", "Rocks3", "RockClusterMedium01",
+ "RockClusterSmall01" };
+ const Int numTreeNames = sizeof(theTreeNames) / sizeof(theTreeNames[0]);
+ const Int numRockNames = sizeof(theRockNames) / sizeof(theRockNames[0]);
+
+ // Snapshot the supply positions before the scan, since the scan appends to
+ // the same list it would otherwise have to search.
+ std::vector<RMGLake> supplyClearances;
+ for( UnsignedInt i = 0; i < m_objects.size(); i++ )
+ {
+ if( m_objects[i].m_templateName.compare( "SupplyDock" ) != 0 )
+ continue;
+
+ RMGLake clearance;
+ clearance.m_cellX = m_objects[i].m_worldX / MAP_XY_FACTOR;
+ clearance.m_cellY = m_objects[i].m_worldY / MAP_XY_FACTOR;
+ clearance.m_radius = RMG_SUPPLY_CLEARANCE;
+ supplyClearances.push_back( clearance );
+ }
+
+ Int placed = 0;
+ Int runningID = 1;
+
+ for( Int cellY = 0; cellY < m_settings.m_playableCells && placed < RMG_PROPS_PER_SECTOR;
+ cellY += RMG_PROP_STEP )
+ {
+ for( Int cellX = 0; cellX < m_settings.m_playableCells && placed < RMG_PROPS_PER_SECTOR;
+ cellX += RMG_PROP_STEP )
+ {
+ Real px = (Real)cellX;
+ Real py = (Real)cellY;
+
+ // Only sector zero is scanned; the copies are rotated out of it.
+ RMGPolar polar = toPolar( px, py );
+ if( polar.m_sector != 0 )
+ continue;
+
+ Int mapX = cellX + RMG_BORDER_CELLS;
+ Int mapY = cellY + RMG_BORDER_CELLS;
+ if( !passableAtCell( mapX, mapY ) )
+ continue;
+
+ // Keep the ground people build and fight over clear.
+ if( distanceToNearestStart( px, py ) < m_blendRadius + RMG_PROP_CLEARANCE )
+ continue;
+
+ if( fabsf( polar.m_radius - gapCentre ) < m_gapHalfCells + RMG_GAP_CLEARANCE )
+ continue;
+
+ Real distanceToShore;
+ insideLake( px, py, &distanceToShore );
+ if( distanceToShore < 2.0f )
+ continue;
+
+ Bool nearSupply = FALSE;
+ for( UnsignedInt i = 0; i < supplyClearances.size(); i++ )
+ {
+ Real sx = supplyClearances[i].m_cellX - px;
+ Real sy = supplyClearances[i].m_cellY - py;
+ if( sqrtf( sx * sx + sy * sy ) < supplyClearances[i].m_radius )
+ {
+ nearSupply = TRUE;
+ break;
+ }
+ }
+ if( nearSupply )
+ continue;
+
+ // Patchy rather than evenly sprinkled: the noise decides where a
+ // stand of trees is, the hash decides which cells of it are used.
+ Real density = fractalNoise( perm, px * scale + 100.0f, py * scale - 100.0f );
+ UnsignedInt hash = hashCell( m_settings.m_seed, cellX, cellY );
+ Real roll = (Real)(hash % 1000U) / 1000.0f;
+ if( roll > (density + 1.0f) * 0.25f )
+ continue;
+
+ Bool rocky = m_terrain[cellIndex( mapX, mapY )] == RMG_TERRAIN_ROCK;
+ const char *name = rocky
+ ? theRockNames[(hash >> 10) % (UnsignedInt)numRockNames]
+ : theTreeNames[(hash >> 10) % (UnsignedInt)numTreeNames];
+
+ Real angle = (Real)((hash >> 20) % 1024U) * (2.0f * PI / 1024.0f);
+ addRotatedCopies( name, "Prop", px, py, angle, runningID );
+ placed++;
}
}
}
+/** The neutral economy: a derrick on every chokepoint, so the crossing is worth
+ holding, a pair of garrisonable buildings in each sector, and a hospital in
+ the middle of a map big enough for one. */
+void RMGLayout::addTechAndCivilians( void )
+{
+ Real playable = (Real)m_settings.m_playableCells;
+ Real centre = playable * 0.5f;
+ Int runningID = 1;
+
+ // The derrick sits in the gap, which is on the boundary between one sector
+ // and the next, so one copy per boundary is one copy per sector.
+ Real gapRadius = playable * RMG_GAP_RADIUS;
+ Real boundaryAngle = m_baseAngle + m_sectorAngle * 0.5f;
+ addRotatedCopies( "TechOilDerrick", "Derrick",
+ centre + gapRadius * Cos( boundaryAngle ),
+ centre + gapRadius * Sin( boundaryAngle ),
+ boundaryAngle + PI, runningID );
+
+ runningID = 1;
+ Real civilianRadius = playable * RMG_CIVILIAN_RING;
+ for( Int i = 0; i < RMG_CIVILIANS_PER_SECTOR; i++ )
+ {
+ Real offset = (i == 0) ? RMG_CIVILIAN_SPREAD : -RMG_CIVILIAN_SPREAD;
+ Real angle = m_baseAngle + offset / civilianRadius;
+ Real cellX = centre + civilianRadius * Cos( angle );
+ Real cellY = centre + civilianRadius * Sin( angle );
+
+ Int mapX = (Int)(cellX + 0.5f) + RMG_BORDER_CELLS;
+ Int mapY = (Int)(cellY + 0.5f) + RMG_BORDER_CELLS;
+ if( mapX < 0 || mapY < 0 || mapX >= m_width || mapY >= m_height )
+ continue;
+ if( !passableAtCell( mapX, mapY ) )
+ continue;
+
+ const char *name = (i == 0) ? "CivilianHighrise01" : "CivilianHighrise02";
+ addRotatedCopies( name, "Civilian", cellX, cellY, angle + PI, runningID );
+ }
+
+ if( m_settings.m_playableCells >= RMG_HOSPITAL_MIN_CELLS )
+ {
+ RMGObject hospital;
+ hospital.m_templateName = "TechHospital";
+ hospital.m_uniqueID = "Hospital 1";
+ hospital.m_worldX = centre * MAP_XY_FACTOR;
+ hospital.m_worldY = centre * MAP_XY_FACTOR;
+ hospital.m_angle = m_baseAngle;
+ hospital.m_waypointID = 0;
+ m_objects.push_back( hospital );
+ }
+}
+
+void RMGLayout::buildObjects( const UnsignedByte perm[512] )
+{
+ m_objects.clear();
+
+ Int waypointID = 1;
+ Int supplyID = 1;
+
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
+ {
+ RMGObject waypoint;
+ waypoint.m_templateName = "*Waypoints/Waypoint";
+ waypoint.m_uniqueID.format( "Player_%d_Start", i + 1 );
+ waypoint.m_worldX = m_starts[i].m_cellX * MAP_XY_FACTOR;
+ waypoint.m_worldY = m_starts[i].m_cellY * MAP_XY_FACTOR;
+ waypoint.m_angle = 0.0f;
+ waypoint.m_waypointID = waypointID++;
+ m_objects.push_back( waypoint );
+ }
+
+ // Supply docks: off to either side of the line from the middle to the start,
+ // written straight rather than through the rotation helper so the numbering
+ // stays player by player.
+ for( Int i = 0; i < m_settings.m_numPlayers; i++ )
+ {
+ for( Int k = 0; k < RMG_SUPPLY_PER_PLAYER; k++ )
+ {
+ Real side = (k == 0) ? (PI * 0.5f) : (-PI * 0.5f);
+ Real angle = m_starts[i].m_angle + side;
+
+ RMGObject dock;
+ dock.m_templateName = "SupplyDock";
+ dock.m_uniqueID.format( "SupplyDock %d", supplyID++ );
+ dock.m_worldX = (m_starts[i].m_cellX + RMG_SUPPLY_DISTANCE * Cos( angle )) * MAP_XY_FACTOR;
+ dock.m_worldY = (m_starts[i].m_cellY + RMG_SUPPLY_DISTANCE * Sin( angle )) * MAP_XY_FACTOR;
+ dock.m_angle = m_starts[i].m_angle + PI;
+ dock.m_waypointID = 0;
+ m_objects.push_back( dock );
+ }
+ }
+
+ addTechAndCivilians();
+ addProps( perm );
+}
+
+void RMGLayout::build( const RandomMapSettings& settings )
+{
+ /* The height field is x87 arithmetic, so it comes out differently at 53-bit precision than at
+ the 24 bits the simulation runs in - the same trap GameLogic::update re-asserts the control
+ word for at the top of every logic frame. A map generated in whatever mode the last DLL left
+ behind is a map the other machine does not have, so put the FPU where the simulation keeps
+ it and give the caller back what it had. */
+ UnsignedInt callersFPMode = getFPMode();
+ setFPMode();
+
+ m_settings = settings;
+ RandomMapGenerator::clampSettings( m_settings );
+
+ m_width = m_settings.m_playableCells + 2 * RMG_BORDER_CELLS;
+ m_height = m_width;
+ m_waterHeight = RMG_BASE_HEIGHT - RMG_WATER_DROP;
+
+ UnsignedByte perm[512];
+ seedPermutation( m_settings.m_seed, perm );
+
+ computeStarts();
+
+ Real playable = (Real)m_settings.m_playableCells;
+
+ m_gapHalfCells = playable * RMG_GAP_HALF;
+
+ // Cap the base discs by how far apart neighbouring starts actually are.
+ Real spacing = 2.0f * PI * playable * RMG_START_RING / (Real)m_settings.m_numPlayers;
+ m_flatRadius = spacing * RMG_FLAT_OF_SPACING;
+ if( m_flatRadius > RMG_FLAT_RADIUS )
+ m_flatRadius = RMG_FLAT_RADIUS;
+
+ m_blendRadius = spacing * RMG_BLEND_OF_SPACING;
+ if( m_blendRadius > RMG_BLEND_RADIUS )
+ m_blendRadius = RMG_BLEND_RADIUS;
+ if( m_blendRadius < m_flatRadius + 4.0f )
+ m_blendRadius = m_flatRadius + 4.0f;
+
+ // After the base discs are sized, since a lake keeps clear of them.
+ placeLakes();
+
+ for( Int attempt = 0; attempt < RMG_LAYOUT_ATTEMPTS; attempt++ )
+ {
+ buildHeights( perm );
+ buildPassability();
+
+ if( everyStartReachable() )
+ break;
+
+ // Widening the gap is the one lever that opens a map the ridge closed.
+ m_gapHalfCells *= RMG_GAP_WIDEN_STEP;
+ }
+
+ buildTerrainClasses();
+ buildObjects( perm );
+
+ _controlfp( callersFPMode, _MCW_PC | _MCW_RC );
+}
+
+//-----------------------------------------------------------------------------
+// Map pieces
+//-----------------------------------------------------------------------------
+
+/** The tile index WorldBuilder computes for a cell: four quadrants packed into
+ each source tile, the source tile picked by tiling the class across the map. */
+static Short tileIndexForCell( Int x, Int y, Int firstTile, Int width )
+{
+ Int ndx = firstTile + ((x / 2) % width) + width * ((y / 2) % width);
+ ndx = (ndx << 2) + 2 * (y & 1) + (x & 1);
+ return (Short)ndx;
+}
+
/// One waypoint object. The reader calls anything with a waypointID a waypoint.
-static void writeWaypoint( MapChunkWriter& w, const char *name, Int waypointID, Real x, Real y )
+static void writeWaypoint( MapChunkWriter& w, const RMGObject& object )
{
w.openChunk( "Object", K_OBJECTS_VERSION_3 );
- w.writeReal( x );
- w.writeReal( y );
+ w.writeReal( object.m_worldX );
+ w.writeReal( object.m_worldY );
w.writeReal( 0.0f );
w.writeReal( 0.0f );
w.writeInt( 0 );
- w.writeAsciiString( "*Waypoints/Waypoint" );
+ w.writeAsciiString( object.m_templateName.str() );
w.beginDict( 12 );
w.dictInt( "objectInitialHealth", 100 );
@@ -423,25 +1188,25 @@ static void writeWaypoint( MapChunkWriter& w, const char *name, Int waypointID,
w.dictBool( "objectPowered", TRUE );
w.dictBool( "objectRecruitableAI", TRUE );
w.dictAsciiString( "originalOwner", "team" );
- w.dictAsciiString( "uniqueID", name );
+ w.dictAsciiString( "uniqueID", object.m_uniqueID.str() );
w.dictAsciiString( "objectLayer", "Start Points" );
- w.dictInt( "waypointID", waypointID );
+ w.dictInt( "waypointID", object.m_waypointID );
w.dictBool( "objectDestructible", TRUE );
w.dictBool( "objectSellable", TRUE );
w.dictBool( "objectRepairable", TRUE );
- w.dictAsciiString( "waypointName", name );
+ w.dictAsciiString( "waypointName", object.m_uniqueID.str() );
w.closeChunk();
}
-static void writeSupplyDock( MapChunkWriter& w, const char *uniqueID, Real x, Real y, Real angle )
+static void writeNeutralObject( MapChunkWriter& w, const RMGObject& object )
{
w.openChunk( "Object", K_OBJECTS_VERSION_3 );
- w.writeReal( x );
- w.writeReal( y );
+ w.writeReal( object.m_worldX );
+ w.writeReal( object.m_worldY );
w.writeReal( 0.0f );
- w.writeReal( angle );
+ w.writeReal( object.m_angle );
w.writeInt( 0 );
- w.writeAsciiString( "SupplyDock" );
+ w.writeAsciiString( object.m_templateName.str() );
w.beginDict( 11 );
w.dictInt( "objectInitialHealth", 100 );
@@ -452,7 +1217,7 @@ static void writeSupplyDock( MapChunkWriter& w, const char *uniqueID, Real x, Re
w.dictBool( "objectRecruitableAI", TRUE );
w.dictAsciiString( "objectName", "" );
w.dictAsciiString( "originalOwner", "team" );
- w.dictAsciiString( "uniqueID", uniqueID );
+ w.dictAsciiString( "uniqueID", object.m_uniqueID.str() );
w.dictAsciiString( "objectLayer", "" );
w.dictBool( "objectSelectable", TRUE );
w.closeChunk();
@@ -539,29 +1304,121 @@ static void writeSides( MapChunkWriter& w )
w.closeChunk();
}
+/** One water area per lake, as the octagon the trigger reader wants. Point zero
+ carries the water height for the whole area, which is what isUnderwater
+ compares the ground against. */
+static void writeWaterAreas( MapChunkWriter& w, const RMGLayout& layout )
+{
+ const Int numSides = 8;
+
+ w.openChunk( "PolygonTriggers", K_TRIGGERS_VERSION_4 );
+ w.writeInt( (Int)layout.m_lakes.size() );
+
+ for( UnsignedInt i = 0; i < layout.m_lakes.size(); i++ )
+ {
+ AsciiString name;
+ name.format( "Lake%d", i + 1 );
+
+ w.writeAsciiString( name.str() );
+ w.writeAsciiString( "" ); // layer
+ w.writeInt( (Int)i + 1 ); // trigger id
+ w.writeByte( 1 ); // is a water area
+ w.writeByte( 0 ); // not a river
+ w.writeInt( 0 ); // river start
+ w.writeInt( numSides );
+
+ Int waterZ = (Int)(layout.m_waterHeight * MAP_HEIGHT_SCALE + 0.5f);
+
+ for( Int point = 0; point < numSides; point++ )
+ {
+ Real angle = (2.0f * PI * (Real)point) / (Real)numSides;
+ Real x = layout.m_lakes[i].m_cellX + layout.m_lakes[i].m_radius * Cos( angle );
+ Real y = layout.m_lakes[i].m_cellY + layout.m_lakes[i].m_radius * Sin( angle );
+
+ w.writeInt( (Int)(x * MAP_XY_FACTOR + 0.5f) );
+ w.writeInt( (Int)(y * MAP_XY_FACTOR + 0.5f) );
+ w.writeInt( waterZ );
+ }
+ }
+ w.closeChunk();
+}
+
+/** Daylight. A map with no lighting chunk keeps whatever GameData.ini left in GlobalData, which is
+ the dusk the shipped maps all override, so a generated map looked like somebody had turned the
+ sun off. These are written for all four times of day: the map has no scripts to change the hour
+ with, and a player who forces one should still be able to see the ground. */
+static void writeGlobalLighting( MapChunkWriter& w )
+{
+ // x and y point the sun across the map, z takes it down onto the ground.
+ static const Real theSunDirection[3] = { -0.58f, 0.42f, -0.70f };
+ static const Real theTerrainAmbient[3] = { 0.35f, 0.35f, 0.36f };
+ static const Real theTerrainDiffuse[3] = { 0.78f, 0.75f, 0.68f };
+ static const Real theObjectAmbient[3] = { 0.45f, 0.45f, 0.47f };
+ static const Real theObjectDiffuse[3] = { 0.82f, 0.79f, 0.72f };
+
+ w.openChunk( "GlobalLighting", K_LIGHTING_VERSION_3 );
+ w.writeInt( TIME_OF_DAY_AFTERNOON );
+
+ Int timeOfDay, light, channel;
+ for( timeOfDay = 0; timeOfDay < 4; timeOfDay++ )
+ {
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theTerrainAmbient[channel] );
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theTerrainDiffuse[channel] );
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theSunDirection[channel] );
+
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theObjectAmbient[channel] );
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theObjectDiffuse[channel] );
+ for( channel = 0; channel < 3; channel++ )
+ w.writeReal( theSunDirection[channel] );
+
+ // The two extra lights of version 3, dark but pointing somewhere valid: one sun is
+ // what this map wants, and a light with no direction at all upsets the shaders.
+ for( light = 1; light < MAX_GLOBAL_LIGHTS; light++ )
+ {
+ for( channel = 0; channel < 6; channel++ )
+ w.writeReal( 0.0f );
+ w.writeReal( 0.0f );
+ w.writeReal( 0.0f );
+ w.writeReal( -1.0f );
+ }
+ for( light = 1; light < MAX_GLOBAL_LIGHTS; light++ )
+ {
+ for( channel = 0; channel < 6; channel++ )
+ w.writeReal( 0.0f );
+ w.writeReal( 0.0f );
+ w.writeReal( 0.0f );
+ w.writeReal( -1.0f );
+ }
+ }
+ w.closeChunk();
+}
+
//-----------------------------------------------------------------------------
// RandomMapGenerator
//-----------------------------------------------------------------------------
+void RandomMapGenerator::clampSettings( RandomMapSettings& settings )
+{
+ if( settings.m_playableCells < MIN_CELLS ) settings.m_playableCells = MIN_CELLS;
+ if( settings.m_playableCells > MAX_CELLS ) settings.m_playableCells = MAX_CELLS;
+ if( settings.m_numPlayers < MIN_PLAYERS ) settings.m_numPlayers = MIN_PLAYERS;
+ if( settings.m_numPlayers > MAX_PLAYERS ) settings.m_numPlayers = MAX_PLAYERS;
+}
+
void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vector<char>& mapBytes )
{
- RandomMapSettings s = settings;
- if( s.m_playableCells < MIN_CELLS ) s.m_playableCells = MIN_CELLS;
- if( s.m_playableCells > MAX_CELLS ) s.m_playableCells = MAX_CELLS;
- if( s.m_numPlayers < MIN_PLAYERS ) s.m_numPlayers = MIN_PLAYERS;
- if( s.m_numPlayers > MAX_PLAYERS ) s.m_numPlayers = MAX_PLAYERS;
+ RMGLayout layout;
+ layout.build( settings );
- Int playable = s.m_playableCells;
- Int width = playable + 2 * RMG_BORDER_CELLS;
- Int height = width;
+ Int width = layout.m_width;
+ Int height = layout.m_height;
Int dataSize = width * height;
- RMGStart starts[MAX_PLAYERS];
- computeStarts( s, starts );
-
- std::vector<UnsignedByte> heights;
- buildHeights( s, starts, width, height, heights );
-
MapChunkWriter w;
/***************HEIGHT MAP DATA ***************/
@@ -570,10 +1427,10 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vecto
w.writeInt( height );
w.writeInt( RMG_BORDER_CELLS );
w.writeInt( 1 ); // one boundary
- w.writeInt( playable );
- w.writeInt( playable );
+ w.writeInt( layout.m_settings.m_playableCells );
+ w.writeInt( layout.m_settings.m_playableCells );
w.writeInt( dataSize );
- w.writeBytes( &heights[0], dataSize );
+ w.writeBytes( &layout.m_heights[0], dataSize );
w.closeChunk();
/***************BLEND TILE DATA ***************/
@@ -584,8 +1441,14 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vecto
std::vector<Short> zeroes( dataSize, 0 );
for( Int y = 0; y < height; y++ )
+ {
for( Int x = 0; x < width; x++ )
- tiles[y * width + x] = tileIndexForCell( x, y, 0, RMG_TEXTURE_WIDTH );
+ {
+ 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 );
+ }
+ }
w.openChunk( "BlendTileData", K_BLEND_TILE_VERSION_6 );
w.writeInt( dataSize );
@@ -594,16 +1457,19 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vecto
w.writeBytes( &zeroes[0], dataSize * sizeof(Short) ); // extra blend tiles
w.writeBytes( &zeroes[0], dataSize * sizeof(Short) ); // cliff info
- w.writeInt( RMG_TEXTURE_TILES ); // bitmap tiles
+ w.writeInt( RMG_TERRAIN_COUNT * RMG_TILES_PER_CLASS ); // bitmap tiles
w.writeInt( 1 ); // blended tiles: entry 0 is the default
w.writeInt( 1 ); // cliff infos: entry 0 is the default
- w.writeInt( 1 ); // one texture class
- w.writeInt( 0 ); // first tile
- w.writeInt( RMG_TEXTURE_TILES );
- w.writeInt( RMG_TEXTURE_WIDTH );
- w.writeInt( 0 ); // legacy field
- w.writeAsciiString( RMG_TEXTURE_NAME );
+ 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 );
+ w.writeInt( 0 ); // legacy field
+ w.writeAsciiString( theTerrainClassNames[terrainClass] );
+ }
w.writeInt( 0 ); // no edge tiles
w.writeInt( 0 ); // no edge texture classes
@@ -624,32 +1490,196 @@ void RandomMapGenerator::generate( const RandomMapSettings& settings, std::vecto
/***************OBJECTS DATA ***************/
w.openChunk( "ObjectsList", K_OBJECTS_VERSION_3 );
+ for( UnsignedInt i = 0; i < layout.m_objects.size(); i++ )
+ {
+ if( layout.m_objects[i].m_waypointID > 0 )
+ writeWaypoint( w, layout.m_objects[i] );
+ else
+ writeNeutralObject( w, layout.m_objects[i] );
+ }
+ w.closeChunk();
+
+ /***************WATER ***************/
+ if( !layout.m_lakes.empty() )
+ writeWaterAreas( w, layout );
+
+ /***************GLOBAL LIGHTING DATA ***************/
+ writeGlobalLighting( w );
+
+ w.finish( mapBytes );
+}
+
+UnsignedInt RandomMapGenerator::fingerprint( const RandomMapSettings& settings )
+{
+ std::vector<char> mapBytes;
+ generate( settings, mapBytes );
+
+ CRC crc;
+ Int version = RANDOM_MAP_GENERATOR_VERSION;
+ crc.computeCRC( &version, sizeof(version) );
+ crc.computeCRC( &mapBytes[0], (Int)mapBytes.size() );
+
+ return crc.get();
+}
+
+//-----------------------------------------------------------------------------
+// Preview
+//-----------------------------------------------------------------------------
+
+/// Uncompressed 24-bit bottom-up tga, the shape every loader in the tree reads.
+static void writeTgaHeader( std::vector<char>& tga, Int pixels )
+{
+ const Int headerBytes = 18;
+ char header[headerBytes];
+ memset( header, 0, headerBytes );
+
+ header[2] = 2; // uncompressed true colour
+ header[12] = (char)(pixels & 0xff);
+ header[13] = (char)((pixels >> 8) & 0xff);
+ header[14] = (char)(pixels & 0xff);
+ header[15] = (char)((pixels >> 8) & 0xff);
+ header[16] = 24; // bits per pixel
+
+ tga.insert( tga.end(), header, header + headerBytes );
+}
+
+void RandomMapGenerator::generatePreview( const RandomMapSettings& settings,
+ std::vector<char>& tgaBytes )
+{
+ RMGLayout layout;
+ layout.build( settings );
+
+ const Int pixels = PREVIEW_PIXELS;
+
+ tgaBytes.clear();
+ writeTgaHeader( tgaBytes, pixels );
+
+ // Ground colours, in the RMGTerrainClass order, plus water and the marks.
+ static const UnsignedByte theGroundColours[RMG_TERRAIN_COUNT][3] =
{
- Int waypointID = 1;
- for( Int i = 0; i < s.m_numPlayers; i++ )
+ { 86, 122, 62 }, // grass
+ { 132, 112, 74 }, // dirt
+ { 118, 118, 112 }, // rock
+ { 190, 176, 130 } // sand
+ };
+ static const UnsignedByte theWaterColour[3] = { 48, 86, 130 };
+ static const UnsignedByte theStartColour[3] = { 240, 240, 240 };
+ static const UnsignedByte theCliffColour[3] = { 58, 54, 50 };
+
+ Real playable = (Real)layout.m_settings.m_playableCells;
+ Real cellsPerPixel = playable / (Real)pixels;
+
+ for( Int row = 0; row < pixels; row++ )
+ {
+ // Bottom-up file order, and the map's y grows the way the image's does.
+ Int previewY = pixels - 1 - row;
+
+ for( Int column = 0; column < pixels; column++ )
{
- AsciiString name;
- name.format( "Player_%d_Start", i + 1 );
- writeWaypoint( w, name.str(), waypointID++,
- starts[i].m_cellX * MAP_XY_FACTOR, starts[i].m_cellY * MAP_XY_FACTOR );
+ Int cellX = (Int)((Real)column * cellsPerPixel) + RMG_BORDER_CELLS;
+ Int cellY = (Int)((Real)previewY * cellsPerPixel) + RMG_BORDER_CELLS;
- for( Int k = 0; k < RMG_SUPPLY_PER_PLAYER; k++ )
+ if( cellX >= layout.m_width ) cellX = layout.m_width - 1;
+ if( cellY >= layout.m_height ) cellY = layout.m_height - 1;
+
+ Real height = (Real)layout.heightAtCell( cellX, cellY );
+ UnsignedByte terrainClass = layout.terrainAtCell( cellX, cellY );
+
+ const UnsignedByte *colour = theGroundColours[terrainClass];
+
+ Real px = (Real)(cellX - RMG_BORDER_CELLS);
+ Real py = (Real)(cellY - RMG_BORDER_CELLS);
+ if( layout.insideLake( px, py, NULL ) && height < layout.m_waterHeight )
+ colour = theWaterColour;
+ else if( !layout.passableAtCell( cellX, cellY ) )
+ colour = theCliffColour;
+
+ // Cheap relief: the higher the ground, the lighter the pixel.
+ Real shade = 0.70f + 0.60f * (height - RMG_BASE_HEIGHT) / (RMG_AMPLITUDE * 2.0f);
+ if( shade < 0.45f ) shade = 0.45f;
+ if( shade > 1.35f ) shade = 1.35f;
+
+ Real blue = (Real)colour[2] * shade;
+ Real green = (Real)colour[1] * shade;
+ Real red = (Real)colour[0] * shade;
+
+ // The start positions, so the list entry says how many players it is for.
+ for( Int i = 0; i < layout.m_settings.m_numPlayers; i++ )
{
- // Off to either side of the line from the middle to the start.
- Real side = (k == 0) ? (PI * 0.5f) : (-PI * 0.5f);
- Real angle = starts[i].m_angle + side;
- Real x = (starts[i].m_cellX + RMG_SUPPLY_DISTANCE * Cos( angle )) * MAP_XY_FACTOR;
- Real y = (starts[i].m_cellY + RMG_SUPPLY_DISTANCE * Sin( angle )) * MAP_XY_FACTOR;
-
- AsciiString uniqueID;
- uniqueID.format( "SupplyDock %d", i * RMG_SUPPLY_PER_PLAYER + k + 1 );
- writeSupplyDock( w, uniqueID.str(), x, y, starts[i].m_angle + PI );
+ Real dx = px - layout.m_starts[i].m_cellX;
+ Real dy = py - layout.m_starts[i].m_cellY;
+ if( dx * dx + dy * dy < 9.0f * cellsPerPixel * cellsPerPixel )
+ {
+ red = (Real)theStartColour[0];
+ green = (Real)theStartColour[1];
+ blue = (Real)theStartColour[2];
+ }
}
+
+ if( red > 255.0f ) red = 255.0f;
+ if( green > 255.0f ) green = 255.0f;
+ if( blue > 255.0f ) blue = 255.0f;
+
+ tgaBytes.push_back( (char)(UnsignedByte)blue );
+ tgaBytes.push_back( (char)(UnsignedByte)green );
+ tgaBytes.push_back( (char)(UnsignedByte)red );
}
}
- w.closeChunk();
+}
- w.finish( mapBytes );
+//-----------------------------------------------------------------------------
+// Writing a generated map where the map cache will find it
+//-----------------------------------------------------------------------------
+
+static Bool writeWholeFile( const AsciiString& path, const std::vector<char>& bytes )
+{
+ FILE *fp = fopen( path.str(), "wb" );
+ if( fp == NULL )
+ {
+ DEBUG_LOG(("random map: could not write '%s'\n", path.str()));
+ return FALSE;
+ }
+
+ fwrite( &bytes[0], 1, bytes.size(), fp );
+ fclose( fp );
+ return TRUE;
+}
+
+Bool writeRandomMap( const RandomMapSettings& settings, AsciiString& mapPathOut )
+{
+ RandomMapSettings clamped = settings;
+ RandomMapGenerator::clampSettings( clamped );
+
+ std::vector<char> mapBytes;
+ std::vector<char> previewBytes;
+ RandomMapGenerator::generate( clamped, mapBytes );
+ RandomMapGenerator::generatePreview( clamped, previewBytes );
+
+ // The map cache expects "<user maps>\<name>\<name>.map" - the directory
+ // carries the name - and getMapPreviewImage wants "<name>.tga" beside it.
+ AsciiString name;
+ name.format( "RMG_v%d_%d_%dp_%dc", RANDOM_MAP_GENERATOR_VERSION, clamped.m_seed,
+ clamped.m_numPlayers, clamped.m_playableCells );
+
+ AsciiString mapsDir, dir, previewPath;
+ mapsDir.format( "%sMaps", TheGlobalData->getPath_UserData().str() );
+ dir.format( "%s\\%s", mapsDir.str(), name.str() );
+ mapPathOut.format( "%s\\%s.map", dir.str(), name.str() );
+ previewPath.format( "%s\\%s.tga", dir.str(), name.str() );
+
+ TheFileSystem->createDirectory( mapsDir ); // createDirectory is one level at a time
+ TheFileSystem->createDirectory( dir );
+
+ if( !writeWholeFile( mapPathOut, mapBytes ) )
+ return FALSE;
+
+ writeWholeFile( previewPath, previewBytes );
+
+ DEBUG_LOG(("random map: wrote '%s' - %d players, %d cells, %d bytes, fingerprint %X\n",
+ mapPathOut.str(), clamped.m_numPlayers, clamped.m_playableCells, mapBytes.size(),
+ RandomMapGenerator::fingerprint( clamped )));
+
+ return TRUE;
}
//-----------------------------------------------------------------------------
diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp
index ece215858..83c16f532 100644
--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp
+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/Menus/SkirmishMapSelectMenu.cpp
@@ -44,6 +44,7 @@
#include "GameClient/GadgetStaticText.h"
#include "GameNetwork/LANAPICallbacks.h"
#include "GameClient/MapUtil.h"
+#include "Common/RandomMapGenerator.h"
// PRIVATE DATA ///////////////////////////////////////////////////////////////////////////////////
static NameKeyType buttonBack = NAMEKEY_INVALID;
@@ -55,6 +56,53 @@ static GameWindow *mapList = NULL;
static NameKeyType radioButtonSystemMapsID = NAMEKEY_INVALID;
static NameKeyType radioButtonUserMapsID = NAMEKEY_INVALID;
+/** The random map row. There is no window layout file in this fork to add a button to - every
+ .wnd lives inside the shipped archives - so the reroll is a row in the map list instead of a
+ control beside it. It is not a map in the cache, so it carries this tag where every other row
+ carries its file name, and choosing it generates a new map and picks that. */
+static const char *theRandomMapRowTag = "**random**";
+#define RMG_MENU_CELLS 160
+
+static Bool isRandomMapRow( const char *itemData )
+{
+ return itemData != NULL && strcmp( itemData, theRandomMapRowTag ) == 0;
+}
+
+static void addRandomMapRow( GameWindow *listbox )
+{
+ if( listbox == NULL )
+ return;
+
+ Color color = GameMakeColor( 255, 255, 255, 255 );
+ Int numColumns = GadgetListBoxGetNumColumns( listbox );
+ // Spelled out here rather than fetched: the string tables live in the shipped
+ // archives, and a missing label would read "MISSING: GUI:RandomMap" on screen.
+ UnicodeString label( L"Random map - new seed every time (8)" );
+ Int index = GadgetListBoxAddEntryText( listbox, label, color, -1, numColumns - 1 );
+ GadgetListBoxSetItemData( listbox, (void *)theRandomMapRowTag, index );
+}
+
+/** Generate a map, write it where the map cache looks, and hand back its path. The seed comes off
+ the clock: this is the client picking a map, not the simulation, so it may be as random as the
+ player expects a reroll to be. */
+static Bool generateRandomMapForSkirmish( AsciiString& mapPathOut )
+{
+ RandomMapSettings settings;
+ settings.m_seed = (Int)GetTickCount();
+ settings.m_numPlayers = RandomMapGenerator::MAX_PLAYERS;
+ settings.m_playableCells = RMG_MENU_CELLS;
+
+ if( !writeRandomMap( settings, mapPathOut ) )
+ return FALSE;
+
+ mapPathOut.toLower();
+
+ if( TheMapCache )
+ TheMapCache->updateCache();
+
+ return TRUE;
+}
+
static GameWindow *buttonMapStartPosition[MAX_SLOTS] = {NULL,NULL,NULL,NULL,
NULL,NULL,NULL,NULL };
static NameKeyType buttonMapStartPositionID[MAX_SLOTS] = { NAMEKEY_INVALID,NAMEKEY_INVALID,
@@ -310,6 +358,7 @@ void SkirmishMapSelectMenuInit( WindowLayout *layout, void *userData )
populateMapListbox( mapList, FALSE, FALSE, TheSkirmishGameInfo->getMap() );
populateMapListboxNoReset( mapList, FALSE, TRUE, TheSkirmishGameInfo->getMap() );
}
+ addRandomMapRow( mapList );
mapList->winSetTooltipFunc(mapListTooltipFunc);
}
@@ -473,6 +522,16 @@ WindowMsgHandledType SkirmishMapSelectMenuSystem( GameWindow *window, UnsignedIn
// set the map name in the global data map name
AsciiString asciiMap;
const char *mapFname = (const char *)GadgetListBoxGetItemData( mapWindow, rowSelected );
+
+ // The random map row has no map behind it until it is chosen, so there is
+ // nothing to preview and no start positions to lay out yet.
+ if( isRandomMapRow( mapFname ) )
+ {
+ winMapPreview->winClearStatus(WIN_STATUS_IMAGE);
+ positionStartSpots( AsciiString::TheEmptyString, buttonMapStartPosition, winMapPreview);
+ break;
+ }
+
DEBUG_ASSERTCRASH(mapFname, ("No map item data"));
if (mapFname)
asciiMap = mapFname;
@@ -506,6 +565,7 @@ WindowMsgHandledType SkirmishMapSelectMenuSystem( GameWindow *window, UnsignedIn
if (TheMapCache)
TheMapCache->updateCache();
populateMapListbox( mapList, TRUE, TRUE, TheSkirmishGameInfo->getMap() );
+ addRandomMapRow( mapList );
//LANPreferences pref;
//pref["UseSystemMapDir"] = "yes";
//pref.write();
@@ -516,6 +576,7 @@ WindowMsgHandledType SkirmishMapSelectMenuSystem( GameWindow *window, UnsignedIn
TheMapCache->updateCache();
populateMapListbox( mapList, FALSE, FALSE, TheSkirmishGameInfo->getMap() );
populateMapListboxNoReset( mapList, FALSE, TRUE, TheSkirmishGameInfo->getMap() );
+ addRandomMapRow( mapList );
//LANPreferences pref;
//pref["UseSystemMapDir"] = "no";
//pref.write();
@@ -549,7 +610,18 @@ WindowMsgHandledType SkirmishMapSelectMenuSystem( GameWindow *window, UnsignedIn
AsciiString asciiMap;
const char *mapFname = (const char *)GadgetListBoxGetItemData( mapWindow, selected );
DEBUG_ASSERTCRASH(mapFname, ("No map item data"));
- if (mapFname)
+
+ // Choosing the random map row is the reroll: a fresh seed, a fresh map on
+ // disk, and the map cache reloaded so the rest of this runs unchanged.
+ if( isRandomMapRow( mapFname ) )
+ {
+ AsciiString generatedMap;
+ if( !generateRandomMapForSkirmish( generatedMap ) )
+ break;
+
+ asciiMap = generatedMap;
+ }
+ else if (mapFname)
asciiMap = mapFname;
else
asciiMap.translate( map );
diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cpp
index 2e4e5b0d7..d7a3a11f4 100644
--- a/GeneralsMD/Code/Tests/test_gameengine.cpp
+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp
@@ -31,6 +31,7 @@
#include "Common/MapObject.h"
#include "Common/RandomMapGenerator.h"
#include "Common/StackDump.h"
+#include "Lib/Trig.h"
#include "GameNetwork/Connection.h"
#include "GameLogic/CRCSnapshotRing.h"
#include "GameNetwork/GameDataMatch.h"
@@ -6354,20 +6355,28 @@ struct RMGParse
Int m_width, m_height, m_border, m_boundaryX, m_boundaryY, m_dataSize;
Int m_blendDataSize, m_numBitmapTiles, m_numBlendedTiles, m_numCliffInfo;
Int m_numTextureClasses, m_firstTile, m_numTiles, m_tileWidth;
- Int m_numSides, m_numTeams, m_numObjects;
- Int m_weather, m_compression;
+ Int m_numSides, m_numTeams, m_numObjects, m_numWaterAreas;
+ Int m_weather, m_compression, m_timeOfDay, m_lightingBytesLeftOver;
+ Real m_terrainAmbient[3];
AsciiString m_textureName;
+ std::vector<AsciiString> m_textureNames;
+ std::vector<Int> m_firstTiles;
std::vector<AsciiString> m_waypointNames;
std::vector<Coord3D> m_waypointPositions;
std::vector<AsciiString> m_objectNames;
std::vector<UnsignedByte> m_heights;
std::vector<Short> m_tiles;
+ std::vector<Coord3D> m_waterPoints; ///< first point of each water area
RMGParse() :
m_width(0), m_height(0), m_border(0), m_boundaryX(0), m_boundaryY(0), m_dataSize(0),
m_blendDataSize(0), m_numBitmapTiles(0), m_numBlendedTiles(0), m_numCliffInfo(0),
m_numTextureClasses(0), m_firstTile(0), m_numTiles(0), m_tileWidth(0),
- m_numSides(0), m_numTeams(0), m_numObjects(0), m_weather(-1), m_compression(-1) { }
+ m_numSides(0), m_numTeams(0), m_numObjects(0), m_numWaterAreas(0),
+ m_weather(-1), m_compression(-1), m_timeOfDay(-1), m_lightingBytesLeftOver(-1)
+ {
+ m_terrainAmbient[0] = m_terrainAmbient[1] = m_terrainAmbient[2] = 0.0f;
+ }
};
static RMGParse theRMGParse;
@@ -6408,11 +6417,74 @@ static Bool RMGParseBlendTile( DataChunkInput &file, DataChunkInfo *info, void *
theRMGParse.m_numCliffInfo = file.readInt();
theRMGParse.m_numTextureClasses = file.readInt();
- theRMGParse.m_firstTile = file.readInt();
- theRMGParse.m_numTiles = file.readInt();
- theRMGParse.m_tileWidth = file.readInt();
- file.readInt(); // legacy field
- theRMGParse.m_textureName = file.readAsciiString();
+ for( Int i = 0; i < theRMGParse.m_numTextureClasses; i++ )
+ {
+ Int firstTile = file.readInt();
+ theRMGParse.m_numTiles = file.readInt();
+ theRMGParse.m_tileWidth = file.readInt();
+ file.readInt(); // legacy field
+
+ AsciiString name = file.readAsciiString();
+ theRMGParse.m_firstTiles.push_back( firstTile );
+ theRMGParse.m_textureNames.push_back( name );
+
+ if( i == 0 )
+ {
+ theRMGParse.m_firstTile = firstTile;
+ theRMGParse.m_textureName = name;
+ }
+ }
+ return TRUE;
+}
+
+/* Four times of day, and for each one a terrain light and an objects light with three lights'
+ worth of colour and direction apiece, exactly as WHeightMapEdit writes them. */
+static Bool RMGParseLighting( DataChunkInput &file, DataChunkInfo *info, void * )
+{
+ theRMGParse.m_timeOfDay = file.readInt();
+
+ for( Int timeOfDay = 0; timeOfDay < 4; timeOfDay++ )
+ {
+ for( Int value = 0; value < 54; value++ )
+ {
+ Real read = file.readReal();
+ if( timeOfDay == 0 && value < 3 )
+ theRMGParse.m_terrainAmbient[value] = read;
+ }
+ }
+
+ theRMGParse.m_lightingBytesLeftOver = file.atEndOfChunk() ? 0 : 1;
+ return TRUE;
+}
+
+static Bool RMGParseWaterAreas( DataChunkInput &file, DataChunkInfo *info, void * )
+{
+ theRMGParse.m_numWaterAreas = file.readInt();
+
+ for( Int area = 0; area < theRMGParse.m_numWaterAreas; area++ )
+ {
+ file.readAsciiString(); // trigger name
+ file.readAsciiString(); // layer
+ file.readInt(); // trigger id
+
+ CHECK( file.readByte() == 1 ); // every one of ours is water
+ file.readByte(); // not a river
+ file.readInt(); // river start
+
+ Int numPoints = file.readInt();
+ CHECK( numPoints >= 3 );
+
+ for( Int point = 0; point < numPoints; point++ )
+ {
+ Coord3D loc;
+ loc.x = (Real)file.readInt();
+ loc.y = (Real)file.readInt();
+ loc.z = (Real)file.readInt();
+
+ if( point == 0 )
+ theRMGParse.m_waterPoints.push_back( loc );
+ }
+ }
return TRUE;
}
@@ -6484,6 +6556,8 @@ static void parseGeneratedMap( std::vector<char>& bytes )
input.registerParser( AsciiString( "WorldInfo" ), AsciiString::TheEmptyString, RMGParseWorldInfo );
input.registerParser( AsciiString( "SidesList" ), AsciiString::TheEmptyString, RMGParseSides );
input.registerParser( AsciiString( "ObjectsList" ), AsciiString::TheEmptyString, RMGParseObjects );
+ input.registerParser( AsciiString( "PolygonTriggers" ), AsciiString::TheEmptyString, RMGParseWaterAreas );
+ input.registerParser( AsciiString( "GlobalLighting" ), AsciiString::TheEmptyString, RMGParseLighting );
CHECK( input.parse( NULL ) == TRUE );
}
@@ -6527,7 +6601,7 @@ TEST(a_generated_map_reads_back_through_the_engines_own_chunk_reader)
RandomMapSettings settings;
settings.m_seed = 777;
- settings.m_playableCells = 96;
+ settings.m_playableCells = 160;
settings.m_numPlayers = 4;
std::vector<char> bytes;
@@ -6535,10 +6609,10 @@ TEST(a_generated_map_reads_back_through_the_engines_own_chunk_reader)
parseGeneratedMap( bytes );
// The playable area is what the boundary says; the rest is border the camera looks across.
- CHECK_EQ( theRMGParse.m_boundaryX, 96 );
- CHECK_EQ( theRMGParse.m_boundaryY, 96 );
+ CHECK_EQ( theRMGParse.m_boundaryX, 160 );
+ CHECK_EQ( theRMGParse.m_boundaryY, 160 );
CHECK( theRMGParse.m_border > 0 );
- CHECK_EQ( theRMGParse.m_width, 96 + 2 * theRMGParse.m_border );
+ CHECK_EQ( theRMGParse.m_width, 160 + 2 * theRMGParse.m_border );
CHECK_EQ( theRMGParse.m_height, theRMGParse.m_width );
CHECK_EQ( theRMGParse.m_dataSize, theRMGParse.m_width * theRMGParse.m_height );
CHECK_EQ( (Int)theRMGParse.m_heights.size(), theRMGParse.m_dataSize );
@@ -6546,14 +6620,18 @@ 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 );
- CHECK_EQ( theRMGParse.m_numTextureClasses, 1 );
+ CHECK_EQ( theRMGParse.m_numTextureClasses, 4 );
CHECK_EQ( theRMGParse.m_firstTile, 0 );
CHECK_EQ( theRMGParse.m_numTiles, 4 );
CHECK_EQ( theRMGParse.m_tileWidth, 2 );
- CHECK_EQ( theRMGParse.m_numBitmapTiles, 4 );
+ CHECK_EQ( theRMGParse.m_numBitmapTiles, 4 * 4 ); // four classes of four tiles
CHECK_EQ( theRMGParse.m_numBlendedTiles, 1 ); // entry 0 is the default, no blends
CHECK_EQ( theRMGParse.m_numCliffInfo, 1 ); // entry 0 is the default, no cliff faces
CHECK_STR( theRMGParse.m_textureName.str(), "GrassType1" );
+ CHECK_STR( theRMGParse.m_textureNames[1].str(), "DirtType1" );
+ CHECK_STR( theRMGParse.m_textureNames[2].str(), "RocksType1" );
+ CHECK_STR( theRMGParse.m_textureNames[3].str(), "SandLargeType1" );
+ CHECK_EQ( theRMGParse.m_firstTiles[3], 12 );
CHECK_EQ( theRMGParse.m_weather, 0 );
CHECK_EQ( theRMGParse.m_compression, 0 );
@@ -6562,11 +6640,40 @@ TEST(a_generated_map_reads_back_through_the_engines_own_chunk_reader)
CHECK_EQ( theRMGParse.m_numSides, 14 );
CHECK_EQ( theRMGParse.m_numTeams, 14 );
- // One start waypoint and two supply docks per player.
- CHECK_EQ( theRMGParse.m_numObjects, 4 * 3 );
+ // One start waypoint per player, and the map is dressed rather than bare.
CHECK_EQ( (Int)theRMGParse.m_waypointNames.size(), 4 );
CHECK_STR( theRMGParse.m_waypointNames[0].str(), "Player_1_Start" );
CHECK_STR( theRMGParse.m_waypointNames[3].str(), "Player_4_Start" );
+ CHECK( theRMGParse.m_numObjects > 4 * 3 );
+
+ Int numSupplyDocks = 0, numDerricks = 0, numProps = 0;
+ for( Int i = 0; i < (Int)theRMGParse.m_objectNames.size(); i++ )
+ {
+ if( theRMGParse.m_objectNames[i].compare( "SupplyDock" ) == 0 )
+ numSupplyDocks++;
+ else if( theRMGParse.m_objectNames[i].compare( "TechOilDerrick" ) == 0 )
+ numDerricks++;
+ else if( theRMGParse.m_objectNames[i].startsWith( "Tree" ) ||
+ theRMGParse.m_objectNames[i].startsWith( "Rock" ) )
+ numProps++;
+ }
+
+ CHECK_EQ( numSupplyDocks, 4 * 2 );
+ CHECK_EQ( numDerricks, 4 ); // one on each chokepoint
+ CHECK( numProps > 0 );
+ CHECK( numProps % 4 == 0 ); // the same scenery in every sector
+
+ // A 160-cell map leaves each player room for a lake in their own sector. A cramped one does
+ // not, and gets none rather than a lake standing on a supply dock.
+ CHECK_EQ( theRMGParse.m_numWaterAreas, 4 );
+ CHECK_EQ( (Int)theRMGParse.m_waterPoints.size(), 4 );
+ if( !theRMGParse.m_waterPoints.empty() )
+ CHECK( theRMGParse.m_waterPoints[0].z > 0.0f );
+
+ // Daylight, written into the map rather than left to whatever GameData.ini holds.
+ CHECK_EQ( theRMGParse.m_timeOfDay, (Int)TIME_OF_DAY_AFTERNOON );
+ CHECK_EQ( theRMGParse.m_lightingBytesLeftOver, 0 );
+ CHECK( theRMGParse.m_terrainAmbient[0] > 0.2f );
}
//-------------------------------------------------------------------------------------------------
@@ -6601,67 +6708,152 @@ TEST(every_generated_tile_index_names_a_tile_the_map_declared)
}
CHECK( worstSource >= 0 );
- CHECK( worstSource < theRMGParse.m_numTiles );
+ CHECK( worstSource < theRMGParse.m_numTextureClasses * theRMGParse.m_numTiles );
CHECK_EQ( quadrantsSeen, 0xf ); // all four quadrants of the sheet get used
}
//-------------------------------------------------------------------------------------------------
-/** A map nobody can walk across is not a map. The engine derives passability from the height
- field alone (BlendTileData below version 7 makes it run initCliffFlagsFromHeights), marking a
- cell impassable when its four corners span more than PATHFIND_CLIFF_SLOPE_LIMIT_F world units.
- The generated hills have to stay under that everywhere, and still be hills. */
+/** The engine derives passability from the height field alone (BlendTileData below version 7
+ makes it run initCliffFlagsFromHeights), marking a cell impassable when its four corners span
+ more than PATHFIND_CLIFF_SLOPE_LIMIT_F world units. The map now has cliffs on purpose - the
+ ridge between two players is one - so the thing to check is not that there are none, but that
+ they are where the layout wanted them: none near a start, and every start still reachable from
+ every other through the chokepoints the ridge leaves open. */
//-------------------------------------------------------------------------------------------------
-TEST(generated_terrain_rolls_without_ever_becoming_a_cliff)
+static Real RMGCellSpan( Int x, Int y )
+{
+ Int width = theRMGParse.m_width;
+ Int a = theRMGParse.m_heights[y * width + x];
+ Int b = theRMGParse.m_heights[y * width + x + 1];
+ Int c = theRMGParse.m_heights[(y + 1) * width + x];
+ Int d = theRMGParse.m_heights[(y + 1) * width + x + 1];
+
+ Int lo = a, hi = a;
+ if( b < lo ) lo = b;
+ if( b > hi ) hi = b;
+ if( c < lo ) lo = c;
+ if( c > hi ) hi = c;
+ if( d < lo ) lo = d;
+ if( d > hi ) hi = d;
+
+ return (Real)(hi - lo) * MAP_HEIGHT_SCALE;
+}
+
+/// Flood fill over the walkable cells of the last parsed map, starting at player one.
+static void RMGFloodFillFromFirstStart( std::vector<char>& seen )
+{
+ const Real cliffLimit = 9.8f; // PATHFIND_CLIFF_SLOPE_LIMIT_F
+ Int width = theRMGParse.m_width;
+ Int height = theRMGParse.m_height;
+
+ seen.assign( width * height, 0 );
+
+ Int startX = (Int)(theRMGParse.m_waypointPositions[0].x / MAP_XY_FACTOR + 0.5f) + theRMGParse.m_border;
+ Int startY = (Int)(theRMGParse.m_waypointPositions[0].y / MAP_XY_FACTOR + 0.5f) + theRMGParse.m_border;
+
+ std::vector<Int> stack;
+ seen[startY * width + startX] = 1;
+ stack.push_back( startY * width + startX );
+
+ while( !stack.empty() )
+ {
+ Int index = stack.back();
+ stack.pop_back();
+
+ Int x = index % width;
+ Int y = index / width;
+
+ static const Int offsetX[4] = { 1, -1, 0, 0 };
+ static const Int offsetY[4] = { 0, 0, 1, -1 };
+
+ for( Int i = 0; i < 4; i++ )
+ {
+ Int nx = x + offsetX[i];
+ Int ny = y + offsetY[i];
+ if( nx < 0 || ny < 0 || nx >= width - 1 || ny >= height - 1 )
+ continue;
+ if( seen[ny * width + nx] )
+ continue;
+ if( RMGCellSpan( nx, ny ) > cliffLimit )
+ continue;
+
+ seen[ny * width + nx] = 1;
+ stack.push_back( ny * width + nx );
+ }
+ }
+}
+
+TEST(the_cliffs_are_where_the_layout_put_them_and_never_between_two_players)
{
CHECK( bootOnce() );
- const Real PATHFIND_CLIFF_SLOPE_LIMIT = 9.8f; // WorldHeightMap.cpp
+ const Real cliffLimit = 9.8f; // PATHFIND_CLIFF_SLOPE_LIMIT_F
RandomMapSettings settings;
settings.m_playableCells = 96;
- settings.m_numPlayers = 4;
- for( Int seed = 1; seed <= 8; seed++ )
+ for( Int players = 2; players <= 8; players += 2 )
{
- settings.m_seed = seed * 7919;
+ settings.m_numPlayers = players;
- std::vector<char> bytes;
- RandomMapGenerator::generate( settings, bytes );
- parseGeneratedMap( bytes );
+ for( Int seed = 1; seed <= 4; seed++ )
+ {
+ settings.m_seed = seed * 7919 + players;
- Int width = theRMGParse.m_width;
- Int height = theRMGParse.m_height;
- Int lowest = 255, highest = 0;
- Real steepest = 0.0f;
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
- for( Int y = 0; y < height - 1; y++ )
- {
- for( Int x = 0; x < width - 1; x++ )
+ Int width = theRMGParse.m_width;
+ Int height = theRMGParse.m_height;
+ Int lowest = 255, highest = 0;
+ Int numCliffCells = 0;
+
+ for( Int y = 0; y < height - 1; y++ )
{
- Int a = theRMGParse.m_heights[y * width + x];
- Int b = theRMGParse.m_heights[y * width + x + 1];
- Int c = theRMGParse.m_heights[(y + 1) * width + x];
- Int d = theRMGParse.m_heights[(y + 1) * width + x + 1];
-
- Int lo = a, hi = a;
- if( b < lo ) lo = b;
- if( b > hi ) hi = b;
- if( c < lo ) lo = c;
- if( c > hi ) hi = c;
- if( d < lo ) lo = d;
- if( d > hi ) hi = d;
-
- Real span = (Real)(hi - lo) * MAP_HEIGHT_SCALE;
- if( span > steepest )
- steepest = span;
-
- if( lo < lowest ) lowest = lo;
- if( hi > highest ) highest = hi;
+ for( Int x = 0; x < width - 1; x++ )
+ {
+ if( RMGCellSpan( x, y ) > cliffLimit )
+ numCliffCells++;
+
+ Int h = theRMGParse.m_heights[y * width + x];
+ if( h < lowest ) lowest = h;
+ if( h > highest ) highest = h;
+ }
}
- }
- CHECK( steepest <= PATHFIND_CLIFF_SLOPE_LIMIT );
- CHECK( highest > lowest + 8 ); // terrain, not a parade ground
+ CHECK( highest > lowest + 8 ); // terrain, not a parade ground
+ CHECK( numCliffCells > 0 ); // the ridge is supposed to be a cliff
+
+ // Nothing steep within a base radius of a start, or the base cannot be laid out.
+ for( Int i = 0; i < players; i++ )
+ {
+ Int cellX = (Int)(theRMGParse.m_waypointPositions[i].x / MAP_XY_FACTOR + 0.5f)
+ + theRMGParse.m_border;
+ Int cellY = (Int)(theRMGParse.m_waypointPositions[i].y / MAP_XY_FACTOR + 0.5f)
+ + theRMGParse.m_border;
+
+ for( Int dy = -12; dy <= 12; dy++ )
+ {
+ for( Int dx = -12; dx <= 12; dx++ )
+ CHECK( RMGCellSpan( cellX + dx, cellY + dy ) <= cliffLimit );
+ }
+ }
+
+ // Every other start has to come back from player one's flood fill.
+ std::vector<char> seen;
+ RMGFloodFillFromFirstStart( seen );
+
+ for( Int i = 1; i < players; i++ )
+ {
+ Int cellX = (Int)(theRMGParse.m_waypointPositions[i].x / MAP_XY_FACTOR + 0.5f)
+ + theRMGParse.m_border;
+ Int cellY = (Int)(theRMGParse.m_waypointPositions[i].y / MAP_XY_FACTOR + 0.5f)
+ + theRMGParse.m_border;
+
+ CHECK( seen[cellY * width + cellX] != 0 );
+ }
+ }
}
}
@@ -6687,7 +6879,14 @@ TEST(start_positions_land_inside_the_map_with_room_between_them)
parseGeneratedMap( bytes );
CHECK_EQ( (Int)theRMGParse.m_waypointPositions.size(), players );
- CHECK_EQ( theRMGParse.m_numObjects, players * 3 );
+
+ Int numSupplyDocks = 0;
+ for( Int k = 0; k < (Int)theRMGParse.m_objectNames.size(); k++ )
+ {
+ if( theRMGParse.m_objectNames[k].compare( "SupplyDock" ) == 0 )
+ numSupplyDocks++;
+ }
+ CHECK_EQ( numSupplyDocks, players * 2 );
Real extent = 128.0f * MAP_XY_FACTOR;
Real margin = 20.0f * MAP_XY_FACTOR; // enough ground for a base
@@ -6750,6 +6949,224 @@ TEST(each_start_position_gets_flat_ground_to_build_on)
}
}
+//-------------------------------------------------------------------------------------------------
+/** Every win rate this fork has measured was measured over generated maps, so terrain that is not
+ the same for both sides is noise in the measurement rather than a feature of the map. Rotate a
+ point into the next player's sector and the ground under it has to be the same ground; the byte
+ is allowed to differ by one, which is where the rotation lands between two cells. */
+//-------------------------------------------------------------------------------------------------
+TEST(every_player_gets_the_same_ground_turned_into_their_own_sector)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_playableCells = 128;
+
+ for( Int players = 2; players <= 8; players += 2 )
+ {
+ settings.m_numPlayers = players;
+ settings.m_seed = 31337 + players;
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ Int width = theRMGParse.m_width;
+ Real centre = (Real)settings.m_playableCells * 0.5f;
+ Real sector = 2.0f * PI / (Real)players;
+ Int worstDifference = 0;
+ Int comparisons = 0;
+
+ for( Int y = 8; y < settings.m_playableCells - 8; y += 3 )
+ {
+ for( Int x = 8; x < settings.m_playableCells - 8; x += 3 )
+ {
+ Real dx = (Real)x - centre;
+ Real dy = (Real)y - centre;
+
+ // Skip the middle, where one cell covers every sector at once.
+ if( sqrtf( dx * dx + dy * dy ) < 8.0f )
+ continue;
+
+ Real rotatedX = centre + dx * Cos( sector ) - dy * Sin( sector );
+ Real rotatedY = centre + dx * Sin( sector ) + dy * Cos( sector );
+
+ // The rotated point lands between cells, so read the height field there
+ // the way the terrain does, by interpolating rather than rounding.
+ Real sampleX = rotatedX + (Real)theRMGParse.m_border;
+ Real sampleY = rotatedY + (Real)theRMGParse.m_border;
+ Int mapX = (Int)sampleX;
+ Int mapY = (Int)sampleY;
+ if( mapX < 1 || mapY < 1 || mapX >= width - 2 || mapY >= theRMGParse.m_height - 2 )
+ continue;
+
+ // A step in the terrain - the ridge is one - is not something an
+ // interpolated sample can follow, so compare away from the steps.
+ Int hereX = x + theRMGParse.m_border;
+ Int hereY = y + theRMGParse.m_border;
+ if( RMGCellSpan( hereX, hereY ) > 1.2f || RMGCellSpan( mapX, mapY ) > 1.2f )
+ continue;
+
+ Real fractionX = sampleX - (Real)mapX;
+ Real fractionY = sampleY - (Real)mapY;
+ Real top = (1.0f - fractionX) * (Real)theRMGParse.m_heights[mapY * width + mapX]
+ + fractionX * (Real)theRMGParse.m_heights[mapY * width + mapX + 1];
+ Real bottom = (1.0f - fractionX) * (Real)theRMGParse.m_heights[(mapY + 1) * width + mapX]
+ + fractionX * (Real)theRMGParse.m_heights[(mapY + 1) * width + mapX + 1];
+ Real there = (1.0f - fractionY) * top + fractionY * bottom;
+
+ Real here = (Real)theRMGParse.m_heights[hereY * width + hereX];
+ Int difference = (Int)(fabsf( here - there ) + 0.5f);
+ if( difference > worstDifference )
+ worstDifference = difference;
+
+ comparisons++;
+ }
+ }
+
+ CHECK( comparisons > 100 );
+ CHECK( worstDifference <= 1 );
+ }
+}
+
+//-------------------------------------------------------------------------------------------------
+/** The seed is worthless across two builds unless both builds turn it into the same bytes, and
+ nothing warns anybody when they stop doing so. These numbers are that warning: change the
+ generator and this test fails until RANDOM_MAP_GENERATOR_VERSION and the recorded fingerprints
+ are both brought up to date, which is exactly the discipline the version was invented for. */
+//-------------------------------------------------------------------------------------------------
+TEST(the_generator_still_turns_a_seed_into_the_bytes_it_used_to)
+{
+ CHECK( bootOnce() );
+
+ CHECK_EQ( RANDOM_MAP_GENERATOR_VERSION, 2 );
+
+ struct RMGFingerprint { Int m_seed, m_players, m_cells; UnsignedInt m_crc; };
+ static const RMGFingerprint theFingerprints[] =
+ {
+ { 0, 2, 64, 0x11C0BC3D },
+ { 12345, 4, 96, 0xF111AB91 },
+ { 7, 8, 128, 0x5FB813E3 },
+ };
+ const Int numFingerprints = sizeof(theFingerprints) / sizeof(theFingerprints[0]);
+
+ for( Int i = 0; i < numFingerprints; i++ )
+ {
+ RandomMapSettings settings;
+ settings.m_seed = theFingerprints[i].m_seed;
+ settings.m_numPlayers = theFingerprints[i].m_players;
+ settings.m_playableCells = theFingerprints[i].m_cells;
+
+ UnsignedInt crc = RandomMapGenerator::fingerprint( settings );
+ if( crc != theFingerprints[i].m_crc )
+ printf( " fingerprint seed %d players %d cells %d is 0x%08X\n",
+ settings.m_seed, settings.m_numPlayers, settings.m_playableCells, crc );
+
+ CHECK( crc == theFingerprints[i].m_crc );
+ }
+
+ /* The height field is x87 arithmetic, so it used to come out differently depending on the
+ precision the last DLL left the FPU in - the machine that generated the map and the machine
+ that joined it would disagree about the ground. generate() now puts the FPU where the
+ simulation keeps it, and this is what says so: the same seed through a control word no
+ simulation would ever run in. */
+ UnsignedInt entry = _controlfp( 0, 0 );
+
+ RandomMapSettings settings;
+ settings.m_seed = theFingerprints[0].m_seed;
+ settings.m_numPlayers = theFingerprints[0].m_players;
+ settings.m_playableCells = theFingerprints[0].m_cells;
+
+ _controlfp( _PC_64 | _RC_CHOP, _MCW_PC | _MCW_RC );
+ UnsignedInt inADriversMode = RandomMapGenerator::fingerprint( settings );
+ _controlfp( entry, _MCW_PC | _MCW_RC );
+
+ CHECK( inADriversMode == theFingerprints[0].m_crc );
+
+ // and the caller's mode is handed back rather than left at the simulation's
+ CHECK_EQ( _controlfp( 0, 0 ), entry );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** getMapPreviewImage looks for a 128x128 tga beside the map and shows nothing at all when it is
+ not there, which is what the map list did for every generated map. The bytes have to be a tga
+ an image loader will take: uncompressed true colour, three bytes a pixel, right way up. */
+//-------------------------------------------------------------------------------------------------
+TEST(a_generated_map_comes_with_a_preview_the_map_list_can_show)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 99;
+ settings.m_playableCells = 128;
+ settings.m_numPlayers = 4;
+
+ std::vector<char> tga;
+ RandomMapGenerator::generatePreview( settings, tga );
+
+ const Int headerBytes = 18;
+ const Int pixels = RandomMapGenerator::PREVIEW_PIXELS;
+
+ CHECK_EQ( (Int)tga.size(), headerBytes + pixels * pixels * 3 );
+ CHECK_EQ( (Int)(UnsignedByte)tga[2], 2 ); // uncompressed true colour
+ CHECK_EQ( (Int)(UnsignedByte)tga[16], 24 ); // bits per pixel
+ CHECK_EQ( (Int)(UnsignedByte)tga[12] + ((Int)(UnsignedByte)tga[13] << 8), pixels );
+ CHECK_EQ( (Int)(UnsignedByte)tga[14] + ((Int)(UnsignedByte)tga[15] << 8), pixels );
+
+ // A picture of a map, not a flat fill: the ground, the water and the start marks differ.
+ Int distinctColours = 0;
+ std::set<Int> colours;
+ for( Int i = headerBytes; i + 2 < (Int)tga.size(); i += 3 )
+ {
+ Int packed = ((Int)(UnsignedByte)tga[i] << 16) | ((Int)(UnsignedByte)tga[i + 1] << 8)
+ | (Int)(UnsignedByte)tga[i + 2];
+ colours.insert( packed );
+ }
+ distinctColours = (Int)colours.size();
+
+ CHECK( distinctColours > 20 );
+
+ // Same settings, same picture.
+ std::vector<char> again;
+ RandomMapGenerator::generatePreview( settings, again );
+ CHECK_EQ( (Int)again.size(), (Int)tga.size() );
+ CHECK_MEM( &again[0], &tga[0], (Int)tga.size() );
+}
+
+//-------------------------------------------------------------------------------------------------
+/** Four texture classes are only worth writing if the map uses more than one of them. Rock wants
+ the steep ground, sand wants the lake shores, and the map should still be mostly walkable
+ ground rather than a quarry. */
+//-------------------------------------------------------------------------------------------------
+TEST(the_ground_is_textured_by_what_the_ground_is_doing)
+{
+ CHECK( bootOnce() );
+
+ RandomMapSettings settings;
+ settings.m_seed = 5150;
+ settings.m_playableCells = 128;
+ settings.m_numPlayers = 4;
+
+ std::vector<char> bytes;
+ RandomMapGenerator::generate( settings, bytes );
+ parseGeneratedMap( bytes );
+
+ Int cellsPerClass[4] = { 0, 0, 0, 0 };
+ for( Int i = 0; i < (Int)theRMGParse.m_tiles.size(); i++ )
+ {
+ Int source = theRMGParse.m_tiles[i] >> 2;
+ Int terrainClass = source / 4;
+ CHECK( terrainClass >= 0 && terrainClass < 4 );
+ cellsPerClass[terrainClass]++;
+ }
+
+ Int total = (Int)theRMGParse.m_tiles.size();
+ for( Int i = 0; i < 4; i++ )
+ CHECK( cellsPerClass[i] > 0 );
+
+ CHECK( cellsPerClass[0] > total / 3 ); // grass still carries the map
+}
+
//////////////////////////////////////////////////////////////////////////////
// Headless runs
//////////////////////////////////////////////////////////////////////////////
diff --git a/Tools/RandomMapLab/mapscore.py b/Tools/RandomMapLab/mapscore.py
new file mode 100644
index 000000000..c4a747b96
--- /dev/null
+++ b/Tools/RandomMapLab/mapscore.py
@@ -0,0 +1,451 @@
+#!/usr/bin/env python3
+"""Score a generated .map for fairness, without launching the game.
+
+The generator writes an uncompressed CkMp stream, which is the same chunk format WorldBuilder
+saves, so everything this needs is in the file: the height field, the tile indices that say which
+texture class a cell got, the start waypoints, the supply docks and the water areas.
+
+What comes out is one row per map:
+
+ cells the playable size
+ players how many start positions
+ build buildable cells within a base radius of a start: worst player / best player
+ supply cells from a start to its nearest supply dock: worst / best
+ path walking distance between the two closest starts, and between the two furthest
+ choke how many separate crossings the flood fill has to squeeze through
+ symm the largest height difference between a cell and its image in the next sector
+
+A map is fair when the worst and the best player differ by nothing. The generator rotates one
+sector into the others, so these columns should read the same on both sides; they are here to
+catch the day that stops being true.
+
+ python mapscore.py <map file or directory> [...]
+"""
+
+import argparse
+import math
+import os
+import struct
+import sys
+from collections import deque
+
+MAP_XY_FACTOR = 10.0
+MAP_HEIGHT_SCALE = MAP_XY_FACTOR / 16.0
+CLIFF_WORLD_SPAN = 9.8
+BASE_RADIUS_CELLS = 14
+
+
+class ChunkReader:
+ """Just enough of DataChunkInput to walk the chunks this tool cares about."""
+
+ def __init__(self, data):
+ if data[:4] != b"CkMp":
+ raise ValueError("not an uncompressed CkMp map: %r" % data[:4])
+
+ self.data = data
+ self.pos = 4
+ self.names = {}
+
+ count = self.read_int()
+ for _ in range(count):
+ length = self.read_byte()
+ name = self.data[self.pos:self.pos + length].decode("latin-1")
+ self.pos += length
+ self.names[self.read_uint()] = name
+
+ def read_byte(self):
+ value = self.data[self.pos]
+ self.pos += 1
+ return value
+
+ def read_int(self):
+ value = struct.unpack_from("<i", self.data, self.pos)[0]
+ self.pos += 4
+ return value
+
+ def read_uint(self):
+ value = struct.unpack_from("<I", self.data, self.pos)[0]
+ self.pos += 4
+ return value
+
+ def read_short(self):
+ value = struct.unpack_from("<h", self.data, self.pos)[0]
+ self.pos += 2
+ return value
+
+ def read_real(self):
+ value = struct.unpack_from("<f", self.data, self.pos)[0]
+ self.pos += 4
+ return value
+
+ def read_ascii(self):
+ length = struct.unpack_from("<H", self.data, self.pos)[0]
+ self.pos += 2
+ text = self.data[self.pos:self.pos + length].decode("latin-1")
+ self.pos += length
+ return text
+
+ def read_dict(self):
+ pairs = struct.unpack_from("<H", self.data, self.pos)[0]
+ self.pos += 2
+
+ entries = {}
+ for _ in range(pairs):
+ key_and_type = self.read_uint()
+ key = self.names.get(key_and_type >> 8, "?")
+ data_type = key_and_type & 0xFF
+
+ if data_type == 0: # bool
+ entries[key] = self.read_byte() != 0
+ elif data_type == 1: # int
+ entries[key] = self.read_int()
+ elif data_type == 2: # real
+ entries[key] = self.read_real()
+ elif data_type == 3: # ascii
+ entries[key] = self.read_ascii()
+ elif data_type == 4: # unicode
+ length = struct.unpack_from("<H", self.data, self.pos)[0]
+ self.pos += 2
+ self.pos += length * 2
+ entries[key] = ""
+ else:
+ raise ValueError("unknown dict type %d for key %s" % (data_type, key))
+
+ return entries
+
+ def chunks(self, end=None):
+ """Yield (name, version, body end offset) for each chunk at this level."""
+ if end is None:
+ end = len(self.data)
+
+ # id, version, size: four bytes, two bytes, four bytes (DataChunkVersionType is a short)
+ while self.pos + 10 <= end:
+ chunk_id = self.read_uint()
+ version = struct.unpack_from("<H", self.data, self.pos)[0]
+ self.pos += 2
+ size = self.read_int()
+ body_end = self.pos + size
+
+ yield self.names.get(chunk_id, "?"), version, body_end
+ self.pos = body_end
+
+
+class GeneratedMap:
+ def __init__(self, path):
+ with open(path, "rb") as handle:
+ data = handle.read()
+
+ self.path = path
+ self.width = 0
+ self.height = 0
+ self.border = 0
+ self.playable = 0
+ self.heights = []
+ self.tiles = []
+ self.starts = []
+ self.supplies = []
+ self.derricks = []
+ self.water_areas = []
+
+ reader = ChunkReader(data)
+ for name, version, body_end in reader.chunks():
+ if name == "HeightMapData":
+ self._read_heights(reader)
+ elif name == "BlendTileData":
+ self._read_tiles(reader)
+ elif name == "ObjectsList":
+ self._read_objects(reader, body_end)
+ elif name == "PolygonTriggers":
+ self._read_water(reader)
+
+ def _read_heights(self, reader):
+ self.width = reader.read_int()
+ self.height = reader.read_int()
+ self.border = reader.read_int()
+
+ for _ in range(reader.read_int()):
+ self.playable = reader.read_int()
+ reader.read_int()
+
+ size = reader.read_int()
+ self.heights = list(reader.data[reader.pos:reader.pos + size])
+ reader.pos += size
+
+ def _read_tiles(self, reader):
+ size = reader.read_int()
+ self.tiles = list(struct.unpack_from("<%dh" % size, reader.data, reader.pos))
+ reader.pos += size * 2
+
+ def _read_objects(self, reader, end):
+ for name, version, body_end in reader.chunks(end):
+ if name != "Object":
+ continue
+
+ x = reader.read_real()
+ y = reader.read_real()
+ reader.read_real() # z
+ reader.read_real() # angle
+ reader.read_int() # flags
+ template = reader.read_ascii()
+ entries = reader.read_dict()
+
+ if "waypointID" in entries and entries.get("waypointName", "").endswith("_Start"):
+ self.starts.append((x / MAP_XY_FACTOR, y / MAP_XY_FACTOR))
+ elif template == "SupplyDock":
+ self.supplies.append((x / MAP_XY_FACTOR, y / MAP_XY_FACTOR))
+ elif template == "TechOilDerrick":
+ self.derricks.append((x / MAP_XY_FACTOR, y / MAP_XY_FACTOR))
+
+ def _read_water(self, reader):
+ for _ in range(reader.read_int()):
+ reader.read_ascii() # name
+ reader.read_ascii() # layer
+ reader.read_int() # id
+ reader.read_byte() # is water
+ reader.read_byte() # is river
+ reader.read_int() # river start
+
+ points = []
+ for _ in range(reader.read_int()):
+ points.append((reader.read_int() / MAP_XY_FACTOR,
+ reader.read_int() / MAP_XY_FACTOR,
+ reader.read_int()))
+ self.water_areas.append(points)
+
+ def height_at(self, x, y):
+ return self.heights[y * self.width + x]
+
+ def cell_span_world(self, x, y):
+ corners = (self.height_at(x, y), self.height_at(x + 1, y),
+ self.height_at(x, y + 1), self.height_at(x + 1, y + 1))
+ return (max(corners) - min(corners)) * MAP_HEIGHT_SCALE
+
+ def passable_grid(self):
+ """Cliff cells only. Water sits inside a polygon and the terrain under it is a basin, so
+ the depth check below catches it without carrying the polygon test around."""
+ water_level = None
+ if self.water_areas:
+ water_level = max(point[2] for point in self.water_areas[0]) / MAP_HEIGHT_SCALE
+
+ grid = bytearray(self.width * self.height)
+ for y in range(self.height - 1):
+ for x in range(self.width - 1):
+ walkable = self.cell_span_world(x, y) <= CLIFF_WORLD_SPAN
+ if walkable and water_level is not None:
+ walkable = self.height_at(x, y) >= water_level
+ grid[y * self.width + x] = 1 if walkable else 0
+
+ return grid
+
+ def cell_of(self, position):
+ return (int(position[0] + 0.5) + self.border, int(position[1] + 0.5) + self.border)
+
+ def walk_distances(self, grid, origin):
+ """Cell counts from one start over the walkable grid, by breadth first search."""
+ distances = [-1] * (self.width * self.height)
+ start = self.cell_of(origin)
+ index = start[1] * self.width + start[0]
+
+ distances[index] = 0
+ queue = deque([index])
+
+ while queue:
+ index = queue.popleft()
+ x = index % self.width
+ y = index // self.width
+
+ for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ nx, ny = x + dx, y + dy
+ if nx < 0 or ny < 0 or nx >= self.width - 1 or ny >= self.height - 1:
+ continue
+
+ next_index = ny * self.width + nx
+ if distances[next_index] >= 0 or not grid[next_index]:
+ continue
+
+ distances[next_index] = distances[index] + 1
+ queue.append(next_index)
+
+ return distances
+
+ def buildable_cells(self, grid, origin):
+ centre = self.cell_of(origin)
+ count = 0
+
+ for dy in range(-BASE_RADIUS_CELLS, BASE_RADIUS_CELLS + 1):
+ for dx in range(-BASE_RADIUS_CELLS, BASE_RADIUS_CELLS + 1):
+ if dx * dx + dy * dy > BASE_RADIUS_CELLS * BASE_RADIUS_CELLS:
+ continue
+
+ x, y = centre[0] + dx, centre[1] + dy
+ if 0 <= x < self.width - 1 and 0 <= y < self.height - 1 and grid[y * self.width + x]:
+ count += 1
+
+ return count
+
+ def symmetry_error(self):
+ """The largest height difference between a cell and its image one sector round, read the
+ way the terrain reads a point between cells."""
+ players = len(self.starts)
+ if players < 2:
+ return 0.0
+
+ centre = self.playable * 0.5
+ sector = 2.0 * math.pi / players
+ worst = 0.0
+
+ for y in range(8, self.playable - 8, 3):
+ for x in range(8, self.playable - 8, 3):
+ dx, dy = x - centre, y - centre
+ if math.hypot(dx, dy) < 8.0:
+ continue
+
+ sample_x = centre + dx * math.cos(sector) - dy * math.sin(sector) + self.border
+ sample_y = centre + dx * math.sin(sector) + dy * math.cos(sector) + self.border
+ map_x, map_y = int(sample_x), int(sample_y)
+ if not (1 <= map_x < self.width - 2 and 1 <= map_y < self.height - 2):
+ continue
+
+ here_x, here_y = x + self.border, y + self.border
+ if self.cell_span_world(here_x, here_y) > 2.0:
+ continue
+ if self.cell_span_world(map_x, map_y) > 2.0:
+ continue
+
+ fx, fy = sample_x - map_x, sample_y - map_y
+ top = (1 - fx) * self.height_at(map_x, map_y) + fx * self.height_at(map_x + 1, map_y)
+ bottom = ((1 - fx) * self.height_at(map_x, map_y + 1)
+ + fx * self.height_at(map_x + 1, map_y + 1))
+ there = (1 - fy) * top + fy * bottom
+
+ worst = max(worst, abs(self.height_at(here_x, here_y) - there))
+
+ return worst
+
+ def tightest_ring(self, grid):
+ """Walk a circle around the middle of the map at a spread of radii and find the one that is
+ blocked the most. What comes back is how much of that circle a unit can stand on, and how
+ many separate gaps that walkable part is broken into - the crossings a player going round
+ the map has to pick between at the tightest point."""
+ if not self.starts:
+ return 1.0, 0
+
+ centre = self.playable * 0.5
+ samples = 720
+ tightest = 1.0
+ crossings = 0
+
+ for step in range(10, 49):
+ radius = self.playable * step / 100.0
+
+ walkable = []
+ for i in range(samples):
+ angle = 2.0 * math.pi * i / samples
+ x = int(centre + radius * math.cos(angle) + 0.5) + self.border
+ y = int(centre + radius * math.sin(angle) + 0.5) + self.border
+ inside = 0 <= x < self.width - 1 and 0 <= y < self.height - 1
+ walkable.append(bool(inside and grid[y * self.width + x]))
+
+ fraction = sum(1 for cell in walkable if cell) / float(samples)
+ if fraction >= tightest:
+ continue
+
+ tightest = fraction
+ crossings = sum(1 for i in range(samples) if walkable[i] and not walkable[i - 1])
+
+ return tightest, crossings
+
+
+def score(path):
+ generated = GeneratedMap(path)
+ grid = generated.passable_grid()
+
+ build = [generated.buildable_cells(grid, start) for start in generated.starts]
+
+ supply_distance = []
+ pair_distances = []
+ for index, start in enumerate(generated.starts):
+ distances = generated.walk_distances(grid, start)
+
+ nearest_supply = None
+ for supply in generated.supplies:
+ cell = generated.cell_of(supply)
+ walked = distances[cell[1] * generated.width + cell[0]]
+ if walked >= 0 and (nearest_supply is None or walked < nearest_supply):
+ nearest_supply = walked
+ supply_distance.append(nearest_supply if nearest_supply is not None else -1)
+
+ for other in range(index + 1, len(generated.starts)):
+ cell = generated.cell_of(generated.starts[other])
+ pair_distances.append(distances[cell[1] * generated.width + cell[0]])
+
+ reachable = [d for d in pair_distances if d >= 0]
+ open_fraction, crossings = generated.tightest_ring(grid)
+
+ return {
+ "name": os.path.basename(path),
+ "cells": generated.playable,
+ "players": len(generated.starts),
+ "build_worst": min(build) if build else 0,
+ "build_best": max(build) if build else 0,
+ "supply_worst": max(supply_distance) if supply_distance else -1,
+ "supply_best": min(supply_distance) if supply_distance else -1,
+ "path_near": min(reachable) if reachable else -1,
+ "path_far": max(reachable) if reachable else -1,
+ "unreachable": len(pair_distances) - len(reachable),
+ "chokes": crossings,
+ "open": open_fraction,
+ "water": len(generated.water_areas),
+ "derricks": len(generated.derricks),
+ "symmetry": generated.symmetry_error(),
+ }
+
+
+def collect(paths):
+ files = []
+ for path in paths:
+ if os.path.isdir(path):
+ for root, _, names in os.walk(path):
+ files.extend(os.path.join(root, name) for name in names if name.endswith(".map"))
+ else:
+ files.append(path)
+ return sorted(files)
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__,
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("paths", nargs="+", help=".map files, or directories holding them")
+ arguments = parser.parse_args()
+
+ files = collect(arguments.paths)
+ if not files:
+ print("no .map files found", file=sys.stderr)
+ return 1
+
+ header = ("map", "cells", "plr", "build w/b", "supply w/b", "path near/far",
+ "cross", "open", "water", "symm")
+ print("%-34s %5s %4s %12s %12s %14s %6s %6s %6s %6s" % header)
+
+ worst_symmetry = 0.0
+ for path in files:
+ row = score(path)
+ worst_symmetry = max(worst_symmetry, row["symmetry"])
+
+ print("%-34s %5d %4d %12s %12s %14s %6d %5d%% %6d %6.2f" % (
+ row["name"][:34], row["cells"], row["players"],
+ "%d/%d" % (row["build_worst"], row["build_best"]),
+ "%d/%d" % (row["supply_worst"], row["supply_best"]),
+ "%d/%d" % (row["path_near"], row["path_far"]),
+ row["chokes"], int(row["open"] * 100 + 0.5), row["water"], row["symmetry"]))
+
+ if row["unreachable"]:
+ print(" %d start pairs cannot walk to each other" % row["unreachable"])
+
+ print()
+ print("worst symmetry error over %d map(s): %.2f height bytes" % (len(files), worst_symmetry))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/ai-batch.ps1 b/ai-batch.ps1
index 9924729a0..e36270702 100644
--- a/ai-batch.ps1
+++ b/ai-batch.ps1
@@ -64,7 +64,12 @@ param(
# (e.g. -ExtraArgs "-aislice",'4') without a rebuild between batches
[string[]] $ExtraArgs = @(),
# minutes before a wedged run is killed rather than waited on forever
- [int] $TimeoutMinutes = 20
+ [int] $TimeoutMinutes = 20,
+ # keep the generated maps after the batch. Every -randommap run leaves a directory in the user
+ # data folder that the map cache re-reads on the next launch, so a few hundred batches is a few
+ # hundred directories and a slower start. They are deleted at the end unless this is set, or
+ # unless a fixed -Map was used, in which case none were made.
+ [switch] $KeepMaps
)
$ErrorActionPreference = "Stop"
@@ -79,6 +84,12 @@ if (-not (Test-Path $exePath)) {
# One row per match. Slot results are kept as a hashtable per row so the summary can pivot on them.
$rows = @()
+# The map directories this batch generates, so they can be taken away again at the end. Two batches
+# can run at once, so only the ones this batch asked for are ever removed.
+$generatedMapDirs = @()
+$userMapsDir = Join-Path ([Environment]::GetFolderPath("MyDocuments")) `
+ "Command and Conquer Generals Zero Hour Data\Maps"
+
for ($i = 0; $i -lt $Runs; $i++) {
$seed = $SeedStart + $i
@@ -106,6 +117,9 @@ for ($i = 0; $i -lt $Runs; $i++) {
$args += ('"Maps\{0}\{0}.map"' -f $Map)
} else {
$args += @("-randommap", $seed, $Players, $cells)
+ # the generator names the directory after its own version as well as the settings, so this
+ # matches whichever version the exe under test was built from
+ $generatedMapDirs += ("RMG_v*_{0}_{1}p_{2}c" -f $seed, $Players, $cells)
}
$args += @(
"-autoskirmish", $Players,
@@ -369,3 +383,16 @@ $rows | Select-Object Seed, Cells, Why, Frames, Wall,
@{n="Repaths";e={ if ($_.Pf) { $_.Pf.Repaths } }},
@{n="Dithers";e={ if ($_.Pf) { $_.Pf.Dithers } }} | Export-Csv -Path $csv -NoTypeInformation
Write-Host "per-match rows: $csv"
+
+# Take the generated maps away again. The seed is the map, so nothing is lost: the same command
+# line rebuilds any of them byte for byte.
+if ($generatedMapDirs.Count -and -not $KeepMaps) {
+ $removed = 0
+ foreach ($pattern in ($generatedMapDirs | Sort-Object -Unique)) {
+ foreach ($dir in @(Get-ChildItem -Path $userMapsDir -Directory -Filter $pattern -ErrorAction SilentlyContinue)) {
+ Remove-Item -LiteralPath $dir.FullName -Recurse -Force -ErrorAction SilentlyContinue
+ $removed++
+ }
+ }
+ Write-Host "removed $removed generated map directories (use -KeepMaps to leave them)"
+}