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
perf: defer d3d9 state, cache hud draw lists and terrain data
Olcay Seygana075d49f9bb7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cd6024b1b..df5a25f07 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -100,7 +100,7 @@ found and fixed — EA's own, not port damage.**- The command bar stopped throwing its own layout away every frame. The few hundred positions and sizes it hands its page were written into a fresh list each frame, copied twice for the frames in front of the buttons, and thrown out, and every price and build time on a button was looked up by copying the text of every figure the bar was already showing. The list is written over in place now, nothing is copied, and the graphics card settings that did not change between two draws are not looked up again. The same Twilight Flame match from a player's seat went from 2.29ms a frame to 1.96ms, and as an observer from 1.64ms to 1.58ms. The picture is the same one.- Raise the particle limit as far as you like and every puff gets drawn. Past about sixteen thousand smoke and fire sprites on screen the game quietly stopped drawing the rest: a test with 68,000 of them showed barely a fifth. A test with 101,000 now draws all of them at 8.3ms a frame, and in 1,200 frames not one fell below 60 a second. The first version that drew them all took 22.4ms; the rest came from sorting and copying them far less and from sharing the work across every core of the processor.- Big fights no longer drag the picture down into the twenties. Every moving tank and soldier, and every puff of smoke, goes to the graphics card through one shared scratch area, and it was so small that a big fight on Bombardment Beach filled it about fifty times a frame. Each refill made the processor wait for the card, 8 to 12ms of every frame, while the card sat two thirds idle. The area is made full size once now and refills about seven times a frame, in 0.02ms. The same 16,000-frame battle, fast-forwarded, finishes in 226 seconds where it took between 263 and 325, and the seconds that fell under 50 frames a second went from 125 or more to 4.-- Crowded battles run a few frames faster again. Six computer players on one map gain 2.4%, and thirty Inferno Cannons against twenty Crusaders gain 7.3% at 720p and 6.2% at 1080p. The game stopped re-sending lights and materials to the graphics card when nothing about them had changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened 16-bit textures with a lookup instead of arithmetic on each pixel. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build to within 0.06% of pixels in all eight test views, and a recorded match plays back to the same checksum.+- Crowded battles run a good deal faster. At 1080p, thirty Inferno Cannons against twenty Crusaders went from 153 to 217 frames a second, and six Brutal computer players on one map from 147 to 183. The slowest one frame in twenty got 17 to 18% shorter, and the slowest one in a hundred 15%. The game stopped re-sending lights, materials, textures and card settings that had not changed, stopped relighting the terrain when no light had moved, stopped adding up the glow of every fire particle twice, and widened 16-bit textures with a lookup instead of arithmetic on each pixel. The new renderer keeps the old one's settings back until something actually reads them, rebuilds a draw's constants only for the half that changed, and remembers each patch of ground's colours, its blend coordinates and its tread marks between frames. The command bar and the console replay what they drew last frame when nothing under them moved. The rules side runs 4% quicker too: locking, the lists of nearby units, the sleeping-unit schedule and text strings all got cheaper. The picture matches the old build in all eight test views on both renderers, and a recorded match plays back to the same checksum.- Every animation runs on a clock instead of counting frames.- Tanks and trucks move the same at any frame rate. Their treads scrolled a fixed step every picture, so at 120 frames a second they ran four times too fast, and a tank turning on the spot rolled both treads forward as if it were driving. Each tread now covers exactly the ground under it. In a tight turn the two run against each other, and backing up runs them backwards. Wheels spin with the distance driven the same way. The hull's springs used to settle four times too fast as well, and every start or stop threw the chassis to its full tilt in a single picture. Now a tank squats as it pulls away and dips its nose when it brakes, easing in over a tenth of a second and settling within half a second. In a corner it leans out, a Crusader up to two and a half degrees. The Humvee, which never moved on its springs at all, rocks too. A run drawing one picture per game tick and one drawing fourteen put every tank in the same pose, to the last digit, for as long as neither skipped a tick.- A scroll that starts after the camera has stood still no longer lurches. The first frame of the move was timed from the last time the camera moved, so after a few seconds of looking at one spot it was worth three frames of scrolling at once. The clock runs while the camera is still now, and the first frame moves one frame's worth.diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.hindex c2598028a..d299e12f6 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/HtmlOverlay.h@@ -39,8 +39,11 @@#include "Lib/BaseType.h"#include "Common/AsciiString.h"+#include "GameClient/HtmlTemplate.h"+#include <map>#include <string>+#include <utility>#include <vector>class HtmlOverlayContainer;@@ -55,6 +58,11 @@ public:/** Lay this page out, unless it is the page already laid out on a screen of the same size. */void setPage( const std::string &html );+ /** setPage( HtmlTemplate_expand( written, values, lists, lookup ) ), expanded again only when the+ * page, the values, the lists or an answer of the lookup's differ from the last call's. */+ void setPage( const std::string &written, const HtmlValues &values, const HtmlLists &lists,+ const HtmlLookup &lookup );+void draw( void );/** Lay the page out at ControlBarHudScale(), the bottom HUD's, rather than the uniform scale. */@@ -91,6 +99,11 @@ public:private:HtmlOverlayContainer *m_container;+ std::string m_written; ///< the last expand's inputs+ HtmlValues m_values;+ HtmlLists m_lists;+ std::map< std::string, std::pair< Bool, std::string > > m_asked; ///< every name it asked the lookup, and the answer+ std::string m_expanded; ///< and what it made of them};#endif // _HTML_OVERLAY_H_diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cppindex 80fdf0f81..2e24133b1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp@@ -552,7 +552,7 @@ void GameConsole::renderCheatPanel( void )std::vector< std::string > clicks;fillCheatPanelCells( lists[ "cells" ], clicks );- m_cheatOverlay->setPage( HtmlTemplate_expand( m_cheatPage, values, lists, lookupCheatPanelText ) );+ m_cheatOverlay->setPage( m_cheatPage, values, lists, lookupCheatPanelText );m_cheatOverlay->hover( TheMouse->getMouseStatus()->pos );m_cheatOverlay->draw();m_cheatPanelShown = TRUE;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cppindex c6b7b07b8..a620077b9 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/HtmlOverlay.cpp@@ -109,7 +109,7 @@ public:std::string tip( IRegion2D &rect );Int bottomOf( const char *selector );void rectsOf( const char *selector, std::vector< IRegion2D > &rects );- void setAlpha( Int alpha ) { m_alpha = alpha; }+ void setAlpha( Int alpha ) { m_drawnValid = m_drawnValid && alpha == m_alpha; m_alpha = alpha; }litehtml::uint_ptr create_font( const litehtml::font_description &description, const litehtml::document *document,litehtml::font_metrics *metrics ) override;@@ -170,6 +170,20 @@ private:};typedef std::vector< SvgRun > SvgRuns;+ /** One 2D call the last draw made: text when `string` is set, else a mapped image when `image`+ * names one, from x, y to width, height as its right and bottom, else a fill. */+ struct DrawnCall+ {+ DisplayString *string;+ AsciiString image;+ Int x;+ Int y;+ Int width;+ Int height;+ Color color;+ Color dropColor;+ };+/** A colour with its alpha scaled by the whole page's, setAlpha's. */Color tint( Int red, Int green, Int blue, Int alpha ) const { return GameMakeColor( red, green, blue, alpha * m_alpha / OPAQUE_ALPHA ); }Color tint( const litehtml::web_color &color ) const { return tint( color.red, color.green, color.blue, color.alpha ); }@@ -181,6 +195,10 @@ private:DisplayString *displayString( GameFont *font, const char *text );void freeStrings( Bool all );void fillBox( const litehtml::position &box, const litehtml::web_color &color );+ void fillRect( Int x, Int y, Int width, Int height, Color color );+ void record( const DrawnCall &call );+ void play( const DrawnCall &call );+ void changed( void );NSVGimage *svgImage( const std::string &source );const SvgRuns &svgRuns( const std::string &source, Int width, Int height );@@ -201,6 +219,13 @@ private:UnsignedInt m_stamp;std::string m_clicked;Int m_alpha; ///< the whole page's, OPAQUE_ALPHA unless it is fading+ std::vector< DrawnCall > m_drawn; ///< what the last draw of this layout made, in order+ Bool m_drawnValid; ///< and nothing it was drawn from has changed since+ ICoord2D m_hoverMouse;+ Bool m_hoverValid; ///< hover() at m_hoverMouse would find what it found last+ Bool m_hovered;+ std::map< std::string, std::vector< IRegion2D > > m_rects; ///< rectsOf() by selector, for this layout+ std::map< std::string, Int > m_bottoms; ///< bottomOf() by selector, for this layoutpublic:Bool m_hud; ///< laid out at ControlBarHudScale(), the bottom HUD's ownBool m_hudPage; ///< laid out at ControlBarHudPageScale(), the in-match HUD's other pages@@ -216,6 +241,9 @@ HtmlOverlayContainer::HtmlOverlayContainer( const AsciiString &defaultFont ) :m_screenHeight( 0 ),m_stamp( 0 ),m_alpha( OPAQUE_ALPHA ),+ m_drawnValid( FALSE ),+ m_hoverValid( FALSE ),+ m_hovered( FALSE ),m_hud( FALSE ),m_hudPage( FALSE ),m_screenPixels( FALSE )@@ -274,20 +302,81 @@ void HtmlOverlayContainer::setPage( const std::string &html )m_document = litehtml::document::createFromString( litehtml::estring( body, litehtml::encoding::utf_8 ), this, "", "",&m_masterCss, &m_pageCss );m_document->render( viewportWidth() );+ changed();}//-------------------------------------------------------------------------------------------------+/** The layout, the styles or what is under the pointer moved: what was drawn, hit and selected from+ * the page before is not what it would be now. */+void HtmlOverlayContainer::changed( void )+{+ m_drawnValid = FALSE;+ m_hoverValid = FALSE;+ m_rects.clear();+ m_bottoms.clear();+}++//-------------------------------------------------------------------------------------------------+/** Walking litehtml's tree to make the same 2D calls as the pass before was most of what a page cost+ * while nothing on it changed, at near two hundred passes a second; the calls are kept and made+ * again instead until the page is laid out, restyled, hovered onto something else or faded. */void HtmlOverlayContainer::draw( void ){if( !m_document )return;+ TheDisplay->beginBatch2D();+ if( m_drawnValid )+ {+ for( std::vector< DrawnCall >::const_iterator call = m_drawn.begin(); call != m_drawn.end(); ++call )+ play( *call );+ TheDisplay->endBatch2D();+ return;+ }++ m_drawn.clear();m_stamp++;const litehtml::position clip( 0, 0, viewportWidth(), viewportHeight() );- TheDisplay->beginBatch2D();m_document->draw( 0, 0, 0, &clip );TheDisplay->endBatch2D();freeStrings( FALSE );+ m_drawnValid = TRUE;+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::record( const DrawnCall &call )+{+ m_drawn.push_back( call );+ play( call );+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::play( const DrawnCall &call )+{+ if( call.string )+ call.string->draw( call.x, call.y, call.color, call.dropColor );+ else if( call.image.isEmpty() )+ TheDisplay->drawFillRect( call.x, call.y, call.width, call.height, call.color );+ else+ {+ const Image *image = TheMappedImageCollection->findImageByName( call.image );+ if( image )+ TheDisplay->drawImage( image, call.x, call.y, call.width, call.height, call.color );+ }+}++//-------------------------------------------------------------------------------------------------+void HtmlOverlayContainer::fillRect( Int x, Int y, Int width, Int height, Color color )+{+ DrawnCall call;+ call.string = NULL;+ call.x = x;+ call.y = y;+ call.width = width;+ call.height = height;+ call.color = color;+ call.dropColor = 0;+ record( call );}//-------------------------------------------------------------------------------------------------@@ -296,15 +385,28 @@ Bool HtmlOverlayContainer::hover( const ICoord2D &mouse )if( !m_document )return FALSE;+ // a pointer that has not moved over a page that has not changed is over what it was over: the+ // same point in the same layout finds the same element, already hovered+ if( m_hoverValid && mouse.x == m_hoverMouse.x && mouse.y == m_hoverMouse.y )+ return m_hovered;+litehtml::position::vector redraw;const litehtml::pixel_t x = page( mouse.x );const litehtml::pixel_t y = page( mouse.y );- if( m_document->on_mouse_over( x, y, x, y, redraw ) )+ const std::shared_ptr< const litehtml::element > was = m_document->get_over_element();+ const Bool restyled = m_document->on_mouse_over( x, y, x, y, redraw );+ if( restyled )m_document->render( viewportWidth() );+ if( restyled || m_document->get_over_element() != was )+ changed();// the root and the body span the whole screen; only what is drawn on them is the page'sstd::shared_ptr< const litehtml::element > over = m_document->get_over_element();- return over && over->parent() && !over->is_body();+ m_hovered = over && over->parent() && !over->is_body();+ m_hoverMouse = mouse;+ // laid out again, the page may have put something else under the same point+ m_hoverValid = !restyled;+ return m_hovered;}//-------------------------------------------------------------------------------------------------@@ -319,6 +421,7 @@ std::string HtmlOverlayContainer::click( const ICoord2D &mouse )const litehtml::pixel_t y = page( mouse.y );m_document->on_lbutton_down( x, y, x, y, redraw );m_document->on_lbutton_up( x, y, x, y, redraw );+ changed();return m_clicked;}@@ -351,20 +454,37 @@ Int HtmlOverlayContainer::bottomOf( const char *selector )if( !m_document )return 0;+ std::map< std::string, Int >::iterator found = m_bottoms.find( selector );+ if( found != m_bottoms.end() )+ return found->second;++ Int &bottom = m_bottoms[ selector ];+ bottom = 0;litehtml::element::ptr element = m_document->root()->select_one( selector );- if( !element )- return 0;- const litehtml::position placement = element->get_placement();- return screen( placement.y + placement.height );+ if( element )+ {+ const litehtml::position placement = element->get_placement();+ bottom = screen( placement.y + placement.height );+ }+ return bottom;}//-------------------------------------------------------------------------------------------------+/** Matched once for each layout: the command bar asked for its keys and solids every pass, and+ * matching a selector against every element of the page was its own share of the frame. */void HtmlOverlayContainer::rectsOf( const char *selector, std::vector< IRegion2D > &rects ){rects.clear();if( !m_document )return;+ std::map< std::string, std::vector< IRegion2D > >::iterator found = m_rects.find( selector );+ if( found != m_rects.end() )+ {+ rects = found->second;+ return;+ }+const litehtml::elements_list elements = m_document->root()->select_all( selector );for( litehtml::elements_list::const_iterator element = elements.begin(); element != elements.end(); ++element ){@@ -379,6 +499,7 @@ void HtmlOverlayContainer::rectsOf( const char *selector, std::vector< IRegion2Drect.hi.y = screen( placement.y + placement.height );rects.push_back( rect );}+ m_rects[ selector ] = rects;}//-------------------------------------------------------------------------------------------------@@ -473,8 +594,14 @@ void HtmlOverlayContainer::draw_text( litehtml::uint_ptr hdc, const char *text,if( font == 0 || color.alpha == 0 )return;- displayString( (GameFont *)font, text )->draw( screen( place.x ), screen( place.y ), tint( color ),- tint( 0, 0, 0, color.alpha ) );+ DrawnCall call;+ call.string = displayString( (GameFont *)font, text );+ call.x = screen( place.x );+ call.y = screen( place.y );+ call.width = call.height = 0;+ call.color = tint( color );+ call.dropColor = tint( 0, 0, 0, color.alpha );+ record( call );}//-------------------------------------------------------------------------------------------------@@ -514,14 +641,25 @@ void HtmlOverlayContainer::draw_image( litehtml::uint_ptr hdc, const litehtml::b{UnsignedByte red, green, blue, alpha;GameGetColorComponents( run->color, &red, &green, &blue, &alpha );- TheDisplay->drawFillRect( left + run->x, top + run->y, run->length, 1, tint( red, green, blue, alpha ) );+ fillRect( left + run->x, top + run->y, run->length, 1, tint( red, green, blue, alpha ) );}return;}- const Image *image = TheMappedImageCollection->findImageByName( AsciiString( url.c_str() ) );- if( image )- TheDisplay->drawImage( image, left, top, right, bottom, tint( OPAQUE_ALPHA, OPAQUE_ALPHA, OPAQUE_ALPHA, OPAQUE_ALPHA ) );+ // kept by name and found again on every replay, as it was on every draw: a name the collection+ // gives a new image draws the new one. No name names no image, and would replay as a fill+ if( url.empty() )+ return;+ DrawnCall call;+ call.string = NULL;+ call.image = url.c_str();+ call.x = left;+ call.y = top;+ call.width = right;+ call.height = bottom;+ call.color = tint( OPAQUE_ALPHA, OPAQUE_ALPHA, OPAQUE_ALPHA, OPAQUE_ALPHA );+ call.dropColor = 0;+ record( call );}//-------------------------------------------------------------------------------------------------@@ -604,7 +742,7 @@ void HtmlOverlayContainer::fillBox( const litehtml::position &box, const litehtmconst Int right = screen( box.x + box.width );const Int bottom = screen( box.y + box.height );if( color.alpha > 0 && right > left && bottom > top )- TheDisplay->drawFillRect( left, top, right - left, bottom - top, tint( color ) );+ fillRect( left, top, right - left, bottom - top, tint( color ) );}//-------------------------------------------------------------------------------------------------@@ -663,9 +801,9 @@ void HtmlOverlayContainer::draw_linear_gradient( litehtml::uint_ptr hdc, const lREAL_TO_INT( from.blue + ( to.blue - from.blue ) * share ),REAL_TO_INT( from.alpha + ( to.alpha - from.alpha ) * share ) );if( across )- TheDisplay->drawFillRect( pixel, top, 1, bottom - top, color );+ fillRect( pixel, top, 1, bottom - top, color );else- TheDisplay->drawFillRect( left, pixel, right - left, 1, color );+ fillRect( left, pixel, right - left, 1, color );}}@@ -739,8 +877,7 @@ void HtmlOverlayContainer::draw_borders( litehtml::uint_ptr hdc, const litehtml:{const IRegion2D &edge = edges[ side ];if( sides[ side ]->color.alpha > 0 && edge.hi.x > edge.lo.x && edge.hi.y > edge.lo.y )- TheDisplay->drawFillRect( edge.lo.x, edge.lo.y, edge.hi.x - edge.lo.x, edge.hi.y - edge.lo.y,- tint( sides[ side ]->color ) );+ fillRect( edge.lo.x, edge.lo.y, edge.hi.x - edge.lo.x, edge.hi.y - edge.lo.y, tint( sides[ side ]->color ) );}}@@ -814,6 +951,40 @@ HtmlOverlay::~HtmlOverlay( void )}void HtmlOverlay::setPage( const std::string &html ) { m_container->setPage( html ); }++//-------------------------------------------------------------------------------------------------+/** The expanded page is made of the written page, the values, the lists and what the lookup answered+ * for the names neither held, nothing else; all of them the same as last time is the same page, and+ * filling 38 KB of command bar in again every pass to find that out was a share of the frame. */+void HtmlOverlay::setPage( const std::string &written, const HtmlValues &values, const HtmlLists &lists,+ const HtmlLookup &lookup )+{+ Bool same = written == m_written && values == m_values && lists == m_lists;+ std::string answer;+ for( std::map< std::string, std::pair< Bool, std::string > >::const_iterator asked = m_asked.begin();+ same && asked != m_asked.end(); ++asked )+ {+ answer.clear();+ const Bool known = lookup && lookup( asked->first, answer );+ same = known == asked->second.first && ( !known || answer == asked->second.second );+ }++ if( !same )+ {+ m_asked.clear();+ const HtmlLookup asking = [ this, &lookup ]( const std::string &name, std::string &value ) -> Bool+ {+ const Bool known = lookup && lookup( name, value );+ m_asked[ name ] = std::make_pair( known, known ? value : std::string() );+ return known;+ };+ m_expanded = HtmlTemplate_expand( written, values, lists, asking );+ m_written = written;+ m_values = values;+ m_lists = lists;+ }+ m_container->setPage( m_expanded );+}void HtmlOverlay::draw( void ) { m_container->draw(); }void HtmlOverlay::setHud( Bool hud ) { m_container->m_hud = hud; }void HtmlOverlay::setHudPage( Bool hudPage ) { m_container->m_hudPage = hudPage; }diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex fee023e27..8dd1cae7e 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -1934,13 +1934,30 @@ static Bool stripSwitchedOff( Bool GlobalData::* flag )}//-------------------------------------------------------------------------------------------------+/** Labels the string table had, by {{text:Label}} name, already turned into UTF-8. The game's own+ * table is read once at startup and searched before the map's, so a label found there answers the+ * same all session; one only the map's map.str has answers the same until reset() at the match's+ * end, the resetAll that also drops the map's table. A missing label is asked again every time.+ * ponytail: map.str reloaded mid-match (the map cache's scan) would leave a map-only label stale;+ * no page asks for one. */+static std::map< std::string, std::string > s_gameTexts;+/** {{text:Label}}: a string table label, in the player's language. *///-------------------------------------------------------------------------------------------------static Bool lookupGameText( const std::string &name, std::string &value ){if( name.compare( 0, TEXT_LOOKUP.size(), TEXT_LOOKUP ) != 0 )return FALSE;- value = WideCharStringToMultiByte( TheGameText->fetch( name.substr( TEXT_LOOKUP.size() ).c_str() ).str() );+ std::map< std::string, std::string >::const_iterator found = s_gameTexts.find( name );+ if( found != s_gameTexts.end() )+ {+ value = found->second;+ return TRUE;+ }+ Bool exists = FALSE;+ value = WideCharStringToMultiByte( TheGameText->fetch( name.substr( TEXT_LOOKUP.size() ).c_str(), &exists ).str() );+ if( exists )+ s_gameTexts[ name ] = value;return TRUE;}@@ -2575,7 +2592,7 @@ void InGameUI::drawSpectatorPage( void )for( std::set< std::string >::const_iterator name = m_spectatorFlipped.begin(); name != m_spectatorFlipped.end(); ++name )values[ FLIP_ACTION + *name ] = "flipped";- m_spectatorOverlay->setPage( HtmlTemplate_expand( m_spectatorPage, values, m_spectatorLists, lookupGameText ) );+ m_spectatorOverlay->setPage( m_spectatorPage, values, m_spectatorLists, lookupGameText );m_spectatorOverlay->hover( TheMouse->getMouseStatus()->pos );m_spectatorOverlay->draw();m_spectatorPageShown = TRUE;@@ -4145,6 +4162,7 @@ void InGameUI::reset( void )m_scoreboardOpen = FALSE;m_scoreboardPageLoaded = FALSE;m_scoreboardHtml.clear();+ s_gameTexts.clear(); // the map's string table goes with the mapm_earnedReadingCount = 0; // a new match and a loaded save both come through herem_controlBarPageLoaded = FALSE;m_netPageLoaded = FALSE;@@ -4527,7 +4545,7 @@ void InGameUI::drawAlertPage( void )values[ "top" ] = std::to_string( REAL_TO_INT_FLOOR( m_topBarBottom / scale + 0.5f ) + ALERT_GAP );values[ "whose" ] = alert.whose;values[ "text" ] = alert.text;- m_alertOverlay->setPage( HtmlTemplate_expand( m_alertPage, values, HtmlLists(), lookupGameText ) );+ m_alertOverlay->setPage( m_alertPage, values, HtmlLists(), lookupGameText );const UnsignedInt left = alertHoldMs( m_alerts.size() - 1 ) - ( nowMs - m_alertStartMs );m_alertOverlay->setAlpha( left < ALERT_FADE_MS ? (Int)( ALERT_OPAQUE * left / ALERT_FADE_MS ) : ALERT_OPAQUE );@@ -4675,7 +4693,7 @@ void InGameUI::drawFeed( void )HtmlValues values;values[ "top" ] = std::to_string( REAL_TO_INT_FLOOR( feedTop() / ControlBarHudPageScale() ) );- m_feedOverlay->setPage( HtmlTemplate_expand( m_feedPage, values, lists, lookupGameText ) );+ m_feedOverlay->setPage( m_feedPage, values, lists, lookupGameText );m_feedOverlay->draw();}@@ -4768,7 +4786,7 @@ void InGameUI::drawChat( void )values[ "typed" ] = WideCharStringToMultiByte( typed.str() );values[ "caret" ] = frame / CHAT_CARET_FRAMES % 2 == 0 ? "lit" : "";values[ "audience" ] = WideCharStringToMultiByte( audience.str() );- m_chatOverlay->setPage( HtmlTemplate_expand( m_chatPage, values, lists, lookupGameText ) );+ m_chatOverlay->setPage( m_chatPage, values, lists, lookupGameText );m_chatOverlay->setAlpha( open ? OPAQUE_PAGE : min( (Int)OPAQUE_PAGE, (Int)( newestUntil - frame ) * OPAQUE_PAGE / CHAT_FADE_FRAMES ) );m_chatOverlay->draw();}@@ -12131,7 +12149,7 @@ void InGameUI::drawNetPage( void )// into the readings themselves rather than a copy of them made every frame; nothing else reads// them, and the next sample clears themm_hudValues[ "side" ] = spectatorSide();- m_netOverlay->setPage( HtmlTemplate_expand( m_netPage, m_hudValues, HtmlLists(), lookupGameText ) );+ m_netOverlay->setPage( m_netPage, m_hudValues, HtmlLists(), lookupGameText );m_netOverlay->draw();}@@ -12154,7 +12172,7 @@ void InGameUI::drawReadoutPage( const HtmlValues &values )m_readoutOverlay->setHud( TRUE );}- m_readoutOverlay->setPage( HtmlTemplate_expand( m_readoutPage, values, HtmlLists(), lookupGameText ) );+ m_readoutOverlay->setPage( m_readoutPage, values, HtmlLists(), lookupGameText );m_readoutOverlay->draw();}@@ -12202,7 +12220,7 @@ void InGameUI::drawCellGridFront( Int grid )// lent to the page and taken back, rather than copied every framestd::vector< HtmlValues > &frontCells = lists[ "frontcells" ];frontCells.swap( m_cellFrontCells[ grid ] );- overlay->setPage( HtmlTemplate_expand( m_controlBarPage, values, lists, lookupGameText ) );+ overlay->setPage( m_controlBarPage, values, lists, lookupGameText );frontCells.swap( m_cellFrontCells[ grid ] );overlay->draw();}@@ -12684,7 +12702,7 @@ Bool InGameUI::drawControlBarPage( const IRegion2D *panels, const Bool *shown, Iif( !m_promotionPage.empty() )standDownPromotionScreen();- m_controlBarOverlay->setPage( HtmlTemplate_expand( m_controlBarPage, values, lists, lookupGameText ) );+ m_controlBarOverlay->setPage( m_controlBarPage, values, lists, lookupGameText );// swapped rather than copied: the front windows get this frame's cells, and the lists get the// front windows' old ones to write the next frame overm_cellFrontCells[ CELL_GRID_COMMAND ].swap( commandCells );@@ -13090,7 +13108,7 @@ void InGameUI::drawPromotionPage( GameWindow *parent, Bool front )headings.push_back( entry );}- overlay->setPage( HtmlTemplate_expand( m_promotionPage, values, lists, lookupGameText ) );+ overlay->setPage( m_promotionPage, values, lists, lookupGameText );overlay->hover( TheMouse->getMouseStatus()->pos );overlay->draw();}@@ -13280,7 +13298,7 @@ void InGameUI::drawQuitMenuPage( GameWindow *parent )keys.push_back( entry );}- m_quitMenuOverlay->setPage( HtmlTemplate_expand( m_quitMenuPage, values, lists, lookupGameText ) );+ m_quitMenuOverlay->setPage( m_quitMenuPage, values, lists, lookupGameText );m_quitMenuOverlay->setAlpha( pageAlpha );m_quitMenuOverlay->draw();@@ -13290,7 +13308,7 @@ void InGameUI::drawQuitMenuPage( GameWindow *parent )if( m_quitMenuKeyOverlays.size() <= each )m_quitMenuKeyOverlays.push_back( new HtmlOverlay( m_superweaponNormalFont ) );keys.assign( 1, fading[ each ].entry );- m_quitMenuKeyOverlays[ each ]->setPage( HtmlTemplate_expand( m_quitMenuPage, values, lists, lookupGameText ) );+ m_quitMenuKeyOverlays[ each ]->setPage( m_quitMenuPage, values, lists, lookupGameText );m_quitMenuKeyOverlays[ each ]->setAlpha( fading[ each ].alpha );m_quitMenuKeyOverlays[ each ]->draw();}@@ -13667,7 +13685,7 @@ void InGameUI::drawQueueTray( void )m_queueFrontOverlay->setHud( TRUE );}values[ "layer" ] = "back";- m_queueOverlay->setPage( HtmlTemplate_expand( m_queuePage, values, lists, lookupGameText ) );+ m_queueOverlay->setPage( m_queuePage, values, lists, lookupGameText );m_queueOverlay->draw();TheDisplay->beginBatch2D();@@ -13675,7 +13693,7 @@ void InGameUI::drawQueueTray( void )TheDisplay->endBatch2D();values[ "layer" ] = "front";- m_queueFrontOverlay->setPage( HtmlTemplate_expand( m_queuePage, values, lists, lookupGameText ) );+ m_queueFrontOverlay->setPage( m_queuePage, values, lists, lookupGameText );m_queueFrontOverlay->draw();}@@ -13878,7 +13896,7 @@ void InGameUI::drawSuperweaponStrip( void )m_superweaponOverlay = new HtmlOverlay( m_superweaponNormalFont );m_superweaponOverlay->setScreenPixels( TRUE );}- m_superweaponOverlay->setPage( HtmlTemplate_expand( m_queuePage, values, lists, lookupGameText ) );+ m_superweaponOverlay->setPage( m_queuePage, values, lists, lookupGameText );m_superweaponOverlay->draw();// a cameo has no frame drawn over its edge, so a readout's plate stands in its very corner: the@@ -15076,7 +15094,7 @@ Bool InGameUI::drawTooltipPage( const UnicodeString &cursorText, const RGBColorbox.hi.x = box.lo.x + m_tooltipSize.x;box.hi.y = box.lo.y + m_tooltipSize.y;putPageRect( values, "box", box, TRUE, ControlBarHudPageScale() );- m_tooltipOverlay->setPage( HtmlTemplate_expand( m_tooltipPage, values, lists, lookupGameText ) );+ m_tooltipOverlay->setPage( m_tooltipPage, values, lists, lookupGameText );std::vector< IRegion2D > laidOut;m_tooltipOverlay->rectsOf( "#box", laidOut );diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.hindex d6d5457b1..bf9d0ebc2 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/BaseHeightMap.h@@ -297,6 +297,29 @@ protected:// STL is "smart." This is a variable sized bitset. Very memory efficient.std::vector<bool> m_showAsVisibleCliff;+ /** getStaticDiffuse's answer per height sample. The 3-way blend pass asks for four of them per+ visible tile on every render pass, and the answer only moves with the five heights it reads+ (kept here as the key) and with the lights, whose every input sits in m_staticDiffuseInputs+ as raw bits; a change there bumps m_staticDiffuseGeneration and so retires every cell.+ The inputs are walked once a render frame, on every 3-way pass, and again after anything+ that says the lighting moved (m_staticDiffuseStale), not on every call. */+ struct StaticDiffuseCell+ {+ Int diffuse;+ UnsignedShort generation; ///< 0 is never valid+ UnsignedByte heights[5]; ///< centre, left, right, below, above+ };+ std::vector<StaticDiffuseCell> m_staticDiffuseCells;+ std::vector<UnsignedInt> m_staticDiffuseInputs;+ UnsignedShort m_staticDiffuseGeneration;+ Bool m_staticDiffuseStale; ///< lighting or map changed since the last walk+ UnsignedInt m_staticDiffuseFrame; ///< WW3D frame of the last walk+ void refreshStaticDiffuseInputs(void);++ /// Bumped by anything that can change what the ground draws: heights, lighting, the 3-way tile+ /// list. A cache of terrain vertices that saw the same value has nothing to rebuild.+ Int m_terrainContentVersion;+ShaderClass m_shaderClass; ///<shader or rendering state for heightmapVertexMaterialClass *m_vertexMaterialClass; ///< vertex shader (lighting) for terraindiff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.hindex 5216cf6ab..82ec4cf5b 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/HeightMap.h@@ -100,6 +100,19 @@ protected:Int m_numExtraBlendTiles; ///<number of blend tiles in m_extraBlendTilePositions.Int m_numVisibleExtraBlendTiles; ///<number rendered last frame.Int m_extraBlendTilePositionsSize; //<total size of array including unused memory.++ /** The 3-way tiles' vertices, kept from one pass to the next. They used to be rebuilt into the+ shared dynamic buffer on every pass, and they only change with what m_extraBlendKey holds:+ the terrain's content version, the drawn rectangle, the buffer's capacity, the map and how+ its tiles sit in the terrain texture. */+ enum { EXTRA_BLEND_KEY_SIZE = 8 };+ DX8VertexBufferClass *m_extraBlendVB;+ DX8IndexBufferClass *m_extraBlendIB;+ Int m_extraBlendCapacity; ///< tiles the two buffers hold+ WorldHeightMap *m_extraBlendMap; ///< map the buffers were filled from; NULL means refill+ Int m_extraBlendKey[EXTRA_BLEND_KEY_SIZE];+ Int m_extraBlendVertexCount;+ Int m_extraBlendIndexCount;DX8VertexBufferClass **m_vertexBufferTiles; ///<collection of smaller vertex buffers that make up 1 heightmapchar **m_vertexBufferBackup; ///< In memory copy of the vertex buffer data for quick update of dynamic lighting.Int m_originX; ///< Origin point in the grid. Slides around.diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.hindex 8bb6ae30c..574dc8ae7 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/WorldHeightMap.h@@ -171,6 +171,24 @@ protected:/// Tiles that hold the alpha channel info.static TileData *m_alphaTiles[NUM_ALPHA_TILES];+ /** getExtraAlphaUVData's answer per blend tile, because the terrain asks again for every visible+ 3-way tile on every render pass. The answer depends on the blend tile, the cell's cliff info+ and where the tiles sit in the terrain texture; the first two are the key, and the last is+ m_extraBlendUVGeneration, bumped whenever the texture is laid out again. */+ struct ExtraBlendUV+ {+ Real U[4];+ Real V[4];+ UnsignedByte alpha[4];+ Bool flip;+ Bool cliff;+ Short cliffInfoNdx;+ Bool adjustCliff;+ Int generation; ///< 0 is never valid+ };+ std::vector<ExtraBlendUV> m_extraBlendUV; ///< indexed by blend tile, allocated on first use+ Int m_extraBlendUVGeneration;+protected:TileData *getSourceTile(UnsignedInt ndx) { if (ndx<NUM_SOURCE_TILES) return(m_sourceTiles[ndx]); return(NULL); };@@ -235,6 +253,7 @@ public: // tile and texture info.Bool getUVData(Int xIndex, Int yIndex, float U[4], float V[4], Bool fullTile);Bool getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *flip, Bool *cliff);+ Int getExtraBlendUVGeneration(void) const { return m_extraBlendUVGeneration; } ///< changes when getExtraAlphaUVData's answers can/// UV mapping data for a cell to map into the alpha terrain texture.void getAlphaUVData(Int xIndex, Int yIndex, float U[4], float V[4], UnsignedByte alpha[4], Bool *flip, Bool fullTile);void getTerrainColorAt(Real x, Real y, RGBColor *pColor);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cppindex 0ccb205e5..3933184f4 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/BaseHeightMap.cpp@@ -88,6 +88,7 @@#include "WW3D2/dx8wrapper.h"#include "WW3D2/light.h"#include "WW3D2/scene.h"+#include "WW3D2/ww3d.h"#include "W3DDevice/GameClient/W3DPoly.h"#include "W3DDevice/GameClient/W3DCustomScene.h"@@ -291,6 +292,10 @@ BaseHeightMapRenderObjClass::BaseHeightMapRenderObjClass(void)m_depthFade.Y = 0.0f;m_depthFade.Z = 0.0f;m_useDepthFade = false;+ m_staticDiffuseGeneration = 1;+ m_staticDiffuseStale = true;+ m_staticDiffuseFrame = 0;+ m_terrainContentVersion = 0;m_disableTextures = false;TheTerrainRenderObject = this;m_treeBuffer = NULL;@@ -1474,6 +1479,8 @@ Int BaseHeightMapRenderObjClass::initHeightData(Int x, Int y, WorldHeightMap *pM{REF_PTR_SET(m_map, pMap); //update our heightmap pointer in case it changed since last call.+ m_staticDiffuseStale = true;+ m_terrainContentVersion++;if (m_shroud)m_shroud->init(m_map,TheGlobalData->m_partitionCellSize,TheGlobalData->m_partitionCellSize);@@ -1590,7 +1597,9 @@ void BaseHeightMapRenderObjClass::allocateScorchBuffers(void)//=============================================================================void BaseHeightMapRenderObjClass::updateScorches(void){- if (m_scorchesInBuffer > 1) {+ // Built already. This read "> 1", so a map with exactly one scorch rebuilt it on every render+ // pass, through two whole-buffer locks: 900 KB copied twice to draw one crater.+ if (m_scorchesInBuffer > 0) {return;}if (m_numScorches==0) {@@ -1844,6 +1853,15 @@ Int BaseHeightMapRenderObjClass::getStaticDiffuse(Int x, Int y)if (up1 >= m_map->getXExtent())up1=m_map->getXExtent()-1;+ const UnsignedByte heights[5] = { m_map->getHeight(x, y), m_map->getHeight(un0, y),+ m_map->getHeight(up1, y), m_map->getHeight(x, vn0), m_map->getHeight(x, vp1) };+ if (m_staticDiffuseStale || m_staticDiffuseFrame != WW3D::Get_Frame_Count() ||+ m_staticDiffuseCells.size() != (size_t)m_map->getXExtent()*m_map->getYExtent())+ refreshStaticDiffuseInputs();+ StaticDiffuseCell &cell = m_staticDiffuseCells[y*m_map->getXExtent() + x];+ if (cell.generation == m_staticDiffuseGeneration && memcmp(cell.heights, heights, sizeof(heights)) == 0)+ return cell.diffuse;+Vector3 lightRay[MAX_GLOBAL_LIGHTS];const Coord3D *lightPos;@@ -1854,16 +1872,16 @@ Int BaseHeightMapRenderObjClass::getStaticDiffuse(Int x, Int y)}//top-left sample- l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(m_map->getHeight(up1, y) - m_map->getHeight(un0, y)));- n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(m_map->getHeight(x, vp1) - m_map->getHeight(x, vn0)));-+ l2r.Set(2*MAP_XY_FACTOR,0,MAP_HEIGHT_SCALE*(heights[2] - heights[1]));+ n2f.Set(0,2*MAP_XY_FACTOR,MAP_HEIGHT_SCALE*(heights[4] - heights[3]));+Vector3::Normalized_Cross_Product(l2r,n2f, &normalAtTexel);VERTEX_FORMAT vertex;vertex.x=ADJUST_FROM_INDEX_TO_REAL(x);vertex.y=ADJUST_FROM_INDEX_TO_REAL(y);- vertex.z= ((float)m_map->getHeight(x,y))*MAP_HEIGHT_SCALE;+ vertex.z= ((float)heights[0])*MAP_HEIGHT_SCALE;vertex.u1=0;vertex.v1=0;vertex.u2=1;@@ -1878,9 +1896,101 @@ Int BaseHeightMapRenderObjClass::getStaticDiffuse(Int x, Int y)} else {doTheLight(&vertex, lightRay, &normalAtTexel, NULL, 1.0f);}+ cell.diffuse = vertex.diffuse;+ cell.generation = m_staticDiffuseGeneration;+ memcpy(cell.heights, heights, sizeof(heights));return vertex.diffuse;}+//=============================================================================+// BaseHeightMapRenderObjClass::refreshStaticDiffuseInputs+//=============================================================================+/** Walks everything getStaticDiffuse reads apart from the heights, as raw 32-bit words, against+the copy taken when the cached cells were filled. The first word that differs turns the rest of+the walk into the new copy and retires every cell. Bits rather than values, because equal bits+in are what guarantee an equal answer out. getStaticDiffuse walks it once a render frame, and the+3-way pass at its start; the frame count alone is not enough, because a map loading changes the+lighting while no frame is drawn (the time of day is set after the roads have asked for theirs),+so staticLightingChanged, initHeightData and Notify_Added mark it stale as well. */+//=============================================================================+namespace+{+ struct StaticDiffuseInputWalk+ {+ std::vector<UnsignedInt> &row;+ size_t pos;+ Bool changed;++ StaticDiffuseInputWalk(std::vector<UnsignedInt> &r) : row(r), pos(0), changed(false) {}++ void bits(const void *p, size_t bytes) // bytes is a multiple of four+ {+ for (size_t i = 0; i < bytes; i += sizeof(UnsignedInt)) {+ UnsignedInt word;+ memcpy(&word, (const unsigned char *)p + i, sizeof(word));+ if (!changed && pos < row.size() && row[pos] == word) {+ ++pos;+ continue;+ }+ if (!changed) {+ row.resize(pos);+ changed = true;+ }+ row.push_back(word);+ ++pos;+ }+ }+ };+}++void BaseHeightMapRenderObjClass::refreshStaticDiffuseInputs(void)+{+ StaticDiffuseInputWalk walk(m_staticDiffuseInputs);++ const Int numLights = TheGlobalData->m_numGlobalLights;+ const Int useDepthFade = m_useDepthFade;+ const Int shape[4] = { m_map->getXExtent(), m_map->getYExtent(), m_map->getBorderSizeInline(), numLights };+ walk.bits(shape, sizeof(shape));+ walk.bits(TheGlobalData->m_terrainLightPos, numLights*sizeof(Coord3D));+ walk.bits(TheGlobalData->m_terrainDiffuse, numLights*sizeof(RGBColor));+ walk.bits(&TheGlobalData->m_terrainAmbient[0], sizeof(RGBColor));+ walk.bits(&TheGlobalData->m_waterPositionZ, sizeof(Real));+ walk.bits(&useDepthFade, sizeof(useDepthFade));+ walk.bits(&m_depthFade, sizeof(m_depthFade));+ walk.bits(&Scene, sizeof(Scene));+ if (Scene) {+ // the same list, in the same order, that doTheLight walks+ RefRenderObjListIterator it(((RTS3DScene *)Scene)->getLightList());+ for (it.First(); !it.Is_Done(); it.Next()) {+ LightClass *pLight = (LightClass*)it.Peek_Obj();+ const Int type = pLight->Get_Type();+ double range[2];+ Vector3 diffuse, ambient;+ pLight->Get_Far_Attenuation_Range(range[0], range[1]);+ pLight->Get_Diffuse(&diffuse);+ pLight->Get_Ambient(&ambient);+ walk.bits(&type, sizeof(type));+ walk.bits(&pLight->Get_Transform(), sizeof(Matrix3D));+ walk.bits(range, sizeof(range));+ walk.bits(&diffuse, sizeof(diffuse));+ walk.bits(&ambient, sizeof(ambient));+ }+ }++ m_staticDiffuseStale = false;+ m_staticDiffuseFrame = WW3D::Get_Frame_Count();+ if (!walk.changed && walk.pos == m_staticDiffuseInputs.size())+ return;++ m_terrainContentVersion++;+ m_staticDiffuseInputs.resize(walk.pos);+ const size_t cells = (size_t)shape[0]*shape[1];+ if (++m_staticDiffuseGeneration == 0 || m_staticDiffuseCells.size() != cells) {+ m_staticDiffuseCells.assign(cells, StaticDiffuseCell());+ m_staticDiffuseGeneration = 1;+ }+}+//=============================================================================// BaseHeightMapRenderObjClass::On_Frame_Update//=============================================================================@@ -2116,6 +2226,8 @@ void BaseHeightMapRenderObjClass::staticLightingChanged( void ){// Cause the terrain to get updated with new lighting.m_needFullUpdate = true;+ m_staticDiffuseStale = true; // before the roads below ask for theirs+ m_terrainContentVersion++;// Cause the scorches to get updated with new lighting.m_scorchesInBuffer = 0; // If we just allocated the buffers, we got no scorches in the buffer.@@ -2137,6 +2249,7 @@ void BaseHeightMapRenderObjClass::terrainHeightChanged( Int x, Int y )/* One cell either side. A vertex's lighting and normal are computed from its neighbours, sorebuilding only the cell that moved leaves a seam of stale shading around it. */const Int PAD = 2;+ m_terrainContentVersion++;if (!m_hasDirtyRegion){m_dirtyRegion.lo.x = x - PAD;@@ -2222,6 +2335,7 @@ void BaseHeightMapRenderObjClass::Notify_Added(SceneClass * scene){RenderObjClass::Notify_Added(scene);scene->Register(this,SceneClass::ON_FRAME_UPDATE);+ m_staticDiffuseStale = true; // getStaticDiffuse lights through this scene's lights now}//=============================================================================diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cppindex 5ffba22e4..1ce7b4c0e 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/HeightMap.cpp@@ -142,6 +142,10 @@ inline Int IABS(Int x) { if (x>=0) return x; return -x;};void HeightMapRenderObjClass::freeIndexVertexBuffers(void){REF_PTR_RELEASE(m_indexBuffer);+ REF_PTR_RELEASE(m_extraBlendVB);+ REF_PTR_RELEASE(m_extraBlendIB);+ m_extraBlendCapacity = 0;+ m_extraBlendMap = NULL;if (m_vertexBufferTiles) {for (int i=0; i<m_numVertexBufferTiles; i++)REF_PTR_RELEASE(m_vertexBufferTiles[i]);@@ -945,6 +949,7 @@ void HeightMapRenderObjClass::doPartialUpdate(const IRegion2D &partialRange, Wor//over the same tile and require an extra render pass.Int i, j;+ m_terrainContentVersion++; // the 3-way list below changes//First remove any existing extra blend tiles within this partial regionfor (j=0; j<m_numExtraBlendTiles; j++){ Int x = m_extraBlendTilePositions[j] & 0xffff;@@ -1071,6 +1076,12 @@ m_extraBlendTilePositions(NULL),m_numExtraBlendTiles(0),m_numVisibleExtraBlendTiles(0),m_extraBlendTilePositionsSize(0),+m_extraBlendVB(NULL),+m_extraBlendIB(NULL),+m_extraBlendCapacity(0),+m_extraBlendMap(NULL),+m_extraBlendVertexCount(0),+m_extraBlendIndexCount(0),m_vertexBufferTiles(NULL),m_vertexBufferBackup(NULL),m_originX(0),@@ -2282,29 +2293,43 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void)if (maxBlendTiles > 10000) //we can only fit about 10000 tiles into a single VB.maxBlendTiles = 10000;- DynamicVBAccessClass vb_access(BUFFER_TYPE_DYNAMIC_DX8,DX8_FVF_XYZNDUV2,maxBlendTiles*4);- DynamicIBAccessClass ib_access(BUFFER_TYPE_DYNAMIC_DX8,maxBlendTiles*6);+ //Loop over visible terrain and extract all the tiles that need extra blend+ Int drawEdgeY=m_map->getDrawOrgY()+m_map->getDrawHeight()-1;+ Int drawEdgeX=m_map->getDrawOrgX()+m_map->getDrawWidth()-1;+ if (drawEdgeX > (m_map->getXExtent()-1))+ drawEdgeX = m_map->getXExtent()-1;+ if (drawEdgeY > (m_map->getYExtent()-1))+ drawEdgeY = m_map->getYExtent()-1;+ Int drawStartX=m_map->getDrawOrgX();+ Int drawStartY=m_map->getDrawOrgY();++ // Everything the fill below reads, apart from the 3-way list, the heights and the lights, which+ // all move m_terrainContentVersion. The lights are checked here, once a pass.+ refreshStaticDiffuseInputs();+ const Int key[EXTRA_BLEND_KEY_SIZE] = { m_terrainContentVersion, drawStartX, drawStartY,+ drawEdgeX, drawEdgeY, maxBlendTiles, m_map->getExtraBlendUVGeneration(),+ TheGlobalData->m_adjustCliffTextures };+ if (m_extraBlendMap != m_map || memcmp(key, m_extraBlendKey, sizeof(key)) != 0){+ m_extraBlendMap = NULL;+ if (m_extraBlendCapacity != maxBlendTiles)+ {+ REF_PTR_RELEASE(m_extraBlendVB);+ REF_PTR_RELEASE(m_extraBlendIB);+ m_extraBlendVB = NEW_REF(DX8VertexBufferClass,(DX8_FVF_XYZNDUV2,maxBlendTiles*4,DX8VertexBufferClass::USAGE_DEFAULT));+ m_extraBlendIB = NEW_REF(DX8IndexBufferClass,(maxBlendTiles*6));+ m_extraBlendCapacity = maxBlendTiles;+ }- DynamicVBAccessClass::WriteLockClass lock(&vb_access);- VertexFormatXYZNDUV2* vb= lock.Get_Formatted_Vertex_Array();- DynamicIBAccessClass::WriteLockClass lockib(&ib_access);+ DX8VertexBufferClass::WriteLockClass lock(m_extraBlendVB);+ VertexFormatXYZNDUV2* vb=(VertexFormatXYZNDUV2*)lock.Get_Vertex_Array();+ DX8IndexBufferClass::WriteLockClass lockib(m_extraBlendIB);UnsignedShort *ib=lockib.Get_Index_Array();if (!vb || !ib) return;const UnsignedByte* data = m_map->getDataPtr();- //Loop over visible terrain and extract all the tiles that need extra blend- Int drawEdgeY=m_map->getDrawOrgY()+m_map->getDrawHeight()-1;- Int drawEdgeX=m_map->getDrawOrgX()+m_map->getDrawWidth()-1;- if (drawEdgeX > (m_map->getXExtent()-1))- drawEdgeX = m_map->getXExtent()-1;- if (drawEdgeY > (m_map->getYExtent()-1))- drawEdgeY = m_map->getYExtent()-1;- Int drawStartX=m_map->getDrawOrgX();- Int drawStartY=m_map->getDrawOrgY();-try {for (Int j=0; j<m_numExtraBlendTiles; j++){@@ -2410,17 +2435,24 @@ void HeightMapRenderObjClass::renderExtraBlendTiles(void)} catch(...) {IndexBufferExceptionFunc();}++ memcpy(m_extraBlendKey, key, sizeof(key));+ m_extraBlendMap = m_map;+ m_extraBlendVertexCount = vertexCount;+ m_extraBlendIndexCount = indexCount;}//unlock vertex buffer+ vertexCount = m_extraBlendVertexCount;+ indexCount = m_extraBlendIndexCount;if (vertexCount){//Check if we couldn't fit all blend tiles into vertex buffer so we can enlarge it for next frame.if (vertexCount == (maxBlendTiles*4))maxBlendTiles += 16; //enlarge by 16 to reduce trashing.-+ShaderClass::Invalidate(); //invalidate to force shader to reset since we directly changed states- DX8Wrapper::Set_Index_Buffer(ib_access,0);- DX8Wrapper::Set_Vertex_Buffer(vb_access);+ DX8Wrapper::Set_Index_Buffer(m_extraBlendIB,0);+ DX8Wrapper::Set_Vertex_Buffer(m_extraBlendVB);VertexMaterialClass *vmat=VertexMaterialClass::Get_Preset(VertexMaterialClass::PRELIT_DIFFUSE);DX8Wrapper::Set_Material(vmat);REF_PTR_RELEASE(vmat);diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cppindex 7a163593d..f190b16d6 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DTerrainTracks.cpp@@ -837,10 +837,17 @@ Try improving the fit to vertical surfaces like cliffs.diffuseLight = REAL_TO_INT(shadeB) | (REAL_TO_INT(shadeG) << 8) | (REAL_TO_INT(shadeR) << 16);Real numFadedEdges=m_maxTankTrackEdges-m_maxTankTrackOpaqueEdges;- //check if there is anything to draw and fill vertex buffer- if (m_edgesToFlush >= 2)+ // Lock only the vertices this pass writes. A whole-buffer lock is every track the detail level+ // allows times every edge, and with Direct3D 11 its unlock copied all of it twice on every pass.+ Int vertsToWrite = 0;+ for (mod=m_usedModules; mod; mod=mod->m_nextSystem)+ if (mod->m_activeEdgeCount >= 2 && mod->Is_Really_Visible())+ vertsToWrite += mod->m_activeEdgeCount*2;++ //check if there is anything to draw and fill vertex buffer (a zero-length lock means the whole buffer)+ if (m_edgesToFlush >= 2 && vertsToWrite > 0){- DX8VertexBufferClass::WriteLockClass lockVtxBuffer(m_vertexBuffer);+ DX8VertexBufferClass::AppendLockClass lockVtxBuffer(m_vertexBuffer, 0, vertsToWrite);VertexFormatXYZDUV1 *verts = (VertexFormatXYZDUV1*)lockVtxBuffer.Get_Vertex_Array();//diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cppindex 6bb996c5e..017e25515 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/WorldHeightMap.cpp@@ -148,7 +148,8 @@ WorldHeightMap::WorldHeightMap():m_tileMode(TILE_4x4),#endifm_numCliffInfo(1),- m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1)+ m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1),+ m_extraBlendUVGeneration(1){Int i;for (i=0; i<NUM_SOURCE_TILES; i++) {@@ -186,7 +187,8 @@ WorldHeightMap::WorldHeightMap(ChunkInputStream *pStrm, Bool logicalDataOnly):m_tileMode(TILE_4x4),#endifm_numCliffInfo(1),- m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1)+ m_terrainTex(NULL), m_alphaTerrainTex(NULL), m_numBitmapTiles(0), m_numBlendedTiles(1),+ m_extraBlendUVGeneration(1){int i;@@ -1379,6 +1381,21 @@ Bool WorldHeightMap::getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], floif (blendNdx == 0) {return FALSE;} else {+ if (m_extraBlendUV.empty())+ m_extraBlendUV.resize(NUM_BLEND_TILES); // zeroed, so generation 0: nothing valid yet+ ExtraBlendUV &memo = m_extraBlendUV[blendNdx];+ const Short cliffInfoNdx = m_cliffInfoNdxes[ndx];+ const Bool adjustCliff = !TheGlobalData || TheGlobalData->m_adjustCliffTextures;+ if (memo.generation == m_extraBlendUVGeneration && memo.cliffInfoNdx == cliffInfoNdx &&+ memo.adjustCliff == adjustCliff) {+ memcpy(U, memo.U, sizeof(memo.U));+ memcpy(V, memo.V, sizeof(memo.V));+ memcpy(alpha, memo.alpha, sizeof(memo.alpha));+ *needFlip = memo.flip;+ *cliff = memo.cliff;+ return TRUE;+ }+*cliff = getUVForTileIndex(ndx, m_blendedTiles[blendNdx].blendNdx, U, V, FALSE);alpha[0] = alpha[1] = alpha[2] = alpha[3] = 0;if (m_blendedTiles[blendNdx].horiz) {@@ -1440,6 +1457,15 @@ Bool WorldHeightMap::getExtraAlphaUVData(Int xIndex, Int yIndex, float U[4], flo// No alpha blend, so never need to flip.*needFlip = FALSE;}++ memcpy(memo.U, U, sizeof(memo.U));+ memcpy(memo.V, V, sizeof(memo.V));+ memcpy(memo.alpha, alpha, sizeof(memo.alpha));+ memo.flip = *needFlip;+ memo.cliff = *cliff;+ memo.cliffInfoNdx = cliffInfoNdx;+ memo.adjustCliff = adjustCliff;+ memo.generation = m_extraBlendUVGeneration;}}@@ -1566,6 +1592,7 @@ TextureClass *WorldHeightMap::getTerrainTexture(void)REF_PTR_RELEASE(m_terrainTex);m_terrainTex = MSGNEW("WorldHeightMap_getTerrainTexture") TerrainTextureClass(pow2Height);m_terrainTexHeight = m_terrainTex->update(this);+ m_extraBlendUVGeneration++; // the tiles just moved in the texture, and its height may have changedif (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.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cppindex 5299849fe..81007bc71 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.cpp@@ -285,6 +285,9 @@ DX11BackendClass::DX11BackendClass()PixelConstantsHeld = false;EngineConstantsHeld = false;ConstantsChanged = true;+ VertexConstantsChanged = false;+ PixelConstantsChanged = false;+ TexturesChanged = true;PipelineChanged = true;StateObjectsChanged = true;for (unsigned sampler = 0; sampler < DX11_BACKEND_TEXTURE_STAGES; ++sampler) {@@ -1077,7 +1080,26 @@ void DX11BackendClass::Set_Render_State(D3DRENDERSTATETYPE state, DWORD value)// The raw value, not Get_Render_State: that one answers for the caster pass while it runs.if (RenderStates.Get_Stored_Render_State(state) != value) {RenderStates.Set_Render_State(state, value);- ConstantsChanged = true;+ // Only these reach the constant blocks; see Upload_Vertex_Constants and+ // Upload_Pixel_Constants. The blend switch is there because the caster pass's alpha+ // reference depends on it. A blend, depth or cull change used to rebuild and compare both+ // blocks to find the same bytes.+ switch (state) {+ case D3DRS_AMBIENT:+ case D3DRS_FOGSTART:+ case D3DRS_FOGEND:+ case D3DRS_FOGDENSITY:+ VertexConstantsChanged = true;+ break;+ case D3DRS_FOGCOLOR:+ case D3DRS_TEXTUREFACTOR:+ case D3DRS_ALPHAREF:+ case D3DRS_ALPHABLENDENABLE:+ PixelConstantsChanged = true;+ break;+ default:+ break;+ }PipelineChanged = true;StateObjectsChanged = true;}@@ -1119,6 +1141,9 @@ void DX11BackendClass::Set_Texture(unsigned stage, ID3D11ShaderResourceView * tePipelineChanged = true;}}+ if (texture != Textures[stage]) {+ TexturesChanged = true;+ }Textures[stage] = texture;}}@@ -1261,7 +1286,13 @@ void DX11BackendClass::Set_Transform(D3DTRANSFORMSTATETYPE state, const float ma}if (held != NULL && memcmp(held, matrix, sizeof(float) * 16) != 0) {memcpy(held, matrix, sizeof(float) * 16);- ConstantsChanged = true;+ // The pixel block reads the view and the projection; the world and the texture transforms+ // are the vertex block's alone.+ if (held == View || held == Projection) {+ ConstantsChanged = true;+ } else {+ VertexConstantsChanged = true;+ }}}@@ -1281,7 +1312,7 @@ void DX11BackendClass::Set_Material(const float ambient[4], const float diffuse[memcpy(MaterialSpecular, specular, sizeof(MaterialSpecular));memcpy(MaterialEmissive, emissive, sizeof(MaterialEmissive));MaterialPower = power;- ConstantsChanged = true;+ VertexConstantsChanged = true;}void DX11BackendClass::Set_Light(unsigned index, DWORD type, const float position[4],@@ -2012,11 +2043,25 @@ void DX11BackendClass::Upload_Constants()EngineConstantsHeld = true;}- // Nothing either block is built from has been set since both buffers were last written.- if (!ConstantsChanged && VertexConstantsHeld && PixelConstantsHeld) {- return;- }+ // Each block is built only when something it is built from has been set since its buffer was+ // last written.+ const bool vertex_due = ConstantsChanged || VertexConstantsChanged || !VertexConstantsHeld;+ const bool pixel_due = ConstantsChanged || PixelConstantsChanged || !PixelConstantsHeld;ConstantsChanged = false;+ VertexConstantsChanged = false;+ PixelConstantsChanged = false;+ if (vertex_due) {+ Upload_Vertex_Constants();+ }+ if (pixel_due) {+ Upload_Pixel_Constants();+ }+}++void DX11BackendClass::Upload_Vertex_Constants()+{+ ID3D11DeviceContext * context = Device->Get_Context();+ D3D11_MAPPED_SUBRESOURCE mapped;VertexConstantBlock vertex_block;memset(&vertex_block, 0, sizeof(vertex_block));@@ -2082,6 +2127,12 @@ void DX11BackendClass::Upload_Constants()VertexConstantsHeld = true;}}+}++void DX11BackendClass::Upload_Pixel_Constants()+{+ ID3D11DeviceContext * context = Device->Get_Context();+ D3D11_MAPPED_SUBRESOURCE mapped;PixelConstantBlock pixel_block;memset(&pixel_block, 0, sizeof(pixel_block));@@ -2388,19 +2439,31 @@ void DX11BackendClass::Bind_State_Objects()Bound.Rasterizer = rasterizer;}- ID3D11SamplerState * samplers[DX11_BACKEND_TEXTURE_STAGES];- ID3D11ShaderResourceView * textures[DX11_BACKEND_TEXTURE_STAGES];- for (unsigned sampler = 0; sampler < DX11_BACKEND_TEXTURE_STAGES; ++sampler) {- samplers[sampler] = Sampler_State(sampler);- textures[sampler] = Readable_Texture(sampler, Textures[sampler]);- }- if (!known || memcmp(samplers, Bound.Samplers, sizeof(samplers)) != 0) {- context->PSSetSamplers(0, DX11_BACKEND_TEXTURE_STAGES, samplers);- memcpy(Bound.Samplers, samplers, sizeof(samplers));- }- if (!known || memcmp(textures, Bound.Textures, sizeof(textures)) != 0) {- context->PSSetShaderResources(0, DX11_BACKEND_TEXTURE_STAGES, textures);- memcpy(Bound.Textures, textures, sizeof(textures));+ // The stages are what the last draw bound unless a texture or a sampler state was set since, or+ // that draw read a copy of the target, which has to be taken again for this one.+ bool stages_changed = !known || TexturesChanged;+ for (unsigned sampler = 0; sampler < DX11_BACKEND_TEXTURE_STAGES && !stages_changed; ++sampler) {+ stages_changed = SamplerChanged[sampler];+ }+ if (stages_changed) {+ TexturesChanged = false;+ ID3D11SamplerState * samplers[DX11_BACKEND_TEXTURE_STAGES];+ ID3D11ShaderResourceView * textures[DX11_BACKEND_TEXTURE_STAGES];+ for (unsigned sampler = 0; sampler < DX11_BACKEND_TEXTURE_STAGES; ++sampler) {+ samplers[sampler] = Sampler_State(sampler);+ textures[sampler] = Readable_Texture(sampler, Textures[sampler]);+ if (textures[sampler] != Textures[sampler]) {+ TexturesChanged = true;+ }+ }+ if (!known || memcmp(samplers, Bound.Samplers, sizeof(samplers)) != 0) {+ context->PSSetSamplers(0, DX11_BACKEND_TEXTURE_STAGES, samplers);+ memcpy(Bound.Samplers, samplers, sizeof(samplers));+ }+ if (!known || memcmp(textures, Bound.Textures, sizeof(textures)) != 0) {+ 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)) {@@ -2424,12 +2487,22 @@ void DX11BackendClass::Bind_State_Objects()}// The smoke's map beside it at t6 and s6, or nothing on a frame without smoke, which the// program never reads: its strength is zero then.+ // Both were bound again on every receiving draw, which is most of the frame.ID3D11ShaderResourceView * const maps[2] = { ShadowMapTexture, Smoke_Map() };- context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES + 1, 2, maps);+ if (!known || maps[0] != Bound.Maps[0] || maps[1] != Bound.Maps[1]) {+ context->PSSetShaderResources(DX11_BACKEND_TEXTURE_STAGES + 1, 2, maps);+ Bound.Maps[0] = maps[0];+ Bound.Maps[1] = maps[1];+ }if (ShadowMapSampler != NULL) {ID3D11SamplerState * const samplers_of_maps[2] = { ShadowMapSampler, SmokeMapSampler };- context->PSSetSamplers(DX11_BACKEND_TEXTURE_STAGES + 1, (SmokeMapSampler != NULL) ? 2 : 1,- samplers_of_maps);+ if (!known || samplers_of_maps[0] != Bound.MapSamplers[0]+ || samplers_of_maps[1] != Bound.MapSamplers[1]) {+ context->PSSetSamplers(DX11_BACKEND_TEXTURE_STAGES + 1,+ (SmokeMapSampler != NULL) ? 2 : 1, samplers_of_maps);+ Bound.MapSamplers[0] = samplers_of_maps[0];+ Bound.MapSamplers[1] = samplers_of_maps[1];+ }}}}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.hindex 5f39079f1..b159aae62 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11backend.h@@ -350,6 +350,8 @@ private:bool Build_Vertex_Description(VertexPipelineDescription & description) const;bool Build_Combiner_Description(CombinerDescription & description) const;void Upload_Constants();+ void Upload_Vertex_Constants();+ void Upload_Pixel_Constants();// Both indexed draws land here; only the topology differs.bool Draw_Indexed(unsigned index_count, unsigned start_index, unsigned base_vertex,@@ -519,8 +521,17 @@ private:// input to any of them needs its setter to raise the flag here, or the draw after it reads the// previous batch's lighting.bool ConstantsChanged;+ // An input of one block only: the world and texture transforms and the material reach only the+ // vertex block, the terrain sun, the scene view and the smoke only the pixel block. A mesh+ // changes its world transform every draw, and rebuilding the pixel block for it was a rebuild+ // whose bytes always matched. ConstantsChanged stands for both.+ bool VertexConstantsChanged;+ bool PixelConstantsChanged;bool PipelineChanged;bool SamplerChanged[DX11_BACKEND_TEXTURE_STAGES];+ // A stage's texture changed, or the last draw sampled the current target and so needs a fresh+ // copy of it: either way the stages have to be looked at again before the next draw binds.+ bool TexturesChanged;// A render state, or the shadow caster pass that answers for some of them, changed since the// three state objects were last looked up.bool StateObjectsChanged;@@ -676,6 +687,10 @@ private:ID3D11SamplerState * Samplers[DX11_BACKEND_TEXTURE_STAGES];ID3D11ShaderResourceView * Textures[DX11_BACKEND_TEXTURE_STAGES];ID3D11ShaderResourceView * NormalMap;+ // The sun's map and the smoke's at t5 and t6, and their samplers as last passed: the+ // second sampler is null when only the first was set.+ ID3D11ShaderResourceView * Maps[2];+ ID3D11SamplerState * MapSamplers[2];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 6441f5ce5..48355cea5 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11runtime.cpp@@ -36,6 +36,13 @@ static bool PresentFailureReported = false;static bool VSyncRequested = false;static bool Active = false;static bool NormalMapsEnabled = true;+// The texture the backend's normal map was last mirrored from, and the mirror generation then.+// TextureClass::Apply hands the same one over on every bind of its texture, and each mirror call is+// three private data lookups on the D3D9 texture. Cleared when stage zero changes, which is when+// the backend drops its normal map, so the D3D9 texture at stage zero (held by the wrapper) is the+// one this was found for.+static struct IDirect3DBaseTexture9 * MirroredNormalMap = NULL;+static unsigned long long MirroredNormalMapGeneration = 0;static DX11DeviceClass Device;static DX11BackendClass Backend;static DX11PostProcessClass Post;@@ -126,6 +133,7 @@ void Direct3D11_Release()Backend.Shutdown();Device.Release();Active = false;+ MirroredNormalMap = NULL;}bool Direct3D11_Resize(unsigned width, unsigned height)@@ -260,6 +268,7 @@ void Direct3D11_Mirror_Texture(unsigned stage, struct IDirect3DBaseTexture9 * te// the new one's right after this, and a texture bound any other way has none.if (stage == 0) {Backend.Set_Normal_Map(NULL);+ MirroredNormalMap = NULL;}}@@ -278,9 +287,15 @@ void Direct3D11_Mirror_Normal_Map(struct IDirect3DBaseTexture9 * normal_map)if (!Active) {return;}+ if (normal_map != NULL && normal_map == MirroredNormalMap+ && DX11Texture_Generation() == MirroredNormalMapGeneration) {+ return;+ }Backend.Set_Normal_Map(normal_map == NULL? NULL: DX11Texture_Mirror(Device.Get_Device(), Device.Get_Context(), normal_map));+ MirroredNormalMap = normal_map;+ MirroredNormalMapGeneration = DX11Texture_Generation();}void Direct3D11_Set_Terrain_Sun(const float direction[3])diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cppindex 5ede941cf..6486396e7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.cpp@@ -86,6 +86,10 @@ static void note_refusal(const char * reason)static std::vector<std::string> Notes;+// Raised whenever a texture's view is replaced or its pixels are marked for a recopy; see+// DX11Texture_Generation.+static unsigned long long Generation = 0;+static unsigned Mirrored = 0;static unsigned Refused = 0;static unsigned Reused = 0;@@ -491,6 +495,7 @@ static ID3D11ShaderResourceView * apply_lod(ID3D11Device * device, IDirect3DBasetexture->SetPrivateData(DX11_TEXTURE_VIEW, replacement, sizeof(replacement), D3DSPD_IUNKNOWN);replacement->Release();texture->SetPrivateData(DX11_TEXTURE_LOD, &lod, sizeof(lod), 0);+ ++Generation;return replacement;}@@ -555,6 +560,12 @@ void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface)const unsigned char dirty = 1;texture->SetPrivateData(DX11_TEXTURE_DIRTY, &dirty, sizeof(dirty), 0);texture->Release();+ ++Generation;+}++unsigned long long DX11Texture_Generation()+{+ return Generation;}bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.hindex 6b98272d7..faf958f5c 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx11texture.h@@ -58,6 +58,12 @@ bool DX11Texture_Update(ID3D11Device * device, ID3D11DeviceContext * context,// surface with no texture behind it is ignored.void DX11Texture_Mark_Dirty(IDirect3DSurface9 * surface);+// Changes whenever a mirror call could hand back something different for a texture it has already+// mirrored: a view replaced for a new level of detail, or pixels marked for a recopy. A caller+// that remembers a view may keep it while this holds still. A SetLOD alone does not move it; the+// next mirror call on that texture does.+unsigned long long DX11Texture_Generation();+// The render target view over the copy of the texture this surface is a level of, built on the// first call and kept on that texture with the shader resource view. Null when the surface has no// texture behind it, which is the device's own back buffer.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cppindex 41fc9630e..63271d9a1 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.cpp@@ -207,6 +207,8 @@ void DX8Wrapper::_Set_DX8_Render_Target(IDirect3DSurface9 * render_target, IDirevoid DX8Wrapper::_Draw_DX8_Primitive_UP(D3DPRIMITIVETYPE type, unsigned primitive_count,const void * vertices, unsigned stride){+ // Drawn on Direct3D 9 whichever device presents: the smudge test reads this draw back.+ Flush_Deferred_D3D9_State();DX8CALL(DrawPrimitiveUP(type, primitive_count, vertices, stride));if (type == D3DPT_TRIANGLESTRIP) {Direct3D11_Draw_User_Strip(vertices, primitive_count, stride);@@ -325,6 +327,16 @@ unsigned DX8Wrapper::texture_stage_state_changes = 0;unsigned DX8Wrapper::draw_calls = 0;unsigned DX8Wrapper::_MainThreadID = 0;bool DX8Wrapper::CurrentDX8LightEnables[4];+bool DX8Wrapper::D3D9StatePending = false;+unsigned DX8Wrapper::PendingRenderStates[256/32];+unsigned DX8Wrapper::PendingTextureStageStates[MAX_TEXTURE_STAGES];+unsigned DX8Wrapper::PendingSamplerStates[MAX_TEXTURE_STAGES];+unsigned DX8Wrapper::PendingTextures = 0;+bool DX8Wrapper::PendingMaterial = false;+D3DMATERIAL9 DX8Wrapper::PendingMaterialValue;+unsigned DX8Wrapper::PendingLights = 0;+unsigned DX8Wrapper::PendingLightEnables = 0;+D3DLIGHT9 DX8Wrapper::PendingLightValues[4];bool DX8Wrapper::IsDeviceLost;int DX8Wrapper::ZBias;float DX8Wrapper::ZNear;@@ -565,6 +577,8 @@ void DX8Wrapper::Shutdown(void)// combiner cache compiled.FixedFunctionProbe_Dump("ffprobe.txt");CombinerShaderCache_Release();+ // The setters stop deferring once Direct3D 11 is gone, so nothing may be left owed across it.+ Flush_Deferred_D3D9_State();Direct3D11_Release();restore_desktop_display();@@ -688,6 +702,7 @@ bool DX8Wrapper::Validate_Device(void){ RenderUInt32 numPasses=0;RenderResult hRes;+ Flush_Deferred_D3D9_State();hRes=_Get_D3D_Device()->ValidateDevice(&numPasses);return (hRes == D3D_OK);@@ -695,6 +710,8 @@ bool DX8Wrapper::Validate_Device(void)void DX8Wrapper::Invalidate_Cached_Render_States(void){+ // The caches below are about to stop holding the values the device is owed.+ Flush_Deferred_D3D9_State();render_state_changed=0;int a;@@ -1069,6 +1086,9 @@ bool DX8Wrapper::Reset_Device(bool reload_assets)WWDEBUG_SAY(("Resetting device.\n"));DX8_THREAD_ASSERT();if ((IsInitted) && (D3DDevice != NULL)) {+ // The textures the device holds bound at Reset() are the ones it held before deferring.+ Flush_Deferred_D3D9_State();+// Release all non-MANAGED stuffWW3D::_Invalidate_Textures();@@ -1124,6 +1144,9 @@ void DX8Wrapper::Release_Device(void){if (D3DDevice) {+ // So that no pending bit outlives this device and is sent to the next one.+ Flush_Deferred_D3D9_State();+// The device made every shader in the combiner cache and outliving it is not something they// can do. Nothing recompiles them: the next draw asks the cache again and it is empty.CombinerShaderCache_Release();@@ -2714,9 +2737,10 @@ void DX8Wrapper::Draw(Apply_Render_State_Changes();// -ffprobe only: the fixed-function inventory phase 2 has to write as HLSL, counted off the- // device rather than off this wrapper's cache, so a call site that set its own states directly- // is seen too.- if (FixedFunctionProbe_Is_Enabled()) {+ // device rather than off this wrapper's cache. Under D3D11 the device is behind that cache, so+ // the sample flushes the wrapper's cached values to it first; only the draws it samples pay.+ if (FixedFunctionProbe_Samples_Draw()) {+ Flush_Deferred_D3D9_State();FixedFunctionProbe_Record(D3DDevice);}@@ -2741,6 +2765,7 @@ void DX8Wrapper::Draw(if (WW3D::Is_Snapshot_Activated()) {RenderUInt32 passes=0; // DWORD on Windows, which ValidateDevice writesSNAPSHOT_SAY(("ValidateDevice: "));+ Flush_Deferred_D3D9_State();RenderResult res=D3DDevice->ValidateDevice(&passes);switch (res) {case D3D_OK:@@ -2819,10 +2844,10 @@ void DX8Wrapper::Draw(DX8_RECORD_RENDER(polygon_count,vertex_count,render_state.shader);DX8_RECORD_DRAW_CALLS();// When Direct3D 11 owns the window, the Direct3D 9 frame is never shown and nothing- // reads its pixels back, so drawing it is only GPU time. The state is still set on- // the D3D9 device above: the fixed-function probe reads it, and the wrapper's own- // cache relies on it. _Draw_DX8_Primitive_UP keeps its D3D9 draw, because the smudge- // hardware test draws with it and reads the D3D9 target back.+ // reads its pixels back, so drawing it is only GPU time. Most of the state for it is+ // deferred as well (Defer_D3D9_State) and sent only before the probe's sampled draws.+ // _Draw_DX8_Primitive_UP keeps its D3D9 draw, because the smudge hardware test draws+ // with it and reads the D3D9 target back.if (!Direct3D11_Present_Is_Enabled()) {DX8CALL(DrawIndexedPrimitive((D3DPRIMITIVETYPE)primitive_type,@@ -3101,6 +3126,63 @@ void DX8Wrapper::Apply_Render_State_Changes()SNAPSHOT_SAY(("DX8Wrapper::Apply_Render_State_Changes() - finished\n"));}+// Each owed value is the latest one the cache holds, sent once however often it changed since the+// last flush. Nothing outside this wrapper writes these states on the device on a modern card+// (shader.cpp's stage 2 writes are Voodoo3 only), so the device ends where it would have been.+void DX8Wrapper::Flush_Deferred_D3D9_State(void)+{+ if (!D3D9StatePending) return;+ D3D9StatePending=false;++ for (unsigned word=0; word<256/32; ++word) {+ unsigned bits=PendingRenderStates[word];+ PendingRenderStates[word]=0;+ for (unsigned bit=0; bits!=0; ++bit, bits>>=1) {+ if (bits&1) {+ const unsigned state=word*32+bit;+ DX8CALL(SetRenderState((D3DRENDERSTATETYPE)state, RenderStates[state]));+ }+ }+ }++ for (unsigned stage=0; stage<MAX_TEXTURE_STAGES; ++stage) {+ unsigned bits=PendingTextureStageStates[stage];+ PendingTextureStageStates[stage]=0;+ for (unsigned state=0; bits!=0; ++state, bits>>=1) {+ if (bits&1) {+ DX8CALL(SetTextureStageState(stage, (D3DTEXTURESTAGESTATETYPE)state, TextureStageStates[stage][state]));+ }+ }+ bits=PendingSamplerStates[stage];+ PendingSamplerStates[stage]=0;+ for (unsigned state=0; bits!=0; ++state, bits>>=1) {+ if (bits&1) {+ DX8CALL(SetSamplerState(stage, (D3DSAMPLERSTATETYPE)state, SamplerStates[stage][state]));+ }+ }+ if (PendingTextures&(1u<<stage)) {+ DX8CALL(SetTexture(stage, Textures[stage]));+ }+ }+ PendingTextures=0;++ if (PendingMaterial) {+ PendingMaterial=false;+ DX8CALL(SetMaterial(&PendingMaterialValue));+ }++ for (unsigned index=0; index<4; ++index) {+ if (PendingLights&(1u<<index)) {+ DX8CALL(SetLight(index, &PendingLightValues[index]));+ }+ if (PendingLightEnables&(1u<<index)) {+ DX8CALL(LightEnable(index, CurrentDX8LightEnables[index]));+ }+ }+ PendingLights=0;+ PendingLightEnables=0;+}+IDirect3DTexture9 * DX8Wrapper::_Create_DX8_Texture(unsigned int width,@@ -5500,6 +5582,7 @@ void DX8Wrapper::Draw_Owned_Triangles(unsigned first_index, unsigned triangle_co// sites, which had them written out by hand and not always the same way.const unsigned index_count=as_strip ? (triangle_count+2) : (triangle_count*3);+ Flush_Deferred_D3D9_State();DX8CALL(DrawIndexedPrimitive(as_strip ? D3DPT_TRIANGLESTRIP : D3DPT_TRIANGLELIST,0, // BaseVertexIndex: the stream offset already moved the vertices@@ -5523,6 +5606,7 @@ void DX8Wrapper::Draw_Owned_Points(unsigned first_vertex, unsigned point_count)DX8_THREAD_ASSERT();if (point_count==0) return;+ Flush_Deferred_D3D9_State();DX8CALL(DrawPrimitive(D3DPT_POINTLIST, first_vertex, point_count));// No mirror: the Direct3D 11 backend resolves triangles out of the fixed-function state anddiff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.hindex 11c642521..376bcb4eb 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/dx8wrapper.h@@ -525,6 +525,11 @@ public:static bool Validate_Device(void);+ // While Direct3D 11 presents, the Direct3D 9 device is not told the render states, stage and+ // sampler states, textures, material or lights as they are set, only marked as owing them.+ // Anything that draws on that device or reads its state back calls this first.+ static void Flush_Deferred_D3D9_State(void);+// Deferredstatic void Set_Shader(const ShaderClass& shader);@@ -1002,6 +1007,20 @@ protected:static unsigned draw_calls;static bool CurrentDX8LightEnables[4];+ // What the Direct3D 9 device has not been told yet, one bit per state, stage or light; the+ // values are the caches above. Defer_D3D9_State says whether a setter marks or calls.+ static bool Defer_D3D9_State();+ static bool D3D9StatePending;+ static unsigned PendingRenderStates[256/32];+ static unsigned PendingTextureStageStates[MAX_TEXTURE_STAGES];+ static unsigned PendingSamplerStates[MAX_TEXTURE_STAGES];+ static unsigned PendingTextures;+ static bool PendingMaterial;+ static D3DMATERIAL9 PendingMaterialValue;+ static unsigned PendingLights;+ static unsigned PendingLightEnables;+ static D3DLIGHT9 PendingLightValues[4];+static unsigned long FrameCount;static DX8Caps* CurrentCaps;@@ -1184,12 +1203,29 @@ WWINLINE void DX8Wrapper::Set_Ambient(const Vector3& color)//// ----------------------------------------------------------------------------+// While Direct3D 11 presents, the Direct3D 9 device skips its indexed draws, and what it was told+// for them was 7-8% of the main thread spent inside d3d9.dll at 1080p. The few readers left - the+// fixed-function probe's sampled draws, the draws that still go to the device, the smudge test's+// read back - call Flush_Deferred_D3D9_State first. True means mark the state pending, not call.+WWINLINE bool DX8Wrapper::Defer_D3D9_State()+{+ if (!Direct3D11_Present_Is_Enabled()) return false;+ D3D9StatePending=true;+ return true;+}+WWINLINE void DX8Wrapper::Set_DX8_Material(const D3DMATERIAL9* mat){DX8_RECORD_MATERIAL_CHANGE();WWASSERT(mat);SNAPSHOT_SAY(("DX8 - SetMaterial\n"));- DX8CALL(SetMaterial(mat));+ if (Defer_D3D9_State()) {+ PendingMaterialValue=*mat;+ PendingMaterial=true;+ }+ else {+ DX8CALL(SetMaterial(mat));+ }// D3DCOLORVALUE is four floats in red, green, blue, alpha order, which is the order the// generated shader reads them, so each one goes across as it stands.@@ -1201,8 +1237,15 @@ WWINLINE void DX8Wrapper::Set_DX8_Light(int index, D3DLIGHT9* light){if (light) {DX8_RECORD_LIGHT_CHANGE();- DX8CALL(SetLight(index,light));- DX8CALL(LightEnable(index,true));+ if (Defer_D3D9_State()) {+ PendingLightValues[index]=*light;+ PendingLights|=1u<<index;+ PendingLightEnables|=1u<<index;+ }+ else {+ DX8CALL(SetLight(index,light));+ DX8CALL(LightEnable(index,true));+ }CurrentDX8LightEnables[index]=true;SNAPSHOT_SAY(("DX8 - SetLight %d\n",index));@@ -1222,7 +1265,12 @@ WWINLINE void DX8Wrapper::Set_DX8_Light(int index, D3DLIGHT9* light)else if (CurrentDX8LightEnables[index]) {DX8_RECORD_LIGHT_CHANGE();CurrentDX8LightEnables[index]=false;- DX8CALL(LightEnable(index,false));+ if (Defer_D3D9_State()) {+ PendingLightEnables|=1u<<index;+ }+ else {+ DX8CALL(LightEnable(index,false));+ }Direct3D11_Mirror_Light_Disabled(index);SNAPSHOT_SAY(("DX8 - DisableLight %d\n",index));}@@ -1244,7 +1292,15 @@ WWINLINE void DX8Wrapper::Set_DX8_Render_State(D3DRENDERSTATETYPE state, unsigne#endifRenderStates[state]=value;- DX8CALL(SetRenderState( state, value ));+ // The water reads the cull mode back off the device and the stencil passes the colour write+ // mask, and each puts what it read back through here into the Direct3D 11 mirror. Those two+ // still reach the device on every call, so what is read is what it always was.+ if (state!=D3DRS_CULLMODE && state!=D3DRS_COLORWRITEENABLE && Defer_D3D9_State()) {+ PendingRenderStates[state>>5]|=1u<<(state&31);+ }+ else {+ DX8CALL(SetRenderState( state, value ));+ }Direct3D11_Mirror_Render_State(state, value);DX8_RECORD_RENDER_STATE_CHANGE();}@@ -1275,7 +1331,12 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture_Stage_State(unsigned stage, D3DTEXTURE#endifTextureStageStates[stage][(unsigned int)state]=value;- DX8CALL(SetTextureStageState( stage, state, value ));+ if (Defer_D3D9_State()) {+ PendingTextureStageStates[stage]|=1u<<(unsigned)state;+ }+ else {+ DX8CALL(SetTextureStageState( stage, state, value ));+ }Direct3D11_Mirror_Texture_Stage_State(stage, state, value);DX8_RECORD_TEXTURE_STAGE_STATE_CHANGE();}@@ -1303,7 +1364,12 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture_Stage_State(unsigned stage, D3DSAMPLER#endifSamplerStates[stage][(unsigned int)state]=value;- DX8CALL(SetSamplerState( stage, state, value ));+ if (Defer_D3D9_State()) {+ PendingSamplerStates[stage]|=1u<<(unsigned)state;+ }+ else {+ DX8CALL(SetSamplerState( stage, state, value ));+ }Direct3D11_Mirror_Sampler_State(stage, state, value);DX8_RECORD_TEXTURE_STAGE_STATE_CHANGE();}@@ -1322,7 +1388,12 @@ WWINLINE void DX8Wrapper::Set_DX8_Texture(unsigned int stage, IDirect3DBaseTextuif (Textures[stage]) Textures[stage]->Release();Textures[stage] = texture;if (Textures[stage]) Textures[stage]->AddRef();- DX8CALL(SetTexture(stage, texture));+ if (Defer_D3D9_State()) {+ PendingTextures|=1u<<stage;+ }+ else {+ DX8CALL(SetTexture(stage, texture));+ }Direct3D11_Mirror_Texture(stage, texture);DX8_RECORD_TEXTURE_CHANGE();}diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cppindex 1d63ee499..a9436a8d7 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.cpp@@ -96,14 +96,16 @@ bool CombinerShaders_Are_Enabled()return _CombinerShadersEnabled;}+bool FixedFunctionProbe_Samples_Draw()+{+ return _Enabled && _DrawsSeen++ % SAMPLE_STRIDE == 0;+}+void FixedFunctionProbe_Record(IDirect3DDevice9 * device){if (!_Enabled || device == NULL) {return;}- if (_DrawsSeen++ % SAMPLE_STRIDE != 0) {- return;- }++_DrawsSampled;// Kept between draws so a draw does not allocate one; clear() keeps the capacity.diff --git a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.hindex 9c5d8b5e8..c11bc518a 100644--- a/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h+++ b/GeneralsMD/Code/Libraries/Source/WWVegas/WW3D2/ffprobe.h@@ -46,7 +46,11 @@ bool FixedFunctionProbe_Is_Enabled();void CombinerShaders_Enable(bool enabled);bool CombinerShaders_Are_Enabled();-// One draw call's worth: reads the stage combiners and the pixel-affecting render states off the+// Counts one draw and says whether it is one of the draws the probe reads, one in sixteen. Asked+// before Record so that a caller owing the device state sends it only for those.+bool FixedFunctionProbe_Samples_Draw();++// One sampled draw's worth: reads the stage combiners and the pixel-affecting render states off the// device and counts the combination.void FixedFunctionProbe_Record(IDirect3DDevice9 * device);diff --git a/dx11-check.ps1 b/dx11-check.ps1index b6b176479..20ff058b6 100644--- a/dx11-check.ps1+++ b/dx11-check.ps1@@ -51,7 +51,7 @@# by design and this script would be measuring the effect rather than the backend. Its own before# and after is a pair of pictures.param([double]$Margin = 1.0, [double]$MeanMargin = 1.0, [string]$Map = '',- [switch]$BackendNoise, [switch]$CountRule, [string[]]$Extra = @())+ [switch]$BackendNoise, [switch]$CountRule, [string[]]$Extra = @(), [string]$Exe = 'generals.exe')$env:ZH_UNATTENDED = "1" # every game this starts is unattended: no box may wait on a person (EarlyCommandLine.h)Add-Type -AssemblyName System.Drawing@@ -84,7 +84,7 @@ function Shoot($c, $tag, $switches) {'-msaa','0','-dx11post','off','-map',"`"Maps\$($c.map)\$($c.map).map`"",'-autoskirmish','4','-aidiff','easy','-seed','5','-maxframes',($c.f+80),'-screenshot',$c.f,'-camera',$c.x,$c.y,'-logPrefix',"dx11chk_$tag`_",'-turbo') + $switches + $Extra- $process = Start-Process (Join-Path $run 'generals.exe') -ArgumentList $arguments -WorkingDirectory $run -PassThru+ $process = Start-Process (Join-Path $run $Exe) -ArgumentList $arguments -WorkingDirectory $run -PassThrutry {$process.PriorityClass = 'AboveNormal'$null = $process.WaitForExit(900000)