Zero Hour rebuilt from EA's source: x64, Direct3D 11, VS2022/CMake, ~60 original bugs fixed, an AI that builds a base. Bring your own game.
C++ cmakecnccommand-and-conquercppdirectx11game-enginegame-preservationgeneralsrtssage-enginex64zero-hour
feat(gameengine): network matches run the tick beside the render
Olcay Seygan17db1390426d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 42960cda2..0dc0960e3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -275,7 +275,7 @@ found and fixed, EA's own, not port damage.**- Mission timers keep EA's clock. A map's countdown still ticks 30 times a second, because the missions read a running timer's number and act on it: the second American mission declares victory when its "Win" timer drops below 1700, and on the first 60-step builds that came after 38 seconds instead of 10. The cutscene cues, the random music pick in the campaigns and the generals' challenges, the shell map's camera loop and the lightning on Eastern Everglades and Rocky Rampage were off the same way, 30 maps in all, and run on their original timing again. Custom maps get the same.- Normal speed is 60 steps a second. Turbo mode, the one other speed a match can have, runs 120 of the same steps a second (see Turbo mode above). Replays still play as fast as you ask.- On a screen faster than 60 Hz the armies glide. The battle moves in 60 steps a second, so a 144 or 240 Hz monitor showed every step two to four times over and a tank crossing the map moved in small hops. Now each picture draws every unit part of the way between its last two steps. The picture runs one step, 16.7 ms, behind the battle; the battle itself does not change, and a replay drawn with it, without it and with no picture at all ends on the same checksum. A 60 Hz screen gets nothing it did not have. `-nosmoothmotion` turns it off for a run, `-smoothmotion` turns it on whatever the screen.-- The battle's arithmetic runs on a thread of its own, beside the drawing, on Windows. The game used to work out a step and then draw, one after the other, so a heavy step stalled the picture; now the screen keeps drawing while the next step is worked out, which pays most in the late game, where the steps are heaviest. In a late 4-player match, uncapped, frames slower than 16.7 ms (one 60 Hz refresh) fell from 23% to 0.8%, the slowest one frame in a hundred fell from 24.0 to 16.5 ms live and from 16.0-16.5 to 10.6-12.5 ms in a replay, and the average frame went from 15.2 to 11.8 ms. The battle still takes 60 steps a second, no more and no fewer. A match too heavy for its clock used to pay for the thread: the catch-up steps after the picture ignored the step already run beside it, so each frame ran one step more than without the thread. Eight Hard AIs on Twilight Flame at minute 20, run at four times normal speed so they cannot keep up: one frame in a thousand took 26.8 ms with the thread and 24.0 without. Both now spend the same budget, and with the thread that frame is 21.5 ms and the average frame 11.9 ms against 13.9 without, at 12% more steps a second. No menu or saved setting turns the thread off; `-logicthread 0` stays on the command line to chase a desync, and Mac and Linux keep the old order for now. Network games use the thread too, but the picture still waits for each step, so they do not overlap yet. Their machines compare checksums every 10 steps where they used to compare every step, so nine steps in ten skip a pass over the whole world, and a desync is caught at most 10 steps late.+- The battle's arithmetic runs on a thread of its own, beside the drawing, on Windows. The game used to work out a step and then draw, one after the other, so a heavy step stalled the picture; now the screen keeps drawing while the next step is worked out, which pays most in the late game, where the steps are heaviest. In a late 4-player match, uncapped, frames slower than 16.7 ms (one 60 Hz refresh) fell from 23% to 0.8%, the slowest one frame in a hundred fell from 24.0 to 16.5 ms live and from 16.0-16.5 to 10.6-12.5 ms in a replay, and the average frame went from 15.2 to 11.8 ms. The battle still takes 60 steps a second, no more and no fewer. A match too heavy for its clock used to pay for the thread: the catch-up steps after the picture ignored the step already run beside it, so each frame ran one step more than without the thread. Eight Hard AIs on Twilight Flame at minute 20, run at four times normal speed so they cannot keep up: one frame in a thousand took 26.8 ms with the thread and 24.0 without. Both now spend the same budget, and with the thread that frame is 21.5 ms and the average frame 11.9 ms against 13.9 without, at 12% more steps a second. No menu or saved setting turns the thread off; `-logicthread 0` stays on the command line to chase a desync, and Mac and Linux keep the old order for now. Network games now draw beside the step as well. Two seats at 240 ms of ping and 5% packet loss, with 400 units fighting: one frame in a thousand went from 18.5-21.5 ms to 10.3-12.5, one in a hundred from 13.0-14.8 to 8.3-9.0, and frames over 16.7 ms from 44-95 a match to 6-9. An order reaches the battle and the screen as fast as it did, and a seat with the thread off still agrees with one that has it on. A seat whose drawing takes longer than a step keeps the old order, so a slow graphics card holds the room no lower than before. Network machines compare checksums every 10 steps where they used to compare every step, so nine steps in ten skip a pass over the whole world, and a desync is caught at most 10 steps late.- That thread went off after 3.3.0, whose crash reports traced the random crashes in the middle of a match to the drawing and the battle writing to the same memory at the same moment. It is back because those collisions are closed. A model or animation the battle loads for the first time now waits for the picture to finish, the trees a unit pushes through move between frames, the team colours and the list of every object stay put while a picture is drawn, and the shadows thrown on units stop asking the battle where things stand while it is moving them. The test that decided it is a 4-against-4 match of 18000 steps, drawn with the thread on, drawn with it off and run with no picture at all, ending on the same checksum each time with the counter that flags the drawing reading the battle at zero.- Opening the pause menu no longer makes boats snap to a different angle or parked aircraft sink into the carrier deck. Boats keep their rocking angle and aircraft remain above the deck while the game is paused.- Replays and games saved in the middle of a match from earlier versions will not load in this one. The "Mission Start" saves a campaign makes between missions do, and every campaign mission can be picked from the campaign menu. A player on an earlier version cannot join a match with a player on this version, whichever of them hosts, so a LAN party needs everyone on the same build.diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex 874fbb676..77f8f22fb 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -3051,19 +3051,30 @@ void GameEngine::planLogicPass( LogicPassPlan &plan )/* LOGIC-THREAD.md phase 3, step 3b. The pass that overlaps: the client update up to the draw, thenhere the message stream and the pacer, which a pass that does not overlap runs after the clientupdate; then the draw's sync point, and the tick goes to the logic thread as the overlap window- opens (LogicThread::OverlapWindow). A network game keeps its own order, the network's update- between the message stream and the tick, and stays serialised until phase 5. So does a -video pass:+ opens (LogicThread::OverlapWindow). A network game keeps its own order (phase 5), the network's+ update between the message stream and the pacer that asks it whether a frame is ready, and the+ catch-up ticks after the draw stay serialised with both in front of each. A -video pass stays out:planned here, the pacer moved the -recordfps picture on in front of the draw, and the picture thatshould have opened the next frame was drawn on the old one, numbered as a picture already taken anddropped: one picture of every recorded frame, half of them at -recordfps 120. A tick beside thedraw would move the frame the picture is numbered by while it is drawn. */Bool GameEngine::planOverlappedTick( void ){- if (TheNetwork != NULL || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame()+ if (!TheGameLogic->isInGame() || TheGameLogic->isInShellGame()|| TheGameLogic->isLoadingMap() || isVideoPass())return FALSE;+#ifdef DEBUG_CRC+ // VERIFY_CRC's two CRCs stand round the client update, and a tick beside its draw would be inside them+ if (g_verifyClientCRC)+ return FALSE;+#endifTheMessageStream->propagateMessages();+ // Alt-F4's instant quit clears the game from inside the message stream, the network with it+ if (!TheGameLogic->isInGame())+ return FALSE;+ if (TheNetwork != NULL)+ TheNetwork->UPDATE();planLogicPass( s_passPlan );s_passPlanned = TRUE;s_frameBeforeOverlap = TheGameLogic->getFrame();@@ -3144,11 +3155,18 @@ void GameEngine::update( void )? (Int)( now % ( TheGlobalData->m_drawDelayJitterMS + 1 ) ) : 0;sleepMilliseconds( TheGlobalData->m_drawDelayMS + jitter );}- // planOverlappedTick ran it in front of the draw on a pass that may overlap+ /* A network frame that comes due during a short draw waits for the next pass's sync point, a+ millisecond away, and runs beside the next render. One that comes due during a long draw+ is asked for now: left to the next pass, this pass ran no frame at all, the rate this+ machine reports fell, and a seat drawing 130 ms took the room from 22 frames a second to 14. */+ if (s_passPlanned && TheNetwork != NULL && !(s_passPlan.mayRun && s_passPlan.due)+ && Clock_Milliseconds() - s_planTimeMs > 1000u / TheNetwork->getFrameRate())+ s_passPlanned = FALSE;+ // planOverlappedTick ran these two in front of the draw on a pass that may overlapif (!s_passPlanned)TheMessageStream->propagateMessages();- if (TheNetwork != NULL)+ if (TheNetwork != NULL && !s_passPlanned){TheNetwork->UPDATE();}diff --git a/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp b/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cppindex 0f2bffbb2..cb61e5e4b 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/System/ControlServer.cpp@@ -32,6 +32,7 @@#include "Common/GameEngine.h"#include "Common/GameState.h"#include "Common/GlobalData.h"+#include "Common/LogicThread.h"#include "Common/MessageStream.h"#include "Common/Money.h"#include "Common/Player.h"@@ -700,6 +701,8 @@ static void handleCommand( const AsciiString &command )if (command == "quit"){+ // a driven run never reaches the unattended report: net_check reads the census from here+ LogicThread::report();theQuitRequested = TRUE;replyOk( "\"quitting\":true" );return;diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/BeaconClientUpdate.cppindex f83efe35d..b0900f228 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/Drawable/Update/BeaconClientUpdate.cpp@@ -33,6 +33,7 @@#include "GameClient/Drawable.h"#include "GameClient/ParticleSys.h"#include "GameClient/Module/BeaconClientUpdate.h"+#include "Common/LogicThread.h"#include "Common/Player.h"#include "Common/PlayerList.h"#include "Common/Radar.h"@@ -127,6 +128,10 @@ static ParticleSystem* createParticleSystem( Drawable *draw )//-------------------------------------------------------------------------------------------------void BeaconClientUpdate::hideBeacon( void ){+ // the tick's beacon messages call this, and it stops a live particle system; a beacon destroyed by+ // the same tick has its drawable until the flush has run this+ LOGIC_AFTER_TICK( [this]() { hideBeacon(); } );+Drawable *draw = getDrawable();if (draw){diff --git a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cppindex 63ce0fbac..deef1f9ed 100644--- a/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameLogic/ScriptEngine/VictoryConditions.cpp@@ -199,8 +199,8 @@ void VictoryConditions::update( void )if (TheGameLogic->getFrame() > 1){ThePartitionManager->revealMapForPlayerPermanently( p->getPlayerIndex() );- TheGameClient->updateFakeDrawables();-+ LogicThread::callAfterTick( []() { TheGameClient->updateFakeDrawables(); } );+UnicodeString defeated;defeated.format( TheGameText->fetch( "GUI:PlayerHasBeenDefeated" ), p->getPlayerDisplayName().str() );TheInGameUI->playerMessage( p, defeated );@@ -226,7 +226,8 @@ void VictoryConditions::update( void )// destroy any remaining units (infantry if its a short game, for example)p->killPlayer();- PopulateInGameDiplomacyPopup();+ // it writes the tab screen's windows, which the render draws beside the tick+ LogicThread::callAfterTick( []() { PopulateInGameDiplomacyPopup(); } );}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cppindex f7e9ca0b2..56701d819 100644--- a/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameNetwork/Network.cpp@@ -46,6 +46,7 @@#include "strtok_r.h"#include "GameClient/Shell.h"#include "Common/CRCDebug.h"+#include "Common/LogicThread.h"#include "GameLogic/GameLogic.h"#include "Common/RandomValue.h"@@ -390,7 +391,9 @@ void Network::setSawCRCMismatch( void )m_sawCRCMismatch = TRUE;TheScriptActions->closeWindows( TRUE );- m_messageWindow = TheWindowManager->winCreateFromScript("Menus/CRCMismatch.wnd");+ // the tick calls this, beside the render: the window list is the render's until the flush, which+ // runs this behind closeWindows' destroy+ LogicThread::callAfterTick( [this]() { m_messageWindow = TheWindowManager->winCreateFromScript("Menus/CRCMismatch.wnd"); } );TheScriptEngine->startEndGameTimer();TheRecorder->logCRCMismatch();diff --git a/GeneralsMD/Code/Tools/net_check.py b/GeneralsMD/Code/Tools/net_check.pyindex c6cff1b3a..ade0e2d1b 100644--- a/GeneralsMD/Code/Tools/net_check.py+++ b/GeneralsMD/Code/Tools/net_check.py@@ -19,6 +19,7 @@ detector did not fire, which is the failure then). docs: the multiplayer referenimport argparseimport os+import reimport shleximport subprocessimport sys@@ -35,6 +36,7 @@ MATCH_START_TIMEOUT_SECONDS = 180.0PRESS_INTERVAL_SECONDS = 0.5PRESSES = ("KEY_A CTRL", "KEY_X", "KEY_S", "KEY_X")MISMATCH_LINE = "CRC Mismatch"+CENSUS_LINES = ("HEADLESS LOGICTHREAD OVERLAP", "HEADLESS LOGICTHREAD CENSUS", "HEADLESS LOGICTHREAD WINDOW")LOGIC_FPS = 60 # LOGICFRAMES_PER_SECOND: frame numbers here and in the logs count thesePROVE_FRAME = 10 * LOGIC_FPSPROVE_SPAWN = "spawn 0 AmericaVehicleHumvee 2 %s"@@ -102,6 +104,20 @@ def count_mismatches(log_path: str) -> int:return sum(MISMATCH_LINE in line for line in log)+def report_census(log_path: str) -> int:+ """Print the thread's report, which a copy writes on "quit", and return how many of its counts are not 0."""+ if not os.path.exists(log_path):+ return 0+ with open(log_path, "r", errors="replace") as log:+ lines = [line.strip() for line in log if line.startswith(CENSUS_LINES)]+ for line in lines:+ print(" " + line)+ if not lines:+ print(" no thread report: the copy never took the quit")+ return sum(count != "0" for line in lines if not line.startswith(CENSUS_LINES[0])+ for count in re.findall(r"[|:] \w+ (\d+)", line))++def play(arguments: argparse.Namespace, games: list) -> list:"""Press keys until every copy passes the target frame; returns (first frame, frame, seconds) per copy."""start = [game.status()["frame"] for game in games]@@ -157,17 +173,19 @@ def main() -> int:process.kill()total = 0+ reads = 0for slot, (first, last, seconds) in enumerate(results):log_path = os.path.join(RUN_DIRECTORY, "%s%d_DebugLogFile.txt" % (arguments.tag, slot))mismatches = count_mismatches(log_path)total += max(mismatches, 0)print("NET CHECK slot %d: frame %d, %.1f logic fps, %s mismatches, %s"% (slot, last, (last - first) / seconds, "no log" if mismatches < 0 else mismatches, log_path))+ reads += report_census(log_path)if arguments.prove:print("NET CHECK: detector %s" % ("fired" if total else "DID NOT FIRE"))return 0 if total else 1- print("NET CHECK: %s" % ("agreed" if total == 0 else "DESYNC"))- return 0 if total == 0 else 1+ print("NET CHECK: %s, %d census or window counts not 0" % ("agreed" if total == 0 else "DESYNC", reads))+ return 0 if total == 0 and reads == 0 else 1if __name__ == "__main__":