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): take camera, cancel and minimap fixes from PRs 5 and 6
Olcay Seygan0788f2e92d0a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 228d90df4..1e1155611 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ found and fixed — EA's own, not port damage.**- A screen full of fire and smoke is cheaper to draw. Thirty Inferno Cannons shelling twenty Crusaders used to send the graphics card 459 separate batches of see-through effects a frame, mostly the same texture again and again, and the game looked up the same seven card settings from scratch for every one of them. Matching effects go out together now, and settings that have not changed are not looked up again: 177 batches, and the same battle went from 11.6ms a frame to 8.6ms. It is at 6.7ms now, since the game stopped preparing everything it draws a second time for a copy of the picture nobody sees. Nothing on screen changes, the effects are drawn in exactly the order they were.- 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.- Every animation runs on a clock instead of counting frames.+- 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.- Briefing and cutscene subtitles hold long enough to read again.- The radar's under-attack pulse throbs instead of strobing, and no longer ends early.- The main menu surf rolls at its proper pace, not ten times too fast.@@ -129,7 +130,7 @@ found and fixed — EA's own, not port damage.**- A box drawn with Ctrl held takes those units back out of your selection instead of replacing it, so a group is trimmed by dragging over the corner of it rather than picked again from scratch. Held with Alt the box keeps only what can shoot: drag across your base and you get the tanks, not the dozers and supply trucks standing among them. Both are drag-only, and a single click still means exactly what it always did.- The three buttons each do one thing now. Left selects, and only selects. Right gives orders, and nothing it does moves the camera. The camera is on the middle button, and it scrolls the way the right button used to: the spot you pressed on stays put, and the further you pull away from it the faster the map runs. Hold Ctrl and the same drag turns the view instead. The wheel zooms toward whatever the cursor is over and the screen edges still scroll. The classic scheme, where left both selected and commanded and right scrolled and deselected, is gone rather than switched off, and the two checkboxes that used to choose between them are out of the options screen.- Drag the right button and you draw a line: the selection spreads itself evenly along it, in the order the units already stand, so a column arrives as a firing line instead of a queue. It is the line you actually drew, curves and all, however far you keep drawing it: a long sweep used to give up partway through and finish as one straight run to the cursor, and now it holds its shape to the end. Letting go over the sidebar finishes the order rather than leaving the line stuck to the cursor. Draw the line with the left button while attack move is armed and the whole line is an attack move: artillery spread across a front, each gun firing on what walks into it, instead of one clump on one spot. The left button, because that is what attack move is aimed with; with F armed a right drag draws nothing. Armed with attack instead, every unit fires on its own station along the line, which is a barrage laid across a ridge in one drag. This is what the right button freed up. `FormationDrag = no` in Options.ini turns it off if you would rather a slipped click did nothing.-- Selected units draw a thread to wherever they are going, and the marker on the spot is the game's own cursor. A group sent to one spot draws each unit's thread to the ground that unit will actually stand on, where every line used to run into the same point. Every order that has a cursor gets that cursor: move, attack move, attack, force fire, ground fire, enter, dock, repair, heal, capture, hack, guard, a waypoint path. Green for a move, pink for an attack-move, red for anything that shoots, so a group told three different things reads as three different colours. It is not a flash at the moment of the order: the line is asked of the unit every frame, so it lasts until the unit gets there, changes its mind or leaves your selection, and it shows on the formation line while you are still drawing it. A unit that has walked off the edge of the screen still draws its line, which is how you see where the half of your army you cannot see is headed. The animated ring the ground used to sprout wherever you clicked is gone: it flashed for a second and told you nothing the marker sitting on the destination does not, and that marker stays for as long as the order does. A marker that has just appeared slides the last few pixels up out of the bottom right and fades in as it lands, over about an eighth of a second, so a fresh order catches your eye without anything flashing. Aircraft draw their thread from the click, not from the moment they leave the runway. A plane parked on its airfield answers an order by starting its takeoff and puts the order itself aside until the wheels are up, so the taxi and the climb, which is exactly the stretch where you are wondering whether the strike went out at all, used to show nothing.+- Selected units draw a thread to wherever they are going, with a marker on the spot. A group sent to one spot draws each unit's thread to the ground that unit will actually stand on, where every line used to run into the same point. Every order draws one: move, attack move, attack, force fire, ground fire, enter, dock, repair, heal, capture, hack, guard, a waypoint path. Green for a move, pink for an attack-move, red for anything that shoots, so a group told three different things reads as three different colours. A move wears a dot and anything that shoots wears a ring, so the shape tells them apart for somebody who cannot tell the red from the green. The marker sits on the middle of the spot and grows with your screen; it used to be a tinted copy of the mouse pointer, hung off to one side of the destination and covering whatever stood beside it. It is not a flash at the moment of the order: the line is asked of the unit every frame, so it lasts until the unit gets there, changes its mind or leaves your selection, and it shows on the formation line while you are still drawing it. A unit that has walked off the edge of the screen still draws its line, which is how you see where the half of your army you cannot see is headed. The animated ring the ground used to sprout wherever you clicked is gone: it flashed for a second and told you nothing the marker sitting on the destination does not, and that marker stays for as long as the order does. A marker that has just appeared slides the last few pixels up out of the bottom right and fades in as it lands, over about an eighth of a second, so a fresh order catches your eye without anything flashing. Aircraft draw their thread from the click, not from the moment they leave the runway. A plane parked on its airfield answers an order by starting its takeoff and puts the order itself aside until the wheels are up, so the taxi and the climb, which is exactly the stretch where you are wondering whether the strike went out at all, used to show nothing.- A unit standing guard draws its marker on the ground it is guarding. A guard order clears the unit's goal on the way in, so every guard marker used to sit in the bottom left corner of the map with a thread running the whole way across it, whatever the unit was actually watching.- A is attack and F is attack move, each arming the next order click. A click on the ground with A held down is a shot at that ground, on your own tank a shot at your own tank, and the mode drops again the moment the order goes out, so nothing stays armed behind your back. The click keeps your group, too: an attack click that was not a drag used to run the same deselect an ordinary left click runs, so the order arrived a moment after the units it was meant for had been dropped. Both orders are aimed with the left button, the way a special power is, and a right click puts the key down again without giving any order. Holding ctrl no longer forces fire: A is the one way to shoot the ground, and ctrl on a move is only the shared pace. The two keys turn each other off, and the letters they took were sitting on grid commands that moved.- G is guard, armed the same way and aimed with the same left button. A left click posts the selection on that spot: they hold it, shoot what walks into range and do not chase it off the post you put them on. The cursor turns into the targeting cross while G is armed, so you can see the key is down before you click, and a right click puts it down again. Drag the left button with G armed (the right one draws nothing while G is down) and they post along the line you draw, one unit per station, which is how a hill or a bridge approach gets covered in one gesture instead of a click per tank. Guard has its own colour, blue, on the line while you draw it and on the thread and marker afterwards, so a group told to hold ground reads apart from one told to walk there. Hold position, which posts every unit on the spot it is already standing on, has moved to H.@@ -313,6 +314,7 @@ found and fixed — EA's own, not port damage.**- An upgrade stays available if any selected building can still buy it.- One right click cancels one thing, counted the moment you press.- A build button takes a batch: Shift queues five, Ctrl twenty, both together as many as the queue will hold and the bank will pay for. Right-click with the same keys and the same number comes back out. Ten tanks used to be ten clicks.+- Right-click a picture on the strip and that one order is cancelled and paid back, without walking the camera over to the building first. A build button greyed out because the bank is empty or the queue is full still takes the right click, so what is already queued on it can come back out.- Buying an upgrade for a group starts it in all of them.- The progress clock over a picture is steady at any frame rate.- A group's upgrade shows its progress, whichever building is paying for it.@@ -562,6 +564,7 @@ found and fixed — EA's own, not port damage.**- Build tooltips no longer paint one letter of the unit's name yellow. That letter was the old one-key shortcut, and the grid keys on the buttons replaced it; the yellow copy was drawn on top of a gap left in the name, so any letter the yellow pass could not draw, the ş in a Turkish name for one, simply went missing from the word.- An ultrawide monitor gets the same interface as a 16:9 one. Everything still sized off how wide the screen is came apart at 32:9: on a 5120x1440 screen the lettering was drawn at two and a half times what the panel under it had grown to, the clock and speed readout crept into the top corner because its margins were flat pixels, and a health bar reached across the whole base of the building it belonged to. All of it now measures off the same number the command bar does. Scale a 32:9 screenshot down to 16:9 and the two lie on top of each other.- The camera shows the same ground whatever shape your monitor is. The game holds the angle it sees across the screen fixed and lets the up-and-down angle shrink as the screen widens, which at 32:9 left fifteen degrees of world against twenty-nine at 16:9 - the same barracks filled twice the height of the screen, and it read as a zoom nobody asked for. Above 16:9 the view opens sideways instead, so a wider monitor buys more battlefield rather than a closer look at less of it. Nothing at 16:9 or below moves.+- The camera reaches the corners of the map. It stopped short of every edge by an amount that changed with the zoom and the angle, so a base in a corner never came to the middle of the screen. It now goes 200 units past any edge of the map, whatever the zoom. `CameraBoundaryMargin` in `Options.ini` sets how far, and 0 puts the old limit back.- The medals on the player info card are round on any screen. They were stretched across and down separately, so a wide monitor turned each one into an oval.- Minimising the command bar sends all three panels down, and they slide back up when you bring them back. The old minimise dropped the bar a tenth of the screen and left a strip of metal, a readable money box and the top of the radar dish lying along the bottom edge, which is neither the bar nor out of the way. The radar and the middle go off the screen entirely; the selection panel stops with the row its minimise tab is in standing on the bottom corner, so what you click to bring the bar back is that tab with its own artwork behind it, not a button floating over the battlefield.- Everything on the command bar that each faction places for itself lands where that faction's artwork paints it. The bar's own arithmetic was overwriting those positions with the ones it had used a moment earlier, so every panel wore the generic layout's vertical placement instead of its own: the minimise button drew a second tab below the painted one, arrow and all, and the GLA money sat high enough in its box to touch the frame. One arrow now, one tab, and the number in the middle of its readout - and the same correction reaches the worker, beacon, chat and options buttons down the side of the grid. The American power bar sits in its rail as well: it was drawing on the ledge above the rail, which put the left half of the bar on the battlefield rather than on the bar, and left the rail it reads in standing empty.@@ -585,7 +588,7 @@ found and fixed — EA's own, not port damage.**- Play it the way it shipped. Options > Controls has a Mouse and Keyboard box with two answers. Modern is this game as it is now. Legacy is the 2003 game: left click selects and orders, right click deselects, a right drag scrolls the map, a middle drag turns the camera, and the command bar answers the game's own letter for each button, painted in the button's corner the way the grid keys are. Holding Ctrl makes a click force fire, at the ground or at your own units. Those letters are the English game's even when the words are Turkish: the translation marks every label's first letter, which would have put K on three GLA structures and S on five. The promotion screen's number keys and the general's power keys are this game's additions, so under Legacy their labels are gone and the number keys pick your groups again. Every key comes from the game's own key map, so the grid keys, the two-key structures, Alt+Z signals, Ctrl+Z barracks, Tab, box select filters, formation lines, zoom to cursor and clickable health bars all stand down. It changes the moment you press Accept, even in the middle of a match, and it only changes your own screen.- The lines from your selection to where it is headed can be switched off. Options > Gameplay has an Order Lines box, on by default. Off, a selected unit shows no line to its goal and none through its queue, but the marker on every point it is headed for stays, so an attack move or a string of waypoints is still there to see. The line you draw while dragging a formation still shows, because that one is the order being given. It changes the moment you press Accept.- Click through the command bar wherever its metal is not. The bar is three shaped plates with sloped tops and cut corners, but it caught clicks over the whole rectangle each plate sits in, so a unit standing in the sky above the radar's slope, or in the notch beside the command grid, could not be clicked or ordered to. Between 3 and 22 percent of each plate's rectangle is empty, depending on the side and the panel. Those parts belong to the battlefield now, and the buttons and metal still take every click they did.-- Drag the camera across the radar. Press on the radar and keep the button down, and the camera follows the cursor over the map until you let go; before, it jumped once per click, so crossing the map meant clicking your way over it. The button that moves the camera with a click is the one that drags it, left under Modern and right under Legacy, and with nothing selected either one does. Run the left button off the side of the radar and the camera waits at the edge of the map. A selection box dragged onto the radar from the battlefield leaves the camera where it is.+- Drag the camera across the radar. Press on the radar and keep the button down, and the camera follows the cursor over the map until you let go; before, it jumped once per click, so crossing the map meant clicking your way over it. The button that moves the camera with a click is the one that drags it, left under Modern and right under Legacy, and with nothing selected either one does. Run the left button off the side of the radar and the camera waits at the edge of the map. It keeps following while the arrow keys are scrolling too, which used to leave the drag dead until the key came up. A selection box dragged onto the radar from the battlefield leaves the camera where it is.- Widescreen resolutions are back in the options menu, and the list works during a match. It was greyed out the moment a game started, because changing it rebuilt the menus and then pushed the main menu over whatever you were playing. It rebuilds the menus for later and leaves you on the battlefield with the command bar back up.- Changing the resolution during a match no longer takes the game down. Two things were behind it. The old command bar's windows were handed back while the menu system still had them on its list, so the next thing that painted a button read whatever had since been written over it. And the bar itself was thrown away and built from scratch, which handed out fresh copies of every build button while your factories, your repair crews and the promotion screen went on pointing at the old ones. The bar's windows are rebuilt now and the bar keeps everything that is not a window.- One command bar, not three. Changing the resolution during a match rebuilt the bar and left the old one behind, still drawn and still taking clicks at the size of the screen it was built for - and the confirmation box you answer afterwards rebuilds it a second time, so two mode changes in a row put three command bars on top of each other across the bottom of the battlefield. The code that was meant to throw the old one away asked the window system for a window called "ControlBar.wnd", and the bar's window is called "ControlBar.wnd:ControlBarParent", so it never found anything to throw away and never had.diff --git a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.hindex 48deee289..6e067b49a 100644--- a/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h+++ b/GeneralsMD/Code/GameEngine/Include/Common/GlobalData.h@@ -380,6 +380,8 @@ public:Real m_scrollAmountCutoff; ///< Scroll speed to not adjust camera heightReal m_cameraAdjustSpeed; ///< Rate at which we adjust camera heightBool m_enforceMaxCameraHeight; ///< Enfoce max camera height while scrolling?+ Bool m_useCameraConstraints; ///< constrain camera movement to the map and its configured margin+ Int m_cameraBoundaryMargin; ///< world units permitted beyond the map; 0 uses the original framing limitBool m_edgeScrollInWindowedMode; ///< allow screen-edge scrolling while running in a windowBool m_snapBuildPlacementTo45; ///< quantize the drag-to-rotate build placement angle to 45 degreesBool m_snapCameraRotateTo45; ///< quantize the camera heading to 45 degrees when a middle-drag rotate ends@@ -593,7 +595,6 @@ public:#if defined(_DEBUG) || defined(_INTERNAL)Bool m_wireframe;Bool m_stateMachineDebug;- Bool m_useCameraConstraints;Bool m_shroudOn;Bool m_fogOfWarOn;Bool m_jabberOn;diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/CameraBoundary.h b/GeneralsMD/Code/GameEngine/Include/GameClient/CameraBoundary.hnew file mode 100644index 000000000..8f25292c3--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/CameraBoundary.h@@ -0,0 +1,28 @@+/* Command & Conquer Generals Zero Hour - GPL-3.0-or-later */+#ifndef CAMERA_BOUNDARY_H+#define CAMERA_BOUNDARY_H++#include "Lib/BaseType.h"++// The camera target can cross an edge, but stays within a finite distance of the actual map.+inline Region2D cameraBoundaryFromMap(const Region3D& map, Real margin)+{+ if (margin < 0.0f) margin = 0.0f;+ Region2D boundary;+ boundary.lo.x = map.lo.x - margin;+ boundary.lo.y = map.lo.y - margin;+ boundary.hi.x = map.hi.x + margin;+ boundary.hi.y = map.hi.y + margin;+ return boundary;+}++inline Coord3D constrainCameraPosition(Coord3D pos, const Region2D& boundary)+{+ if (pos.x < boundary.lo.x) pos.x = boundary.lo.x;+ if (pos.x > boundary.hi.x) pos.x = boundary.hi.x;+ if (pos.y < boundary.lo.y) pos.y = boundary.lo.y;+ if (pos.y > boundary.hi.y) pos.y = boundary.hi.y;+ return pos;+}++#endifdiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/CameraScrollClock.h b/GeneralsMD/Code/GameEngine/Include/GameClient/CameraScrollClock.hnew file mode 100644index 000000000..8e039af81--- /dev/null+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/CameraScrollClock.h@@ -0,0 +1,31 @@+/* Command & Conquer Generals Zero Hour - GPL-3.0-or-later */+#ifndef CAMERA_SCROLL_CLOCK_H+#define CAMERA_SCROLL_CLOCK_H++#include <stdint.h>++// Sample once per render tick, even when the camera is stationary. Each view owns its clock.+class CameraScrollClock+{+public:+ CameraScrollClock() : m_previousTime(0), m_started(false) {}++ float sample(uint32_t now, int tickMilliseconds)+ {+ const uint32_t elapsed = now - m_previousTime;+ m_previousTime = now;+ if (!m_started)+ {+ m_started = true;+ return 0.0f;+ }+ const float factor = elapsed / (float)tickMilliseconds;+ return factor > 3.0f ? 3.0f : factor;+ }++private:+ uint32_t m_previousTime;+ bool m_started;+};++#endifdiff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.hindex d750045ec..abf56f2cd 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/GameWindow.h@@ -184,6 +184,7 @@ enumWIN_STATUS_ALWAYS_COLOR = 0x01000000, // Never render these buttons using greyscale renderer when button disabled.WIN_STATUS_ON_MOUSE_DOWN = 0x02000000, // Pushbutton triggers on mouse down.WIN_STATUS_SHORTCUT_BUTTON = 0x04000000, // Oh god... this is a total hack for shortcut buttons to handle rendering text top left corner...+ WIN_STATUS_CANCEL_WHEN_DISABLED = 0x08000000, // Queued production may still receive right clicks while buying is disabled.// when you edit this, remember to edit WindowStatusNames[]};@@ -361,7 +362,7 @@ public:/** given a piont, return the child window which contains the mouse pointer,if the point is not in a chilc, the function returns the 'window' paramaterback to the caller */- GameWindow *winPointInChild( Int x, Int y, Bool ignoreEnableCheck = FALSE, Bool playDisabledSound = FALSE );+ GameWindow *winPointInChild( Int x, Int y, Bool ignoreEnableCheck = FALSE, Bool playDisabledSound = FALSE, Bool allowDisabledCancel = FALSE );/** finds the child which contains the mouse pointer - reguardless ofthe enabled status of the child */GameWindow *winPointInAnyChild( Int x, Int y, Bool ignoreHidden, Bool ignoreEnableCheck = FALSE );diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/PlaceEventTranslator.h b/GeneralsMD/Code/GameEngine/Include/GameClient/PlaceEventTranslator.hindex 2a2e357ea..246f58804 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/PlaceEventTranslator.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/PlaceEventTranslator.h@@ -38,6 +38,7 @@ class PlaceEventTranslator : public GameMessageTranslatorprivate:UnsignedInt m_frameOfUpButton;Bool m_stripClickTaken; ///< the down went to the global production strip, so its up belongs there too+ Bool m_stripRightClickTaken; ///< keep a strip cancellation out of world orders and dragspublic:PlaceEventTranslator();diff --git a/GeneralsMD/Code/GameEngine/Include/GameClient/WindowXlat.h b/GeneralsMD/Code/GameEngine/Include/GameClient/WindowXlat.hindex c3bfb7967..2878da648 100644--- a/GeneralsMD/Code/GameEngine/Include/GameClient/WindowXlat.h+++ b/GeneralsMD/Code/GameEngine/Include/GameClient/WindowXlat.h@@ -36,7 +36,7 @@class WindowTranslator : public GameMessageTranslator{private:- // nothing+ Bool m_rightClickTaken; ///< a GUI right press owns its drag/release even outside the windowpublic:WindowTranslator();~WindowTranslator();diff --git a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cppindex 2acafad04..4b564bacd 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/GlobalData.cpp@@ -190,6 +190,8 @@ GlobalData* GlobalData::m_theOriginal = NULL;{ "CameraYaw", INI::parseReal, NULL, offsetof( GlobalData, m_cameraYaw ) },{ "CameraHeight", INI::parseReal, NULL, offsetof( GlobalData, m_cameraHeight ) },{ "MaxCameraHeight", INI::parseReal, NULL, offsetof( GlobalData, m_maxCameraHeight ) },+ { "UseCameraConstraints", INI::parseBool, NULL, offsetof( GlobalData, m_useCameraConstraints ) },+ { "CameraBoundaryMargin", INI::parseInt, NULL, offsetof( GlobalData, m_cameraBoundaryMargin ) },{ "EdgeScrollInWindowedMode", INI::parseBool, NULL, offsetof( GlobalData, m_edgeScrollInWindowedMode ) },{ "SnapBuildPlacementTo45", INI::parseBool, NULL, offsetof( GlobalData, m_snapBuildPlacementTo45 ) },{ "SnapCameraRotateTo45", INI::parseBool, NULL, offsetof( GlobalData, m_snapCameraRotateTo45 ) },@@ -531,7 +533,6 @@ GlobalData* GlobalData::m_theOriginal = NULL;{ "CheckMemoryLeaks", INI::parseBool, NULL, offsetof(GlobalData, m_checkForLeaks) },{ "Wireframe", INI::parseBool, NULL, offsetof( GlobalData, m_wireframe ) },{ "StateMachineDebug", INI::parseBool, NULL, offsetof( GlobalData, m_stateMachineDebug ) },- { "UseCameraConstraints", INI::parseBool, NULL, offsetof( GlobalData, m_useCameraConstraints ) },{ "ShroudOn", INI::parseBool, NULL, offsetof( GlobalData, m_shroudOn ) },{ "FogOfWarOn", INI::parseBool, NULL, offsetof( GlobalData, m_fogOfWarOn ) },{ "ShowCollisionExtents", INI::parseBool, NULL, offsetof( GlobalData, m_showCollisionExtents ) },@@ -592,7 +593,6 @@ GlobalData::GlobalData()#if defined(_DEBUG) || defined(_INTERNAL)m_wireframe = 0;m_stateMachineDebug = FALSE;- m_useCameraConstraints = TRUE;m_shroudOn = TRUE;m_fogOfWarOn = FALSE;m_jabberOn = FALSE;@@ -1101,6 +1101,8 @@ GlobalData::GlobalData()// controls that used to set them, and what is written here is what every game gets. GameData.ini// remains the way to change one, because the field table above still names it.//+ m_useCameraConstraints = TRUE;+ m_cameraBoundaryMargin = 200;m_edgeScrollInWindowedMode = TRUE;m_snapCameraRotateTo45 = TRUE;m_zoomToCursor = TRUE;diff --git a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cppindex f2cc3e7c6..54c3fdd00 100644--- a/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp+++ b/GeneralsMD/Code/GameEngine/Source/Common/OptionsCatalog.cpp@@ -26,6 +26,7 @@#include "Common/GlobalData.h"#include "Common/UserPreferences.h"#include "GameClient/PlayerColorScheme.h"+#include "GameClient/View.h"//-----------------------------------------------------------------------------// The accessors. Each is two lines and exists only because a member pointer cannot span Bool and@@ -41,6 +42,18 @@static Int get_##field( void ) { return TheGlobalData->field; } \static void set_##field( Int value ) { TheWritableGlobalData->field = value; }+OPTION_BOOL_ACCESSORS( m_useCameraConstraints )++static Int get_m_cameraBoundaryMargin( void ) { return TheGlobalData->m_cameraBoundaryMargin; }+static void set_m_cameraBoundaryMargin( Int value )+{+ TheWritableGlobalData->m_cameraBoundaryMargin = value;+ if (TheTacticalView)+ {+ TheTacticalView->forceCameraConstraintRecalc();+ TheTacticalView->forceRedraw();+ }+}OPTION_BOOL_ACCESSORS( m_edgeScrollInWindowedMode )OPTION_BOOL_ACCESSORS( m_snapCameraRotateTo45 )OPTION_BOOL_ACCESSORS( m_zoomToCursor )@@ -162,6 +175,14 @@ const OptionDef TheOptionCatalog[] =// loads, clamps and saves each one and a player who wants the old behaviour can put the key// back by hand. The defaults in GlobalData are what everybody else gets.+ { "UseCameraConstraints", "", "",+ OPTION_BOOL, APPLY_LIVE, 0, 1,+ get_m_useCameraConstraints, set_m_useCameraConstraints },++ { "CameraBoundaryMargin", "", "",+ OPTION_INT, APPLY_LIVE, 0, 1000,+ get_m_cameraBoundaryMargin, set_m_cameraBoundaryMargin },+// Retail refuses to edge-scroll in a window because the cursor can legitimately sit on the// border while you reach for something else; on a second monitor, or borderless, that is// exactly the behaviour you want back.diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cppindex 90da9bb37..f426ebe25 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/ControlBar/ControlBarCommand.cpp@@ -778,6 +778,7 @@ void ControlBar::updateContextCommand( void )// whatever is still running below puts its own clock back on//GadgetButtonClearClock( win );+ win->winClearStatus( WIN_STATUS_CANCEL_WHEN_DISABLED );//// a unit build button wears its own queue: a radial fill over the cameo while its unit@@ -804,6 +805,8 @@ void ControlBar::updateContextCommand( void )p->getProductionObject() == command->getThingTemplate() )queued++;GadgetButtonSetCount( win, queued );+ if( queued > 0 && obj->isLocallyControlled() )+ win->winSetStatus( WIN_STATUS_CANCEL_WHEN_DISABLED );const ProductionEntry *first = pu->firstProduction();if( first && first->getProductionType() == PRODUCTION_UNIT &&diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cppindex 81be1c393..570eb9f27 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GUICallbacks/ControlBarCallback.cpp@@ -267,6 +267,11 @@ WindowMsgHandledType LeftHUDInput( GameWindow *window, UnsignedInt msg,if( msg != s_radarLookDrag )return MSG_IGNORED;+ // A left press on the radar holds it until the release, so a left drag that is not held+ // here started somewhere else, even if the release that ended the last one never reached us+ if( msg == GWM_LEFT_DRAG && TheWindowManager->winGetGrabWindow() != window )+ return MSG_IGNORED;+// A left press holds the radar for the whole drag, so the cursor can run off the picture.// It pins to the picture's edge there and the camera stops on the map's edge, rather than// wherever the last move inside the picture happened to leave it.diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cppindex 2791fa1ca..1cca79925 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/Gadget/GadgetPushButton.cpp@@ -831,6 +831,8 @@ void GadgetButtonSetData(GameWindow *g, void *data)pData = getNewPushButtonData();}pData->userData = data;+ // Reused command windows must not keep another command's cancellation permission.+ g->winClearStatus( WIN_STATUS_CANCEL_WHEN_DISABLED );g->winSetUserData(pData);}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cppindex e68d1a086..e73ee2e7c 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindow.cpp@@ -1390,7 +1390,7 @@ Int GameWindow::winDrawWindow( void )* window which contains the mouse pointer. Child windows are* relative to their parents *///=============================================================================-GameWindow *GameWindow::winPointInChild( Int x, Int y, Bool ignoreEnableCheck, Bool playDisabledSound )+GameWindow *GameWindow::winPointInChild( Int x, Int y, Bool ignoreEnableCheck, Bool playDisabledSound, Bool allowDisabledCancel ){GameWindow *parent;GameWindow *child;@@ -1419,12 +1419,13 @@ GameWindow *GameWindow::winPointInChild( Int x, Int y, Bool ignoreEnableCheck, Bcontinue;Bool enabled = ignoreEnableCheck || BitTest( child->m_status, WIN_STATUS_ENABLED );+ Bool cancellable = allowDisabledCancel && BitTest( child->m_status, WIN_STATUS_CANCEL_WHEN_DISABLED );Bool hidden = BitTest( child->m_status, WIN_STATUS_HIDDEN );if( !hidden ){- if( enabled )+ if( enabled || cancellable ){- return child->winPointInChild( x, y, ignoreEnableCheck, playDisabledSound );+ return child->winPointInChild( x, y, ignoreEnableCheck, playDisabledSound, allowDisabledCancel );}else if( playDisabledSound ){diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cppindex 89634293e..dac7cc0b5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManager.cpp@@ -851,6 +851,9 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msGameWindow *childWindow;Int dx, dy;Bool clearGrabWindow = FALSE;+ // Only right-button events may reach disabled production buttons. Left clicks and+ // hotkeys still obey the normal availability check.+ Bool allowDisabledCancel = msg == GWM_RIGHT_DOWN || msg == GWM_RIGHT_UP;// pack mouse coords into one entity for message passingpackedMouseCoords = SHORTTOLONG( mousePos->x, mousePos->y );@@ -866,7 +869,7 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msm_grabWindow = NULL;// what what window within the captured window are we in- window = m_mouseCaptor->winPointInChild( mousePos->x, mousePos->y );+ window = m_mouseCaptor->winPointInChild( mousePos->x, mousePos->y, FALSE, FALSE, allowDisabledCancel );//// send buttons, drags, wheels to the windows, we don't continually@@ -1013,7 +1016,7 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msif( m_modalHead && m_modalHead->window ){- window = m_modalHead->window->winPointInChild( mousePos->x, mousePos->y );+ window = m_modalHead->window->winPointInChild( mousePos->x, mousePos->y, FALSE, FALSE, allowDisabledCancel );}else{@@ -1045,7 +1048,7 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msif( BitTest( window->m_status, WIN_STATUS_ENABLED ) ){// determine which child window the mouse is in- window = window->winPointInChild( mousePos->x, mousePos->y );+ window = window->winPointInChild( mousePos->x, mousePos->y, FALSE, FALSE, allowDisabledCancel );break; // exit for}@@ -1081,7 +1084,7 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msif( BitTest( window->m_status, WIN_STATUS_ENABLED )){// determine which child window the mouse is in- window = window->winPointInChild( mousePos->x, mousePos->y );+ window = window->winPointInChild( mousePos->x, mousePos->y, FALSE, FALSE, allowDisabledCancel );break; // exit for}}@@ -1115,7 +1118,7 @@ WinInputReturnCode GameWindowManager::winProcessMouseEvent( GameWindowMessage msif( BitTest( window->m_status, WIN_STATUS_ENABLED )){// determine which child window the mouse is in- window = window->winPointInChild( mousePos->x, mousePos->y );+ window = window->winPointInChild( mousePos->x, mousePos->y, FALSE, FALSE, allowDisabledCancel );break; // exit for}}diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cppindex ad462b895..a30dc5dc5 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/GUI/GameWindowManagerScript.cpp@@ -150,6 +150,7 @@ const char *WindowStatusNames[] = { "ACTIVE", "TOGGLE", "DRAGABLE", "ENABLED", ""RIGHT_CLICK", "WRAP_CENTERED", "CHECK_LIKE","HOTKEY_TEXT","USE_OVERLAY_STATES", "NOT_READY", "FLASHING", "ALWAYS_COLOR","ON_MOUSE_DOWN",+ "SHORTCUT_BUTTON", "CANCEL_WHEN_DISABLED",NULL };const char *WindowStyleNames[] = { "PUSHBUTTON", "RADIOBUTTON", "CHECKBOX",diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cppindex 825bf7fde..520904119 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/InGameUI.cpp@@ -7384,7 +7384,7 @@ void InGameUI::drawHudOverlay( void )// PRODUCTION_STRIP_ROW_MAX cameos and closes with a sixth cell wearing a "+N" for whatever else is// queued. Units and upgrades wear the same two border colours the command bar uses. The item a// building is actually working on wears a radial fill. A click takes the camera to the building an-// item is queued on; ctrl-click cancels it.+// item is queued on; right-click (or Ctrl-click) cancels one queued item.//-------------------------------------------------------------------------------------------------//-------------------------------------------------------------------------------------------------diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cppindex 5c856c095..cd93d89ea 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/LookAtXlat.cpp@@ -82,6 +82,9 @@ void LookAtTranslator::setScrolling(Int x)TheInGameUI->setScrolling( TRUE );TheTacticalView->setMouseLock( TRUE );m_scrollType = x;+ // A manual pan restores map constraints widened by scripted camera paths.+ if (TheGlobalData->m_useCameraConstraints && TheGlobalData->m_cameraBoundaryMargin > 0)+ TheTacticalView->forceCameraConstraintRecalc();if(TheStatsCollector)TheStatsCollector->startScrollTime();}@@ -623,11 +626,13 @@ GameMessageDisposition LookAtTranslator::translateGameMessage(const GameMessage}TheInGameUI->setScrollAmount(offset);- TheTacticalView->scrollBy( &offset );}else //not scrolling so reset amountTheInGameUI->setScrollAmount(offset);+ // Advance the pan clock even while stationary, so restarting does not include idle time.+ TheTacticalView->scrollBy( &offset );+//if (TheGlobalData->m_saveCameraInReplay /*&& TheRecorder->getMode() != RECORDERMODETYPE_PLAYBACK *//**/&& (TheGameLogic->isInSinglePlayerGame() || TheGameLogic->isInSkirmishGame())/**/)//if (TheGlobalData->m_saveCameraInReplay && (TheGameLogic->isInMultiplayerGame() || TheGameLogic->isInSinglePlayerGame() || TheGameLogic->isInSkirmishGame()))if (TheGlobalData->m_saveCameraInReplay && (TheGameLogic->isInSinglePlayerGame() || TheGameLogic->isInSkirmishGame()))diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cppindex 60fb66061..2a8853246 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/PlaceEventTranslator.cpp@@ -107,7 +107,7 @@ static Object *resolvePlacementBuilder( void )}//--------------------------------------------------------------------------------------------------PlaceEventTranslator::PlaceEventTranslator() : m_frameOfUpButton(-1), m_stripClickTaken(FALSE)+PlaceEventTranslator::PlaceEventTranslator() : m_frameOfUpButton(-1), m_stripClickTaken(FALSE), m_stripRightClickTaken(FALSE){}@@ -123,15 +123,43 @@ GameMessageDisposition PlaceEventTranslator::translateGameMessage(const GameMess{GameMessageDisposition disp = KEEP_MESSAGE;- // the up that closes a click the strip took is not a selection either- if( m_stripClickTaken && msg->getType() == GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP )+ // MetaEvent runs before us and inserts a logical click after the raw release.+ // Consume both: otherwise cancelling on the strip can also issue a world order.+ if( m_stripClickTaken && (msg->getType() == GameMessage::MSG_MOUSE_LEFT_CLICK ||+ msg->getType() == GameMessage::MSG_MOUSE_LEFT_DOUBLE_CLICK) ){m_stripClickTaken = FALSE;return DESTROY_MESSAGE;}+ if( m_stripClickTaken && (msg->getType() == GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP ||+ msg->getType() == GameMessage::MSG_RAW_MOUSE_LEFT_DRAG) )+ return DESTROY_MESSAGE;+ if( m_stripRightClickTaken )+ {+ if( msg->getType() == GameMessage::MSG_MOUSE_RIGHT_CLICK ||+ msg->getType() == GameMessage::MSG_MOUSE_RIGHT_DOUBLE_CLICK )+ {+ m_stripRightClickTaken = FALSE;+ return DESTROY_MESSAGE;+ }+ if( msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP ||+ msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_DRAG )+ return DESTROY_MESSAGE;+ }switch(msg->getType()){+ case GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN:+ case GameMessage::MSG_RAW_MOUSE_RIGHT_DOUBLE_CLICK:+ {+ m_stripRightClickTaken = FALSE;+ if( TheInGameUI->handleProductionStripClick( &msg->getArgument(0)->pixel, TRUE ) )+ {+ m_stripRightClickTaken = TRUE;+ return DESTROY_MESSAGE;+ }+ break;+ }//---------------------------------------------------------------------------------------------//@@ -145,10 +173,11 @@ GameMessageDisposition PlaceEventTranslator::translateGameMessage(const GameMesscase GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN:case GameMessage::MSG_RAW_MOUSE_LEFT_DOUBLE_CLICK:{+ m_stripClickTaken = FALSE;//// The global production strip lies over the world rather than inside a window, so// nothing above us has claimed a click on it. Take it here, before placement and long- // before selection turns it into a move order. Ctrl cancels the item, a plain click+ // before selection turns it into a move order. Right-click (or Ctrl-click) cancels one, a plain click// takes the camera to the building it is queued on.//if( TheInGameUI->handleProductionStripClick( &msg->getArgument(0)->pixel,diff --git a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cppindex 6b1ac34e2..6b9ab7aa0 100644--- a/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp+++ b/GeneralsMD/Code/GameEngine/Source/GameClient/MessageStream/WindowXlat.cpp@@ -50,6 +50,7 @@// USER INCLUDES //////////////////////////////////////////////////////////////#include "Common/MessageStream.h"+#include "Common/Radar.h"#include "GameClient/GameWindowManager.h"#include "GameClient/WindowXlat.h"#include "GameClient/Shell.h"@@ -157,7 +158,7 @@ static GameWindowMessage rawMouseToWindowMessage( const GameMessage *msg )/////////////////////////////////////////////////////////////////////////////////=============================================================================-WindowTranslator::WindowTranslator()+WindowTranslator::WindowTranslator() : m_rightClickTaken(FALSE){}@@ -175,8 +176,29 @@ GameMessageDisposition WindowTranslator::translateGameMessage(const GameMessageGameMessageDisposition disp = KEEP_MESSAGE;Bool forceKeepMessage = FALSE;WinInputReturnCode returnCode = WIN_INPUT_NOT_USED;+ if( msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN ||+ msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_DOUBLE_CLICK )+ m_rightClickTaken = FALSE;+ if( m_rightClickTaken && msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_DRAG )+ return DESTROY_MESSAGE;+ if( m_rightClickTaken && msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP )+ {+ m_rightClickTaken = FALSE;+ // Update the button's visual state, then swallow the release before MetaEvent can+ // turn it into a world click if the cursor moved away from the cancellation button.+ if( TheWindowManager )+ {+ ICoord2D mousePos = msg->getArgument(0)->pixel;+ TheWindowManager->winProcessMouseEvent(GWM_RIGHT_UP, &mousePos, NULL);+ }+ return DESTROY_MESSAGE;+ }- if (TheTacticalView && TheTacticalView->isMouseLocked())+ // A minimap press already owns its drag and its release, even if keyboard scrolling has locked+ // the tactical view's mouse input in the meantime.+ const Bool minimapGrab = TheWindowManager && TheRadar &&+ TheRadar->isRadarWindow( TheWindowManager->winGetGrabWindow() );+ if (TheTacticalView && TheTacticalView->isMouseLocked() && !minimapGrab){//Kris: Aug 15, 2003//Added the scrolling check that will not return KEEP_MESSAGE if we happen@@ -366,6 +388,9 @@ GameMessageDisposition WindowTranslator::translateGameMessage(const GameMessage// If TheShell doesn't exist, then well, we're not in RTS, we're in GUIEditif( returnCode == WIN_INPUT_USED && !forceKeepMessage )// || (TheShell && TheShell->isShellActive())){+ if( msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN ||+ msg->getType() == GameMessage::MSG_RAW_MOUSE_RIGHT_DOUBLE_CLICK )+ m_rightClickTaken = TRUE;disp = DESTROY_MESSAGE;}diff --git a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.hindex a9ad75717..fcfec2e88 100644--- a/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h+++ b/GeneralsMD/Code/GameEngineDevice/Include/W3DDevice/GameClient/W3DView.h@@ -43,6 +43,7 @@#include "Common/STLTypedefs.h"#include "GameClient/ParabolicEase.h"#include "GameClient/View.h"+#include "GameClient/CameraScrollClock.h"#include "WW3D2/Camera.h"// FORWARD REFERENCES /////////////////////////////////////////////////////////////////////////////@@ -276,6 +277,7 @@ private:Coord3D m_cameraOffset; ///< offset for camera from view centerCoord3D m_previousLookAtPosition; ///< offset for camera from view centerCoord2D m_scrollAmount; ///< scroll speed+ CameraScrollClock m_scrollClock; ///< elapsed render time, also sampled while idleReal m_scrollAmountCutoff; ///< scroll speed at which we do not adjust heightReal m_groundLevel; ///< height of ground.diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cppindex fb08ec359..71728457b 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DInGameUI.cpp@@ -873,8 +873,8 @@ void W3DInGameUI::drawFormationLine( void )TheDisplay->drawLine( curve[ i - 1 ].x, curve[ i - 1 ].y, curve[ i ].x, curve[ i ].y,width, color );- // no ticks along it any more. Every station already carries the cursor of the order it is about- // to receive, drawn by drawOrderHints off the same hints, and a tick beside a cursor was the+ // no ticks along it any more. Every station already carries the marker of the order it is about+ // to receive, drawn by drawOrderHints off the same hints, and a tick beside a marker was the// same fact said twice} // end drawFormationLine@@ -927,20 +927,11 @@ void W3DInGameUI::drawAttackCircle( void )} // end drawAttackCircle-//--------------------------------------------------------------------------------------------------/** The marker on a destination is the cursor the player would be holding if they were pointing at- * it: the move cursor for a move, the attack-move one for an attack-move, the attack one for an- * attack. Same art, out of Mouse.ini, so nothing here has to invent a second visual language. */-//--------------------------------------------------------------------------------------------------//--------------------------------------------------------------------------------------------------/** One cursor per order, out of the set the game already draws under the hand. A unit told to- * garrison shows the garrison cursor where it is going, one sent to a repair bay shows that one,- * and a group given four different jobs reads as four different markers rather than four arrows. *///-------------------------------------------------------------------------------------------------/** The thread is coloured by what it is for: anything that ends in a shot is red, an attack move- * is pink, a post to be held is blue, everything else is green. The marker on the end of it is- * the plain pointer in the same colour - one shape for every order, so the colour is the whole- * message. */+ * is pink, a post to be held is blue, everything else is green. The marker on the end of it is a+ * dot in the same colour, and an order that ends in a shot wears a ring instead, so the shape+ * still says which is which to somebody who cannot tell the red from the green. *///-------------------------------------------------------------------------------------------------static UnsignedInt orderHintLineColor( InGameUI::OrderHintKind kind ){@@ -964,140 +955,95 @@ static UnsignedInt orderHintMarkerColor( InGameUI::OrderHintKind kind )return orderHintLineColor( kind ) | 0xFF000000;}-struct OrderCursorArt+static Bool orderHintEndsInAShot( InGameUI::OrderHintKind kind ){- const Image *image;- ICoord2D hotSpot;- Bool tried;-};-static OrderCursorArt s_orderCursorArt[ Mouse::NUM_MOUSE_CURSORS ];+ return kind == InGameUI::ORDER_HINT_ATTACK || kind == InGameUI::ORDER_HINT_FORCE_ATTACK ||+ kind == InGameUI::ORDER_HINT_ATTACK_GROUND;+}++static Real edgeCoverage( Real edge )+{+ return edge < 0.0f ? 0.0f : ( edge > 1.0f ? 1.0f : edge );+}//--------------------------------------------------------------------------------------------------/** Turn one Windows cursor into something the 2D renderer can draw. Mouse.ini's Image entries- * name mapped images that do not exist in the shipped data, and the Texture entries name .ANI- * files rather than textures - so the art the player is actually holding only exists as an HCURSOR.- * Pull the first frame's bits out of it and keep them as a texture. */+/** A marker is drawn once into a texture several times the size it is shown at, so the shrink on+ * the way to the screen leaves a soft edge at any resolution. The body is near white and takes+ * the order's colour from the tint; the outline is near black and stays dark on any ground. *///--------------------------------------------------------------------------------------------------static const Image *loadOrderCursorImage( Mouse::MouseCursor cursor, ICoord2D *hotSpot )+static const Image *buildOrderMarkerImage( Bool ring ){- const AsciiString& name = TheMouse->m_cursorInfo[ cursor ].textureName;- if( name.isEmpty() )- return NULL;-- char path[ 256 ];- snprintf( path, ARRAY_SIZE(path), "data\\cursors\\%s.ANI", name.str() );-- HCURSOR hcursor = LoadCursorFromFile( path );- if( hcursor == NULL )- return NULL;-- ICONINFO info;- if( GetIconInfo( hcursor, &info ) == FALSE )- return NULL;-- const Image *result = NULL;-- BITMAP bm;- if( info.hbmColor && GetObject( info.hbmColor, sizeof( BITMAP ), &bm ) )+ const Int size = 64;+ const Real centre = size * 0.5f;+ const Real outer = size * 0.47f; // outside edge of the outline+ const Real body = outer * 0.72f; // where the outline gives way to the body+ const Real hole = outer * 0.38f; // inside edge of a ring's inner outline+ const Real holeBody = hole + ( outer - body ); // where that inner outline gives way to the body+ const Real OUTLINE_GREY = 24.0f;+ const Real BODY_GREY = 245.0f;++ TextureClass *texture = MSGNEW("TextureClass") TextureClass( size, size, WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_1 );+ SurfaceClass *surface = texture->Get_Surface_Level();+ Int pitch;+ UnsignedByte *bits = (UnsignedByte *)surface->Lock( &pitch );+ for( Int y = 0; y < size; ++y ){- const Int w = bm.bmWidth;- const Int h = bm.bmHeight;-- BITMAPINFO bi;- memset( &bi, 0, sizeof( bi ) );- bi.bmiHeader.biSize = sizeof( BITMAPINFOHEADER );- bi.bmiHeader.biWidth = w;- bi.bmiHeader.biHeight = -h; // negative means top down, which is the order a texture wants- bi.bmiHeader.biPlanes = 1;- bi.bmiHeader.biBitCount = 32;- bi.bmiHeader.biCompression = BI_RGB;-- UnsignedInt *color = NEW UnsignedInt[ w * h ];- UnsignedInt *mask = NEW UnsignedInt[ w * h ];-- HDC dc = GetDC( NULL );- GetDIBits( dc, info.hbmColor, 0, h, color, &bi, DIB_RGB_COLORS );- GetDIBits( dc, info.hbmMask, 0, h, mask, &bi, DIB_RGB_COLORS );- ReleaseDC( NULL, dc );-- //- // a 32-bit cursor carries its own alpha; an older one leaves it zero and says what is- // transparent in the AND mask instead, where a white pixel is a hole- //- Bool hasAlpha = FALSE;- for( Int i = 0; i < w * h; ++i )- if( color[ i ] & 0xFF000000 )+ UnsignedInt *pixel = (UnsignedInt *)( bits + y * pitch );+ for( Int x = 0; x < size; ++x )+ {+ const Real dx = x + 0.5f - centre;+ const Real dy = y + 0.5f - centre;+ const Real distance = (Real)sqrt( dx * dx + dy * dy );+ Real alpha = edgeCoverage( outer + 0.5f - distance );+ Real light = edgeCoverage( body + 0.5f - distance );+ if( ring ){- hasAlpha = TRUE;- break;+ alpha *= edgeCoverage( distance - ( hole - 0.5f ) );+ light *= edgeCoverage( distance - ( holeBody - 0.5f ) );}-- if( hasAlpha == FALSE )- for( Int i = 0; i < w * h; ++i )- color[ i ] |= (mask[ i ] & 0x00FFFFFF) ? 0x00000000 : 0xFF000000;-- TextureClass *texture = MSGNEW("TextureClass") TextureClass( w, h, WW3D_FORMAT_A8R8G8B8, MIP_LEVELS_1 );- SurfaceClass *surface = texture->Get_Surface_Level();- Int pitch;- UnsignedByte *bits = (UnsignedByte *)surface->Lock( &pitch );- for( Int row = 0; row < h; ++row )- memcpy( bits + row * pitch, color + row * w, w * sizeof( UnsignedInt ) );- surface->Unlock();- REF_PTR_RELEASE( surface );-- delete [] color;- delete [] mask;-- Image *image = newInstance(Image);- Region2D uv;- uv.lo.x = 0.0f;- uv.lo.y = 0.0f;- uv.hi.x = 1.0f;- uv.hi.y = 1.0f;- image->setStatus( IMAGE_STATUS_RAW_TEXTURE );- image->setRawTextureData( texture );- image->setUV( &uv );- image->setTextureWidth( w );- image->setTextureHeight( h );- ICoord2D size;- size.x = w;- size.y = h;- image->setImageSize( &size );-- hotSpot->x = info.xHotspot;- hotSpot->y = info.yHotspot;- result = image;+ const UnsignedInt grey = (UnsignedInt)REAL_TO_INT( OUTLINE_GREY + light * ( BODY_GREY - OUTLINE_GREY ) );+ const UnsignedInt opacity = (UnsignedInt)REAL_TO_INT( alpha * 255.0f );+ pixel[ x ] = ( opacity << 24 ) | ( grey << 16 ) | ( grey << 8 ) | grey;+ }}-- if( info.hbmColor )- DeleteObject( info.hbmColor );- if( info.hbmMask )- DeleteObject( info.hbmMask );-- return result;+ surface->Unlock();+ REF_PTR_RELEASE( surface );++ Image *image = newInstance(Image);+ Region2D uv;+ uv.lo.x = 0.0f;+ uv.lo.y = 0.0f;+ uv.hi.x = 1.0f;+ uv.hi.y = 1.0f;+ image->setStatus( IMAGE_STATUS_RAW_TEXTURE );+ image->setRawTextureData( texture );+ image->setUV( &uv );+ image->setTextureWidth( size );+ image->setTextureHeight( size );+ ICoord2D dimensions;+ dimensions.x = size;+ dimensions.y = size;+ image->setImageSize( &dimensions );+ return image;}//--------------------------------------------------------------------------------------------------/** The marker on a destination is the cursor the player would be holding if they were pointing at- * it: the move cursor for a move, the attack-move one for an attack-move, the attack one for an- * attack. Same art, so nothing here has to invent a second visual language. Built once. */+/** The dot for anything that goes somewhere, the ring for anything that ends in a shot. Built the+ * first time each is drawn. *///--------------------------------------------------------------------------------------------------static const Image *orderCursorImage( Mouse::MouseCursor cursor, ICoord2D *hotSpot )+static const Image *orderMarkerImage( Bool ring ){- OrderCursorArt& art = s_orderCursorArt[ cursor ];- if( art.tried == FALSE )- {- art.image = loadOrderCursorImage( cursor, &art.hotSpot );- art.tried = TRUE;- }-- *hotSpot = art.hotSpot;- return art.image;+ static const Image *s_dot = NULL;+ static const Image *s_ring = NULL;+ const Image *&image = ring ? s_ring : s_dot;+ if( image == NULL )+ image = buildOrderMarkerImage( ring );+ return image;}//-------------------------------------------------------------------------------------------------/** One faint line per selected unit, from where it stands to where it is going, with the order's- * own cursor sitting on the destination. Green for a move, pink for an attack-move, red for an+ * marker sitting on the destination. Green for a move, pink for an attack-move, red for an* attack. The goals are read off the units every frame, so the lines last as long as the orders* do and go when the units arrive or the selection changes. *///-------------------------------------------------------------------------------------------------@@ -1113,7 +1059,9 @@ void W3DInGameUI::drawOrderHints( void )// has just been given announces itself instead of appearing fully formed. Wall clock rather// than frames: the picture is uncapped, so a frame count would run at the frame rate.const UnsignedInt MARKER_SLIDE_MS = 130;- const Real MARKER_SLIDE_PIXELS = 13.0f;+ const Real MARKER_SLIDE_PIXELS = 8.0f; // at 800x600, like the diameter+ const Real MARKER_DIAMETER = 11.0f;+ const Real uiScale = TheUIScale();const UnsignedInt nowMs = timeGetTime();@@ -1144,19 +1092,16 @@ void W3DInGameUI::drawOrderHints( void )if( TheGlobalData->m_showOrderLines )TheDisplay->drawLine( from.x, from.y, to.x, to.y, width, lineColor );- // the marker is the plain pointer, tinted: its white body takes the order colour and the- // dark outline stays. The hot spot is the pixel the player aims with, so that is the pixel- // that goes on the destination - a pointer hung by its top left corner points at the wrong- // ground- ICoord2D hotSpot;- const Image *image = orderCursorImage( Mouse::ARROW, &hotSpot );+ // the marker sits centred on the destination, and grows with the screen the way a health bar+ // does+ const Image *image = orderMarkerImage( orderHintEndsInAShot( it->kind ) );if( image ){- const Int w = image->getImageWidth();- const Int h = image->getImageHeight();- const Int slide = REAL_TO_INT_FLOOR( ( 1.0f - eased ) * MARKER_SLIDE_PIXELS );- const Int x = to.x - hotSpot.x + slide;- const Int y = to.y - hotSpot.y + slide;+ const Int w = REAL_TO_INT( MARKER_DIAMETER * uiScale );+ const Int h = w;+ const Int slide = REAL_TO_INT_FLOOR( ( 1.0f - eased ) * MARKER_SLIDE_PIXELS * uiScale );+ const Int x = to.x - w / 2 + slide;+ const Int y = to.y - h / 2 + slide;// the tint carries the fade as well as the order's colourconst UnsignedInt markerColor = ( orderHintMarkerColor( it->kind ) & 0x00FFFFFF )diff --git a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cppindex 09c8c6000..77dd66433 100644--- a/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp+++ b/GeneralsMD/Code/GameEngineDevice/Source/W3DDevice/GameClient/W3DView.cpp@@ -49,6 +49,7 @@#include "Common/Player.h"#include "GameClient/Color.h"+#include "GameClient/CameraBoundary.h"#include "GameClient/CommandXlat.h"#include "GameClient/Drawable.h"#include "GameClient/GameClient.h"@@ -177,6 +178,10 @@ W3DView::W3DView()m_FXPitch = 1.0f;m_freezeTimeForCameraMovement = false;m_cameraHasMovedSinceRequest = true;+ // Scripted pans may expand this region even while map constraints are disabled.+ m_cameraConstraint.lo.x = m_cameraConstraint.lo.y = 0.0f;+ m_cameraConstraint.hi.x = m_cameraConstraint.hi.y = 0.0f;+ m_cameraConstraintValid = false;m_locationRequests.clear();m_locationRequests.reserve(MAX_REQUEST_CACHE_SIZE + 10); // This prevents the vector from ever re-allocing@@ -295,12 +300,9 @@ void W3DView::buildCameraTransform( Matrix3D *transform )pos.x += m_shakeOffset.x;pos.y += m_shakeOffset.y;- if (m_cameraConstraintValid)+ if (TheGlobalData->m_useCameraConstraints && m_cameraConstraintValid){- pos.x = maxf(m_cameraConstraint.lo.x, pos.x);- pos.x = minf(m_cameraConstraint.hi.x, pos.x);- pos.y = maxf(m_cameraConstraint.lo.y, pos.y);- pos.y = minf(m_cameraConstraint.hi.y, pos.y);+ pos = constrainCameraPosition(pos, m_cameraConstraint);}// set position of camera itself@@ -530,6 +532,13 @@ void W3DView::calcCameraConstraints(){Region3D mapRegion;TheTerrainLogic->getExtent( &mapRegion );+ if (TheGlobalData->m_cameraBoundaryMargin > 0)+ {+ // A fixed margin follows the map rather than shrinking with zoom or camera angle.+ m_cameraConstraint = cameraBoundaryFromMap(mapRegion, (Real)TheGlobalData->m_cameraBoundaryMargin);+ m_cameraConstraintValid = true;+ return;+ }/*Note the following restrictions on camera constraints!@@ -672,9 +681,7 @@ void W3DView::setCameraTransform( void )}m_3DCamera->Set_Clip_Planes(nearZ, farZ);-#if defined(_DEBUG) || defined(_INTERNAL)if (TheGlobalData->m_useCameraConstraints)-#endif{if (!m_cameraConstraintValid){@@ -686,11 +693,7 @@ void W3DView::setCameraTransform( void )if (m_cameraConstraintValid){- Coord3D pos = *getPosition();- pos.x = maxf(m_cameraConstraint.lo.x, pos.x);- pos.x = minf(m_cameraConstraint.hi.x, pos.x);- pos.y = maxf(m_cameraConstraint.lo.y, pos.y);- pos.y = minf(m_cameraConstraint.hi.y, pos.y);+ Coord3D pos = constrainCameraPosition(*getPosition(), m_cameraConstraint);setPosition(&pos);}}@@ -2097,27 +2100,19 @@ void W3DView::setSnapMode( CameraLockType lockType, Real lockDist )//-------------------------------------------------------------------------------------------------void W3DView::scrollBy( Coord2D *delta ){- // if we haven't moved, ignore+ // Sample every render tick, including zero movement. Measuring only nonzero scrolls+ // includes all the idle time in the first move and produces a jump on every restart.+ const Real scrollDtFactor = m_scrollClock.sample(timeGetTime(), TheW3DFrameLengthInMsec);+ if (delta)+ m_scrollAmount = *delta;+if( delta && (delta->x != 0 || delta->y != 0) ){const Real SCROLL_RESOLUTION = 250.0f;- // The scroll offsets are tuned as per-30Hz-tick amounts but arrive once per render- // frame, so scale the applied movement by real elapsed time to keep scroll speed- // framerate-independent. m_scrollAmount stays unscaled - the height-adjust cutoff- // in update() compares it against per-tick thresholds.- static DWORD prevScrollTime = timeGetTime();- DWORD nowScrollTime = timeGetTime();- Real scrollDtFactor = (nowScrollTime - prevScrollTime) / (Real)TheW3DFrameLengthInMsec;- prevScrollTime = nowScrollTime;- if (scrollDtFactor > 3.0f)- scrollDtFactor = 3.0f; // after a hitch or idle, don't teleport the camera-Vector3 world, worldStart, worldEnd;Vector2 screen, start, end;- m_scrollAmount = *delta;-screen.X = delta->x;screen.Y = delta->y;diff --git a/GeneralsMD/Code/Tests/test_camera_behavior.inc b/GeneralsMD/Code/Tests/test_camera_behavior.incnew file mode 100644index 000000000..d89bdf1e6--- /dev/null+++ b/GeneralsMD/Code/Tests/test_camera_behavior.inc@@ -0,0 +1,186 @@+// Exercise upstream camera input and GUI routing with lightweight subsystem fixtures.+#include "GameClient/LookAtXlat.h"+#include "GameClient/CameraBoundary.h"+#include "GameClient/MetaEvent.h"+#include "GameClient/Keyboard.h"+#include "GameClient/KeyDefs.h"+#include "GameClient/Shell.h"+#include "GameClient/GameWindowManager.h"+#include "Common/StatsCollector.h"+#include "Common/PlayerList.h"+#include "GameLogic/RankInfo.h"+#include "GameLogic/GameLogic.h"++namespace+{+class CameraTestKeyboard : public Keyboard+{+public:+ Bool getCapsState() { return FALSE; }+ void getKey(KeyboardIO *key) { key->key = KEY_NONE; }+ void modifiers(Int flags) { m_modifiers = flags; }+};++class CameraTestMouse : public Mouse+{+public:+ Int cursorChanges = 0, captures = 0, releases = 0;+ void initCursorResources() {}+ void setCursor(MouseCursor cursor) { m_currentCursor = cursor; ++cursorChanges; }+ void capture() { ++captures; }+ void releaseCapture() { ++releases; }+ UnsignedByte getMouseEvent(MouseIO*, Bool) { return 0; }+};++class CameraTestUI : public InGameUI+{+public:+ void draw() {}+ View *createView() { return NULL; }+ Bool scrolling = FALSE, selecting = FALSE, enabled = TRUE;+ void setScrolling(Bool value) { InGameUI::setScrolling(value); scrolling = value; }+ Bool isScrolling() { return scrolling; }+ Bool isSelecting() { return selecting; }+ Bool getInputEnabled() { return enabled; }+};++class CameraTestView : public View+{+public:+ using View::getPosition;+ using View::setPosition;+ Coord2D last = {0, 0};+ Int samples = 0;+ Int constraintRecalcs = 0;+ Bool terrainHit = FALSE;+ Coord3D terrainPoint = {0, 0, 0};+ Int terrainPicks = 0;+ Int lookAtCalls = 0;+ void lookAt(const Coord3D *pos) { ++lookAtCalls; setPosition(pos); }+ void forceCameraConstraintRecalc() { ++constraintRecalcs; }+ void scrollBy(Coord2D *delta) { last = *delta; ++samples; }+ Drawable *pickDrawable(const ICoord2D*, Bool, PickType) { return NULL; }+ Int iterateDrawablesInRegion(IRegion2D*, Bool (*)(Drawable*, void*), void*) { return 0; }+ void forceRedraw() {}+ const Coord3D& get3DCameraPosition() const { return m_pos; }+ WorldToScreenReturn worldToScreenTriReturn(const Coord3D*, ICoord2D*) { return WTS_INSIDE_FRUSTUM; }+ void screenToWorld(const ICoord2D*, Coord3D*) {}+ Bool screenToTerrain(const ICoord2D*, Coord3D *world)+ { ++terrainPicks; *world = terrainPoint; return terrainHit; }+ void screenToWorldAtZ(const ICoord2D*, Coord3D *world, Real z)+ { *world = terrainPoint; world->z = z; }+ void drawView() {}+ void updateView() {}+ void setGuardBandBias(const Coord2D*) {}+};++struct CameraInputFixture+{+ GlobalData *savedGlobal = TheWritableGlobalData;+ InGameUI *savedUI = TheInGameUI;+ View *savedView = TheTacticalView;+ Keyboard *savedKeyboard = TheKeyboard;+ Mouse *savedMouse = TheMouse;+ Shell *savedShell = TheShell;+ GameWindowManager *savedWindows = TheWindowManager;+ StatsCollector *savedStats = TheStatsCollector;+ PlayerList *savedPlayers = ThePlayerList;+ RankInfoStore *savedRanks = TheRankInfoStore;+ GameLogic *savedLogic = TheGameLogic;+ GlobalData *global;+ CameraTestUI *ui;+ CameraTestView view;+ CameraTestKeyboard keyboard;+ CameraTestMouse mouse;+ LookAtTranslator camera;++ CameraInputFixture()+ {+ global = NEW GlobalData;+ TheWritableGlobalData = global;+ // Like bootOnce's subsystems, keep one UI until process exit. Its production destructor+ // requires a fully built control bar and a device, which this input test does not create.+ static CameraTestUI *testUI = NEW CameraTestUI;+ ui = testUI;+ ui->scrolling = ui->selecting = FALSE;+ ui->enabled = TRUE;+ TheInGameUI = ui;+ TheTacticalView = &view;+ TheKeyboard = &keyboard;+ TheMouse = &mouse;+ TheShell = NULL;+ TheWindowManager = NULL;+ TheStatsCollector = NULL;+ static RankInfoStore *ranks = NEW RankInfoStore;+ TheRankInfoStore = ranks;+ static PlayerList *players = NEW PlayerList;+ ThePlayerList = players;+ static GameLogic *logic = NEW GameLogic;+ TheGameLogic = logic;+ global->m_saveCameraInReplay = FALSE;+ }+ ~CameraInputFixture()+ {+ camera.resetModes();+ TheInGameUI = savedUI;+ TheTacticalView = savedView;+ TheKeyboard = savedKeyboard;+ TheMouse = savedMouse;+ TheShell = savedShell;+ TheWindowManager = savedWindows;+ TheStatsCollector = savedStats;+ ThePlayerList = savedPlayers;+ TheRankInfoStore = savedRanks;+ TheGameLogic = savedLogic;+ TheWritableGlobalData = savedGlobal;+ delete global;+ }+};+}++TEST(camera_margin_allows_map_corners_but_bounds_large_pans)+{+ const Region3D maps[] = {+ {{0, 0, 0}, {3000, 2000, 100}},+ {{-500, 700, -20}, {-450, 730, 80}} // small map with a nonzero origin+ };+ for (Int m = 0; m < 2; ++m)+ {+ const Region3D& map = maps[m];+ const Region2D boundary = cameraBoundaryFromMap(map, 200.0f);+ for (Int x = 0; x < 2; ++x)+ for (Int y = 0; y < 2; ++y)+ {+ Coord3D corner = {x ? map.hi.x : map.lo.x, y ? map.hi.y : map.lo.y, 42.0f};+ Coord3D allowed = constrainCameraPosition(corner, boundary);+ CHECK(allowed == corner); // every map corner must remain reachable+ corner.x += x ? 100.0f : -100.0f;+ corner.y += y ? 100.0f : -100.0f;+ allowed = constrainCameraPosition(corner, boundary);+ CHECK(allowed == corner); // there is useful room outside both edges+ Coord3D outsideMap = {x ? 1e7f : -1e7f, y ? 1e7f : -1e7f, corner.z};+ Coord3D limited = constrainCameraPosition(outsideMap, boundary);+ CHECK_NEAR(limited.x, (x ? map.hi.x + 200.0f : map.lo.x - 200.0f), 0.00001f);+ CHECK_NEAR(limited.y, (y ? map.hi.y + 200.0f : map.lo.y - 200.0f), 0.00001f);+ CHECK_EQ(limited.z, corner.z);+ Coord3D inward = limited;+ inward.x += x ? -10.0f : 10.0f;+ inward.y += y ? -10.0f : 10.0f;+ allowed = constrainCameraPosition(inward, boundary);+ CHECK(allowed == inward); // reaching a corner must not trap the camera+ }+ }+}++TEST(camera_margin_preferences_load_and_rebuild_constraints)+{+ CHECK(bootOnce());+ CameraInputFixture f;+ UserPreferences pref;+ pref[AsciiString("UseCameraConstraints")] = AsciiString("Yes");+ pref[AsciiString("CameraBoundaryMargin")] = AsciiString("300");+ loadOptionsFromPreferences(pref);+ CHECK(f.global->m_useCameraConstraints);+ CHECK_EQ(f.global->m_cameraBoundaryMargin, 300);+ CHECK_EQ(f.view.constraintRecalcs, 1);+}diff --git a/GeneralsMD/Code/Tests/test_gameengine.cpp b/GeneralsMD/Code/Tests/test_gameengine.cppindex b0ea75e14..ba3facb5e 100644--- a/GeneralsMD/Code/Tests/test_gameengine.cpp+++ b/GeneralsMD/Code/Tests/test_gameengine.cpp@@ -11989,3 +11989,62 @@ TEST(button_flash_draws_nothing_for_a_button_the_layout_lacks)CHECK_EQ( flash.drawState(), (Int)ButtonFlashWithoutWindow::NOTHING_TO_DRAW );}}++// Camera scroll timing must advance during stationary frames as well as moving frames.+#include "GameClient/CameraScrollClock.h"++TEST(camera_scroll_restarts_after_idle_without_a_jump)+{+ CameraScrollClock clock;+ CHECK_NEAR(clock.sample(1000, 33), 0.0f, 0.00001f);+ for (uint32_t now = 1016; now <= 17000; now += 16)+ clock.sample(now, 33); // stationary render frames+ CHECK_NEAR(clock.sample(17016, 33), 16.0f / 33.0f, 0.00001f);+ CHECK_NEAR(clock.sample(17032, 33), 16.0f / 33.0f, 0.00001f);+}++TEST(camera_scroll_elapsed_time_is_independent_of_render_rate)+{+ const int rates[] = {30, 60, 144, 240};+ for (int r = 0; r < 4; ++r)+ {+ CameraScrollClock clock;+ clock.sample(1000, 33);+ float distance = 0.0f;+ for (int frame = 1; frame <= rates[r]; ++frame)+ distance += clock.sample(1000 + frame * 1000 / rates[r], 33);+ CHECK_NEAR(distance, 1000.0f / 33.0f, 0.0001f);+ }+}++TEST(camera_scroll_clocks_are_independent_and_handle_timer_wrap)+{+ CameraScrollClock first, second;+ first.sample(0xfffffff0u, 33);+ second.sample(2000, 33);+ CHECK_NEAR(first.sample(0u, 33), 16.0f / 33.0f, 0.00001f);+ CHECK_NEAR(second.sample(2033, 33), 1.0f, 0.00001f);+ CHECK_NEAR(second.sample(9000, 33), 3.0f, 0.00001f);+}++TEST(camera_preferences_default_to_a_finite_map_margin)+{+ CHECK(bootOnce());+ GlobalData *saved = TheWritableGlobalData;+ GlobalData *scratch = NEW GlobalData;+ TheWritableGlobalData = scratch;+ CHECK(scratch->m_useCameraConstraints);+ CHECK_EQ(scratch->m_cameraBoundaryMargin, 200);+ const OptionDef *bounds = findOptionDef("UseCameraConstraints");+ CHECK(bounds != NULL);+ if (bounds)+ {+ bounds->set(0);+ CHECK(!scratch->m_useCameraConstraints);+ }+ TheWritableGlobalData = saved;+ delete scratch;+}+#include "test_camera_behavior.inc"+#include "test_production_input.inc"+#include "test_minimap_input.inc"diff --git a/GeneralsMD/Code/Tests/test_minimap_input.inc b/GeneralsMD/Code/Tests/test_minimap_input.incnew file mode 100644index 000000000..926899dc3--- /dev/null+++ b/GeneralsMD/Code/Tests/test_minimap_input.inc@@ -0,0 +1,342 @@+// Drive minimap gestures through the actual window and mouse message translators.+#include "GameClient/MetaEvent.h"+#include "GameClient/Keyboard.h"+#include "GameClient/KeyDefs.h"+#include "GameClient/Shell.h"+#include "GameClient/GameWindowManager.h"+#include "GameClient/WindowXlat.h"+#include "GameClient/GUICallbacks.h"+#include "Common/Radar.h"+#include "Common/StatsCollector.h"+#include "Common/PlayerList.h"+#include "GameLogic/RankInfo.h"+#include "GameLogic/GameLogic.h"++namespace+{+class MinimapInputKeyboard : public Keyboard+{+public:+ Bool getCapsState() { return FALSE; }+ void getKey(KeyboardIO *key) { key->key = KEY_NONE; }+ void modifiers(Int flags) { m_modifiers = flags; }+};++class MinimapInputMouse : public Mouse+{+public:+ Int cursorChanges = 0, captures = 0, releases = 0;+ void initCursorResources() {}+ void setCursor(MouseCursor cursor) { m_currentCursor = cursor; ++cursorChanges; }+ void capture() { ++captures; }+ void releaseCapture() { ++releases; }+ UnsignedByte getMouseEvent(MouseIO*, Bool) { return 0; }+};++class MinimapInputUI : public InGameUI+{+public:+ void draw() {}+ View *createView() { return NULL; }+ Bool scrolling = FALSE, selecting = FALSE, enabled = TRUE;+ void setScrolling(Bool value) { InGameUI::setScrolling(value); scrolling = value; }+ Bool isScrolling() { return scrolling; }+ Bool isSelecting() { return selecting; }+ Bool getInputEnabled() { return enabled; }+};++class MinimapInputView : public View+{+public:+ using View::getPosition;+ using View::setPosition;+ Coord2D last = {0, 0};+ Int samples = 0;+ Int constraintRecalcs = 0;+ Bool terrainHit = FALSE;+ Coord3D terrainPoint = {0, 0, 0};+ Int terrainPicks = 0;+ Int lookAtCalls = 0;+ void lookAt(const Coord3D *pos) { ++lookAtCalls; setPosition(pos); }+ void forceCameraConstraintRecalc() { ++constraintRecalcs; }+ void scrollBy(Coord2D *delta) { last = *delta; ++samples; }+ Drawable *pickDrawable(const ICoord2D*, Bool, PickType) { return NULL; }+ Int iterateDrawablesInRegion(IRegion2D*, Bool (*)(Drawable*, void*), void*) { return 0; }+ void forceRedraw() {}+ const Coord3D& get3DCameraPosition() const { return m_pos; }+ WorldToScreenReturn worldToScreenTriReturn(const Coord3D*, ICoord2D*) { return WTS_INSIDE_FRUSTUM; }+ void screenToWorld(const ICoord2D*, Coord3D*) {}+ Bool screenToTerrain(const ICoord2D*, Coord3D *world)+ { ++terrainPicks; *world = terrainPoint; return terrainHit; }+ void screenToWorldAtZ(const ICoord2D*, Coord3D *world, Real z)+ { *world = terrainPoint; world->z = z; }+ void drawView() {}+ void updateView() {}+ void setGuardBandBias(const Coord2D*) {}+};++struct MinimapEngineFixture+{+ GlobalData *savedGlobal = TheWritableGlobalData;+ InGameUI *savedUI = TheInGameUI;+ View *savedView = TheTacticalView;+ Keyboard *savedKeyboard = TheKeyboard;+ Mouse *savedMouse = TheMouse;+ Shell *savedShell = TheShell;+ GameWindowManager *savedWindows = TheWindowManager;+ StatsCollector *savedStats = TheStatsCollector;+ PlayerList *savedPlayers = ThePlayerList;+ RankInfoStore *savedRanks = TheRankInfoStore;+ GameLogic *savedLogic = TheGameLogic;+ GlobalData *global;+ MinimapInputUI *ui;+ MinimapInputView view;+ MinimapInputKeyboard keyboard;+ MinimapInputMouse mouse;++ MinimapEngineFixture()+ {+ global = NEW GlobalData;+ TheWritableGlobalData = global;+ // Like bootOnce's subsystems, keep one UI until process exit. Its production destructor+ // requires a fully built control bar and a device, which this input test does not create.+ static MinimapInputUI *testUI = NEW MinimapInputUI;+ ui = testUI;+ ui->scrolling = ui->selecting = FALSE;+ ui->enabled = TRUE;+ TheInGameUI = ui;+ TheTacticalView = &view;+ TheKeyboard = &keyboard;+ TheMouse = &mouse;+ TheShell = NULL;+ TheWindowManager = NULL;+ TheStatsCollector = NULL;+ static RankInfoStore *ranks = NEW RankInfoStore;+ TheRankInfoStore = ranks;+ static PlayerList *players = NEW PlayerList;+ ThePlayerList = players;+ static GameLogic *logic = NEW GameLogic;+ TheGameLogic = logic;+ global->m_saveCameraInReplay = FALSE;+ }+ ~MinimapEngineFixture()+ {+ TheInGameUI = savedUI;+ TheTacticalView = savedView;+ TheKeyboard = savedKeyboard;+ TheMouse = savedMouse;+ TheShell = savedShell;+ TheWindowManager = savedWindows;+ TheStatsCollector = savedStats;+ ThePlayerList = savedPlayers;+ TheRankInfoStore = savedRanks;+ TheGameLogic = savedLogic;+ TheWritableGlobalData = savedGlobal;+ delete global;+ }+};++class MinimapWindow : public GameWindow+{+ MEMORY_POOL_GLUE_WITH_EXPLICIT_CREATE(MinimapWindow, "MinimapWindow", 16, 16)+public:+ void winDrawBorder() {}+ void winSetFont(GameFont*) {}+};+MinimapWindow::~MinimapWindow() {}++class MinimapWindows : public GameWindowManager+{+public:+ GameWindow *allocateNewWindow() { return newInstance(MinimapWindow)(); }+ GameFont *winFindFont(AsciiString, Int, Bool) { return NULL; }+ GameWinDrawFunc getPushButtonImageDrawFunc() { return NULL; }+ GameWinDrawFunc getPushButtonDrawFunc() { return NULL; }+ GameWinDrawFunc getCheckBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getCheckBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getRadioButtonImageDrawFunc() { return NULL; }+ GameWinDrawFunc getRadioButtonDrawFunc() { return NULL; }+ GameWinDrawFunc getTabControlImageDrawFunc() { return NULL; }+ GameWinDrawFunc getTabControlDrawFunc() { return NULL; }+ GameWinDrawFunc getListBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getListBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getComboBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getComboBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getHorizontalSliderImageDrawFunc() { return NULL; }+ GameWinDrawFunc getHorizontalSliderDrawFunc() { return NULL; }+ GameWinDrawFunc getVerticalSliderImageDrawFunc() { return NULL; }+ GameWinDrawFunc getVerticalSliderDrawFunc() { return NULL; }+ GameWinDrawFunc getProgressBarImageDrawFunc() { return NULL; }+ GameWinDrawFunc getProgressBarDrawFunc() { return NULL; }+ GameWinDrawFunc getStaticTextImageDrawFunc() { return NULL; }+ GameWinDrawFunc getStaticTextDrawFunc() { return NULL; }+ GameWinDrawFunc getTextEntryImageDrawFunc() { return NULL; }+ GameWinDrawFunc getTextEntryDrawFunc() { return NULL; }+};++struct MinimapMessages+{+ MessageStream stream;+ CommandList commands;+ MessageStream *savedStream = TheMessageStream;+ CommandList *savedCommands = TheCommandList;+ MinimapMessages()+ {+ TheMessageStream = &stream;+ TheCommandList = &commands;+ stream.attachTranslator(NEW MetaEventTranslator, 20);+ }+ ~MinimapMessages()+ {+ TheMessageStream = savedStream;+ TheCommandList = savedCommands;+ }+};++class MinimapTestRadar : public Radar+{+public:+ void configure(GameWindow *window, Real width = 1280, Real height = 1280)+ {+ m_radarWindow = window;+ m_mapExtent.lo.zero();+ m_mapExtent.hi.x = width;+ m_mapExtent.hi.y = height;+ m_xSample = width / RADAR_CELL_WIDTH;+ m_ySample = height / RADAR_CELL_HEIGHT;+ forceOn(TRUE);+ }+ void draw(Int, Int, Int, Int) {}+ void clearShroud() {}+ void setShroudLevel(Int, Int, CellShroudStatus) {}+};++class MinimapTestTerrain : public TerrainLogic+{+public:+ Real getGroundHeight(Real, Real, Coord3D* = NULL) const { return 25; }+};++class MinimapTestUI : public MinimapInputUI+{+public:+ DrawableList selected;+ const DrawableList *getAllSelectedLocalDrawables() { return &selected; }+};++struct MinimapInputFixture+{+ MinimapEngineFixture engine;+ MinimapWindows windows;+ MinimapTestRadar radar;+ MinimapTestTerrain terrain;+ Radar *savedRadar = TheRadar;+ TerrainLogic *savedTerrain = TheTerrainLogic;+ GameWindow *window;+ MinimapInputFixture()+ {+ TheWindowManager = &windows;+ TheRadar = &radar;+ TheTerrainLogic = &terrain;+ window = windows.winCreate(NULL, WIN_STATUS_ENABLED, 100, 200, 128, 128, NULL);+ window->winSetInputFunc(LeftHUDInput);+ radar.configure(window);+ static MinimapTestUI *ui = NEW MinimapTestUI;+ ui->selected.clear();+ ui->scrolling = ui->selecting = FALSE;+ ui->enabled = TRUE;+ TheInGameUI = ui;+ }+ ~MinimapInputFixture()+ {+ windows.winDestroyAll();+ TheRadar = savedRadar;+ TheTerrainLogic = savedTerrain;+ }+ void event(MinimapMessages &messages, GameMessage::Type type, Int x, Int y)+ {+ GameMessage *message = messages.stream.appendMessage(type);+ ICoord2D pixel = {x, y};+ message->appendPixelArgument(pixel);+ if(type == GameMessage::MSG_RAW_MOUSE_LEFT_DRAG)+ {+ ICoord2D delta = {1, 1};+ message->appendPixelArgument(delta);+ }+ else+ message->appendIntegerArgument(0);+ message->appendIntegerArgument(100);+ messages.stream.propagateMessages();+ }+};+}++TEST(minimap_drag_tracks_held_left_click_and_stops_on_release_with_units_selected)+{+ CHECK(bootOnce());+ MinimapInputFixture f;+ MinimapMessages messages;+ messages.stream.attachTranslator(NEW WindowTranslator, 10);+ // A selected unit must not turn left dragging into move orders.+ ((MinimapTestUI*)TheInGameUI)->selected.push_back(NULL);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN, 120, 220);+ CHECK(f.engine.view.lookAtCalls == 1);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 150, 250);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 190, 290);+ CHECK(f.engine.view.lookAtCalls == 3);+ CHECK(f.engine.view.getPosition()->x == 900);+ CHECK(f.engine.view.getPosition()->y == 380);+ CHECK(f.engine.view.getPosition()->z == 25);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP, 190, 290);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_POSITION, 130, 230);+ CHECK(f.engine.view.lookAtCalls == 3);+ CHECK(f.windows.winGetGrabWindow() == NULL);+ CHECK(messages.commands.getFirstMessage() == NULL);+}++/* Off the radar the drag pins to the picture's edge, so the camera waits at the map's edge instead of+ wherever the last move inside left it. A release outside never reaches the radar, and the next drag+ that starts on the battlefield and crosses the radar must still leave the camera alone. */+TEST(minimap_drag_pins_to_the_edge_off_the_radar_and_a_world_drag_after_it_leaves_the_camera)+{+ CHECK(bootOnce());+ MinimapInputFixture f;+ MinimapMessages messages;+ messages.stream.attachTranslator(NEW WindowTranslator, 10);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN, 120, 220);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 300, 400);+ CHECK(f.engine.view.lookAtCalls == 2);+ // the radar's bottom right is the map's high x and low y: the picture is drawn with y upside down+ CHECK(f.engine.view.getPosition()->x > 1200);+ CHECK(f.engine.view.getPosition()->y < 20);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 170, 270);+ CHECK(f.engine.view.lookAtCalls == 3);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP, 300, 400);+ CHECK(f.windows.winGetGrabWindow() == NULL);+ CHECK(messages.commands.getFirstMessage() == NULL);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN, 300, 400);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 150, 250);+ CHECK(f.engine.view.lookAtCalls == 3);+}++/* Arrow-key scrolling locks the tactical view's mouse input; a press that the radar already holds keeps+ its drag anyway. Above a letterboxed map the drag pins to the top of the picture. */+TEST(minimap_drag_works_during_keyboard_scroll_and_pins_to_a_letterboxed_picture)+{+ CHECK(bootOnce());+ MinimapInputFixture f;+ MinimapMessages messages;+ messages.stream.attachTranslator(NEW WindowTranslator, 10);+ f.radar.configure(f.window, 1280, 640);+ f.engine.view.setMouseLock(TRUE);+ TheInGameUI->setScrolling(TRUE);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN, 120, 240);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 170, 260);+ CHECK(f.engine.view.lookAtCalls == 2);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_DRAG, 170, 210);+ CHECK(f.engine.view.lookAtCalls == 3);+ // the top of the picture is the map's far y edge, 640 on this map+ CHECK(f.engine.view.getPosition()->y > 600);+ f.event(messages, GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP, 300, 400);+ CHECK(f.windows.winGetGrabWindow() == NULL);+}diff --git a/GeneralsMD/Code/Tests/test_production_input.inc b/GeneralsMD/Code/Tests/test_production_input.incnew file mode 100644index 000000000..ccaecd6e8--- /dev/null+++ b/GeneralsMD/Code/Tests/test_production_input.inc@@ -0,0 +1,295 @@+// Exercise the actual GUI hit testing/button callbacks and strip input translator.+#include "GameClient/PlaceEventTranslator.h"+#include "GameClient/GadgetPushButton.h"+#include "GameClient/WindowXlat.h"++namespace+{+class ProductionInputWindow : public GameWindow+{+ MEMORY_POOL_GLUE_WITH_EXPLICIT_CREATE(ProductionInputWindow, "ProductionInputWindow", 16, 16)+public:+ void winDrawBorder() {}+ void winSetFont(GameFont*) {}+};+ProductionInputWindow::~ProductionInputWindow() {}++class ProductionInputWindows : public GameWindowManager+{+public:+ GameWindow *allocateNewWindow() { return newInstance(ProductionInputWindow)(); }+ GameFont *winFindFont(AsciiString, Int, Bool) { return NULL; }+ GameWinDrawFunc getPushButtonImageDrawFunc() { return NULL; }+ GameWinDrawFunc getPushButtonDrawFunc() { return NULL; }+ GameWinDrawFunc getCheckBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getCheckBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getRadioButtonImageDrawFunc() { return NULL; }+ GameWinDrawFunc getRadioButtonDrawFunc() { return NULL; }+ GameWinDrawFunc getTabControlImageDrawFunc() { return NULL; }+ GameWinDrawFunc getTabControlDrawFunc() { return NULL; }+ GameWinDrawFunc getListBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getListBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getComboBoxImageDrawFunc() { return NULL; }+ GameWinDrawFunc getComboBoxDrawFunc() { return NULL; }+ GameWinDrawFunc getHorizontalSliderImageDrawFunc() { return NULL; }+ GameWinDrawFunc getHorizontalSliderDrawFunc() { return NULL; }+ GameWinDrawFunc getVerticalSliderImageDrawFunc() { return NULL; }+ GameWinDrawFunc getVerticalSliderDrawFunc() { return NULL; }+ GameWinDrawFunc getProgressBarImageDrawFunc() { return NULL; }+ GameWinDrawFunc getProgressBarDrawFunc() { return NULL; }+ GameWinDrawFunc getStaticTextImageDrawFunc() { return NULL; }+ GameWinDrawFunc getStaticTextDrawFunc() { return NULL; }+ GameWinDrawFunc getTextEntryImageDrawFunc() { return NULL; }+ GameWinDrawFunc getTextEntryDrawFunc() { return NULL; }+};++struct ProductionClickCount+{+ Int left = 0, right = 0;+ static WindowMsgHandledType system(GameWindow *window, UnsignedInt msg, WindowMsgData, WindowMsgData)+ {+ ProductionClickCount *count = (ProductionClickCount*)window->winGetUserData();+ if(msg == GBM_SELECTED) ++count->left;+ if(msg == GBM_SELECTED_RIGHT) ++count->right;+ return MSG_HANDLED;+ }+};++struct ProductionButtonFixture+{+ CameraInputFixture engine;+ ProductionInputWindows windows;+ ProductionClickCount count;+ GameWindow *parent, *button;+ ICoord2D pixel = {30, 30};+ ProductionButtonFixture(UnsignedInt layer = 0)+ {+ TheWindowManager = &windows;+ parent = windows.winCreate(NULL, WIN_STATUS_ENABLED | layer, 0, 0, 200, 200,+ ProductionClickCount::system);+ parent->winSetUserData(&count);+ button = windows.winCreate(parent, WIN_STATUS_RIGHT_CLICK | WIN_STATUS_CANCEL_WHEN_DISABLED,+ 20, 20, 40, 40, GadgetPushButtonSystem);+ button->winSetInputFunc(GadgetPushButtonInput);+ button->winSetOwner(parent);+ button->winGetInstanceData()->m_status |= WIN_STATUS_RIGHT_CLICK;+ }+ ~ProductionButtonFixture()+ {+ // Dispose of windows while their global manager and mouse are still installed.+ windows.winDestroyAll();+ }+ WinInputReturnCode click(GameWindowMessage msg) { return windows.winProcessMouseEvent(msg, &pixel, NULL); }+};++class ProductionStripTestUI : public CameraTestUI+{+public:+ void staleCameo()+ {+ for(Int row = 0; row < PRODUCTION_STRIP_ROWS; ++row) m_productionStripCount[row] = 0;+ m_productionStripCameoW = m_productionStripCameoH = 40;+ m_productionStripCount[0] = 1;+ ProductionStripSlot &slot = m_productionStrip[0][0];+ slot.producer = INVALID_ID; // producer died after the last draw; the strip still owns the click+ slot.pos.x = slot.pos.y = 20;+ }+};++struct ProductionStripFixture+{+ CameraInputFixture engine;+ PlaceEventTranslator strip;+ ProductionStripFixture()+ {+ static ProductionStripTestUI *ui = NEW ProductionStripTestUI;+ ui->staleCameo();+ TheInGameUI = ui;+ }+ GameMessageDisposition event(GameMessage::Type type, Int x = 30, Int y = 30)+ {+ GameMessage *message = newInstance(GameMessage)(type);+ ICoord2D pixel = {x, y};+ message->appendPixelArgument(pixel);+ GameMessageDisposition result = strip.translateGameMessage(message);+ message->deleteInstance();+ return result;+ }+};++struct ProductionMessageFixture+{+ MessageStream stream;+ CommandList commands;+ MessageStream *savedStream = TheMessageStream;+ CommandList *savedCommands = TheCommandList;+ ProductionMessageFixture()+ {+ TheMessageStream = &stream;+ TheCommandList = &commands;+ stream.attachTranslator(NEW MetaEventTranslator, 20);+ stream.attachTranslator(NEW PlaceEventTranslator, 30);+ }+ ~ProductionMessageFixture()+ {+ TheMessageStream = savedStream;+ TheCommandList = savedCommands;+ }+ void append(GameMessage::Type type, Int x, Int y)+ {+ GameMessage *message = stream.appendMessage(type);+ ICoord2D pixel = {x, y};+ message->appendPixelArgument(pixel);+ if(type == GameMessage::MSG_RAW_MOUSE_RIGHT_DRAG)+ message->appendPixelArgument(pixel);+ else+ message->appendIntegerArgument(0); // modifiers+ message->appendIntegerArgument(100); // event time+ }+};+}++TEST(production_cancel_disabled_button_accepts_only_right_click_once)+{+ CHECK(bootOnce());+ ProductionButtonFixture f;+ CHECK(!(f.button->winGetStatus() & WIN_STATUS_ENABLED));+ CHECK(f.click(GWM_RIGHT_DOWN) == WIN_INPUT_USED);+ CHECK(f.count.right == 1 && f.count.left == 0);+ CHECK(f.click(GWM_RIGHT_UP) == WIN_INPUT_USED);+ CHECK(f.count.right == 1 && f.count.left == 0);+ f.click(GWM_LEFT_DOWN);+ f.click(GWM_LEFT_UP);+ CHECK(f.count.right == 1 && f.count.left == 0);+ CHECK(!(f.button->winGetStatus() & WIN_STATUS_ENABLED));+}++TEST(production_cancel_respects_hidden_disabled_parents_and_ordinary_buttons)+{+ CHECK(bootOnce());+ ProductionButtonFixture f;+ f.button->winClearStatus(WIN_STATUS_CANCEL_WHEN_DISABLED);+ f.click(GWM_RIGHT_DOWN); f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 0);+ f.button->winSetStatus(WIN_STATUS_CANCEL_WHEN_DISABLED);+ f.button->winHide(TRUE);+ f.click(GWM_RIGHT_DOWN); f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 0);+ f.button->winHide(FALSE);+ f.parent->winEnable(FALSE);+ f.click(GWM_RIGHT_DOWN); f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 0);+ f.parent->winEnable(TRUE);+ f.click(GWM_RIGHT_DOWN); f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 1);+}++TEST(production_cancel_works_in_above_below_modal_and_captured_windows)+{+ CHECK(bootOnce());+ for(UnsignedInt layer : {WIN_STATUS_ABOVE, WIN_STATUS_BELOW})+ {+ ProductionButtonFixture f(layer);+ CHECK(f.click(GWM_RIGHT_DOWN) == WIN_INPUT_USED);+ f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 1);+ }+ ProductionButtonFixture f;+ f.windows.winSetModal(f.parent);+ CHECK(f.click(GWM_RIGHT_DOWN) == WIN_INPUT_USED);+ f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 1);+ f.windows.winUnsetModal(f.parent);+ f.windows.winCapture(f.parent);+ CHECK(f.click(GWM_RIGHT_DOWN) == WIN_INPUT_USED);+ f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 2);+}++TEST(production_cancel_reusing_a_button_clears_disabled_cancellation)+{+ CHECK(bootOnce());+ ProductionButtonFixture f;+ GadgetButtonSetData(f.button, &f.count);+ CHECK(!(f.button->winGetStatus() & WIN_STATUS_CANCEL_WHEN_DISABLED));+ f.click(GWM_RIGHT_DOWN); f.click(GWM_RIGHT_UP);+ CHECK(f.count.right == 0);+}++TEST(production_cancel_strip_consumes_press_drag_release_and_double_click)+{+ CHECK(bootOnce());+ ProductionStripFixture f;+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_DRAG, 100, 100) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 100, 100) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_RIGHT_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 100, 100) == KEEP_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_DOUBLE_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_RIGHT_DOUBLE_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_RIGHT_CLICK) == KEEP_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN, 60, 30) == KEEP_MESSAGE);+ CHECK(!TheInGameUI->handleProductionStripClick(NULL, TRUE));+}++TEST(production_cancel_strip_preserves_left_click_and_independent_button_releases)+{+ CHECK(bootOnce());+ ProductionStripFixture f;+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_DOWN) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP, 100, 100) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_LEFT_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 100, 100) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_RIGHT_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP) == KEEP_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_LEFT_DOUBLE_CLICK) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_LEFT_BUTTON_UP) == DESTROY_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_LEFT_DOUBLE_CLICK) == DESTROY_MESSAGE);+}++TEST(production_cancel_strip_new_press_recovers_when_gui_consumed_the_previous_release)+{+ CHECK(bootOnce());+ ProductionStripFixture f;+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN) == DESTROY_MESSAGE);+ // The player released over a window, so WindowTranslator consumed the release before us.+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN, 100, 100) == KEEP_MESSAGE);+ CHECK(f.event(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 100, 100) == KEEP_MESSAGE);+ CHECK(f.event(GameMessage::MSG_MOUSE_RIGHT_CLICK) == KEEP_MESSAGE);+}++TEST(production_cancel_strip_filters_real_meta_clicks_without_blocking_world_clicks)+{+ CHECK(bootOnce());+ ProductionStripFixture engine;+ ProductionMessageFixture f;+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN, 30, 30);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 30, 30);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_DOUBLE_CLICK, 30, 30);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 30, 30);+ f.stream.propagateMessages();+ CHECK(f.commands.getFirstMessage() == NULL);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN, 100, 100);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 100, 100);+ f.stream.propagateMessages();+ Int worldClicks = 0;+ for(GameMessage *m = f.commands.getFirstMessage(); m; m = m->next())+ if(m->getType() == GameMessage::MSG_MOUSE_RIGHT_CLICK) ++worldClicks;+ CHECK(worldClicks == 1);+}++TEST(production_cancel_disabled_button_release_outside_does_not_create_world_click)+{+ CHECK(bootOnce());+ ProductionButtonFixture engine;+ ProductionMessageFixture f;+ f.stream.attachTranslator(NEW WindowTranslator, 10);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_DOWN, 30, 30);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_DRAG, 300, 300);+ f.append(GameMessage::MSG_RAW_MOUSE_RIGHT_BUTTON_UP, 300, 300);+ f.stream.propagateMessages();+ CHECK(engine.count.right == 1 && engine.count.left == 0);+ CHECK(f.commands.getFirstMessage() == NULL);+}