1 // ==============================================================
2 //	This file is part of Glest (www.glest.org)
3 //
4 //	Copyright (C) 2001-2008 Martiño Figueroa
5 //
6 //	You can redistribute this code and/or modify it under
7 //	the terms of the GNU General Public License as published
8 //	by the Free Software Foundation; either version 2 of the
9 //	License, or (at your option) any later version
10 // ==============================================================
11 
12 #ifndef _GLEST_GAME_GAME_H_
13 #define _GLEST_GAME_GAME_H_
14 
15 #ifdef WIN32
16     #include <winsock2.h>
17     #include <winsock.h>
18 #endif
19 
20 #include <vector>
21 #include "gui.h"
22 #include "game_camera.h"
23 #include "world.h"
24 #include "ai_interface.h"
25 #include "program.h"
26 #include "chat_manager.h"
27 #include "script_manager.h"
28 #include "game_settings.h"
29 #include "network_interface.h"
30 #include "data_types.h"
31 #include "selection.h"
32 #include "leak_dumper.h"
33 
34 using std::vector;
35 using namespace Shared::Platform;
36 using namespace Shared::PlatformCommon;
37 
38 namespace Shared { namespace Graphics {
39 	class VideoPlayer;
40 }};
41 
42 namespace Glest{ namespace Game{
43 
44 class GraphicMessageBox;
45 class ServerInterface;
46 
47 enum LoadGameItem {
48 	lgt_FactionPreview 	= 0x01,
49 	lgt_TileSet 		= 0x02,
50 	lgt_TechTree		= 0x04,
51 	lgt_Map				= 0x08,
52 	lgt_Scenario		= 0x10,
53 
54 	lgt_All				= (lgt_FactionPreview | lgt_TileSet | lgt_TechTree | lgt_Map | lgt_Scenario)
55 };
56 
57 // =====================================================
58 // 	class Game
59 //
60 //	Main game class
61 // =====================================================
62 class Game: public ProgramState, public FileCRCPreCacheThreadCallbackInterface,
63             public CustomInputCallbackInterface, public ClientLagCallbackInterface {
64 public:
65 	static const float highlightTime;
66 
67 private:
68 	typedef vector<Ai*> Ais;
69 	typedef vector<AiInterface*> AiInterfaces;
70 
71 private:
72 	//main data
73 	World world;
74     AiInterfaces aiInterfaces;
75     Gui gui;
76     GameCamera gameCamera;
77     Commander commander;
78     Console console;
79 	ChatManager chatManager;
80 	ScriptManager scriptManager;
81 
82 	//misc
83 	Checksum checksum;
84     string loadingText;
85     int mouse2d;
86     int mouseX;
87     int mouseY; //coords win32Api
88     Vec2i mouseCellPos;
89 
90 	int updateFps, lastUpdateFps, avgUpdateFps;
91 	int framesToCatchUpAsClient;
92 	int framesToSlowDownAsClient;
93 	int receivedTooEarlyInFrames[GameConstants::networkSmoothInterval];
94 	int framesNeededToWaitForServerMessage[GameConstants::networkSmoothInterval];
95 	int totalRenderFps, renderFps, lastRenderFps, avgRenderFps,currentAvgRenderFpsTotal;
96 	uint64 tickCount;
97 	bool paused;
98 	bool pauseRequestSent;
99 	bool resumeRequestSent;
100 	bool pauseStateChanged;
101 	bool pausedForJoinGame;
102 	bool pausedBeforeJoinGame;
103 
104 	bool gameOver;
105 	bool renderNetworkStatus;
106 	bool renderInGamePerformance;
107 	bool showFullConsole;
108 	bool setMarker;
109 	bool cameraDragAllowed;
110 	bool mouseMoved;
111 	float scrollSpeed;
112 	bool camLeftButtonDown;
113 	bool camRightButtonDown;
114 	bool camUpButtonDown;
115 	bool camDownButtonDown;
116 
117 	int speed;
118 	GraphicMessageBox mainMessageBox;
119 	GraphicMessageBox errorMessageBox;
120 
121 	//misc ptr
122 	ParticleSystem *weatherParticleSystem;
123 	GameSettings gameSettings;
124 	Vec2i lastMousePos;
125 	time_t lastRenderLog2d;
126 	DisplayMessageFunction originalDisplayMsgCallback;
127 	bool isFirstRender;
128 
129 	bool quitTriggeredIndicator;
130 	bool quitPendingIndicator;
131 
132 	int original_updateFps;
133 	int original_cameraFps;
134 
135 	bool captureAvgTestStatus;
136 	int updateFpsAvgTest;
137 	int renderFpsAvgTest;
138 
139 	int renderExtraTeamColor;
140 	static const int renderTeamColorCircleBit=1;
141 	static const int renderTeamColorPlaneBit=2;
142 
143 	bool photoModeEnabled;
144 	int healthbarMode;
145 	bool visibleHUD;
146 	bool timeDisplay;
147 	bool withRainEffect;
148 	Program *program;
149 
150 	bool gameStarted;
151 
152 	time_t lastMaxUnitCalcTime;
153 
154 	PopupMenu popupMenu;
155 	PopupMenu popupMenuSwitchTeams;
156 	PopupMenu popupMenuDisconnectPlayer;
157 
158 	std::map<int,int> switchTeamIndexMap;
159 	GraphicMessageBox switchTeamConfirmMessageBox;
160 
161 	std::map<int,int> disconnectPlayerIndexMap;
162 	int playerIndexDisconnect;
163 	GraphicMessageBox disconnectPlayerConfirmMessageBox;
164 
165 	int exitGamePopupMenuIndex;
166 	int joinTeamPopupMenuIndex;
167 	int pauseGamePopupMenuIndex;
168 	int saveGamePopupMenuIndex;
169 	int loadGamePopupMenuIndex;
170 	//int markCellPopupMenuIndex;
171 	//int unmarkCellPopupMenuIndex;
172 	int keyboardSetupPopupMenuIndex;
173 	int disconnectPlayerPopupMenuIndex;
174 	//GLuint statelist3dMenu;
175 	ProgramState *currentUIState;
176 
177 	bool isMarkCellEnabled;
178 	Vec2i cellMarkedPos;
179 	MarkedCell cellMarkedData;
180 	bool isMarkCellTextEnabled;
181 
182 	Texture2D *markCellTexture;
183 	bool isUnMarkCellEnabled;
184 	Texture2D *unmarkCellTexture;
185 	std::map<Vec2i, MarkedCell> mapMarkedCellList;
186 	Texture2D *highlightCellTexture;
187 	std::vector<MarkedCell> highlightedCells;
188 	bool masterserverMode;
189 
190 	StrSound *currentAmbientSound;
191 
192 	time_t lastNetworkPlayerConnectionCheck;
193 
194 	time_t lastMasterServerGameStatsDump;
195 
196 	XmlNode *loadGameNode;
197 	int lastworldFrameCountForReplay;
198 	std::vector<std::pair<int,NetworkCommand> > replayCommandList;
199 
200 	std::vector<string> streamingVideos;
201 	::Shared::Graphics::VideoPlayer *videoPlayer;
202 	bool playingStaticVideo;
203 
204 	Unit *currentCameraFollowUnit;
205 
206 	std::map<int,HighlightSpecialUnitInfo> unitHighlightList;
207 
208 	MasterSlaveThreadController masterController;
209 
210 	bool inJoinGameLoading;
211 	bool initialResumeSpeedLoops;
212 
213 	bool quitGameCalled;
214 	bool disableSpeedChange;
215 
216 	std::map<int,FowAlphaCellsLookupItem> teamFowAlphaCellsLookupItem;
217 	std::map<string,int64> gamePerformanceCounts;
218 
219 	bool networkPauseGameForLaggedClientsRequested;
220 	bool networkResumeGameForLaggedClientsRequested;
221 
222 public:
223 	Game();
224     Game(Program *program, const GameSettings *gameSettings, bool masterserverMode);
225     ~Game();
226 
227     void reInitGUI();
228     bool isFlagType1BitEnabled(FlagTypes1 type) const;
229 
isMarkCellMode()230     bool isMarkCellMode() const { return isMarkCellEnabled; }
getMarkCellTexture()231     const Texture2D * getMarkCellTexture() const { return markCellTexture; }
isUnMarkCellMode()232     bool isUnMarkCellMode() const { return isUnMarkCellEnabled; }
getUnMarkCellTexture()233     const Texture2D * getUnMarkCellTexture() const { return unmarkCellTexture; }
234 
getMapMarkedCellList()235     std::map<Vec2i, MarkedCell> getMapMarkedCellList() const { return mapMarkedCellList; }
236 
getHighlightCellTexture()237     const Texture2D * getHighlightCellTexture() const { return highlightCellTexture; }
getHighlightedCells()238     const std::vector<MarkedCell> * getHighlightedCells() const { return &highlightedCells; }
239     void addOrReplaceInHighlightedCells(MarkedCell mc);
240 
isMasterserverMode()241     bool isMasterserverMode() const { return masterserverMode; }
242     //get
getGameSettings()243     GameSettings *getGameSettings() 	    		{return &gameSettings;}
setGameSettings(GameSettings * settings)244     void setGameSettings(GameSettings *settings) 	{ gameSettings = *settings;}
getReadOnlyGameSettings()245 	const GameSettings *getReadOnlyGameSettings() const	{return &gameSettings;}
setQuitPendingIndicator()246 	void setQuitPendingIndicator() 	{ quitPendingIndicator = true;}
247 
getGameCamera()248 	const GameCamera *getGameCamera() const	{return &gameCamera;}
getGameCameraPtr()249 	GameCamera *getGameCameraPtr()			{return &gameCamera;}
getCommander()250 	const Commander *getCommander() const	{return &commander;}
getGuiPtr()251 	Gui *getGuiPtr()							{return &gui;}
getGui()252 	const Gui *getGui() const				{return &gui;}
getCommander()253 	Commander *getCommander()				{return &commander;}
getConsole()254 	Console *getConsole()					{return &console;}
getScriptManager()255 	ScriptManager *getScriptManager()		{return &scriptManager;}
getWorld()256 	World *getWorld()						{return &world;}
getWorld()257 	const World *getWorld() const			{return &world;}
258 
getProgram()259 	Program *getProgram()					{return program;}
260 
getMouseCellPos()261 	Vec2i getMouseCellPos() const			{return mouseCellPos;}
262 	bool isValidMouseCellPos() const;
263 
264 	void removeUnitFromSelection(const Unit *unit);
265 	bool addUnitToSelection(Unit *unit);
266 	void addUnitToGroupSelection(Unit *unit,int groupIndex);
267 	void removeUnitFromGroupSelection(int unitId,int groupIndex);
268 	void recallGroupSelection(int groupIndex);
269 
getTickCount()270 	Uint64 getTickCount()					{return tickCount;}
271 	bool getPaused();
272 	void setPaused(bool value, bool forceAllowPauseStateChange,bool clearCaches,bool joinNetworkGame);
273 	void tryPauseToggle(bool pause);
274 	void setupRenderForVideo();
275 	void saveGame();
getTotalRenderFps()276 	const int getTotalRenderFps() const					{return totalRenderFps;}
277 
278 	void toggleTeamColorMarker();
279     //init
280 	void resetMembers();
281     virtual void load(int loadTypes);
282     virtual void load();
283     virtual void init();
284     virtual void init(bool initForPreviewOnly);
285 	virtual void update();
286 	virtual void updateCamera();
287 	virtual void render();
288 	virtual void tick();
289 
290     //event managing
291 	virtual bool textInput(std::string text);
292 	virtual bool sdlKeyDown(SDL_KeyboardEvent key);
293 	virtual void keyDown(SDL_KeyboardEvent key);
294     virtual void keyUp(SDL_KeyboardEvent key);
295     virtual void keyPress(SDL_KeyboardEvent c);
296     virtual void mouseDownLeft(int x, int y);
297     virtual void mouseDownRight(int x, int y);
298     virtual void mouseUpCenter(int x, int y);
299     virtual void mouseUpLeft(int x, int y);
300     virtual void mouseDoubleClickLeft(int x, int y);
301     virtual void eventMouseWheel(int x, int y, int zDelta);
302     virtual void mouseMove(int x, int y, const MouseState *mouseState);
303 
isInSpecialKeyCaptureEvent()304 	virtual bool isInSpecialKeyCaptureEvent() { return chatManager.getEditEnabled(); }
305 
306 	virtual bool quitTriggered();
307 	virtual Stats quitAndToggleState();
308 	Stats quitGame();
309 	static void exitGameState(Program *program, Stats &endStats);
310 
311 	void startPerformanceTimer();
312 	void endPerformanceTimer();
313 	Vec2i getPerformanceTimerResults();
314 
315 	static Texture2D * findFactionLogoTexture(const GameSettings *settings, Logger *logger=NULL,string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER, bool useTechDefaultIfFilterNotFound=true);
316 	static string findFactionLogoFile(const GameSettings *settings, Logger *logger=NULL, string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER);
317 	static string extractScenarioLogoFile(const GameSettings *settings, string &result, bool &loadingImageUsed, Logger *logger=NULL, string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER);
318 	static string extractFactionLogoFile(bool &loadingImageUsed, string factionName, string scenarioDir, string techName, Logger *logger=NULL, string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER);
319 	static string extractTechLogoFile(string scenarioDir, string techName, bool &loadingImageUsed, Logger *logger=NULL,string factionLogoFilter=GameConstants::LOADING_SCREEN_FILE_FILTER);
320 
321 	void loadHudTexture(const GameSettings *settings);
322 
getGameOver()323 	bool getGameOver() { return gameOver; }
hasGameStarted()324 	bool hasGameStarted() { return gameStarted;}
325 	virtual vector<Texture2D *> processTech(string techName);
326 	virtual void consoleAddLine(string line);
327 
328 	void endGame();
329 
330 	void playStaticVideo(const string &playVideo);
331 	void playStreamingVideo(const string &playVideo);
332 	void stopStreamingVideo(const string &playVideo);
333 	void stopAllVideo();
334 
335 	string saveGame(string name, string path="saved/");
336 	static void loadGame(string name,Program *programPtr,bool isMasterserverMode, const GameSettings *joinGameSettings=NULL);
337 
338 	void addNetworkCommandToReplayList(NetworkCommand* networkCommand,int worldFrameCount);
339 
340 	bool factionLostGame(int factionIndex);
341 
342 	void addCellMarker(Vec2i cellPos, MarkedCell cellData);
343 	void removeCellMarker(Vec2i surfaceCellPos, const Faction *faction);
344 	void showMarker(Vec2i cellPos, MarkedCell cellData);
345 
346 	void highlightUnit(int unitId,float radius, float thickness, Vec4f color);
347 	void unhighlightUnit(int unitId);
348 
349 	bool showTranslatedTechTree() const;
350 
351 	void DumpCRCWorldLogIfRequired(string fileSuffix="");
352 
getDisableSpeedChange()353 	bool getDisableSpeedChange() const { return disableSpeedChange; }
setDisableSpeedChange(bool value)354 	void setDisableSpeedChange(bool value) { disableSpeedChange = value; }
355 
356 	string getGamePerformanceCounts(bool displayWarnings) const;
357 	virtual void addPerformanceCount(string key,int64 value);
getRenderInGamePerformance()358 	bool getRenderInGamePerformance() const { return renderInGamePerformance; }
359 
360 private:
361 	//render
362     void render3d();
363     void render2d();
364 
365 	//misc
366 	void checkWinner();
367 	void checkWinnerStandard();
368 	void checkWinnerScripted();
369 	void setEndGameTeamWinnersAndLosers();
370 
371 	bool hasBuilding(const Faction *faction);
372 	bool factionLostGame(const Faction *faction);
373 	void incSpeed();
374 	void decSpeed();
375 	int getUpdateLoops();
376 
377 	void showLoseMessageBox();
378 	void showWinMessageBox();
379 	void showMessageBox(const string &text, const string &header, bool toggle);
380 	void showErrorMessageBox(const string &text, const string &header, bool toggle);
381 
382 	void renderWorker();
383 	static int ErrorDisplayMessage(const char *msg, bool exitApp);
384 
385 	void ReplaceDisconnectedNetworkPlayersWithAI(bool isNetworkGame, NetworkRole role);
386 	void calcCameraMoveX();
387 	void calcCameraMoveZ();
388 
389 	int getFirstUnusedTeamNumber();
390 	void updateWorldStats();
391 
392 	void setupPopupMenus(bool checkClientAdminOverrideOnly);
393 
394 	string getDebugStats(std::map<int,string> &factionDebugInfo);
395 
396 	void renderVideoPlayer();
397 
398 	void updateNetworkMarkedCells();
399 	void updateNetworkUnMarkedCells();
400 	void updateNetworkHighligtedCells();
401 
402 	virtual void processInputText(string text, bool cancelled);
403 
404 	void startMarkCell();
405 	void startCameraFollowUnit();
406 
407 	bool switchSetupForSlots(ServerInterface *& serverInterface,
408 			int startIndex, int endIndex, bool onlyNetworkUnassigned);
409 	void processNetworkSynchChecksIfRequired();
410 	Stats getEndGameStats();
411 	void checkWinnerStandardHeadlessOrObserver();
412 	void checkWinnerStandardPlayer();
413 	std::map<int, int> getTeamsAlive();
414 	void initCamera(Map *map);
415 
416 	virtual bool clientLagHandler(int slotIndex,bool networkPauseGameForLaggedClients);
417 };
418 
419 }}//end namespace
420 
421 #endif
422