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(gameclient): director record mode with split screen
Olcay Seygan1fd1c8323f4f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e0b06173e..e8d2c67a8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -748,6 +748,7 @@ A third pass went through the generals' powers, promotions and unit abilities.- Watching, the bars over the buildings are everyone's too - what each factory is turning out, and how long the superweapons have left. An observer used to see none of it.- Watching, the camera can drive itself. Two drop-downs in the camera panel on the right, above the board, say who has it and which player you follow, and you can follow nobody. The Director goes to the fight with the most on the line over the last five seconds, where a dead Overlord counts for more than six riflemen being shot at and anything happening to a superweapon counts three times over. It stays with that fight twelve seconds, leaves after six only for one four times the size, and after half a minute on the same fight a third bigger is enough. So a 4v4 is watched like a broadcast rather than hunted for, and it does not hop between spots every few seconds. Any general's power used on the map outranks every fight. A nuke is shown in its silo as it leaves, then the camera waits at the target for it to come down and stays through the blast. The particle cannon's beam is followed along its whole sweep, and a Scud Storm or a carpet bomb is watched until the last explosion has died down. Then it goes back to the fighting. The camera glides between places and slows into each one, and only cuts when the next one is across most of the map. When nobody is shooting it no longer parks on empty ground: it goes round what is worth seeing, an army on the march, a superweapon, a base going up, the rest of a base, the dearest first and fourteen seconds each, and does not come back to one of the last three while there is anything else to show. With a player picked it keeps to his fights and his own armies and buildings. Player camera shows his screen: a human player's camera comes over the network five times a second, smoothed in between, and a computer player, who has no camera, gets the Director narrowed to his own fights. Scroll with the keys or a drag, turn the view or click the radar and the camera is yours again, still following the same player. The edge of the screen does not scroll while it drives: the panel on the right stands on that edge, and reaching for it used to hand the camera back to you, so the Director stopped following the fighting the first time you went to change a setting. In a replay with the recorded camera switched on in the options, the player you follow still drives the camera the way his button in the old list did.- Watching, the Director climbs over a wide battle until the whole of it is on the screen, and comes back down to your own height when it moves on or you take the camera. The mouse wheel still zooms while it drives, and it keeps what you chose. It stops short of the map's border too, where a fight on the edge used to come with a black corner of nothing beside it. A nuke or a Scud Storm is shown leaving its silo even when the Director has only just arrived at another fight; before, the launch was over by the time it was allowed to move. Rewinding a replay leaves your camera settings as they were, where a rewind used to hand you back a free camera with nobody followed. And following one player while a superweapon wiped out everything he had at the spot could close the game. It no longer does.+- Watching can be filmed. Start the game with `-directorrecord` and the Director has the camera from the first second, with nothing over the picture but the radar, and the whole match goes into one video; the game closes itself when the match is decided or the replay runs out. Beside `-replay` it turns an old match into footage, and beside four computer players it films a match nobody played. When two real fights far apart are both worth watching, the picture splits along a line leaning a little off upright, one fight on each side with its own camera gliding to it, and the radar moves to the middle of the line. A split holds at least six seconds and ends once the second fight has burnt down to a quarter of the first, so the picture does not flicker between one and two. Only the video shows the split; the window keeps the Director's own fight. Two bases going up are not a fight, and the split ends the moment the camera's own fight and the second one turn out to be the same. The pictures go straight into ffmpeg as they are drawn, so an hour of 1080p does not need tens of gigabytes of disk first; put ffmpeg beside the game or on your PATH, because without it nothing is recorded and the game says so and closes. Any recorded clip also plays its animations at their real speed now. The animation clock used to move by however long each picture took to save, and a slow disk made every explosion in the footage run fast.- Watching, tick Fog of war under the camera and you see what the player you follow sees and nothing more: black where he has never been, grey where he has been, none of the enemy he cannot see, and an enemy base as he last saw it. Stealth goes by his eyes too: a Jarmen Kell he has not found is gone from the screen and the radar, and his own stealthed units show the way they show him. It stays on whoever drives the camera, until you switch it off or follow nobody. Switch to another player and his fog comes in whole, shadows included: a building he has never seen casts nothing on his grey ground. An observer used to have no fog at all: the whole map, all match, with no way to see the game the way one of its players was seeing it.- An ally, and anyone watching, now sees a stealthed unit's muzzle flash, its promotion and the cash it earns - if they can see the unit at all. Those three asked 'is it mine' instead of 'can I see it', so allies and observers got nothing.- Watching, the match opens on the middle of the map. An observer has no start position, so the game looked for the camera waypoint of "player zero", did not find it, and fell back to the corner of the map: every match watched from the stands began pointed at empty ground in the south west.@@ -1083,7 +1084,7 @@ A third pass went through the generals' powers, promotions and unit abilities.- The whole map is drawn out to its edges from wherever the camera is. The usual view draws the ground and the shadows the camera can see from above; aimed at the horizon, the old limits cut the world off a short way out and left the far half of a map dark and shadowless. In the freecam the shadows cover the whole map, with a shadow map four times as wide so the far ones are as sharp as the near ones.- The match carries on underneath, and the fog of war stays as it is: the camera sees what you could already see. It changes nothing in the battle, so it works in replays and in multiplayer too.- `freecam 1200 900 600 45 -30` flies straight to a spot: the position, then the heading and the tilt in degrees. Leaving the freecam prints where it was in that same form, so a good angle can be found again.-- `director` in the console hands an observer's camera to the director on the Classic interface too, where there is no spectator page to pick it from, and `director` again takes it back. `hidehud` takes the whole interface off the screen in any match or replay and brings it back the next time you type it.+- `director` in the console hands an observer's camera to the director on the Classic interface too, where there is no spectator page to pick it from, and `director` again takes it back. `hidehud` takes the whole interface off the screen in any match or replay and brings it back the next time you type it. `hidehud showmap=true` leaves the radar standing in the bottom left corner while everything else goes, for a screenshot with the map in it.## A scoreboard on Tabdiff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 157cfa98f..f8f9b1ae3 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -477,6 +477,7 @@ public:Int m_videoStartFrame; ///< -video <from> <to> [name]: the first logic frame recordedInt m_videoEndFrame; ///< -video: the last logic frame recorded (0 = no video)AsciiString m_videoName; ///< -video: the recording is Videos\<name>.mp4 next to the save games+ Bool m_directorRecord; ///< -directorrecord [name]: the director films the whole match, split for two fights, and the run quits at its endInt m_wavStartFrame; ///< -wav <from> <to> [name]: the first logic frame of the sound recordingInt m_wavEndFrame; ///< -wav: the last logic frame recorded (0 = no sound recording)AsciiString m_wavName; ///< -wav: the recording is Videos\<name>.wav next to the save gamesdiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/CinemaDirector.h b/GeneralsMD/Code/GameEngine/Include/GameClient/CinemaDirector.hindex f428ff330..11861a9e6 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/CinemaDirector.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/CinemaDirector.h@@ -75,9 +75,11 @@ void CinemaDirector_routePoint( const Real *xs, const Real *ys, Int count, Real/// once a render pass, after the logic tickvoid CinemaDirector_update( void );-/// the console's hidehud: the interface off or back on without a shot list-void CinemaDirector_setHudHidden( Bool hidden );+/// the console's hidehud: the interface off or back on without a shot list, the radar kept in the+/// bottom left corner when showMap is set+void CinemaDirector_setHudHidden( Bool hidden, Bool showMap );Bool CinemaDirector_isHudHidden( void );+Bool CinemaDirector_showsMap( void );void CinemaDirector_forgetHudHidden( void );/// the interface is off, under -cinema or the console's freecam: nothing but the world is drawndiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/ObserverCamera.h b/GeneralsMD/Code/GameEngine/Include/GameClient/ObserverCamera.hindex ff98bf9ab..cd7cbd8f1 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/ObserverCamera.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/ObserverCamera.h@@ -129,6 +129,17 @@ Coord2D ObserverCamera_keepInMap( const Coord2D &place, const Coord2D *corners,/// it jumps there and stopsViewLocation ObserverCamera_approach( const ViewLocation &from, const ViewLocation &to, Real elapsedSeconds, Real smoothSeconds,Real topSpeed, ObserverCameraVelocity *velocity );+/// -directorrecord's second fight: the hottest place among the hits far enough from first that the+/// two halves of a split screen never show the same ground. FALSE when nothing that far was hit+Bool ObserverCamera_secondPlace( const std::vector< DirectorHeat > &hits, const Coord2D &first, Coord2D *place, Real *heat );+/// whether the recording's picture is split, given whether it is now, how far apart the two places+/// are and how long ago it last went on or off: on, after a rest, for a second fight that is big on+/// its own and next to a first one; off once it has been held a while and the second fight has burnt+/// down, and at once when the second fight is over or the two places come together+Bool ObserverCamera_holdSplit( Bool split, Real firstHeat, Real secondHeat, Real apart, UnsignedInt framesSince );+/// the column the split's divider crosses row y of a width by height picture at: through the middle,+/// leaning 12 degrees with its top to the right. Columns left of it are the first fight's+Int ObserverCamera_splitBoundary( Int y, Int width, Int height );class ObserverCamera{@@ -168,6 +179,14 @@ public:/// the watcher's own height back on the view, if the director had raised it over a fightvoid releaseHeight( void );+ /// -directorrecord: two fights far apart are recorded side by side. The frame is drawn twice, the+ /// second fight first and never presented, then the first; the recording joins the two halves+ Bool isSplit( void ) const { return m_split; }+ Bool isDrawingSecond( void ) const { return m_drawingSecond; }+ /// the view moved to the second fight for one draw, and put back after it+ void beginSecondPass( void );+ void endSecondPass( void );+enum { NO_PLAYER = -1 };private:@@ -176,6 +195,8 @@ private:void driveHeight( Real extra );Bool takenByHand( const ViewLocation ¤t ) const;Coord2D keepInMap( const Coord2D &place, const ViewLocation ¤t ) const;+ Coord2D screenQuarter( const ViewLocation ¤t ) const;+ void updateSplit( void );Bool isShowingPlayerView( void ) const;Bool chooseTarget( const ViewLocation ¤t, ViewLocation *target );Bool directorPlace( const Player *narrowTo, Coord2D *place );@@ -210,6 +231,16 @@ private:std::vector< Coord2D > m_seen; ///< the last few sights, oldest first, not gone back to while there is anotherstd::vector< DirectorEvent > m_events; ///< the special powers still worth watching, oldest firstUnsignedInt m_nextEventId;++ std::vector< DirectorHeat > m_fights; ///< the last scan's hits one player dealt another he is at war with; the split counts only these+ Bool m_split; ///< -directorrecord's picture is two fights side by side+ Bool m_splitCut; ///< the split just went on: the camera cuts to its place in the left half+ UnsignedInt m_splitChanged; ///< the logic frame the split last went on or off+ Coord2D m_secondPlace; ///< the second fight, shown in the right half+ ViewLocation m_secondView; ///< the right half's camera, gliding on its own+ ObserverCameraVelocity m_secondVelocity;+ ViewLocation m_firstView; ///< the camera's own place, put back after the right half is drawn+ Bool m_drawingSecond;};extern ObserverCamera TheObserverCamera;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cppindex 68c40c6e0..8e18d1637 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/CommandLine.cpp@@ -1532,6 +1532,41 @@ Int parseVideo(char *args[], int num)return consumed;}+/* -directorrecord [name]: film a whole match with the director camera, as Videos\<name>.mp4.+ *+ * -video records a range of frames from wherever the camera happens to be. This hands the camera+ * to the observer's director from the first frame, takes the interface off but for the radar, and+ * records from frame 1 until the match is decided or the replay runs out, then quits. When two+ * fights far apart are both worth watching, the picture splits down a leaning line, one fight a+ * half. It sets -observer, so an -autoskirmish run is watched rather than played; with -replay the+ * watcher is the replay's own. The name defaults to "director" and takes -video's rules. */+Int parseDirectorRecord(char *args[], int num)+{+ AsciiString name = "director";+ Int consumed = 1;+ if (num > 1 && args[1][0] != '-')+ {+ consumed = 2;+ if (isVideoNameUsable(args[1]))+ name = args[1];+ else+ DEBUG_LOG(("-directorrecord: '%s' is not a usable name (letters, digits, '-' and '_'), recording as %s\n",+ args[1], name.str()));+ }++ if (TheWritableGlobalData)+ {+ // no last frame: the run ends with the match, and the display's teardown finishes the movie+ const Int NO_LAST_FRAME = 0x3FFFFFFF;+ TheWritableGlobalData->m_directorRecord = TRUE;+ TheWritableGlobalData->m_videoStartFrame = 1;+ TheWritableGlobalData->m_videoEndFrame = NO_LAST_FRAME;+ TheWritableGlobalData->m_videoName = name;+ TheWritableGlobalData->m_autoSkirmishObserver = TRUE;+ }+ return consumed;+}+/* -wav <from> <to> [name]: record what the game sounds like over logic frames <from> to <to>.** A movie made by -video has no sound in it: the picture comes from a frame dump and the frames are@@ -2546,6 +2581,7 @@ static CommandLineParam params[] ={ "-screenshot", parseScreenShot },{ "-showHudOverlay", parseShowHudOverlay },{ "-video", parseVideo },+ { "-directorrecord", parseDirectorRecord },{ "-wav", parseWav },{ "-turbo", parseTurbo },{ "-msaa", parseMSAA },diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cppindex c85a11e90..8a66d775d 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GameEngine.cpp@@ -2305,7 +2305,7 @@ static void updateHeadlessRun( void )was here that run had to be -headless to end by itself, which is to say it could not bephotographed at all. */const Bool unattended = TheGlobalData->m_headless || TheGlobalData->m_autoSkirmishPlayers > 0 ||- !TheGlobalData->m_netGameHosts.isEmpty();+ !TheGlobalData->m_netGameHosts.isEmpty() || TheGlobalData->m_directorRecord;/* Except that a run with a control socket open is not unattended at all - somebody is drivingit from the other end, and tearing the process down the moment a match is decided takes the@@ -2313,6 +2313,25 @@ static void updateHeadlessRun( void )if (TheGlobalData->m_controlPort > 0)return;+ /* -directorrecord films one match. A replay that runs out, or a match that ends some other way+ than a decision, goes back to the shell, and the run ends there; the display's teardown+ finishes the movie. */+ static Bool directorRecordSawMatch = FALSE;+ if (TheGlobalData->m_directorRecord && !TheGameEngine->getQuitting())+ {+ const Bool inMatch = TheGameLogic->isInGame() && !TheGameLogic->isInShellGame();+ if (inMatch)+ {+ directorRecordSawMatch = TRUE;+ }+ else if (directorRecordSawMatch)+ {+ DEBUG_LOG(("-directorrecord: the match is over, quitting\n"));+ TheGameEngine->setQuitting( TRUE );+ return;+ }+ }+if (!unattended || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())return;@@ -2387,7 +2406,8 @@ static void updateHeadlessRun( void )/* A -video range that runs up to or past -maxframes keeps the run alive until its last picture isdrawn, which happens on the pass after the logic reaches that frame. */Int maxGameFrames = TheGlobalData->m_maxGameFrames;- if (maxGameFrames > 0 && !TheGlobalData->m_headless && TheGlobalData->m_videoEndFrame >= maxGameFrames)+ if (maxGameFrames > 0 && !TheGlobalData->m_headless && !TheGlobalData->m_directorRecord+ && TheGlobalData->m_videoEndFrame >= maxGameFrames)maxGameFrames = TheGlobalData->m_videoEndFrame + 1;if (maxGameFrames > 0)maxGameFrames += frameLimitOvershoot(); // a test's overshoot: 0 for every real rundiff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex f5a9b22ce..9f1c66eda 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -732,6 +732,7 @@ GlobalData::GlobalData()m_videoStartFrame = 0;m_videoEndFrame = 0; // record nothing unless -video asks for a rangem_videoName.clear();+ m_directorRecord = FALSE;m_wavStartFrame = 0;m_wavEndFrame = 0; // record no sound unless -wav asks for a rangem_wavName.clear();diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/CinemaDirector.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/CinemaDirector.cppindex b68b394a5..89a03b2a6 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/CinemaDirector.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/CinemaDirector.cpp@@ -364,6 +364,7 @@ static Bool theCinemaLoaded = FALSE;static std::vector<CinemaShot> theCinemaShots;static size_t theCinemaNext = 0;static Bool theCinemaHudHidden = FALSE;+static Bool theCinemaShowMap = FALSE; ///< the console's hidehud showmap: the radar stays in the bottom left cornerstatic Bool theCinemaLetterbox = FALSE;static Bool theCinemaFlying = FALSE; ///< a camera verb has run; until then the player has the camerastatic Real theCinemaBaseZoom = 1.0f;@@ -778,16 +779,20 @@ static void cinemaChase( Real now )cinemaCentreOn( theCinemaStillX, theCinemaStillY, obj->getPosition()->z );}-void CinemaDirector_setHudHidden( Bool hidden )+void CinemaDirector_setHudHidden( Bool hidden, Bool showMap ){cinemaSetHud( hidden );+ theCinemaShowMap = hidden && showMap;}/// the match is over and the next one builds its own bar, so the flag goes without touching the barvoid CinemaDirector_forgetHudHidden( void ){if (TheGlobalData->m_cinemaScript.isEmpty())+ {theCinemaHudHidden = FALSE;+ theCinemaShowMap = FALSE;+ }}Bool CinemaDirector_isHudHidden( void )@@ -795,6 +800,11 @@ Bool CinemaDirector_isHudHidden( void )return theCinemaHudHidden;}+Bool CinemaDirector_showsMap( void )+{+ return theCinemaHudHidden && theCinemaShowMap;+}+void CinemaDirector_update( void ){// the console's hidehud: no shot list, but the match still puts the bar back on its owndiff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cppindex d424644f8..d361d553d 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameClient.cpp@@ -934,6 +934,15 @@ void GameClient::update( void )Int64 drawStart, drawEnd;drawStart = Clock_Ticks();#endif+ /* -directorrecord with two fights on: the second fight is drawn first, for the recording+ only and never presented, then the frame everybody sees. W3D's clock stands still for+ a second draw on one client frame, so nothing animates twice. */+ if( TheObserverCamera.isSplit() )+ {+ TheObserverCamera.beginSecondPass();+ TheDisplay->DRAW();+ TheObserverCamera.endSecondPass();+ }TheDisplay->DRAW();#ifdef DEBUG_LOGGINGdrawEnd = Clock_Ticks();diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cppindex 2729de0e4..98ec107b1 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GameConsole.cpp@@ -286,7 +286,9 @@ static AsciiString runDirector( void )return result;}-static AsciiString runHideHud( void )+/** 'hidehud' toggles the interface; 'hidehud showmap=true' (or 'showmap true', or 'showmap') hides it+ * with the radar left in the bottom left corner, and 'showmap=false' is the plain hide. */+static AsciiString runHideHud( AsciiString arguments ){AsciiString result;if( !TheGameLogic->isInGame() || TheGameLogic->isInShellGame() )@@ -295,8 +297,32 @@ static AsciiString runHideHud( void )return result;}- const Bool hide = !CinemaDirector_isHudHidden();- CinemaDirector_setHudHidden( hide );+ Bool showMap = FALSE;+ if( !arguments.isEmpty() )+ {+ char text[ 64 ];+ strncpy( text, arguments.str(), sizeof( text ) - 1 );+ text[ sizeof( text ) - 1 ] = '\0';+ for( char *c = text; *c; ++c )+ if( *c == '=' )+ *c = ' ';++ char name[ 16 ], value[ 16 ] = "true";+ const Int given = sscanf( text, "%15s %15s", name, value );+ const AsciiString word( value );+ const Bool isTrue = word.compareNoCase( "true" ) == 0 || word.compareNoCase( "1" ) == 0;+ const Bool isFalse = word.compareNoCase( "false" ) == 0 || word.compareNoCase( "0" ) == 0;+ if( given < 1 || AsciiString( name ).compareNoCase( "showmap" ) != 0 || !( isTrue || isFalse ) )+ {+ result = "hidehud: takes nothing, or showmap=true to keep the radar in the bottom left corner";+ return result;+ }+ showMap = isTrue;+ }++ // with an argument it hides (again) with that setting, bare it toggles+ const Bool hide = arguments.isEmpty() ? !CinemaDirector_isHudHidden() : TRUE;+ CinemaDirector_setHudHidden( hide, showMap );result = hide ? "hud hidden; 'hidehud' again brings it back" : "hud shown";return result;}@@ -526,7 +552,7 @@ void GameConsole::runCommand( AsciiString commandLine )printLine( AsciiString( " Shift faster; Esc or 'freecam' again lands. 'freecam x y z heading tilt'" ) );printLine( AsciiString( " flies to a pose, angles in degrees" ) );printLine( AsciiString( "director observer: the director camera on, again gives the camera back" ) );- printLine( AsciiString( "hidehud the interface off, again brings it back" ) );+ printLine( AsciiString( "hidehud the interface off, again brings it back; showmap=true keeps the radar" ) );if( areCheatsAvailable() ){printLine( AsciiString( "cheats single-player cheats" ) );@@ -598,7 +624,7 @@ void GameConsole::runCommand( AsciiString commandLine )if( command == "hidehud" ){- printLine( runHideHud() );+ printLine( runHideHud( arguments ) );return;}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex e6fd203a8..d4b096354 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -4174,7 +4174,21 @@ void InGameUI::update( void )// a watcher's camera is driven for him while it is not in his own hands (ObserverCamera.h)if( TheGameLogic->isInGame() && localPlayerWatching() )- TheObserverCamera.update( cameraNowMs );+ {+ // -directorrecord: the director has the camera all match, nothing but the radar is over the+ // picture, and the glide runs on the logic clock, which is what each recorded picture is+ UnsignedInt observerNowMs = cameraNowMs;+ if( TheGlobalData->m_directorRecord && !TheGameLogic->isInShellGame() )+ {+ if( TheObserverCamera.getMode() != OBSERVER_CAMERA_DIRECTOR )+ TheObserverCamera.setMode( OBSERVER_CAMERA_DIRECTOR );+ if( !CinemaDirector_showsMap() )+ CinemaDirector_setHudHidden( TRUE, TRUE );+ TheMouse->setVisibility( FALSE );+ observerNowMs = TheGameLogic->getFrame() * 1000 / LOGICFRAMES_PER_SECOND;+ }+ TheObserverCamera.update( observerNowMs );+ }Real cameraSteps = 1.0f;if( m_cameraKeyLastMs != 0 )diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/ObserverCamera.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/ObserverCamera.cppindex 9ef5f96db..0496650af 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/ObserverCamera.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/ObserverCamera.cpp@@ -106,6 +106,19 @@ static const Real PLAYER_TOP_SPEED = 4000.0f;/// a frame longer than this is a hitch, and is not allowed to throw the camera across the mapstatic const UnsignedInt LONGEST_STEP_MILLISECONDS = 100;static const Real MILLISECONDS_PER_SECOND = 1000.0f;+/// -directorrecord: a second fight closer than this to the first shares its ground, and the split+/// would show one fight twice+static const Real SPLIT_APART = 3.0f * DIRECTOR_GATHER_RADIUS;+/// the picture splits for a second fight at least this hot, and at least this share of the first+static const Real SPLIT_ENTER_HEAT = 2.0f;+static const Real SPLIT_ENTER_SHARE = 0.5f;+/// a split stays this long at least, and after that while the second fight keeps this share+static const UnsignedInt SPLIT_HOLD_FRAMES = 6 * LOGICFRAMES_PER_SECOND;+static const Real SPLIT_STAY_SHARE = 0.25f;+/// once the picture is whole again it stays whole this long, so it does not flicker between the two+static const UnsignedInt SPLIT_REST_FRAMES = 4 * LOGICFRAMES_PER_SECOND;+/// how far the divider leans off the upright+static const Real SPLIT_LEAN_DEGREES = 12.0f;//-------------------------------------------------------------------------------------------------static Bool sameFight( const Coord2D &a, const Coord2D &b )@@ -363,6 +376,39 @@ ViewLocation ObserverCamera_approach( const ViewLocation &from, const ViewLocatireturn step;}+//-------------------------------------------------------------------------------------------------+Bool ObserverCamera_secondPlace( const std::vector< DirectorHeat > &hits, const Coord2D &first, Coord2D *place, Real *heat )+{+ std::vector< DirectorHeat > apart;+ for( size_t index = 0; index < hits.size(); index++ )+ {+ const Real dx = hits[ index ].position.x - first.x;+ const Real dy = hits[ index ].position.y - first.y;+ if( dx * dx + dy * dy > SPLIT_APART * SPLIT_APART )+ apart.push_back( hits[ index ] );+ }+ return ObserverCamera_hottestPlace( apart, place, heat );+}++//-------------------------------------------------------------------------------------------------+Bool ObserverCamera_holdSplit( Bool split, Real firstHeat, Real secondHeat, Real apart, UnsignedInt framesSince )+{+ // two halves of one fight, or a half with no fight left in it, is no split at all+ if( secondHeat <= 0.0f || apart <= SPLIT_APART )+ return FALSE;+ if( split )+ return framesSince < SPLIT_HOLD_FRAMES || secondHeat >= firstHeat * SPLIT_STAY_SHARE;+ return framesSince >= SPLIT_REST_FRAMES && firstHeat > 0.0f && secondHeat >= SPLIT_ENTER_HEAT+ && secondHeat >= firstHeat * SPLIT_ENTER_SHARE;+}++//-------------------------------------------------------------------------------------------------+Int ObserverCamera_splitBoundary( Int y, Int width, Int height )+{+ const Real lean = tanf( SPLIT_LEAN_DEGREES * PI / 180.0f );+ return (Int)floorf( width * 0.5f + ( height * 0.5f - y ) * lean + 0.5f );+}+//-------------------------------------------------------------------------------------------------ObserverCamera::ObserverCamera(){@@ -397,6 +443,15 @@ void ObserverCamera::reset( void )m_seen.clear();m_events.clear();m_nextEventId = 1;+ m_fights.clear();+ m_split = FALSE;+ m_splitCut = FALSE;+ m_splitChanged = 0;+ m_secondPlace.x = m_secondPlace.y = 0.0f;+ m_secondView = ViewLocation();+ m_secondVelocity.x = m_secondVelocity.y = m_secondVelocity.z = m_secondVelocity.angle = m_secondVelocity.pitch = m_secondVelocity.zoom = 0.0f;+ m_firstView = ViewLocation();+ m_drawingSecond = FALSE;}//-------------------------------------------------------------------------------------------------@@ -598,6 +653,81 @@ Coord2D ObserverCamera::keepInMap( const Coord2D &place, const ViewLocation &curreturn ObserverCamera_keepInMap( place, corners, 4, map );}+//-------------------------------------------------------------------------------------------------+/** A quarter of the screen's width on the ground, pointing right: moving the look point by it puts+ * what was in the middle of the screen in the middle of its left half. */+//-------------------------------------------------------------------------------------------------+Coord2D ObserverCamera::screenQuarter( const ViewLocation ¤t ) const+{+ const Coord3D &at = current.getPosition();+ Coord3D world[ 4 ];+ TheTacticalView->getScreenCornerWorldPointsAtZ( &world[ 0 ], &world[ 1 ], &world[ 2 ], &world[ 3 ],+ TheTerrainLogic->getGroundHeight( at.x, at.y ) );+ // the corners come top left, top right, bottom right, bottom left; the two edges across are averaged+ Coord2D quarter;+ quarter.x = ( world[ 1 ].x - world[ 0 ].x + world[ 2 ].x - world[ 3 ].x ) / 8.0f;+ quarter.y = ( world[ 1 ].y - world[ 0 ].y + world[ 2 ].y - world[ 3 ].y ) / 8.0f;+ return quarter;+}++//-------------------------------------------------------------------------------------------------+/** -directorrecord: whether the picture is split, and the second fight it shows. Asked again only+ * when the hits were counted again. Only real fighting counts, on both sides of the line: a base+ * going up, or a dozer clearing trees, is no reason to split. A special power the director is+ * showing counts as a fight beside it. */+//-------------------------------------------------------------------------------------------------+void ObserverCamera::updateSplit( void )+{+ const UnsignedInt frame = TheGameLogic->getFrame();+ Coord2D middle;+ Real firstHeat = ObserverCamera_heatAround( m_fights, m_place, &middle );+ if( m_placeKind == PLACE_EVENT )+ firstHeat = max( firstHeat, SPLIT_ENTER_HEAT );+ Coord2D second = { 0.0f, 0.0f };+ Real secondHeat = 0.0f;+ ObserverCamera_secondPlace( m_fights, m_place, &second, &secondHeat );++ // the second fight is followed once it has moved a little, the way the director follows its own+ Coord2D shown = m_secondPlace;+ const Real dx = second.x - m_secondPlace.x;+ const Real dy = second.y - m_secondPlace.y;+ if( !m_split || dx * dx + dy * dy > DIRECTOR_FOLLOW_SLACK * DIRECTOR_FOLLOW_SLACK )+ shown = second;+ const Real ax = shown.x - m_place.x;+ const Real ay = shown.y - m_place.y;+ const Real apart = sqrtf( ax * ax + ay * ay );++ const UnsignedInt since = frame >= m_splitChanged ? frame - m_splitChanged : 0;+ const Bool split = ObserverCamera_holdSplit( m_split, firstHeat, secondHeat, apart, since );+ if( split != m_split )+ {+ DEBUG_LOG(( "OBSCAM frame %u split %s, first heat %.1f, second (%.0f,%.0f) heat %.1f, %.0f apart\n", frame,+ split ? "on" : "off", firstHeat, shown.x, shown.y, secondHeat, apart ));+ m_split = split;+ m_splitChanged = frame;+ // both halves cut to their places rather than gliding in from the middle of the screen+ m_splitCut = split;+ m_secondView = ViewLocation();+ }+ if( m_split )+ m_secondPlace = shown;+}++//-------------------------------------------------------------------------------------------------+void ObserverCamera::beginSecondPass( void )+{+ TheTacticalView->getLocation( &m_firstView );+ TheTacticalView->setLocation( &m_secondView );+ m_drawingSecond = TRUE;+}++//-------------------------------------------------------------------------------------------------+void ObserverCamera::endSecondPass( void )+{+ TheTacticalView->setLocation( &m_firstView );+ m_drawingSecond = FALSE;+}+//-------------------------------------------------------------------------------------------------Bool ObserverCamera::takenByHand( const ViewLocation ¤t ) const{@@ -634,6 +764,7 @@ Bool ObserverCamera::directorPlace( const Player *narrowTo, Coord2D *place )m_placeScanned = frame;std::vector< DirectorHeat > hits;+ std::vector< DirectorHeat > fights;std::vector< DirectorHeat > sights;for( Object *obj = TheGameLogic->getFirstObject(); obj != NULL; obj = obj->getNextObject() ){@@ -665,7 +796,18 @@ Bool ObserverCamera::directorPlace( const Player *narrowTo, Coord2D *place )heat.weight = ObserverCamera_hitWeight( cost, obj->isEffectivelyDead(), superweapon );hits.push_back( heat );++ // -directorrecord's split counts a hit only when one player dealt it to another he is at war+ // with: a tree a dozer cleared, or a building's own wear, is no fight+ const PlayerMaskType sourceMask = body->getLastDamageInfo()->in.m_sourcePlayerMask;+ const Player *victim = obj->getControllingPlayer();+ if( sourceMask == 0 || victim == NULL || ( sourceMask & victim->getPlayerMask() ) != 0 )+ continue;+ const Player *source = ThePlayerList->getPlayerFromMask( sourceMask );+ if( source != NULL && victim->getRelationship( source->getDefaultTeam() ) == ENEMIES )+ fights.push_back( heat );}+ m_fights = fights;Coord2D hottest;Real hottestHeat = 0.0f;@@ -785,6 +927,7 @@ Bool ObserverCamera::chooseTarget( const ViewLocation ¤t, ViewLocation *taif( isShowingPlayerView() ){+ m_split = FALSE;*target = m_playerViews[ m_followed ];return TRUE;}@@ -794,6 +937,15 @@ Bool ObserverCamera::chooseTarget( const ViewLocation ¤t, ViewLocation *taCoord2D place;if( !directorPlace( narrowTo, &place ) )return FALSE;+ if( TheGlobalData->m_directorRecord && m_placeScanned == TheGameLogic->getFrame() )+ updateSplit();+ // split, the first fight goes in the middle of the left half+ if( m_split )+ {+ const Coord2D quarter = screenQuarter( current );+ place.x += quarter.x;+ place.y += quarter.y;+ }place = keepInMap( place, current );target->init( place.x, place.y, at.z, current.getAngle(), current.getPitch(), current.getZoom() );return TRUE;@@ -810,6 +962,7 @@ void ObserverCamera::update( UnsignedInt nowMilliseconds )if( m_mode == OBSERVER_CAMERA_FREE ){m_driving = FALSE;+ m_split = FALSE;holdHeight( FALSE );releaseHeight();return;@@ -823,6 +976,7 @@ void ObserverCamera::update( UnsignedInt nowMilliseconds )DEBUG_LOG(( "OBSCAM frame %u the watcher took the camera\n", TheGameLogic->getFrame() ));m_mode = OBSERVER_CAMERA_FREE;m_driving = FALSE;+ m_split = FALSE;holdHeight( FALSE );releaseHeight();return;@@ -832,6 +986,7 @@ void ObserverCamera::update( UnsignedInt nowMilliseconds )if( !chooseTarget( current, &target ) ){m_driving = FALSE;+ m_split = FALSE;holdHeight( FALSE );releaseHeight();return;@@ -844,15 +999,41 @@ void ObserverCamera::update( UnsignedInt nowMilliseconds )elsedriveHeight( m_placeHeight );holdHeight( isShowingPlayerView() );- if( !m_driving )+ // a split going on cuts the camera to its place in the left half: gliding there would carry the+ // fight out of the middle of the screen and across the line for a second+ if( !m_driving || m_splitCut )m_velocity.x = m_velocity.y = m_velocity.z = m_velocity.angle = m_velocity.pitch = m_velocity.zoom = 0.0f;const Bool player = m_mode == OBSERVER_CAMERA_PLAYER;- const ViewLocation step = ObserverCamera_approach( current, target, elapsed / MILLISECONDS_PER_SECOND,+ const ViewLocation step = m_splitCut ? target : ObserverCamera_approach( current, target, elapsed / MILLISECONDS_PER_SECOND,player ? PLAYER_PAN_SECONDS : DIRECTOR_PAN_SECONDS, player ? PLAYER_TOP_SPEED : DIRECTOR_TOP_SPEED, &m_velocity );+ m_splitCut = FALSE;TheTacticalView->setLocation( &step );// the view keeps its look point inside its constraint when it draws; held there now, a cut to a// place past the constraint is not mistaken next frame for the watcher moving the cameraTheTacticalView->applyCameraConstraint();TheTacticalView->getPosition( &m_drivenTo );m_driving = TRUE;++ // the right half's camera glides to the second fight on its own, the second fight in the middle+ // of the right half, and takes everything but the place from the camera's own step+ if( !m_split )+ return;+ const Coord2D quarter = screenQuarter( step );+ Coord2D place;+ place.x = m_secondPlace.x - quarter.x;+ place.y = m_secondPlace.y - quarter.y;+ place = keepInMap( place, step );+ const Coord3D &at = step.getPosition();+ ViewLocation secondTarget;+ secondTarget.init( place.x, place.y, at.z, step.getAngle(), step.getPitch(), step.getZoom() );+ if( !m_secondView.isValid() )+ {+ m_secondVelocity.x = m_secondVelocity.y = m_secondVelocity.z = m_secondVelocity.angle = m_secondVelocity.pitch = m_secondVelocity.zoom = 0.0f;+ m_secondView = secondTarget;+ return;+ }+ const ViewLocation glide = ObserverCamera_approach( m_secondView, secondTarget, elapsed / MILLISECONDS_PER_SECOND,+ DIRECTOR_PAN_SECONDS, DIRECTOR_TOP_SPEED, &m_secondVelocity );+ const Coord3D &glidedTo = glide.getPosition();+ m_secondView.init( glidedTo.x, glidedTo.y, at.z, step.getAngle(), step.getPitch(), step.getZoom() );}diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cppindex b026aaf5b..c6783b10d 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DDisplay.cpp@@ -83,6 +83,7 @@ static void drawFramerateBar(void);#include "GameClient/GraphDraw.h"#include "GameClient/Line2D.h"#include "GameClient/Mouse.h"+#include "GameClient/ObserverCamera.h"#include "GameClient/GlobalLanguage.h"#include "GameClient/Water.h"@@ -2155,6 +2156,7 @@ DECLARE_PERF_TIMER(W3DDisplay_draw)static Bool s_screenShotPending = FALSE; // F12 pressed: save the frame at the end of the next draw()static void saveScreenShot(void);static void captureVideoFrame(void);+static Bool videoRecordingFrame(void);#ifdef DEBUG_LOGGING//@@ -2448,6 +2450,10 @@ AGAIN:prevSyncMs = nowSyncMs;if (deltaMs > TheW3DFrameLengthInMsec * 4)deltaMs = TheW3DFrameLengthInMsec * 4; // a level load must not fast-forward everything+ // a recorded picture is one logic frame however long it took to draw and save, so the clock+ // moves one logic frame too, or the footage plays every animation fast+ if (videoRecordingFrame())+ deltaMs = TheW3DFrameLengthInMsec;syncTime += deltaMs;// allow W3D to update its internals@@ -2704,8 +2710,9 @@ AGAIN:saveScreenShot();}captureVideoFrame();- // render is all done!- WW3D::End_Render();+ // render is all done! -directorrecord's second fight is for the recording only and is+ // never presented: the frame drawn next over it is+ WW3D::End_Render(!TheObserverCamera.isDrawingSecond());/* A pipeline is compiled and a texture copied the first time it reaches a Direct3D 11draw, which is the frame a new explosion first shows up on. A frame that spent more@@ -3784,7 +3791,8 @@ static void CreateBMPFile(char *pszFile, char *image, Int width, Int height)// the image's own 3 * width * height bytes are read. The Windows writer this replaces sized the image// (width + 7) / 8 * height * 24 bytes and wrote that many out of a 3 * width * height buffer: past its// end whenever the width is not a multiple of 8 (a 1366-wide screen), and with unpadded rows, so a- // skewed picture, whenever it is not a multiple of 4 (port defect 18).+ // skewed picture, whenever it is not a multiple of 4 (port defect 18). The image comes top row+ // first, the way the screen is read, and the file takes the bottom row first.FILE *fp = zh_fopen(pszFile, "wb");if (fp == NULL)return;@@ -3809,7 +3817,7 @@ static void CreateBMPFile(char *pszFile, char *image, Int width, Int height)Put::u32(header + 34, imageBytes);fwrite(header, 1, sizeof(header), fp);static const unsigned char pad[3] = { 0, 0, 0 };- for (Int row = 0; row < height; ++row) {+ for (Int row = height - 1; row >= 0; --row) {fwrite(image + row * rowBytes, 1, rowBytes, fp);fwrite(pad, 1, stride - rowBytes, fp);}@@ -3872,9 +3880,10 @@ void W3DDisplay::takeScreenShot(void)s_screenShotPending = TRUE;}-/** Write the frame being drawn to pathname. FALSE when there was no picture to read, which is what- * a device that has gone away gives. Runs before End_Render, while the back buffers still hold it. */-static Bool writeFrameBMP(char *pathname)+/** The frame being drawn, as blue-green-red bytes, top row first, width * 3 bytes a row, in a buffer+ * the caller deletes. NULL when there was no picture to read, which is what a device that has gone+ * away gives. Runs before End_Render, while the back buffers still hold it. */+static char *captureFrameRows(Int *rowsWidth, Int *rowsHeight){// With -dx11present the picture on the screen is the Direct3D 11 one, so that is what a// screenshot has to be: reading the D3D9 back buffer here would photograph a frame nobody saw@@ -3888,13 +3897,12 @@ static Bool writeFrameBMP(char *pathname)unsigned char *captured =Direct3D11_Capture_Back_Buffer(captureWidth, captureHeight, capturePitch);if (captured == NULL)- return FALSE;+ return NULL;char *rows = NEW char[3*captureWidth*captureHeight];for (unsigned row = 0; row < captureHeight; row++){- // Bottom row first, which is the order a .bmp stores them.- const unsigned char *in = captured + (captureHeight-1-row)*capturePitch;+ const unsigned char *in = captured + row*capturePitch;char *out = rows + row*captureWidth*3;for (unsigned column = 0; column < captureWidth; column++){@@ -3903,10 +3911,10 @@ static Bool writeFrameBMP(char *pathname)out[column*3+2] = (char)in[column*4+2];}}- CreateBMPFile(pathname, rows, captureWidth, captureHeight);- delete [] rows;Direct3D11_Release_Capture(captured);- return TRUE;+ *rowsWidth = (Int)captureWidth;+ *rowsHeight = (Int)captureHeight;+ return rows;}RenderRect bounds;@@ -3962,7 +3970,7 @@ static Bool writeFrameBMP(char *pathname){if (fb != NULL)fb->Release();- return FALSE; // nothing to save; better than a fault+ return NULL; // nothing to save; better than a fault}}@@ -3976,36 +3984,6 @@ static Bool writeFrameBMP(char *pathname)height=bounds.bottom-bounds.top;char *image=NEW char[3*width*height];-#ifdef CAPTURE_TO_TARGA- //bytes are mixed in targa files, not rgb order.- for (y=0; y<height; y++)- {- for (x=0; x<width; x++)- {- // index for image- index=3*(x+y*width);- // index for fb- index2=y*lrect.Pitch+4*x;-- image[index]=*((char *) lrect.pBits + index2+2);- image[index+1]=*((char *) lrect.pBits + index2+1);- image[index+2]=*((char *) lrect.pBits + index2+0);- }- }-- fb->Release();-- Targa targ;- memset(&targ.Header,0,sizeof(targ.Header));- targ.Header.Width=width;- targ.Header.Height=height;- targ.Header.PixelDepth=24;- targ.Header.ImageType=TGA_TRUECOLOR;- targ.SetImage(image);- targ.YFlip();-- targ.Save(pathname,TGAF_IMAGE,false);-#else //capturing to bmp file//bmp is same byte orderfor (y=0; y<height; y++){@@ -4024,31 +4002,20 @@ static Bool writeFrameBMP(char *pathname)fb->Release();- //Flip the image- char *ptr,*ptr1;- char v,v1;-- for (y = 0; y < (height >> 1); y++)- {- /* Compute address of lines to exchange. */- ptr = (image + ((width * y) * 3));- ptr1 = (image + ((width * (height - 1)) * 3));- ptr1 -= ((width * y) * 3);+ *rowsWidth = (Int)width;+ *rowsHeight = (Int)height;+ return image;+}- /* Exchange all the pixels on this scan line. */- for (x = 0; x < (width * 3); x++)- {- v = *ptr;- v1 = *ptr1;- *ptr = v1;- *ptr1 = v;- ptr++;- ptr1++;- }- }+/** Write the frame being drawn to pathname. FALSE when there was no picture to read. */+static Bool writeFrameBMP(char *pathname)+{+ Int width = 0;+ Int height = 0;+ char *image = captureFrameRows(&width, &height);+ if (image == NULL)+ return FALSE;CreateBMPFile(pathname, image, width, height);-#endif-delete [] image;return TRUE;}@@ -4096,6 +4063,45 @@ static UnsignedInt s_videoLastFrame = 0;static Int s_videoFramesWritten = 0;static Int s_videoFramesMissed = 0;static char s_videoDirectory[_MAX_PATH];+/* -directorrecord's second fight, drawn first and kept here until the frame everybody sees is read and+ the right of the leaning line is taken from it */+static char *s_videoHeld = NULL;+static Int s_videoHeldWidth = 0;+static Int s_videoHeldHeight = 0;+static UnsignedInt s_videoHeldFrame = 0;+#if defined(_WIN32)+/* -directorrecord writes no frames to disk: they go down a pipe into ffmpeg as they are drawn, which a+ whole match of 1080p bitmaps would need tens of gigabytes for. With no ffmpeg it records nothing+ and quits. */+static Bool s_videoPipeTried = FALSE;+static HANDLE s_videoPipe = NULL;+static HANDLE s_videoEncoder = NULL;+static Int s_videoPipeWidth = 0;+static Int s_videoPipeHeight = 0;++// the directory with its trailing backslash taken off is the movie's own name+static void buildVideoMoviePath(char *moviePath, size_t size)+{+ strlcpy(moviePath, s_videoDirectory, size);+ moviePath[strlen(moviePath) - 1] = '\0';+ strlcat(moviePath, ".mp4", size);+}++// ffmpeg.exe beside generals.exe first, then off the PATH. FALSE when neither has one+static Bool findVideoEncoder(char *encoderPath, DWORD size)+{+ const DWORD length = GetModuleFileNameA(NULL, encoderPath, size);+ char *slash = strrchr(encoderPath, '\\');+ if (length > 0 && length < size && slash != NULL)+ {+ slash[1] = '\0';+ strlcat(encoderPath, VIDEO_ENCODER, size);+ if (GetFileAttributesA(encoderPath) != INVALID_FILE_ATTRIBUTES)+ return TRUE;+ }+ return SearchPathA(NULL, VIDEO_ENCODER, NULL, size, encoderPath, NULL) != 0;+}+#endifstatic void buildVideoFramePath(char *pathname, size_t size, Int index){@@ -4130,6 +4136,33 @@ static void finishVideo(void)DEBUG_LOG(("VIDEO: %d frames written to %s, %d logic frames went by without a picture\n",s_videoFramesWritten, s_videoDirectory, s_videoFramesMissed));+ delete [] s_videoHeld;+ s_videoHeld = NULL;++#if defined(_WIN32)+ // the end of the pipe is the end of the stream: ffmpeg finishes the movie and exits+ if (s_videoEncoder != NULL)+ {+ CloseHandle(s_videoPipe);+ s_videoPipe = NULL;+ WaitForSingleObject(s_videoEncoder, INFINITE);+ DWORD pipedExitCode = 0;+ GetExitCodeProcess(s_videoEncoder, &pipedExitCode);+ CloseHandle(s_videoEncoder);+ s_videoEncoder = NULL;+ RemoveDirectoryA(s_videoDirectory);++ char pipedMoviePath[_MAX_PATH];+ buildVideoMoviePath(pipedMoviePath, ARRAY_SIZE(pipedMoviePath));+ if (pipedExitCode != 0)+ DEBUG_LOG(("VIDEO: %s exited with %u, so %s may be short or missing\n",+ VIDEO_ENCODER, (unsigned)pipedExitCode, pipedMoviePath));+ else+ DEBUG_LOG(("VIDEO: wrote %s\n", pipedMoviePath));+ return;+ }+#endif+if (s_videoFramesWritten == 0)return;@@ -4139,17 +4172,14 @@ static void finishVideo(void)LOGICFRAMES_PER_SECOND, s_videoDirectory, VIDEO_FRAME_PATTERN));#elsechar encoderPath[_MAX_PATH];- if (SearchPathA(NULL, VIDEO_ENCODER, NULL, ARRAY_SIZE(encoderPath), encoderPath, NULL) == 0)+ if (!findVideoEncoder(encoderPath, ARRAY_SIZE(encoderPath))){- DEBUG_LOG(("VIDEO: %s is not on the PATH, so the frames stay where they are\n", VIDEO_ENCODER));+ DEBUG_LOG(("VIDEO: no %s beside the game or on the PATH, so the frames stay where they are\n", VIDEO_ENCODER));return;}- // the directory with its trailing backslash taken off is the movie's own namechar moviePath[_MAX_PATH];- strlcpy(moviePath, s_videoDirectory, ARRAY_SIZE(moviePath));- moviePath[strlen(moviePath) - 1] = '\0';- strlcat(moviePath, ".mp4", ARRAY_SIZE(moviePath));+ buildVideoMoviePath(moviePath, ARRAY_SIZE(moviePath));// yuv420p is what every player opens and it wants even dimensions, which a window need not havechar commandLine[4 * _MAX_PATH];@@ -4189,6 +4219,120 @@ static void finishVideo(void)#endif}+/** A -video range is being recorded and this logic frame is inside it. */+static Bool videoRecordingFrame(void)+{+ if (TheGlobalData->m_videoEndFrame <= 0 || s_videoFinished || TheGameLogic == NULL+ || !TheGameLogic->isInGame() || TheGameLogic->isInShellGame())+ return FALSE;+ const UnsignedInt frame = TheGameLogic->getFrame();+ return frame >= (UnsignedInt)TheGlobalData->m_videoStartFrame && frame <= (UnsignedInt)TheGlobalData->m_videoEndFrame;+}++#if defined(_WIN32)+/** ffmpeg started with its stdin a pipe this end writes raw frames of this size into. FALSE when+ * there is no ffmpeg or it would not start. */+static Bool openVideoPipe(Int width, Int height)+{+ char encoderPath[_MAX_PATH];+ if (!findVideoEncoder(encoderPath, ARRAY_SIZE(encoderPath)))+ {+ DEBUG_LOG(("VIDEO: no %s beside the game or on the PATH\n", VIDEO_ENCODER));+ return FALSE;+ }++ SECURITY_ATTRIBUTES inherited;+ memset(&inherited, 0, sizeof(inherited));+ inherited.nLength = sizeof(inherited);+ inherited.bInheritHandle = TRUE;+ HANDLE readEnd = NULL;+ HANDLE writeEnd = NULL;+ if (!CreatePipe(&readEnd, &writeEnd, &inherited, 0))+ {+ DEBUG_LOG(("VIDEO: no pipe to %s (error %u)\n", VIDEO_ENCODER, (unsigned)GetLastError()));+ return FALSE;+ }+ // ffmpeg holding the end written to as well would never see the stream end+ SetHandleInformation(writeEnd, HANDLE_FLAG_INHERIT, 0);++ char moviePath[_MAX_PATH];+ buildVideoMoviePath(moviePath, ARRAY_SIZE(moviePath));+ char commandLine[4 * _MAX_PATH];+ snprintf(commandLine, ARRAY_SIZE(commandLine),+ "\"%s\" -y -loglevel error -f rawvideo -pix_fmt bgr24 -s %dx%d -framerate %d -i - "+ "-vf pad=ceil(iw/2)*2:ceil(ih/2)*2 -c:v libx264 -pix_fmt yuv420p -crf 18 \"%s\"",+ encoderPath, width, height, LOGICFRAMES_PER_SECOND, moviePath);++ STARTUPINFOA startup;+ memset(&startup, 0, sizeof(startup));+ startup.cb = sizeof(startup);+ startup.dwFlags = STARTF_USESTDHANDLES;+ startup.hStdInput = readEnd;+ PROCESS_INFORMATION process;+ const BOOL started = CreateProcessA(encoderPath, commandLine, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL,+ &startup, &process);+ CloseHandle(readEnd);+ if (!started)+ {+ CloseHandle(writeEnd);+ DEBUG_LOG(("VIDEO: %s would not start (error %u)\n",+ encoderPath, (unsigned)GetLastError()));+ return FALSE;+ }++ CloseHandle(process.hThread);+ s_videoPipe = writeEnd;+ s_videoEncoder = process.hProcess;+ s_videoPipeWidth = width;+ s_videoPipeHeight = height;+ DEBUG_LOG(("VIDEO: %dx%d frames go straight into %s for %s\n", width, height, encoderPath, moviePath));+ return TRUE;+}+#endif++/** One picture of the recording, into ffmpeg's pipe under -directorrecord, as the next numbered .bmp+ * otherwise. */+static Bool writeVideoFrame(char *rows, Int width, Int height)+{+#if defined(_WIN32)+ if (TheGlobalData->m_directorRecord && !s_videoPipeTried)+ {+ s_videoPipeTried = TRUE;+ openVideoPipe(width, height);+ }+ if (s_videoPipe != NULL)+ {+ // ffmpeg was told one size; a picture of another would shear every frame after it+ if (width != s_videoPipeWidth || height != s_videoPipeHeight)+ return FALSE;+ const DWORD bytes = (DWORD)(3 * width * height);+ DWORD written = 0;+ if (WriteFile(s_videoPipe, rows, bytes, &written, NULL) && written == bytes)+ return TRUE;+ DEBUG_LOG(("VIDEO: %s stopped taking frames (error %u) at logic frame %u\n", VIDEO_ENCODER,+ (unsigned)GetLastError(), TheGameLogic->getFrame()));+ return FALSE;+ }+#endif+ // a whole match as bitmaps is tens of gigabytes, and one run filled a disk with 13 GB before it+ // was stopped, so without the encoder there is no recording at all+ if (TheGlobalData->m_directorRecord)+ {+ DEBUG_LOG(("VIDEO: -directorrecord records only through %s, beside the game or on the PATH; nothing recorded, quitting\n",+ VIDEO_ENCODER));+ s_videoFinished = TRUE;+#if defined(_WIN32)+ RemoveDirectoryA(s_videoDirectory);+#endif+ TheGameEngine->setQuitting(TRUE);+ return FALSE;+ }+ char pathname[_MAX_PATH];+ buildVideoFramePath(pathname, ARRAY_SIZE(pathname), s_videoFramesWritten);+ CreateBMPFile(pathname, rows, width, height);+ return TRUE;+}+static void captureVideoFrame(void){if (TheGlobalData->m_videoEndFrame <= 0 || s_videoFinished || TheGameLogic == NULL@@ -4205,6 +4349,15 @@ static void captureVideoFrame(void)return;}+ // -directorrecord's second fight: kept for the frame that follows it on this logic frame+ if (TheObserverCamera.isDrawingSecond())+ {+ delete [] s_videoHeld;+ s_videoHeld = captureFrameRows(&s_videoHeldWidth, &s_videoHeldHeight);+ s_videoHeldFrame = frame;+ return;+ }+if (!s_videoStarted){s_videoStarted = TRUE;@@ -4238,12 +4391,31 @@ static void captureVideoFrame(void)}s_videoLastFrame = frame;- char pathname[_MAX_PATH];- buildVideoFramePath(pathname, ARRAY_SIZE(pathname), s_videoFramesWritten);- if (writeFrameBMP(pathname))+ Int width = 0;+ Int height = 0;+ char *rows = captureFrameRows(&width, &height);+ if (rows == NULL)+ {+ ++s_videoFramesMissed;+ return;+ }++ // split: right of the leaning line is the second fight's picture+ if (s_videoHeld != NULL && s_videoHeldFrame == frame && s_videoHeldWidth == width && s_videoHeldHeight == height)+ {+ for (Int y = 0; y < height; ++y)+ {+ const Int from = min(max(ObserverCamera_splitBoundary(y, width, height), 0), width);+ const Int at = (y * width + from) * 3;+ memcpy(rows + at, s_videoHeld + at, (width - from) * 3);+ }+ }++ if (writeVideoFrame(rows, width, height))++s_videoFramesWritten;else++s_videoFramesMissed;+ delete [] rows;}/** Start/Stop campturing an AVI movie*/diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cppindex 9800803a0..905ba5b39 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp@@ -35,6 +35,7 @@#include "Common/GlobalData.h"#include "Common/Player.h"#include "Common/PlayerList.h"+#include "Common/Radar.h"#include "Common/ThingTemplate.h"#include "Common/ThingFactory.h"#include "GameLogic/AI.h"@@ -56,6 +57,7 @@#include "GameClient/ControlBar.h"#include "GameClient/Image.h"#include "GameClient/Mouse.h"+#include "GameClient/ObserverCamera.h"#include "W3DDevice/GameClient/W3DAssetManager.h"#include "W3DDevice/GameClient/W3DGUICallbacks.h"#include "W3DDevice/GameClient/W3DInGameUI.h"@@ -430,7 +432,50 @@ void W3DInGameUI::draw( void )// star banner slide in at the top right of an observer's footage (twice in trailer_chaos, frames// 930 and 1230), and nothing on the list belongs in a shot. The letterbox is the display's own.if( CinemaDirector_hidesHud() )+ {+ // -directorrecord's two fights side by side: the line between the halves, drawn the same in+ // both draws so the joined picture has it whole+ const Bool split = TheObserverCamera.isSplit();+ if( split )+ {+ const Int width = TheDisplay->getWidth();+ const Int height = TheDisplay->getHeight();+ TheDisplay->drawLine( ObserverCamera_splitBoundary( 0, width, height ), 0,+ ObserverCamera_splitBoundary( height, width, height ), height, 3.0f, GameMakeColor( 235, 235, 235, 255 ) );+ }++ // the console's 'hidehud showmap=true': the bar is hidden, so its radar window is put in the+ // corner by hand, where the radar's own pixel maths find it too, and painted. Over a split+ // picture it sits in the middle, on the line, where it covers neither fight+ if( CinemaDirector_showsMap() )+ {+ GameWindow *radarWindow = TheWindowManager->winGetWindowFromId( NULL, TheNameKeyGenerator->nameToKey( "ControlBar.wnd:LeftHUD" ) );+ // W3DLeftHUDDraw paints one pixel inside the window, and the radar keeps the map's shape+ // inside that, with black bars for the rest. The window is cut to the map's own shape,+ // a pixel larger each side and one pixel over the screen's edges, so the map is flush+ enum { RADAR_BEZEL = 1 };+ ICoord2D size, ul, lr;+ radarWindow->winGetSize( &size.x, &size.y );+ TheRadar->findDrawPositions( 0, 0, size.x - 2 * RADAR_BEZEL, size.y - 2 * RADAR_BEZEL, &ul, &lr );+ IRegion2D corner;+ corner.lo.x = -RADAR_BEZEL;+ corner.hi.x = corner.lo.x + ( lr.x - ul.x ) + 2 * RADAR_BEZEL;+ corner.hi.y = TheDisplay->getHeight() + RADAR_BEZEL;+ corner.lo.y = corner.hi.y - ( lr.y - ul.y ) - 2 * RADAR_BEZEL;+ if( split )+ {+ const Int mapWidth = corner.hi.x - corner.lo.x;+ const Int mapHeight = corner.hi.y - corner.lo.y;+ corner.lo.x = ( TheDisplay->getWidth() - mapWidth ) / 2;+ corner.hi.x = corner.lo.x + mapWidth;+ corner.lo.y = ( TheDisplay->getHeight() - mapHeight ) / 2;+ corner.hi.y = corner.lo.y + mapHeight;+ }+ TheControlBar->placeWindowAt( radarWindow, corner );+ W3DLeftHUDDraw( radarWindow, NULL );+ }return;+ }preDraw();diff --git a/GeneralsMD/Code/Tests/test_observer_camera.inc b/GeneralsMD/Code/Tests/test_observer_camera.incindex fdd78c0c1..087035a6e 100644--- a/GeneralsMD/Code/Tests/test_observer_camera.inc+++ b/GeneralsMD/Code/Tests/test_observer_camera.inc@@ -289,3 +289,75 @@ TEST(the_observer_camera_eases_in_holds_its_top_speed_and_settles_without_overshCHECK_NEAR( at.getPosition().x, 2200.0f, 1.0f );CHECK( lastStep < 1.0f );}++TEST(the_recording_splits_for_a_second_fight_far_from_the_first_and_never_for_the_same_one)+{+ Coord2D first;+ first.x = first.y = 1000.0f;+ std::vector< DirectorHeat > hits;+ for( Int each = 0; each < 6; each++ )+ hits.push_back( directorHit( 1000.0f + each * 20.0f, 1000.0f ) );+ // a hit 500 away is near enough that the two halves would show the same ground+ hits.push_back( directorHit( 1500.0f, 1000.0f ) );++ Coord2D second;+ Real heat = 0.0f;+ CHECK( !ObserverCamera_secondPlace( hits, first, &second, &heat ) );++ for( Int each = 0; each < 3; each++ )+ hits.push_back( directorHit( 3000.0f, 3000.0f + each * 20.0f ) );+ CHECK( ObserverCamera_secondPlace( hits, first, &second, &heat ) );+ CHECK_NEAR( heat, 3.0f, 0.001f );+ CHECK_NEAR( second.x, 3000.0f, 0.001f );+ CHECK_NEAR( second.y, 3020.0f, 0.001f );+}++TEST(the_recording_splits_for_a_big_second_fight_holds_it_and_rests_after)+{+ const UnsignedInt rested = 5 * LOGICFRAMES_PER_SECOND;+ const UnsignedInt justJoined = 2 * LOGICFRAMES_PER_SECOND;+ const UnsignedInt longHeld = 8 * LOGICFRAMES_PER_SECOND;+ const Real farApart = 2000.0f;+ // on for a second fight hot on its own and at least half the first+ CHECK( ObserverCamera_holdSplit( FALSE, 6.0f, 3.0f, farApart, rested ) );+ CHECK( !ObserverCamera_holdSplit( FALSE, 8.0f, 3.0f, farApart, rested ) );+ CHECK( !ObserverCamera_holdSplit( FALSE, 1.0f, 1.5f, farApart, rested ) );+ // not straight back on after it went off+ CHECK( !ObserverCamera_holdSplit( FALSE, 6.0f, 3.0f, farApart, 2 * LOGICFRAMES_PER_SECOND ) );+ // held a few seconds while the second fight goes on at all, then only while it keeps a quarter+ CHECK( ObserverCamera_holdSplit( TRUE, 6.0f, 0.5f, farApart, justJoined ) );+ CHECK( ObserverCamera_holdSplit( TRUE, 8.0f, 2.0f, farApart, longHeld ) );+ CHECK( !ObserverCamera_holdSplit( TRUE, 8.0f, 1.9f, farApart, longHeld ) );+}++TEST(the_recording_split_ends_at_once_when_the_two_halves_show_one_fight)+{+ const UnsignedInt justJoined = 2 * LOGICFRAMES_PER_SECOND;+ // the director moved onto the second fight: both halves would show the same ground+ CHECK( !ObserverCamera_holdSplit( TRUE, 12.0f, 8.0f, 60.0f, justJoined ) );+ CHECK( !ObserverCamera_holdSplit( FALSE, 6.0f, 6.0f, 600.0f, 5 * LOGICFRAMES_PER_SECOND ) );+ // the second fight is over, however new the split+ CHECK( !ObserverCamera_holdSplit( TRUE, 6.0f, 0.0f, 2000.0f, justJoined ) );+}++TEST(the_recording_splits_only_beside_a_real_fight)+{+ // bases going up are no fight: the split's hits are only one side's on another, so the director+ // looking at a sight has no heat of its own and a second fight does not split the picture+ CHECK( !ObserverCamera_holdSplit( FALSE, 0.0f, 10.0f, 2000.0f, 5 * LOGICFRAMES_PER_SECOND ) );+ // and with no fight anywhere there is no second place to show+ std::vector< DirectorHeat > none;+ Coord2D first;+ first.x = first.y = 1000.0f;+ Coord2D second;+ Real heat = 0.0f;+ CHECK( !ObserverCamera_secondPlace( none, first, &second, &heat ) );+}++TEST(the_split_line_leans_twelve_degrees_through_the_middle)+{+ CHECK_EQ( ObserverCamera_splitBoundary( 360, 1280, 720 ), 640 );+ // 360 rows from the middle at tan 12 degrees is 76.5 columns+ CHECK_EQ( ObserverCamera_splitBoundary( 0, 1280, 720 ), 717 );+ CHECK_EQ( ObserverCamera_splitBoundary( 720, 1280, 720 ), 563 );+}