Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(w3ddevice): double the ground's detail and give it relief
Olcay Seyganaa0542b2ea85
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c248c82be..2404e0339 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -242,6 +242,8 @@ found and fixed — EA's own, not port damage.**- Fullscreen gets the Direct3D 11 picture too. The old renderer took the whole display for itself and refused the new one its window, so every fullscreen game quietly ran on Direct3D 9, and the DX9 in the corner readout was the only sign. Fullscreen is now your chosen resolution set on the monitor with the game's window over it: alt-tab drops you on the desktop at its own resolution and brightness, and coming back puts the game's on again. A 1280x720 match on a 1920x1080 screen drew 40.7 million times without one draw refused, before and after an alt-tab.- Alt-tabbing out of a fullscreen match and back no longer leaves every building already on the map as a dark shadow with nothing standing in it. Coming back from the desktop switched the game over to Direct3D 11 halfway through the match, and the new picture only knew about what was built after the switch, so older buildings drew as their shadow alone while a new one beside them looked fine. A match keeps the picture it started with now.- 481 base-game textures at four times the resolution now beat Zero Hour's downscaled copies.+- The ground is drawn at twice the detail. Every map square used to get a 64-pixel patch of its ground texture, squeezed into sixteen-bit colour; it gets 128 pixels now in full colour, so sand, gravel and tracks stop turning to blocks and bands when you zoom in, and a ground texture that ships at twice the size is shown at that size.+- The ground has relief. Every grain of sand, pebble and crack catches the map's own sun on one side and falls into shade on the other, worked out from the ground's own picture when the map loads, and it follows the sun on a dusk map or a night one. The light the ground already had from its hills is kept; the relief goes on top. It is part of the new picture, so a machine on the old renderer keeps the flat ground.- A long thin texture loads at the size it was drawn at. Anything wider than eight to one used to be stretched onto a bigger, blurrier one, because that was the limit of a 2002 graphics card; the card is asked now, and modern ones have no such limit.- Anything standing still keeps its shadow in the fog. A town you have already walked through usedto sit on flat ground the moment you looked away, buildings and derricks and walls with nothingdiff --git a/GeneralsMD/Code/CMakeLists.txt b/GeneralsMD/Code/CMakeLists.txtindex 36ccc49e5..c911ffda2 100644--- a/GeneralsMD/Code/CMakeLists.txt+++ b/GeneralsMD/Code/CMakeLists.txt@@ -722,7 +722,7 @@ add_lib_test(test_dx11device dx11device)add_lib_test(test_dx11state dx11state)add_lib_test(test_dx11layout dx11layout)add_lib_test(test_ffvertex ffvertex)-add_lib_test(test_ffvertexcompile ffvertex)+add_lib_test(test_ffvertexcompile ffvertex ffshader)# The generated vertex program run against the fixed-function pipeline it replaces, on a real# Direct3D 9 device. It skips itself on a machine with no device rather than failing.add_lib_test(test_ffvertexd3d9 ffvertex d3d9 user32)diff --git a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.hindex ce39d548b..fb72a52be 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/FileSystem.h@@ -75,6 +75,7 @@ typedef FilenameList::iterator FilenameListIter;#define W3D_DIR_PATH "Art/W3D/" ///< .w3d files live here#define TGA_DIR_PATH "Art/Textures/" ///< .tga texture files live here#define TERRAIN_TGA_DIR_PATH "Art/Terrain/" ///< terrain .tga texture files live here+#define TERRAIN_HD_TGA_DIR_PATH "Art/TerrainHD/" ///< the same files at twice the size, loose, if there are any#define MAP_PREVIEW_DIR_PATH "%sMapPreviews/" ///< We need a common place we can copy the map previews to at runtime.#define USER_W3D_DIR_PATH "%sW3D/" ///< .w3d files live here#define USER_TGA_DIR_PATH "%sTextures/" ///< User .tga texture files live herediff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.hindex bccad10ff..7716431a7 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TerrainTex.h@@ -55,11 +55,18 @@ public:/// Create texture for a height map.TerrainTextureClass(int height, int width);+ /// The atlas's shape in a format of the caller's choosing: the normal atlas.+ TerrainTextureClass(int height, WW3DFormat format);+// just use default destructor. ~TerrainTextureClass(void);public:int update(WorldHeightMap *htMap); ///< Sets the pixels, and returns the actual height of the texture.+ /// The same layout filled with each tile's normals instead of its colours. Needs a 32 bit texture.+ int updateNormals(WorldHeightMap *htMap);Bool updateFlat(WorldHeightMap *htMap, Int xCell, Int yCell, Int cellWidth, Int pixelsPerCell); ///< Sets the pixels.void setLOD(Int LOD);+protected:+ int fill(WorldHeightMap *htMap, Bool normals);};diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.hindex 02e07a7d9..4814187a9 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/TileData.h@@ -50,17 +50,20 @@ typedef struct {#define INVERTED_MASK 0x1 //AND this with TBlendTileInfo.inverted to get actual inverted state#define FLIPPED_MASK 0x2 //AND this with TBlendTileInfo.inverted to get forced flip state (for horizontal/vertical flips).-#define TILE_PIXEL_EXTENT 64+// A terrain tile's side in the atlas. EA fixed it at 64; a run that draws doubles it, set once+// before any map loads (W3DDisplay::init). The shipped images and every map are laid out in 64 pixel tiles,+// which is SOURCE_TILE_PIXEL_EXTENT, and a source image is read in those and scaled to this one.+extern Int TheTilePixelExtent;+#define TILE_PIXEL_EXTENT TheTilePixelExtent+#define SOURCE_TILE_PIXEL_EXTENT 64+#define MAX_TILE_PIXEL_EXTENT 128#define TILE_BYTES_PER_PIXEL 4-#define DATA_LEN_BYTES TILE_PIXEL_EXTENT*TILE_PIXEL_EXTENT*TILE_BYTES_PER_PIXEL-#define DATA_LEN_PIXELS TILE_PIXEL_EXTENT*TILE_PIXEL_EXTENT-#define TILE_PIXEL_EXTENT_MIP1 32-#define TILE_PIXEL_EXTENT_MIP2 16-#define TILE_PIXEL_EXTENT_MIP3 8-#define TILE_PIXEL_EXTENT_MIP4 4-#define TILE_PIXEL_EXTENT_MIP5 2-#define TILE_PIXEL_EXTENT_MIP6 1-#define TEXTURE_WIDTH 2048 // was 1024 jba+#define DATA_LEN_BYTES MAX_TILE_PIXEL_EXTENT*MAX_TILE_PIXEL_EXTENT*TILE_BYTES_PER_PIXEL+// Every mip below the largest, down to one pixel: a third of the largest level, rounded up.+#define MIP_LEN_BYTES (DATA_LEN_BYTES/3 + TILE_BYTES_PER_PIXEL)+// The atlas is 32 tiles wide however big a tile is, so a map's layout and the cliff coordinates+// it stores, which are fractions of this width, come out the same at either extent.+#define TEXTURE_WIDTH (32*TILE_PIXEL_EXTENT) // was 1024 jba/** This class holds the bitmap data from the .tga texture files. It is used tocreate the D3D texture in the game and 3d windows, and to create DIB data for the@@ -73,13 +76,8 @@ protected:// Also, first byte is lower left pixel, not upper left pixel.// so 0,0 is lower left, not upper left.UnsignedByte m_tileData[DATA_LEN_BYTES];- /// Mipped down copies of the tile data.- UnsignedByte m_tileDataMip32[TILE_PIXEL_EXTENT_MIP1*TILE_PIXEL_EXTENT_MIP1*TILE_BYTES_PER_PIXEL];- UnsignedByte m_tileDataMip16[TILE_PIXEL_EXTENT_MIP2*TILE_PIXEL_EXTENT_MIP2*TILE_BYTES_PER_PIXEL];- UnsignedByte m_tileDataMip8[TILE_PIXEL_EXTENT_MIP3*TILE_PIXEL_EXTENT_MIP3*TILE_BYTES_PER_PIXEL];- UnsignedByte m_tileDataMip4[TILE_PIXEL_EXTENT_MIP4*TILE_PIXEL_EXTENT_MIP4*TILE_BYTES_PER_PIXEL];- UnsignedByte m_tileDataMip2[TILE_PIXEL_EXTENT_MIP5*TILE_PIXEL_EXTENT_MIP5*TILE_BYTES_PER_PIXEL];- UnsignedByte m_tileDataMip1[TILE_PIXEL_EXTENT_MIP6*TILE_PIXEL_EXTENT_MIP6*TILE_BYTES_PER_PIXEL];+ /// Mipped down copies of the tile data, each half the side of the one before, packed in order.+ UnsignedByte m_tileDataMips[MIP_LEN_BYTES];public:ICoord2D m_tileLocationInTexture;@@ -97,10 +95,16 @@ public:public:UnsignedByte *getDataPtr(void) {return(m_tileData);};- static Int dataLen(void) {return(DATA_LEN_BYTES);};-+ static Int dataLen(void) {return(TILE_PIXEL_EXTENT*TILE_PIXEL_EXTENT*TILE_BYTES_PER_PIXEL);};+void updateMips(void);+ /** The tile was filled at sourceExtent, which is smaller than TILE_PIXEL_EXTENT: stretch it to+ fill the tile, bilinearly, wrapping at its own edges. That is right for a texture class of+ one tile; in a bigger one the neighbour is another tile, so the edge can show a faint seam,+ which a source image already at the full extent does not have. */+ void scaleUpFrom(Int sourceExtent);+Bool hasRGBDataForWidth(Int width);UnsignedByte *getRGBDataForWidth(Int width);};diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.hindex 94af45985..b4ffbfb30 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h@@ -313,8 +313,12 @@ public: // modify height valueif ((ndx>=0) && (ndx<m_dataSize) && m_data) m_data[ndx]=height;};public: // Read tile utilities. jba [7/9/2003]- static Bool readTiles(InputStream *pStrm, TileData **tiles, Int numRows);- static Int countTiles(InputStream *pStrm, Bool *halfTile=NULL);+ // sourceExtent is the tile side the image was drawn in: 64 for everything the game ships, 128+ // for an image from Art/TerrainHD. The tiles come out at TILE_PIXEL_EXTENT either way.+ static Bool readTiles(InputStream *pStrm, TileData **tiles, Int numRows,+ Int sourceExtent=SOURCE_TILE_PIXEL_EXTENT);+ static Int countTiles(InputStream *pStrm, Bool *halfTile=NULL,+ Int sourceExtent=SOURCE_TILE_PIXEL_EXTENT);protected:void setCliffState(Int xIndex, Int yIndex, Bool state);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cppindex efc162758..3fe50887e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TerrainTex.cpp@@ -68,8 +68,10 @@texture of the desired height and mip level. *///=============================================================================TerrainTextureClass::TerrainTextureClass(int height) :- TextureClass(TEXTURE_WIDTH, height,- WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_3 )+ TextureClass(TEXTURE_WIDTH, height,+ // The bigger tiles keep eight bits a channel: five would band the detail they bring.+ TILE_PIXEL_EXTENT > SOURCE_TILE_PIXEL_EXTENT ? WW3D_FORMAT_A8R8G8B8 : WW3D_FORMAT_A1R5G5B5,+ MIP_LEVELS_3 ){}@@ -80,20 +82,71 @@ TerrainTextureClass::TerrainTextureClass(int height) :texture of the desired height and mip level. *///=============================================================================TerrainTextureClass::TerrainTextureClass(int height, int width) :- TextureClass(width, height,+ TextureClass(width, height,WW3D_FORMAT_A1R5G5B5, MIP_LEVELS_ALL ){}+TerrainTextureClass::TerrainTextureClass(int height, WW3DFormat format) :+ TextureClass(TEXTURE_WIDTH, height, format, MIP_LEVELS_3 )+{+}++int TerrainTextureClass::update(WorldHeightMap *htMap)+{+ return fill(htMap, false);+}++int TerrainTextureClass::updateNormals(WorldHeightMap *htMap)+{+ return fill(htMap, true);+}++// How steep the ground's own detail is made: a brightness step of one across a pixel tilts the+// normal by this much. Chosen by eye on the desert and grass tiles; the backend's+// NORMAL_MAP_STRENGTH scales it again at draw time.+static const Real TERRAIN_BUMP_DEPTH = 6.0f;++/** One tile's normals, stored the way the tile's own data is (bottom row first), which is what+ fill turns the right way up. Brightness stands in for height, so every grain, crack and pebble+ gets a slope and a flat patch of paint stays flat. Rows here run against v in the atlas, hence+ the sign on the green channel. It wraps at the tile's own edge: right for a class of one tile,+ a faint seam between the tiles of a bigger one. */+static void terrainTileNormals(const UnsignedByte *tileBGRA, Int extent, UnsignedByte *normalsBGRA)+{+ static Real height[MAX_TILE_PIXEL_EXTENT*MAX_TILE_PIXEL_EXTENT];+ for (Int pixel = 0; pixel < extent*extent; ++pixel) {+ const UnsignedByte *source = tileBGRA + pixel*TILE_BYTES_PER_PIXEL;+ height[pixel] = (0.114f*source[0] + 0.587f*source[1] + 0.299f*source[2]) / 255.0f;+ }+ for (Int row = 0; row < extent; ++row) {+ for (Int column = 0; column < extent; ++column) {+ const Int left = row*extent + (column + extent - 1) % extent;+ const Int right = row*extent + (column + 1) % extent;+ const Int below = ((row + extent - 1) % extent)*extent + column;+ const Int above = ((row + 1) % extent)*extent + column;+ const Real slopeU = (height[right] - height[left]) * 0.5f * TERRAIN_BUMP_DEPTH;+ // The row above in the tile is the row before in the atlas, so v grows downwards here.+ const Real slopeV = (height[below] - height[above]) * 0.5f * TERRAIN_BUMP_DEPTH;+ const Real length = sqrtf(slopeU*slopeU + slopeV*slopeV + 1.0f);+ UnsignedByte *target = normalsBGRA + (row*extent + column)*TILE_BYTES_PER_PIXEL;+ target[0] = (UnsignedByte)((1.0f/length*0.5f + 0.5f)*255.0f + 0.5f); // z in blue+ target[1] = (UnsignedByte)((-slopeV/length*0.5f + 0.5f)*255.0f + 0.5f); // y in green+ target[2] = (UnsignedByte)((-slopeU/length*0.5f + 0.5f)*255.0f + 0.5f); // x in red+ target[3] = 0xff;+ }+ }+}//=============================================================================-// TerrainTextureClass::update+// TerrainTextureClass::fill//=============================================================================/** Sets the tile bitmap data into the texture. The tiles are placed with 4pixel borders around them, so that when the tiles are scaled and bilinearly- interpolated, you don't get seams between the tiles. */+ interpolated, you don't get seams between the tiles. With normals, each+ tile's normals go where its colours would, into a 32 bit texture. *///=============================================================================-int TerrainTextureClass::update(WorldHeightMap *htMap)+int TerrainTextureClass::fill(WorldHeightMap *htMap, Bool normals){// D3DTexture is our texture;@@ -122,7 +175,8 @@ int TerrainTextureClass::update(WorldHeightMap *htMap)//DEBUG_ASSERTCRASH(tilesPerRow*numRows >= htMap->m_numBitmapTiles, ("Too many tiles."));DEBUG_ASSERTCRASH((Int)surface_desc.Width >= tilePixelExtent*tilesPerRow, ("Bitmap too small."));#endif- if (surface_desc.Format == D3DFMT_A1R5G5B5) {+ const Bool fullColour = surface_desc.Format == D3DFMT_A8R8G8B8;+ if (surface_desc.Format == D3DFMT_A1R5G5B5 || fullColour) {#if 0UnsignedInt cellX, cellY;for (cellX = 0; cellX < surface_desc.Width; cellX++) {@@ -133,16 +187,20 @@ int TerrainTextureClass::update(WorldHeightMap *htMap)}#endifInt tileNdx;- Int pixelBytes = 2;+ Int pixelBytes = fullColour ? 4 : 2;for (tileNdx=0; tileNdx < htMap->m_numBitmapTiles; tileNdx++) {TileData *pTile = htMap->getSourceTile(tileNdx);if (!pTile) continue;ICoord2D position = pTile->m_tileLocationInTexture;if (position.x<=0) continue; // all real tile offsets start at 2. jba.+ static UnsignedByte tileNormals[DATA_LEN_BYTES];+ if (normals) {+ terrainTileNormals(pTile->getRGBDataForWidth(tilePixelExtent), tilePixelExtent, tileNormals);+ }Int i,j;for (j=0; j<tilePixelExtent; j++) {- UnsignedByte *pBGR = pTile->getRGBDataForWidth(tilePixelExtent);+ UnsignedByte *pBGR = normals ? tileNormals : pTile->getRGBDataForWidth(tilePixelExtent);pBGR += (tilePixelExtent-1-j)*TILE_BYTES_PER_PIXEL*tilePixelExtent; // invert to match.Int row = position.y+j;UnsignedByte *pBGRX = ((UnsignedByte*)locked_rect.pBits) +@@ -151,7 +209,14 @@ int TerrainTextureClass::update(WorldHeightMap *htMap)Int column = position.x;pBGRX += column*pixelBytes;for (i=0; i<tilePixelExtent; i++) {- *((Short*)pBGRX) = 0x8000 + ((pBGR[2]>>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3);+ if (fullColour) {+ pBGRX[0] = pBGR[0];+ pBGRX[1] = pBGR[1];+ pBGRX[2] = pBGR[2];+ pBGRX[3] = 0xff;+ } else {+ *((Short*)pBGRX) = 0x8000 + ((pBGR[2]>>3)<<10) + ((pBGR[1]>>3)<<5) + (pBGR[0]>>3);+ }pBGRX +=pixelBytes;pBGR +=TILE_BYTES_PER_PIXEL;}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cppindex d750a4b71..40a042a62 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/TileData.cpp@@ -43,45 +43,69 @@ TileData::TileData()}-#define TILE_PIXEL_EXTENT_MIP1 32-#define TILE_PIXEL_EXTENT_MIP2 16-#define TILE_PIXEL_EXTENT_MIP3 8-#define TILE_PIXEL_EXTENT_MIP4 4-#define TILE_PIXEL_EXTENT_MIP5 2-#define TILE_PIXEL_EXTENT_MIP6 1--Bool TileData::hasRGBDataForWidth(Int width)+Int TheTilePixelExtent = SOURCE_TILE_PIXEL_EXTENT;++Bool TileData::hasRGBDataForWidth(Int width){- if (width == TILE_PIXEL_EXTENT) return(true);- if (width == TILE_PIXEL_EXTENT_MIP1) return(true);- if (width == TILE_PIXEL_EXTENT_MIP2) return(true);- if (width == TILE_PIXEL_EXTENT_MIP3) return(true);- if (width == TILE_PIXEL_EXTENT_MIP4) return(true);- if (width == TILE_PIXEL_EXTENT_MIP5) return(true);- if (width == TILE_PIXEL_EXTENT_MIP6) return(true);+ for (Int side = TILE_PIXEL_EXTENT; side >= 1; side /= 2) {+ if (width == side) return(true);+ }return(false);}-UnsignedByte * TileData::getRGBDataForWidth(Int width)+// The mips sit one after another, largest first, so a level starts where the sizes of the levels+// above it end. The full size level is m_tileData itself; a width that is no level gets that too.+UnsignedByte * TileData::getRGBDataForWidth(Int width){- // default- if (width == TILE_PIXEL_EXTENT_MIP1) return(m_tileDataMip32);- if (width == TILE_PIXEL_EXTENT_MIP2) return(m_tileDataMip16);- if (width == TILE_PIXEL_EXTENT_MIP3) return(m_tileDataMip8);- if (width == TILE_PIXEL_EXTENT_MIP4) return(m_tileDataMip4);- if (width == TILE_PIXEL_EXTENT_MIP5) return(m_tileDataMip2);- if (width == TILE_PIXEL_EXTENT_MIP6) return(m_tileDataMip1);+ Int offset = 0;+ for (Int side = TILE_PIXEL_EXTENT/2; side >= 1; side /= 2) {+ if (width == side) return(m_tileDataMips + offset);+ offset += side*side*TILE_BYTES_PER_PIXEL;+ }return(m_tileData);}-void TileData::updateMips(void)+void TileData::updateMips(void)+{+ UnsignedByte *higher = m_tileData;+ for (Int side = TILE_PIXEL_EXTENT; side > 1; side /= 2) {+ UnsignedByte *lower = getRGBDataForWidth(side/2);+ doMip(higher, side, lower);+ higher = lower;+ }+}++void TileData::scaleUpFrom(Int sourceExtent){- doMip(m_tileData, TILE_PIXEL_EXTENT, m_tileDataMip32);- doMip(m_tileDataMip32, TILE_PIXEL_EXTENT_MIP1, m_tileDataMip16);- doMip(m_tileDataMip16, TILE_PIXEL_EXTENT_MIP2, m_tileDataMip8);- doMip(m_tileDataMip8, TILE_PIXEL_EXTENT_MIP3, m_tileDataMip4);- doMip(m_tileDataMip4, TILE_PIXEL_EXTENT_MIP4, m_tileDataMip2);- doMip(m_tileDataMip2, TILE_PIXEL_EXTENT_MIP5, m_tileDataMip1);+ const Int extent = TILE_PIXEL_EXTENT;+ if (sourceExtent >= extent) return;++ UnsignedByte source[SOURCE_TILE_PIXEL_EXTENT*SOURCE_TILE_PIXEL_EXTENT*TILE_BYTES_PER_PIXEL];+ memcpy(source, m_tileData, sourceExtent*sourceExtent*TILE_BYTES_PER_PIXEL);+ const Real step = (Real)sourceExtent / (Real)extent;+ for (Int row = 0; row < extent; ++row) {+ // Sample at the centre of each destination pixel, so the stretched tile is not shifted+ // half a source pixel towards its corner.+ const Real y = (row + 0.5f)*step - 0.5f;+ const Int y0 = (Int)floorf(y);+ const Real fy = y - y0;+ const Int rowA = (y0 + sourceExtent) % sourceExtent;+ const Int rowB = (y0 + 1) % sourceExtent;+ for (Int column = 0; column < extent; ++column) {+ const Real x = (column + 0.5f)*step - 0.5f;+ const Int x0 = (Int)floorf(x);+ const Real fx = x - x0;+ const Int columnA = (x0 + sourceExtent) % sourceExtent;+ const Int columnB = (x0 + 1) % sourceExtent;+ for (Int p = 0; p < TILE_BYTES_PER_PIXEL; ++p) {+ const Real top = source[(rowA*sourceExtent + columnA)*TILE_BYTES_PER_PIXEL + p]*(1 - fx)+ + source[(rowA*sourceExtent + columnB)*TILE_BYTES_PER_PIXEL + p]*fx;+ const Real bottom = source[(rowB*sourceExtent + columnA)*TILE_BYTES_PER_PIXEL + p]*(1 - fx)+ + source[(rowB*sourceExtent + columnB)*TILE_BYTES_PER_PIXEL + p]*fx;+ m_tileData[(row*extent + column)*TILE_BYTES_PER_PIXEL + p] = (UnsignedByte)(top*(1 - fy) + bottom*fy + 0.5f);+ }+ }+ }}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex 97eab75b5..0009eecf5 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -457,6 +457,11 @@ W3DDisplay::~W3DDisplay()// Same reason as above: WW3D2 has no logging in a shipping build, and a -dx11 run that made no// device at all would otherwise look exactly like one that made a device nothing drew through.+ if( Direct3D11_Normal_Maps_Active() )+ {+ DEBUG_LOG(("NORMALMAPS: %I64u draws lit per pixel\n", Direct3D11_Normal_Mapped_Draws()));+ }+if( Direct3D11_Is_Enabled() ){unsigned pipelines = 0;@@ -1085,6 +1090,9 @@ void W3DDisplay::init( void )Direct3D11_Present_Enable( TheGlobalData->m_direct3D11 != FALSE );Direct3D11_Dump_Programs_To( TheGlobalData->m_direct3D11DumpPath.str() );pushDirect3D11PostChain();+ // Before any map is read: every tile and the atlas are sized by it. A headless run draws no+ // ground, so it keeps EA's tile and the memory.+ TheTilePixelExtent = TheGlobalData->m_headless ? SOURCE_TILE_PIXEL_EXTENT : MAX_TILE_PIXEL_EXTENT;// Same problem, same answer: the filter table is built the moment the device exists and WW3D2// cannot see GlobalData, so the player's texture filtering goes in here. Nothing in the game@@ -2363,6 +2371,11 @@ AGAIN:{USE_PERF_TIMER(BigAssRenderLoop)static Bool couldRender = true;+ // The bumped ground is shaded against the first terrain light, the one its+ // vertex colours were lit by. A script can change the time of day, so every frame.+ const Coord3D &sun = TheGlobalData->m_terrainLightPos[0];+ const float sunDirection[3] = { sun.x, sun.y, sun.z };+ Direct3D11_Set_Terrain_Sun( sunDirection );if ((TheGlobalData->m_breakTheMovie == FALSE) && (TheGlobalData->m_disableRender == false) && WW3D::Begin_Render( true, true, Vector3( 0.0f, 0.0f, 0.0f ), TheWaterTransparency->m_minWaterOpacity ) == WW3D_ERROR_OK){diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cppindex c2c6d4228..60baff342 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DShaderManager.cpp@@ -2236,6 +2236,13 @@ Int TerrainShaderPixelShader::set(Int pass)//setup base passDX8Wrapper::Set_DX8_Texture(0, W3DShaderManager::getShaderTexture(0)->Peek_D3D_Texture());DX8Wrapper::Set_DX8_Texture(1, W3DShaderManager::getShaderTexture(1)->Peek_D3D_Texture());+ // The atlas is bound here straight to the device, past TextureClass::Apply, so its+ // normal atlas has to be handed over here too.+ if (Direct3D11_Normal_Maps_Active())+ {+ TextureClass *normalAtlas = W3DShaderManager::getShaderTexture(0)->Peek_Normal_Map();+ Direct3D11_Mirror_Normal_Map(normalAtlas != NULL ? normalAtlas->Peek_D3D_Base_Texture() : NULL);+ }DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP);DX8Wrapper::Set_DX8_Texture_Stage_State( 0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cppindex 364252eca..d28936c32 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTreeBuffer.cpp@@ -484,11 +484,13 @@ public:void W3DTreeBuffer::updateTexture(void){- const Int MAX_TEX_WIDTH = 2048;+ // Thirty-two tiles across, the way the terrain atlas is, so the bigger tiles fit the+ // same number of trees.+ const Int MAX_TEX_WIDTH = 32*TILE_PIXEL_EXTENT;Int i, j;Int maxHeight = 0;- const Int maxTilesPerRow = MAX_TEX_WIDTH/(TILE_PIXEL_EXTENT);+ const Int maxTilesPerRow = 32;REF_PTR_RELEASE(m_treeTexture);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cppindex ee19f9cad..181000fad 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp@@ -51,6 +51,7 @@#include "W3DDevice/GameClient/HeightMap.h"#include "W3DDevice/GameClient/TerrainTex.h"#include "W3DDevice/GameClient/W3DShadow.h"+#include "dx11runtime.h"#include "Common/file.h"@@ -1041,7 +1042,18 @@ void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData)theFile = TheFileSystem->openFile( texClass->name.str(), File::READ|File::BINARY);#endif}- else+ Int sourceExtent = SOURCE_TILE_PIXEL_EXTENT;+ if (terrain != NULL && TILE_PIXEL_EXTENT > SOURCE_TILE_PIXEL_EXTENT)+ {+ // The same image drawn at the bigger tile, if there is one. Without it the+ // shipped image is read and each tile stretched.+ snprintf( texturePath, ARRAY_SIZE(texturePath), "%s%s", TERRAIN_HD_TGA_DIR_PATH, terrain->getTexture().str() );+ theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY);+ if (theFile != NULL) {+ sourceExtent = TILE_PIXEL_EXTENT;+ }+ }+ if (terrain != NULL && theFile == NULL){snprintf( texturePath, ARRAY_SIZE(texturePath), "%s%s", TERRAIN_TGA_DIR_PATH, terrain->getTexture().str() );theFile = TheFileSystem->openFile( texturePath, File::READ|File::BINARY);@@ -1050,7 +1062,7 @@ void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData)if (theFile != NULL) {GDIFileStream theStream(theFile);InputStream *pStr = &theStream;- Int numTiles = WorldHeightMap::countTiles(pStr);+ Int numTiles = WorldHeightMap::countTiles(pStr, NULL, sourceExtent);theFile->seek(0, File::START);if (numTiles >= texClass->numTiles) {numTiles = texClass->numTiles;@@ -1061,7 +1073,7 @@ void WorldHeightMap::readTexClass(TXTextureClass *texClass, TileData **tileData)break;}}- WorldHeightMap::readTiles(pStr, tileData+texClass->firstTile, width);+ WorldHeightMap::readTiles(pStr, tileData+texClass->firstTile, width, sourceExtent);}theFile->close();}@@ -1341,7 +1353,7 @@ typedef struct {/// Count how many tiles come in from a targa file.-Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile)+Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile, Int sourceExtent){TTargaHeader hdr;if (halfTile) {@@ -1349,8 +1361,8 @@ Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile)}Int len = pStr->read(&hdr,sizeof(hdr));if (len!=sizeof(hdr)) return(0);- Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT;- Int tileHeight = hdr.imageHeight/TILE_PIXEL_EXTENT;+ Int tileWidth = hdr.imageWidth/sourceExtent;+ Int tileHeight = hdr.imageHeight/sourceExtent;if (hdr.colorMapType != 0) {return(0); // we don't do indexed at this time. jba.@@ -1376,26 +1388,29 @@ Int WorldHeightMap::countTiles(InputStream *pStr, Bool *halfTile)if (tileWidth>=3 && tileHeight >=3) return(9);if (tileWidth>=2 && tileHeight >=2) return(4);if (tileWidth>=1 && tileHeight >=1) return(1);- if (halfTile && hdr.imageHeight==TILE_PIXEL_EXTENT/2 && hdr.imageWidth==TILE_PIXEL_EXTENT/2) {+ if (halfTile && hdr.imageHeight==sourceExtent/2 && hdr.imageWidth==sourceExtent/2) {*halfTile = true;return 1;}return(0);}/*Break down a .tga file into a collection of tiles. numRows * numRows total tiles.*/-Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows)+Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows, Int sourceExtent){TTargaHeader hdr;pStr->read(&hdr, sizeof(hdr));- Int tileWidth = hdr.imageWidth/TILE_PIXEL_EXTENT;- Int tileHeight = hdr.imageHeight/TILE_PIXEL_EXTENT;+ Int tileWidth = hdr.imageWidth/sourceExtent;+ Int tileHeight = hdr.imageHeight/sourceExtent;- if (hdr.imageHeight==TILE_PIXEL_EXTENT/2) {+ if (hdr.imageHeight==sourceExtent/2) {tileHeight = 1;}- if (hdr.imageWidth==TILE_PIXEL_EXTENT/2) {+ if (hdr.imageWidth==sourceExtent/2) {tileWidth = 1;}+ if (sourceExtent > TILE_PIXEL_EXTENT) {+ return(false);+ }if (tileWidth<numRows && tileHeight<numRows) {return(false);@@ -1418,7 +1433,7 @@ Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows)int repeatCount = 0;// Bool read = false;Bool running = false;- for (row = 0; row < numRows*TILE_PIXEL_EXTENT; row++) {+ for (row = 0; row < numRows*sourceExtent; row++) {for (column=0; column<hdr.imageWidth; column++) {UnsignedByte r, g, b, a;if (row < hdr.imageHeight) {@@ -1447,9 +1462,9 @@ Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows)} else {r = g = b = a = 0;}- if (column >= (numRows*TILE_PIXEL_EXTENT)) continue;- int tileNdx = (column/TILE_PIXEL_EXTENT) + numRows*(row/TILE_PIXEL_EXTENT);- int pixelNdx = (column%TILE_PIXEL_EXTENT) + TILE_PIXEL_EXTENT*(row%TILE_PIXEL_EXTENT);+ if (column >= (numRows*sourceExtent)) continue;+ int tileNdx = (column/sourceExtent) + numRows*(row/sourceExtent);+ int pixelNdx = (column%sourceExtent) + sourceExtent*(row%sourceExtent);UnsignedByte *pixel = tiles[tileNdx]->getDataPtr();@@ -1463,6 +1478,7 @@ Bool WorldHeightMap::readTiles(InputStream *pStr, TileData **tiles, Int numRows)DEBUG_ASSERTCRASH(repeatCount==0, ("Invalid tga."));}for (i=0; i<numRows*numRows; i++) {+ tiles[i]->scaleUpFrom(sourceExtent);tiles[i]->updateMips();}return(true);@@ -1478,7 +1494,9 @@ Int WorldHeightMap::updateTileTexturePositions(Int *edgeHeight)Int maxHeight = 0;const Int tilesPerRow = TEXTURE_WIDTH/(TILE_PIXEL_EXTENT+TILE_OFFSET);- Bool availableGrid[tilesPerRow][tilesPerRow];+ // The width is thirty-two tiles and a gutter each, so a row always holds fewer than 32.+ const Int MAX_TILES_PER_ROW = 32;+ Bool availableGrid[MAX_TILES_PER_ROW][MAX_TILES_PER_ROW];Int row, column;for (row=0; row<tilesPerRow; row++) {for (column=0; column<tilesPerRow; column++) {@@ -2186,6 +2204,15 @@ TextureClass *WorldHeightMap::getTerrainTexture(void)REF_PTR_RELEASE(m_terrainTex);m_terrainTex = MSGNEW("WorldHeightMap_getTerrainTexture") TerrainTextureClass(pow2Height);m_terrainTexHeight = m_terrainTex->update(this);+ if (Direct3D11_Normal_Maps_Active()) {+ // The ground's normals, laid out exactly as its colours, so the pixel program+ // reads both at the same coordinate. Built from the tiles every load; nothing ships one.+ TerrainTextureClass *normalTex = MSGNEW("WorldHeightMap_getTerrainTexture")+ TerrainTextureClass(pow2Height, WW3D_FORMAT_A8R8G8B8);+ normalTex->updateNormals(this);+ m_terrainTex->Set_Normal_Map(normalTex);+ REF_PTR_RELEASE(normalTex);+ }char buf[64];sprintf(buf, "Base tex height %d\n", pow2Height);DEBUG_LOG((buf));diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 7aaa4c626..aef077073 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -38,6 +38,13 @@ static const char * const ENTRY_POINT = "main";static const char * const VERTEX_PROFILE = "vs_4_0";static const char * const PIXEL_PROFILE = "ps_4_0";+// How far a normal map tilts the normal (1 is as the map is written), the exponent of the+// highlight it adds, and how bright that highlight is where the map's alpha is one. Picked by eye+// on four tanks and a desert base.+static const float NORMAL_MAP_STRENGTH = 1.0f;+static const float NORMAL_MAP_HIGHLIGHT_POWER = 24.0f;+static const float NORMAL_MAP_HIGHLIGHT_SCALE = 0.5f;+// The three stage counts are one count in three headers. The vertex constant block is copied// wholesale out of the backend's own texture transforms, the generated pixel shader declares one// sampler per texture the backend binds, and a mismatch is a silent overrun rather than a build@@ -192,6 +199,8 @@ DX11BackendClass::DX11BackendClass(), CurrentTargetResource(NULL), TargetCopy(NULL), TargetCopyView(NULL)+ , NormalMap(NULL)+ , NormalMappedDraws(0), DrawsMade(0), DrawsRefused(0), RefusedNoBuffer(0)@@ -219,6 +228,7 @@ DX11BackendClass::DX11BackendClass()memset(EngineConstants, 0, sizeof(EngineConstants));memset(MissingTexture, 0, sizeof(MissingTexture));memset(Lights, 0, sizeof(Lights));+ memset(TerrainSun, 0, sizeof(TerrainSun));memset(MaterialAmbient, 0, sizeof(MaterialAmbient));memset(MaterialDiffuse, 0, sizeof(MaterialDiffuse));memset(MaterialSpecular, 0, sizeof(MaterialSpecular));@@ -394,6 +404,40 @@ void DX11BackendClass::Set_Texture(unsigned stage, ID3D11ShaderResourceView * te}}+void DX11BackendClass::Set_Normal_Map(ID3D11ShaderResourceView * normal_map)+{+ NormalMap = normal_map;+}++// Directional lights only, because the pixel half sums nothing else; a draw under a point light is+// lit per vertex the way it always was. A transcribed program is its own lighting.+bool DX11BackendClass::Normal_Mapped() const+{+ if (NormalMap == NULL || Textures[0] == NULL+ || VertexProgram != ENGINE_SHADER_NONE || PixelProgram != ENGINE_SHADER_NONE+ || RenderStates.Get_Render_State(D3DRS_LIGHTING) == FALSE+ || (VertexFormat & D3DFVF_NORMAL) == 0) {+ return false;+ }+ for (unsigned index = 0; index < MAXIMUM_VERTEX_LIGHTS; ++index) {+ if (Lights[index].Enabled && Lights[index].Type != D3DLIGHT_DIRECTIONAL) {+ return false;+ }+ }+ return true;+}++bool DX11BackendClass::Terrain_Bumped() const+{+ return NormalMap != NULL && Textures[0] != NULL && VertexProgram == ENGINE_SHADER_NONE+ && EngineShader_Can_Bump(PixelProgram) && (VertexFormat & D3DFVF_XYZRHW) == 0;+}++void DX11BackendClass::Set_Terrain_Sun(const float direction[3])+{+ memcpy(TerrainSun, direction, sizeof(TerrainSun));+}+void DX11BackendClass::Set_Vertex_Format(DWORD fvf){VertexFormat = fvf;@@ -870,6 +914,7 @@ bool DX11BackendClass::Build_Combiner_Description(CombinerDescription & descripttarget.TextureBound = Textures[stage] != NULL;description.StageCount = stage + 1;}+ description.NormalMapped = description.StageCount > 0 && Normal_Mapped();return description.StageCount > 0;}@@ -914,6 +959,8 @@ bool DX11BackendClass::Build_Vertex_Description(VertexPipelineDescription & descdescription.FogEnabled = RenderStates.Get_Render_State(D3DRS_FOGENABLE) != FALSE;description.FogVertexMode = RenderStates.Get_Render_State(D3DRS_FOGVERTEXMODE);+ description.NormalMapped = (Normal_Mapped()+ && StageStates[0][D3DTSS_COLOROP] != D3DTOP_DISABLE) || Terrain_Bumped();return true;}@@ -961,9 +1008,11 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)const std::string vertex_key = (VertexProgram != ENGINE_SHADER_NONE)? std::string(EngineShader_Name(VertexProgram)): VertexShader_Key(vertex_description);+ const bool terrain_bumped = vertex_description.NormalMapped && PixelProgram != ENGINE_SHADER_NONE;const std::string pixel_key = (PixelProgram != ENGINE_SHADER_NONE)? EngineShader_Name(PixelProgram)+ CombinerShader_Pipeline_Key(combiner_description.PixelPipeline)+ + (terrain_bumped ? ":N" : ""): CombinerShader_Key(combiner_description);const std::string key = vertex_key + pixel_key + format;@@ -991,7 +1040,8 @@ bool DX11BackendClass::Resolve(Pipeline & pipeline)return false;}const bool wrote_pixel = (PixelProgram != ENGINE_SHADER_NONE)- ? EngineShader_Pixel_Program(PixelProgram, combiner_description.PixelPipeline, pixel_hlsl)+ ? EngineShader_Pixel_Program(PixelProgram, combiner_description.PixelPipeline, pixel_hlsl,+ terrain_bumped): CombinerShader_Generate(combiner_description, COMBINER_SHADER_TARGET_D3D11, pixel_hlsl);if (!wrote_pixel) {Note_Refusal("the pixel half would not generate this description");@@ -1217,6 +1267,44 @@ void DX11BackendClass::Upload_Constants()pixel_block.AlphaReference[0] =static_cast<float>(RenderStates.Get_Render_State(D3DRS_ALPHAREF) & 0xff);+ // The normal mapped program's lights, the enabled ones first and in camera space like the+ // vertex block's. A slot with no light gets a direction anyway: the highlight normalises the+ // half vector, and a zero direction there is a NaN that no zero colour cancels.+ unsigned normal_slot = 0;+ for (unsigned index = 0; index < MAXIMUM_VERTEX_LIGHTS && normal_slot < NORMAL_MAPPED_LIGHTS;+ ++index) {+ if (!Lights[index].Enabled) {+ continue;+ }+ float * direction = pixel_block.NormalLightDirection[normal_slot];+ transform_direction(Lights[index].Direction, View, direction);+ const float length = sqrtf(direction[0] * direction[0] + direction[1] * direction[1]+ + direction[2] * direction[2]);+ if (length > 0.0f) {+ direction[0] /= length;+ direction[1] /= length;+ direction[2] /= length;+ }+ memcpy(pixel_block.NormalLightDiffuse[normal_slot], Lights[index].Diffuse, sizeof(float) * 4);+ ++normal_slot;+ }+ for (; normal_slot < NORMAL_MAPPED_LIGHTS; ++normal_slot) {+ pixel_block.NormalLightDirection[normal_slot][2] = 1.0f;+ }+ pixel_block.NormalMapParameters[0] = NORMAL_MAP_STRENGTH;+ pixel_block.NormalMapParameters[1] = NORMAL_MAP_HIGHLIGHT_POWER;+ pixel_block.NormalMapParameters[2] = NORMAL_MAP_HIGHLIGHT_SCALE;+ const float sun[4] = { TerrainSun[0], TerrainSun[1], TerrainSun[2], 0.0f };+ transform_direction(sun, View, pixel_block.TerrainSunDirection);+ const float sun_length = sqrtf(pixel_block.TerrainSunDirection[0] * pixel_block.TerrainSunDirection[0]+ + pixel_block.TerrainSunDirection[1] * pixel_block.TerrainSunDirection[1]+ + pixel_block.TerrainSunDirection[2] * pixel_block.TerrainSunDirection[2]);+ if (sun_length > 0.0f) {+ for (unsigned axis = 0; axis < 3; ++axis) {+ pixel_block.TerrainSunDirection[axis] /= sun_length;+ }+ }+if ((!PixelConstantsHeld|| memcmp(&HeldPixelConstants, &pixel_block, sizeof(pixel_block)) != 0)&& SUCCEEDED(context->Map(PixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped))) {@@ -1407,6 +1495,11 @@ void DX11BackendClass::Bind_State_Objects()context->PSSetShaderResources(0, DX11_BACKEND_TEXTURE_STAGES, textures);memcpy(Bound.Textures, textures, sizeof(textures));}+ // Left bound when the draw does not read it, since only a normal mapped program declares t4.+ if (NormalMap != NULL && (!known || NormalMap != Bound.NormalMap)) {+ context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES, 1, &NormalMap);+ Bound.NormalMap = NormalMap;+ }}void DX11BackendClass::Bind_Pipeline(const Pipeline & pipeline, ID3D11Buffer * vertices, UINT stride,@@ -1561,6 +1654,9 @@ bool DX11BackendClass::Draw_Indexed(unsigned index_count, unsigned start_index,context->DrawIndexed(index_count, start_index, base_vertex);++DrawsMade;+ if (Normal_Mapped() || Terrain_Bumped()) {+ ++NormalMappedDraws;+ }if (CurrentTarget != NULL) {++DrawsIntoTargets;MaskWhileTargeted |= RenderStates.Get_Render_State(D3DRS_COLORWRITEENABLE);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex 5590e3963..93307528a 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -81,6 +81,16 @@ public:void Set_Sampler_State(unsigned sampler, D3DSAMPLERSTATETYPE state, DWORD value);void Set_Texture(unsigned stage, ID3D11ShaderResourceView * texture);+ // The normal map that goes with the texture at stage zero, or null when it has none. A lit+ // draw with directional lights only is then lit per pixel through it, and so is the terrain;+ // every other draw ignores it.+ void Set_Normal_Map(ID3D11ShaderResourceView * normal_map);+ unsigned long long Normal_Mapped_Draw_Count() const { return NormalMappedDraws; }++ // The way the sun's light travels, in world space: the terrain has no D3D light of its own, its+ // light is baked into the vertices, so its bump is shaded against this.+ void Set_Terrain_Sun(const float direction[3]);+// The engine bound a texture at this stage that has no D3D11 copy - a render target it drew// into, most often. Sampling white there paints a full screen quad over the frame, so a draw// that reads one is refused instead.@@ -236,12 +246,22 @@ private:float LightFields[MAXIMUM_VERTEX_LIGHTS][6][4];};+ // The normal map fields go last: a program that is not normal mapped declares the first three+ // and nothing else, which a larger buffer serves.struct PixelConstantBlock{float TextureFactor[4];float FogColour[4];float AlphaReference[4];+ float NormalLightDirection[NORMAL_MAPPED_LIGHTS][4];+ float NormalLightDiffuse[NORMAL_MAPPED_LIGHTS][4];+ float NormalMapParameters[4];+ float TerrainSunDirection[4];};+ // A model under directional lights, drawn by generated programs.+ bool Normal_Mapped() const;+ // The ground, drawn by one of the transcribed terrain programs with its light baked in.+ bool Terrain_Bumped() const;bool Resolve(Pipeline & pipeline);bool Build_Vertex_Description(VertexPipelineDescription & description) const;@@ -269,6 +289,9 @@ private:DX11SamplerBlockClass Samplers[DX11_BACKEND_TEXTURE_STAGES];DWORD StageStates[DX11_BACKEND_TEXTURE_STAGES][DX11_BACKEND_STAGE_STATES];ID3D11ShaderResourceView * Textures[DX11_BACKEND_TEXTURE_STAGES];+ ID3D11ShaderResourceView * NormalMap;+ unsigned long long NormalMappedDraws;+ float TerrainSun[3];DWORD VertexFormat;ID3D11Buffer * StreamBuffer;@@ -468,6 +491,7 @@ private:ID3D11RasterizerState * Rasterizer;ID3D11SamplerState * Samplers[DX11_BACKEND_TEXTURE_STAGES];ID3D11ShaderResourceView * Textures[DX11_BACKEND_TEXTURE_STAGES];+ ID3D11ShaderResourceView * NormalMap;ID3D11InputLayout * Layout;ID3D11Buffer * VertexBuffer;UINT VertexStride;diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cppindex 8bf5fd7e3..7e2b16d0c 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -240,6 +240,39 @@ void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * te: DX11Texture_Mirror(Device.Get_Device(), Device.Get_Context(), texture);Backend.Set_Texture(stage, view);Backend.Set_Texture_Missing(stage, texture != NULL && view == NULL);++ // A new texture at stage zero drops the old one's normal map. TextureClass::Apply hands over+ // the new one's right after this, and a texture bound any other way has none.+ if (stage == 0) {+ Backend.Set_Normal_Map(NULL);+ }+}++bool Direct3D11_Normal_Maps_Active()+{+ return Active;+}++void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 * normal_map)+{+ if (!Active) {+ return;+ }+ Backend.Set_Normal_Map(normal_map == NULL+ ? NULL+ : DX11Texture_Mirror(Device.Get_Device(), Device.Get_Context(), normal_map));+}++void Direct3D11_Set_Terrain_Sun(const float direction[3])+{+ if (Active) {+ Backend.Set_Terrain_Sun(direction);+ }+}++unsigned long long Direct3D11_Normal_Mapped_Draws()+{+ return Active ? Backend.Normal_Mapped_Draw_Count() : 0;}void Direct3D11_Mirror_Render_Target(struct IDirect3DSurface9 * surface)diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.hindex 2d6aeb016..1498559d7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.h@@ -87,6 +87,16 @@ DX11BufferTwinClass * Direct3D11_Twin_Index_Buffer(unsigned byte_count, bool dyn// first bind and kept on it, so nothing in the loaders has to know this exists.void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * texture);+// Normal maps: TextureClass looks for a "<name>_nrm.dds" beside every texture it binds at stage+// zero and hands it over here, null when there is none; the terrain builds its own. Active is+// false on a Direct3D 9 run, which has no pixel half to light with.+bool Direct3D11_Normal_Maps_Active();+void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 * normal_map);++// The way the sun's light travels, world space, for the bumped terrain. Set once a frame.+void Direct3D11_Set_Terrain_Sun(const float direction[3]);+unsigned long long Direct3D11_Normal_Mapped_Draws();+// The CPU has just written this surface. The next bind of its texture fills the Direct3D 11 copy// again. A no-op when the backend is not running.void Direct3D11_Mark_Surface_Dirty(struct IDirect3DSurface9 * surface);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cppindex 8819df26f..a7e5e7e60 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.cpp@@ -17,6 +17,7 @@*/#include "engineshader.h"+#include "ffvertex.h"#include <stdio.h>#include <string.h>@@ -183,7 +184,32 @@ static void write_trees(std::string & hlsl)// ffshader's declarations, member for member and in the same order, so a transcribed pixel program// is bound with the same constant buffer, the same textures and the same samplers as a generated// one. Reading fewer of them than are declared costs nothing.-static void write_pixel_preamble(std::string & hlsl)+// The bumped terrain's own light: the share of it that does not depend on which way the ground+// faces. Without one the ratio below divides by nearly nothing on ground turned from the sun.+static const char * const TERRAIN_BUMP_AMBIENT = "0.4";++// A tangent space normal from the atlas, put into camera space on the frame the coordinate set+// actually has at this pixel: tangent where u grows, bitangent where v grows. The same+// construction ffshader uses for models, as a function because the terrain has two layers.+static const char * const TERRAIN_BUMP_FUNCTION =+ "float3 bumped_normal(float3 position, float3 surface, float2 coordinate, float3 texel)\n"+ "{\n"+ " float3 position_dx = ddx(position);\n"+ " float3 position_dy = ddy(position);\n"+ " float2 coordinate_dx = ddx(coordinate);\n"+ " float2 coordinate_dy = ddy(coordinate);\n"+ " float3 across_dy = cross(position_dy, surface);\n"+ " float3 across_dx = cross(surface, position_dx);\n"+ " float3 tangent = across_dy * coordinate_dx.x + across_dx * coordinate_dy.x;\n"+ " float3 bitangent = across_dy * coordinate_dx.y + across_dx * coordinate_dy.y;\n"+ " float frame_scale = rsqrt(max(max(dot(tangent, tangent), dot(bitangent, bitangent)), 1e-20));\n"+ " float3 bump = texel * 2.0 - 1.0;\n"+ " bump.xy *= NormalMapParameters.x;\n"+ " return normalize((tangent * bump.x + bitangent * bump.y) * frame_scale + surface * bump.z);\n"+ "}\n"+ "\n";++static void write_pixel_preamble(std::string & hlsl, bool bumped = false){for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {char line[128];@@ -199,8 +225,23 @@ static void write_pixel_preamble(std::string & hlsl)"{\n"" float4 TextureFactor;\n"" float4 FogColour;\n"- " float4 AlphaReference;\n"- "};\n"+ " float4 AlphaReference;\n";+ if (bumped) {+ // The whole of DX11BackendClass::PixelConstantBlock up to the sun, in its order.+ char line[256];+ snprintf(line, sizeof(line),+ " float4 NormalLightDirection[%u];\n"+ " float4 NormalLightDiffuse[%u];\n"+ " float4 NormalMapParameters;\n"+ " float4 TerrainSunDirection;\n",+ NORMAL_MAPPED_LIGHTS, NORMAL_MAPPED_LIGHTS);+ hlsl += line;+ }+ hlsl += "};\n";+ if (bumped) {+ hlsl += "Texture2D NormalMap : register(t4);\n";+ }+ hlsl +="\n""struct Input\n""{\n"@@ -214,10 +255,17 @@ static void write_pixel_preamble(std::string & hlsl)hlsl += line;}+ hlsl += " float Fog : FOG;\n";+ if (bumped) {+ hlsl += NORMAL_MAPPED_VARYINGS;+ }hlsl +=- " float Fog : FOG;\n""};\n"- "\n"+ "\n";+ if (bumped) {+ hlsl += TERRAIN_BUMP_FUNCTION;+ }+ hlsl +="float4 main(Input input) : SV_Target\n""{\n";@@ -334,9 +382,10 @@ static void write_monochrome(std::string & hlsl)// Every ps_1_1 instruction clamps its result to zero and one, so each step saturates and not only// the last: a chain that overflows in the middle and comes back down is a different colour with the// clamps than without them.-static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & entry)+static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & entry,+ bool bumped){- write_pixel_preamble(hlsl);+ write_pixel_preamble(hlsl, bumped);hlsl += " float4 current = saturate(";hlsl += entry.Opening;@@ -347,6 +396,36 @@ static void write_multiply_chain(std::string & hlsl, const EngineShaderEntry & ehlsl += *step;hlsl += ");\n";}++ if (!bumped) {+ return;+ }++ // The vertex colour already carries the light the ground's own slope gets, so the bump is a+ // ratio on top of it: how much more or less the bumped surface faces the sun than the flat one+ // the triangle is. The two layers blend by the same alpha the colours do.+ char line[1024];+ snprintf(line, sizeof(line),+ " float3 flat_normal = normalize(cross(ddx(input.ViewPosition), ddy(input.ViewPosition)));\n"+ " if (dot(flat_normal, input.ViewPosition) > 0.0) { flat_normal = -flat_normal; }\n"+ " float3 to_sun = -TerrainSunDirection.xyz;\n"+ " float3 near_layer = bumped_normal(input.ViewPosition, flat_normal, input.TexCoord0,"+ " NormalMap.Sample(Sampler0, input.TexCoord0).xyz);\n"+ " float3 far_layer = bumped_normal(input.ViewPosition, flat_normal, input.TexCoord1,"+ " NormalMap.Sample(Sampler1, input.TexCoord1).xyz);\n"+ " float3 surface = normalize(lerp(near_layer, far_layer, input.Diffuse.a));\n"+ " float flat_light = %s + (1.0 - %s) * saturate(dot(flat_normal, to_sun));\n"+ " float bumped_light = %s + (1.0 - %s) * saturate(dot(surface, to_sun));\n"+ " float shade = bumped_light / flat_light;\n"+ " current.rgb = saturate(current.rgb * shade);\n",+ TERRAIN_BUMP_AMBIENT, TERRAIN_BUMP_AMBIENT, TERRAIN_BUMP_AMBIENT, TERRAIN_BUMP_AMBIENT);+ hlsl += line;+}++bool EngineShader_Can_Bump(EngineShaderProgram program)+{+ return program == ENGINE_SHADER_TERRAIN || program == ENGINE_SHADER_TERRAIN_NOISE+ || program == ENGINE_SHADER_TERRAIN_NOISE_2;}static char lowered(char character)@@ -396,13 +475,16 @@ bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl}bool EngineShader_Pixel_Program(EngineShaderProgram program,- const PixelPipelineDescription & pipeline, std::string & hlsl)+ const PixelPipelineDescription & pipeline, std::string & hlsl, bool bumped){hlsl.clear();+ if (bumped && !EngineShader_Can_Bump(program)) {+ return false;+ }const EngineShaderEntry * entry = entry_for(program);if (entry != NULL && entry->Opening != NULL) {- write_multiply_chain(hlsl, *entry);+ write_multiply_chain(hlsl, *entry, bumped);}else if (program == ENGINE_SHADER_WATER_TRAPEZOID) {write_trapezoid_water(hlsl);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.hindex 08aed41cb..274bc3621 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/engineshader.h@@ -84,8 +84,15 @@ bool EngineShader_Vertex_Program(EngineShaderProgram program, std::string & hlsl// The pixel half. The alpha test and the fog come from the render state and are written into the// program the way ffshader writes them, because D3D9 applies both around a bound pixel shader and// D3D11 applies neither.+//+// bumped is the terrain's normal atlas at work: the ground is shaded again through the normal atlas at t4,+// by how much the bumped surface faces the sun more or less than the flat one does. Only the three+// blending terrain programs take it; for any other the call is refused.bool EngineShader_Pixel_Program(EngineShaderProgram program,- const PixelPipelineDescription & pipeline, std::string & hlsl);+ const PixelPipelineDescription & pipeline, std::string & hlsl, bool bumped = false);++// Whether a program is one bumped can be asked of.+bool EngineShader_Can_Bump(EngineShaderProgram program);// What the pipeline cache keys this program under and what the dump calls its file.const char * EngineShader_Name(EngineShaderProgram program);diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cppindex ab38051bd..11264fcc7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.cpp@@ -17,6 +17,7 @@*/#include "ffshader.h"+#include "ffvertex.h"#include <stdio.h>@@ -214,12 +215,56 @@ static bool alpha_test_expression(DWORD function, std::string & expression)}}+// The vertex colour lit again with the normal the map gives, written over input.Diffuse before the+// stages read it, and the highlight the stages add afterwards. The map carries no tangents and+// the game's meshes have none either, so the frame is rebuilt per pixel from how the position and+// the coordinate change across the screen: a tangent is whichever way u grows and a bitangent+// whichever way v grows, which is the convention the maps are written in and which holds on a+// mirrored island too. The light directions are the way the light travels, in camera space.+static void append_normal_mapped_lighting(std::string & hlsl, unsigned coordinate_set)+{+ char line[2048];+ snprintf(line, sizeof(line),+ " float3 surface_normal = normalize(input.ViewNormal);\n"+ " float3 position_dx = ddx(input.ViewPosition);\n"+ " float3 position_dy = ddy(input.ViewPosition);\n"+ " float2 coordinate_dx = ddx(input.TexCoord%u);\n"+ " float2 coordinate_dy = ddy(input.TexCoord%u);\n"+ " float3 across_dy = cross(position_dy, surface_normal);\n"+ " float3 across_dx = cross(surface_normal, position_dx);\n"+ " float3 tangent = across_dy * coordinate_dx.x + across_dx * coordinate_dy.x;\n"+ " float3 bitangent = across_dy * coordinate_dx.y + across_dx * coordinate_dy.y;\n"+ " float frame_scale = rsqrt(max(max(dot(tangent, tangent), dot(bitangent, bitangent)), 1e-20));\n"+ " float4 normal_texel = NormalMap.Sample(Sampler0, input.TexCoord%u);\n"+ " float3 bump = normal_texel.xyz * 2.0 - 1.0;\n"+ " bump.xy *= NormalMapParameters.x;\n"+ " float3 bumped = normalize((tangent * bump.x + bitangent * bump.y) * frame_scale"+ " + surface_normal * bump.z);\n"+ " float3 to_eye = normalize(-input.ViewPosition);\n"+ " float3 bumped_light = float3(0.0, 0.0, 0.0);\n"+ " float3 highlight = float3(0.0, 0.0, 0.0);\n"+ " for (int light = 0; light < %u; ++light) {\n"+ " float3 to_light = -NormalLightDirection[light].xyz;\n"+ " bumped_light += NormalLightDiffuse[light].rgb * saturate(dot(bumped, to_light));\n"+ " highlight += NormalLightDiffuse[light].rgb"+ " * pow(saturate(dot(bumped, normalize(to_light + to_eye))), NormalMapParameters.y);\n"+ " }\n"+ " highlight *= normal_texel.a * NormalMapParameters.z;\n"+ " input.Diffuse.rgb = saturate(input.LitMaterial * bumped_light + input.LitBase);\n",+ coordinate_set, coordinate_set, coordinate_set, NORMAL_MAPPED_LIGHTS);+ hlsl += line;+}+bool CombinerShader_Generate(const CombinerDescription & description, CombinerShaderTarget target,std::string & hlsl){if (description.StageCount == 0 || description.StageCount > MAXIMUM_COMBINER_STAGES) {return false;}+ if (description.NormalMapped+ && (target != COMBINER_SHADER_TARGET_D3D11 || !description.Stages[0].TextureBound)) {+ return false;+ }std::string body;for (unsigned stage = 0; stage < description.StageCount; ++stage) {@@ -309,8 +354,20 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh"{\n"" float4 TextureFactor;\n"" float4 FogColour;\n"- " float4 AlphaReference;\n"- "};\n";+ " float4 AlphaReference;\n";+ if (description.NormalMapped) {+ char line[256];+ snprintf(line, sizeof(line),+ " float4 NormalLightDirection[%u];\n"+ " float4 NormalLightDiffuse[%u];\n"+ " float4 NormalMapParameters;\n",+ NORMAL_MAPPED_LIGHTS, NORMAL_MAPPED_LIGHTS);+ hlsl += line;+ }+ hlsl += "};\n";+ if (description.NormalMapped) {+ hlsl += "Texture2D NormalMap : register(t4);\n";+ }}else {for (unsigned stage = 0; stage < MAXIMUM_COMBINER_STAGES; ++stage) {@@ -347,6 +404,9 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerShif (target == COMBINER_SHADER_TARGET_D3D11) {hlsl += " float Fog : FOG;\n";}+ if (description.NormalMapped) {+ hlsl += NORMAL_MAPPED_VARYINGS;+ }hlsl +="};\n""\n";@@ -355,9 +415,16 @@ bool CombinerShader_Generate(const CombinerDescription & description, CombinerSh: "float4 main(Input input) : COLOR\n";hlsl +="{\n"- " float4 texel;\n"- " float4 current = input.Diffuse;\n";+ " float4 texel;\n";+ if (description.NormalMapped) {+ append_normal_mapped_lighting(hlsl,+ coordinate_register(description.Stages[0].TextureCoordinateIndex));+ }+ hlsl += " float4 current = input.Diffuse;\n";hlsl += body;+ if (description.NormalMapped) {+ hlsl += " current.rgb = saturate(current.rgb + highlight);\n";+ }if (target == COMBINER_SHADER_TARGET_D3D11&& !CombinerShader_Append_Pixel_Pipeline(description.PixelPipeline, hlsl)) {@@ -429,5 +496,8 @@ std::string CombinerShader_Key(const CombinerDescription & description)// both, which costs a D3D9 cache entry that generates the same text as another and buys one// cache that is right for either profile.key += CombinerShader_Pipeline_Key(description.PixelPipeline);+ if (description.NormalMapped) {+ key += ":N";+ }return key;}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.hindex 4e5783c9a..8fd9382b2 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffshader.h@@ -83,8 +83,18 @@ struct CombinerDescription// Only read when generating for D3D11. On D3D9 the device still applies both itself around a// bound pixel shader, and generating them there would apply each of them twice.PixelPipelineDescription PixelPipeline;++ // D3D11 only: light the pixel again through the normal map at t4 before the+ // stages read the diffuse colour, and add a highlight scaled by the map's alpha after them.+ // The vertex half has to have been generated with the same flag. Initialised here because+ // callers fill a description field by field and one written before this existed never sets it.+ bool NormalMapped = false;};+// The normal mapped pixel program reads this many directional lights from its constants. Slots+// past the draw's own lights carry no colour and add nothing.+const unsigned NORMAL_MAPPED_LIGHTS = 4;+// The HLSL for one description, or false when the description names an operation or an argument// this does not generate. A refusal is not a failure: the caller keeps the fixed-function path for// that draw, which is the only reason an unmeasured operation is safe to meet at run time.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cppindex 19f5f5394..2cd33e5a7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.cpp@@ -338,7 +338,7 @@ static void append_input_coordinate_sets(std::string & hlsl, unsigned coordinate// What every generated vertex program writes, whatever it was generated from. Shader model 4// links the stages by slot in declaration order, so this structure and ffshader's input structure// are one thing in two files: a program that writes a different set links against nothing.-static void append_output_structure(std::string & hlsl, bool for_d3d11)+static void append_output_structure(std::string & hlsl, bool for_d3d11, bool normal_mapped){hlsl +="struct Output\n"@@ -354,8 +354,11 @@ static void append_output_structure(std::string & hlsl, bool for_d3d11)hlsl += line;}+ hlsl += " float Fog : FOG;\n";+ if (normal_mapped) {+ hlsl += NORMAL_MAPPED_VARYINGS;+ }hlsl +=- " float Fog : FOG;\n""};\n""\n";}@@ -390,7 +393,7 @@ static bool generate_pretransformed(const VertexPipelineDescription & descriptiohlsl +="};\n""\n";- append_output_structure(hlsl, for_d3d11);+ append_output_structure(hlsl, for_d3d11, false);hlsl +="Output main(Input input)\n""{\n"@@ -449,6 +452,9 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,if (description.LightingEnabled && !has_normal(description.FVF)) {return false;}+ if (description.NormalMapped && is_pretransformed(description.FVF)) {+ return false;+ }// A pre-transformed vertex has been through the transform, the lighting and the coordinate// generation already: its position is in pixels, its colour is in the vertex, and D3D9 reads@@ -520,6 +526,14 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,+ ambient + ".rgb * GlobalAmbient.rgb + " + emissive + ".rgb);\n";body += " output.Diffuse.a = " + diffuse + ".a;\n";+ if (description.NormalMapped) {+ body += " output.ViewPosition = view_position.xyz;\n";+ body += " output.ViewNormal = view_normal;\n";+ body += " output.LitBase = " + ambient + ".rgb * GlobalAmbient.rgb + " + emissive+ + ".rgb;\n";+ body += " output.LitMaterial = " + diffuse + ".rgb;\n";+ }+if (description.SpecularEnabled) {std::string specular;if (!material_source_expression(description.SpecularMaterialSource, "MaterialSpecular",@@ -568,6 +582,17 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,body += " output.Fog = 1.0;\n";}+ // An unlit normal mapped draw is the terrain, whose light is baked into its vertex colour. The+ // pixel half only wants the position from it, to rebuild the surface frame; the lit colour it+ // would otherwise be handed is not used.+ if (description.NormalMapped && !description.LightingEnabled) {+ body +=+ " output.ViewPosition = view_position.xyz;\n"+ " output.ViewNormal = view_normal;\n"+ " output.LitBase = float3(0.0, 0.0, 0.0);\n"+ " output.LitMaterial = float3(0.0, 0.0, 0.0);\n";+ }+const bool for_d3d11 = (target == VERTEX_SHADER_TARGET_D3D11);hlsl = "// Generated from a fixed-function vertex pipeline description. See ffvertex.h.\n";@@ -603,7 +628,7 @@ bool VertexShader_Generate(const VertexPipelineDescription & description,hlsl +="};\n""\n";- append_output_structure(hlsl, for_d3d11);+ append_output_structure(hlsl, for_d3d11, description.NormalMapped);hlsl +="Output main(Input input)\n""{\n"@@ -651,5 +676,8 @@ std::string VertexShader_Key(const VertexPipelineDescription & description)snprintf(field, sizeof(field), ":F%u,%lu", description.FogEnabled ? 1u : 0u,description.FogEnabled ? description.FogVertexMode : 0ul);key += field;+ if (description.NormalMapped) {+ key += ":N";+ }return key;}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.hindex dedfbad5d..673dbd162 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffvertex.h@@ -52,6 +52,14 @@ const unsigned MAXIMUM_VERTEX_STAGES = 4;// three, and every register past this one is a register the D3D9 profile does not have to spare.const unsigned MAXIMUM_VERTEX_LIGHTS = 4;+// What a normal mapped vertex program writes after the fog factor, and what the pixel program+// declares after it. One string in one place because shader model 4 links the two by slot.+#define NORMAL_MAPPED_VARYINGS \+ " float3 ViewPosition : TEXCOORD4;\n" \+ " float3 ViewNormal : TEXCOORD5;\n" \+ " float3 LitBase : TEXCOORD6;\n" \+ " float3 LitMaterial : TEXCOORD7;\n"+// Where each constant sits in the D3D9 profile's register file, which is what// SetVertexShaderConstantF is given. The D3D11 profile puts the same values in one constant buffer// in this order instead, so the two halves of the generator share the layout and nothing else.@@ -123,6 +131,13 @@ struct VertexPipelineDescription// D3DRS_FOGVERTEXMODE: D3DFOG_LINEAR, D3DFOG_EXP or D3DFOG_EXP2. D3DFOG_NONE with the fog// enabled is table fog, which is the pixel half's business and not this one's.DWORD FogVertexMode;++ // Stage zero's texture has a normal map beside it, so the lights are summed per+ // pixel instead of here. The program still lights the vertex, and past the fog factor it also+ // writes the camera space position and normal and the two halves of the lit colour that do+ // not depend on the normal, which ffshader reads to light the pixel again. An unlit one is the+ // terrain, whose pixel half (engineshader) reads only the position. Initialised here for a caller that fills the rest field by field.+ bool NormalMapped = false;};// Which profile the generated text is for. The two differ in the output semantic and in how thediff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cppindex 06beed171..044a95c63 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.cpp@@ -118,6 +118,8 @@ TextureBaseClass::TextureBaseClass: MipLevelCount(mip_level_count),D3DTexture(NULL),Initialized(false),+ NormalMap(NULL),+ NormalMapLooked(false),Name(""),FullPath(""),texture_id(unused_texture_id++),@@ -151,11 +153,12 @@ TextureBaseClass::~TextureBaseClass(void)delete ThumbnailLoadTask;ThumbnailLoadTask=NULL;- if (D3DTexture)+ if (D3DTexture){D3DTexture->Release();D3DTexture = NULL;}+ REF_PTR_RELEASE(NormalMap);DX8TextureManagerClass::Remove(this);}@@ -997,18 +1000,60 @@ void TextureClass::Apply(unsigned int stage)DX8_RECORD_TEXTURE(this);// Set texture itself- if (WW3D::Is_Texturing_Enabled())+ if (WW3D::Is_Texturing_Enabled()){DX8Wrapper::Set_DX8_Texture(stage, Peek_D3D_Base_Texture());}- else+ else{DX8Wrapper::Set_DX8_Texture(stage, NULL);}+ if (stage == 0 && Direct3D11_Normal_Maps_Active())+ {+ TextureClass * normal_map = Find_Normal_Map();+ Direct3D11_Mirror_Normal_Map(normal_map != NULL ? normal_map->Peek_D3D_Base_Texture() : NULL);+ }+Filter.Apply(stage);}+void TextureClass::Set_Normal_Map(TextureClass * normal_map)+{+ REF_PTR_SET(NormalMap, normal_map);+ NormalMapLooked = true;+}++TextureClass * TextureClass::Find_Normal_Map()+{+ static const char NORMAL_MAP_SUFFIX[] = "_nrm.dds";++ if (!NormalMapLooked)+ {+ NormalMapLooked = true;+ char name[_MAX_PATH];+ strncpy(name, Get_Texture_Name(), sizeof(name) - sizeof(NORMAL_MAP_SUFFIX));+ name[sizeof(name) - sizeof(NORMAL_MAP_SUFFIX)] = '\0';+ char * extension = strrchr(name, '.');+ if (extension != NULL)+ {+ *extension = '\0';+ }+ strcat(name, NORMAL_MAP_SUFFIX);++ file_auto_ptr file(_TheFileFactory, name);+ if (file->Is_Available())+ {+ NormalMap = WW3DAssetManager::Get_Instance()->Get_Texture(name);+ }+ }+ if (NormalMap != NULL && !NormalMap->Is_Initialized())+ {+ NormalMap->Init();+ }+ return NormalMap;+}+//**********************************************************************************************//! Get surface from mip level/*!diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.hindex e61255acb..26d17e4fd 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/texture.h@@ -213,6 +213,11 @@ protected:bool Initialized;+ // What TextureClass::Find_Normal_Map found, and whether it has looked. Here rather than on+ // TextureClass because this is the one constructor every texture goes through.+ TextureClass * NormalMap;+ bool NormalMapLooked;+// For debug purposes the texture sets this true if it is a lightmap texturebool IsLightmap;bool IsCompressionAllowed;@@ -343,8 +348,19 @@ public:virtual TextureClass* As_TextureClass() { return this; }+ // Hand a texture built in memory its normal map, for one with no file name to look+ // one up by - the terrain atlas.+ void Set_Normal_Map(TextureClass * normal_map);++ // What Set_Normal_Map or an earlier lookup found, without looking. For a caller that binds the+ // Direct3D texture itself and so never passes through Apply.+ TextureClass * Peek_Normal_Map() const { return NormalMap; }+protected:+ // "<name>_nrm.dds" through the file factory, looked for once and kept.+ TextureClass * Find_Normal_Map();+WW3DFormat TextureFormat;// legacydiff --git a/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp b/GeneralsMD/Code/Tests/test_ffvertexcompile.cppindex ea3780011..244473336 100644--- a/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp+++ b/GeneralsMD/Code/Tests/test_ffvertexcompile.cpp@@ -30,6 +30,7 @@#include "test_harness.h"+#include "ffshader.h"#include "ffvertex.h"#include <d3dcommon.h>@@ -209,3 +210,42 @@ TEST(ffvertexcompile_a_two_stage_program_compiles)CHECK(compiles(compile, nine, D3D9_PROFILE));CHECK(compiles(compile, eleven, D3D11_PROFILE));}++// Normal maps: a unit's draw, lit by the game's three directional lights, with both halves+// generated normal mapped. The pixel half uses ddx and ddy, which only a pixel profile has, and+// reads the four values the vertex half writes past the fog factor.+TEST(ffvertexcompile_a_normal_mapped_pair_compiles_on_d3d11)+{+ D3DCompileFunction compile = load_compiler();+ if (compile == NULL) {+ printf(" d3dcompiler_47.dll not present, skipping\n");+ return;+ }++ VertexPipelineDescription vertex = plain_description();+ vertex.LightingEnabled = true;+ vertex.LightCount = 3;+ for (unsigned index = 0; index < vertex.LightCount; ++index) {+ vertex.Lights[index].Type = D3DLIGHT_DIRECTIONAL;+ }+ vertex.NormalMapped = true;++ CombinerDescription pixel;+ memset(&pixel, 0, sizeof(pixel));+ pixel.StageCount = 1;+ pixel.Stages[0].ColourOperation = D3DTOP_MODULATE;+ pixel.Stages[0].ColourArgument1 = D3DTA_TEXTURE;+ pixel.Stages[0].ColourArgument2 = D3DTA_DIFFUSE;+ pixel.Stages[0].AlphaOperation = D3DTOP_SELECTARG1;+ pixel.Stages[0].AlphaArgument1 = D3DTA_TEXTURE;+ pixel.Stages[0].TextureBound = true;+ pixel.NormalMapped = true;++ std::string vertex_hlsl;+ std::string pixel_hlsl;+ CHECK(VertexShader_Generate(vertex, VERTEX_SHADER_TARGET_D3D11, vertex_hlsl));+ CHECK(CombinerShader_Generate(pixel, COMBINER_SHADER_TARGET_D3D11, pixel_hlsl));+ CHECK(compiles(compile, vertex_hlsl, D3D11_PROFILE));+ CHECK(compiles(compile, pixel_hlsl, "ps_4_0"));+ CHECK(!CombinerShader_Generate(pixel, COMBINER_SHADER_TARGET_D3D9, pixel_hlsl));+}