From d33e1174a5ad4806a4830c752c4fc208e78237f0 Mon Sep 17 00:00:00 2001 From: Mark Vejvoda Date: Fri, 2 Dec 2011 16:07:59 +0000 Subject: [PATCH] - bugfixes related to cppcheck report - bugfixes found using valgrind (memory leaks) --- source/glest_game/ai/path_finder.cpp | 10 +- source/glest_game/ai/path_finder.h | 10 +- source/glest_game/facilities/components.cpp | 37 ++++++ source/glest_game/facilities/components.h | 7 +- source/glest_game/game/chat_manager.cpp | 6 +- source/glest_game/game/game.cpp | 32 +++-- source/glest_game/game/game.h | 3 +- source/glest_game/game/game_camera.cpp | 4 +- source/glest_game/game/game_camera.h | 3 +- source/glest_game/game/script_manager.cpp | 15 ++- source/glest_game/global/core_data.cpp | 8 +- source/glest_game/global/core_data.h | 1 + source/glest_game/graphics/particle_type.cpp | 14 ++ source/glest_game/graphics/particle_type.h | 3 + source/glest_game/graphics/renderer.cpp | 31 +++-- source/glest_game/graphics/renderer.h | 10 +- source/glest_game/gui/gui.cpp | 2 +- source/glest_game/gui/selection.h | 7 +- source/glest_game/main/intro.cpp | 22 ++-- source/glest_game/main/main.cpp | 11 +- source/glest_game/main/program.cpp | 4 +- .../menu/menu_state_connected_game.cpp | 10 +- .../menu/menu_state_custom_game.cpp | 2 +- .../menu/menu_state_graphic_info.cpp | 2 +- source/glest_game/menu/menu_state_mods.cpp | 4 +- source/glest_game/network/connection_slot.cpp | 68 ++++++---- source/glest_game/network/connection_slot.h | 12 +- source/glest_game/network/network_message.cpp | 2 +- .../glest_game/network/server_interface.cpp | 124 +++++++++++------- source/glest_game/network/server_interface.h | 14 +- source/glest_game/type_instances/faction.cpp | 77 ++++++++++- source/glest_game/type_instances/faction.h | 6 +- source/glest_game/type_instances/unit.cpp | 31 +++-- source/glest_game/type_instances/unit.h | 2 +- source/glest_game/types/command_type.cpp | 2 +- source/glest_game/types/damage_multiplier.h | 8 +- source/glest_game/types/object_type.h | 7 +- source/glest_game/types/tileset_model_type.h | 7 +- source/glest_game/types/unit_type.cpp | 2 +- source/glest_game/types/unit_type.h | 3 + source/glest_game/world/tileset.h | 18 +++ source/glest_game/world/time_flow.h | 9 +- source/glest_game/world/unit_updater.cpp | 69 +++++++--- source/glest_game/world/unit_updater.h | 2 + source/glest_game/world/world.cpp | 105 ++++++++++++++- source/glest_game/world/world.h | 8 +- .../include/platform/posix/socket.h | 8 +- source/shared_lib/include/util/conversion.h | 2 + .../sources/feathery_ftp/ftpAccount.c | 13 +- .../shared_lib/sources/feathery_ftp/ftpCmds.c | 8 +- .../sources/feathery_ftp/ftpTargetWin32.c | 4 +- .../graphics/gl/font_text_freetypegl.cpp | 5 +- .../sources/graphics/md5/Md5Model.cpp | 6 +- source/shared_lib/sources/map/map_preview.cpp | 2 +- .../platform/common/simple_threads.cpp | 4 +- .../sources/platform/miniupnpc/miniwget.c | 1 + .../sources/platform/posix/socket.cpp | 108 +++++++++------ .../sources/platform/sdl/thread.cpp | 29 ++-- source/shared_lib/sources/util/conversion.cpp | 20 +++ 59 files changed, 772 insertions(+), 272 deletions(-) diff --git a/source/glest_game/ai/path_finder.cpp b/source/glest_game/ai/path_finder.cpp index 17c8139f..d36ed0e6 100644 --- a/source/glest_game/ai/path_finder.cpp +++ b/source/glest_game/ai/path_finder.cpp @@ -476,7 +476,7 @@ bool PathFinder::addToOpenSet(Unit *unit, Node *node,const Vec2i finalPos, Vec2i } -direction PathFinder::directionOfMove(Vec2i to, Vec2i from) { +direction PathFinder::directionOfMove(Vec2i to, Vec2i from) const { if (from.x == to.x) { if (from.y == to.y) return -1; @@ -545,16 +545,16 @@ Vec2i PathFinder::adjustInDirection(Vec2i c, int dir) { return Vec2i( -1, -1 ); } -bool PathFinder::directionIsDiagonal(direction dir) { +bool PathFinder::directionIsDiagonal(direction dir) const { return (dir % 2) != 0; } // logical implication operator -bool PathFinder::implies (bool a, bool b) { +bool PathFinder::implies(bool a, bool b) const { return a ? b : true; } -directionset PathFinder::addDirectionToSet (directionset dirs, direction dir) { +directionset PathFinder::addDirectionToSet(directionset dirs, direction dir) const { return dirs | 1 << dir; } @@ -595,7 +595,7 @@ directionset PathFinder::naturalNeighbours(direction dir) { // return and remove a direction from the set // returns NO_DIRECTION if the set was empty -direction PathFinder::nextDirectionInSet (directionset *dirs) { +direction PathFinder::nextDirectionInSet(directionset *dirs) const { for (int i = 0; i < 8; i++) { char bit = 1 << i; if (*dirs & bit) { diff --git a/source/glest_game/ai/path_finder.h b/source/glest_game/ai/path_finder.h index fb11ac64..b4aa6fa5 100644 --- a/source/glest_game/ai/path_finder.h +++ b/source/glest_game/ai/path_finder.h @@ -133,16 +133,16 @@ private: bool contained(Vec2i c); - direction directionOfMove(Vec2i to, Vec2i from); + direction directionOfMove(Vec2i to, Vec2i from) const; direction directionWeCameFrom(Vec2i node, Vec2i nodeFrom); bool isEnterable(Vec2i coord); Vec2i adjustInDirection(Vec2i c, int dir); - bool directionIsDiagonal(direction dir); + bool directionIsDiagonal(direction dir) const; directionset forcedNeighbours(Vec2i coord,direction dir); - bool implies (bool a, bool b); - directionset addDirectionToSet (directionset dirs, direction dir); + bool implies(bool a, bool b) const; + directionset addDirectionToSet(directionset dirs, direction dir) const; directionset naturalNeighbours(direction dir); - direction nextDirectionInSet (directionset *dirs); + direction nextDirectionInSet(directionset *dirs) const; Vec2i jump(Vec2i dest, direction dir, Vec2i start,std::vector &path,int pathLength); bool addToOpenSet(Unit *unit, Node *node,const Vec2i finalPos, Vec2i sucPos, bool &nodeLimitReached,int maxNodeCount,Node **newNodeAdded,bool bypassChecks); }; diff --git a/source/glest_game/facilities/components.cpp b/source/glest_game/facilities/components.cpp index 2fc6c663..82ecde3b 100644 --- a/source/glest_game/facilities/components.cpp +++ b/source/glest_game/facilities/components.cpp @@ -335,6 +335,12 @@ bool GraphicButton::mouseMove(int x, int y){ const int GraphicListBox::defH= 22; const int GraphicListBox::defW= 140; +GraphicListBox::GraphicListBox(std::string containerName, std::string objName) +: GraphicComponent(containerName, objName) { + selectedItemIndex = 0; + lighted = false; +} + void GraphicListBox::init(int x, int y, int w, int h, Vec3f textColor){ GraphicComponent::init(x, y, w, h); @@ -450,6 +456,13 @@ bool GraphicListBox::mouseClick(int x, int y){ const int GraphicMessageBox::defH= 240; const int GraphicMessageBox::defW= 350; +GraphicMessageBox::GraphicMessageBox(std::string containerName, std::string objName) +: GraphicComponent(containerName, objName) { + buttonCount = 0; + header = ""; +} + + void GraphicMessageBox::init(const string &button1Str, const string &button2Str, int newWidth,int newHeight) { init(button1Str,newWidth,newHeight); @@ -546,6 +559,11 @@ bool GraphicMessageBox::mouseClick(int x, int y, int &clickedButton){ const int GraphicLine::defH= 5; const int GraphicLine::defW= 1000; +GraphicLine::GraphicLine(std::string containerName, std::string objName) +: GraphicComponent(containerName, objName) { + horizontal = false; +} + void GraphicLine::init(int x, int y, int w, int h){ GraphicComponent::init(x, y, w, h); horizontal=true; @@ -558,6 +576,12 @@ void GraphicLine::init(int x, int y, int w, int h){ const int GraphicCheckBox::defH= 22; const int GraphicCheckBox::defW= 22; +GraphicCheckBox::GraphicCheckBox(std::string containerName, std::string objName) +: GraphicComponent(containerName, objName) { + value = false; + lighted = false; +} + void GraphicCheckBox::init(int x, int y, int w, int h){ GraphicComponent::init(x, y, w, h); value=true; @@ -591,6 +615,19 @@ bool GraphicCheckBox::mouseClick(int x, int y){ const int GraphicScrollBar::defThickness=20; const int GraphicScrollBar::defLength= 200; +GraphicScrollBar::GraphicScrollBar(std::string containerName, std::string objName) +: GraphicComponent(containerName, objName) { + lighted = false; + horizontal = false; + elementCount = 0; + visibleSize = 0; + visibleStart = 0; + + // position on component for renderer + visibleCompPosStart = 0; + visibleCompPosEnd = 0; +} + void GraphicScrollBar::init(int x, int y, bool horizontal,int length, int thickness){ GraphicComponent::init(x, y, horizontal?length:thickness,horizontal?thickness:length ); this->horizontal=horizontal; diff --git a/source/glest_game/facilities/components.h b/source/glest_game/facilities/components.h index a02b1260..d968675b 100644 --- a/source/glest_game/facilities/components.h +++ b/source/glest_game/facilities/components.h @@ -199,7 +199,8 @@ private: bool lighted; Vec3f textColor; -public: +public: + GraphicListBox(std::string containerName="", std::string objName=""); void init(int x, int y, int w=defW, int h=defH, Vec3f textColor=Vec3f(1.f, 1.f, 1.f)); int getItemCount() const {return items.size();} @@ -243,6 +244,7 @@ private: string header; public: + GraphicMessageBox(std::string containerName="", std::string objName=""); void init(const string &button1Str, const string &button2Str, int newWidth=-1,int newHeight=-1); void init(const string &button1Str, int newWidth=-1,int newHeight=-1); @@ -274,6 +276,7 @@ private: bool horizontal; public: + GraphicLine(std::string containerName="", std::string objName=""); void init(int x, int y, int w=defW, int h=defH); bool getHorizontal() const {return horizontal;} void setHorizontal(bool horizontal) {this->horizontal= horizontal;} @@ -293,6 +296,7 @@ private: bool lighted; public: + GraphicCheckBox(std::string containerName="", std::string objName=""); void init(int x, int y, int w=defW, int h=defH); bool getValue() const {return value;} void setValue(bool value) {this->value= value;} @@ -323,6 +327,7 @@ private: int visibleCompPosEnd; public: + GraphicScrollBar(std::string containerName="", std::string objName=""); void init(int x, int y, bool horizontal,int length=defLength, int thickness=defThickness); virtual bool mouseDown(int x, int y); virtual bool mouseMove(int x, int y); diff --git a/source/glest_game/game/chat_manager.cpp b/source/glest_game/game/chat_manager.cpp index 1ea219bf..bd752621 100644 --- a/source/glest_game/game/chat_manager.cpp +++ b/source/glest_game/game/chat_manager.cpp @@ -200,7 +200,7 @@ void ChatManager::keyDown(SDL_KeyboardEvent key) { } } } - if(matchedIndexes.size() > 0) { + if(matchedIndexes.empty() == false) { int newMatchedIndex = -1; for(unsigned int index = 0; index < matchedIndexes.size(); ++index) { int possibleMatchIndex = matchedIndexes[index]; @@ -248,7 +248,7 @@ void ChatManager::keyDown(SDL_KeyboardEvent key) { } } } - if(matchedIndexes.size() > 0) { + if(matchedIndexes.empty() == false) { int newMatchedIndex = -1; for(unsigned int index = 0; index < matchedIndexes.size(); ++index) { int possibleMatchIndex = matchedIndexes[index]; @@ -333,7 +333,7 @@ void ChatManager::switchOnEdit() { void ChatManager::deleteText(int deleteCount,bool addToAutoCompleteBuffer) { if(text.empty() == false) { for(unsigned int i = 0; i < deleteCount; ++i) { - if(textCharLength.size() > 0) { + if(textCharLength.empty() == false) { //printf("BEFORE DEL textCharLength.size() = %d textCharLength[textCharLength.size()-1] = %d text.length() = %d\n",textCharLength.size(),textCharLength[textCharLength.size()-1],text.length()); if(textCharLength[textCharLength.size()-1] > text.length()) { diff --git a/source/glest_game/game/game.cpp b/source/glest_game/game/game.cpp index 4da364d1..f382b452 100644 --- a/source/glest_game/game/game.cpp +++ b/source/glest_game/game/game.cpp @@ -941,7 +941,7 @@ void Game::init(bool initForPreviewOnly) { //init renderer state if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Initializing renderer\n",__FILE__,__FUNCTION__); logger.add(Lang::getInstance().get("LogScreenGameLoadingInitRenderer","",true), true); - renderer.initGame(this); + renderer.initGame(this,this->getGameCameraPtr()); for(int i=0; i < world.getFactionCount(); ++i) { Faction *faction= world.getFaction(i); @@ -1307,7 +1307,7 @@ void Game::update() { } scriptManager.init(&world, &gameCamera); - renderer.initGame(this); + renderer.initGame(this,this->getGameCameraPtr()); //sounds //soundRenderer.stopAllSounds(fadeMusicMilliseconds); @@ -1349,7 +1349,7 @@ void Game::update() { catch(const exception &ex) { gameStarted = true; - throw ex; + throw; } } } @@ -1457,7 +1457,7 @@ void Game::render() { renderFps++; totalRenderFps++; - NetworkManager &networkManager= NetworkManager::getInstance(); + //NetworkManager &networkManager= NetworkManager::getInstance(); if(this->masterserverMode == false) { renderWorker(); } @@ -1470,8 +1470,7 @@ void Game::render() { int connectedClients=0; for(int i = 0; i < world.getFactionCount(); ++i) { Faction *faction = world.getFaction(i); - ConnectionSlot *slot = server->getSlot(faction->getStartLocationIndex()); - if(slot != NULL && slot->isConnected() == true) { + if(server->isClientConnected(faction->getStartLocationIndex()) == true) { connectedClients++; } } @@ -2572,7 +2571,7 @@ Stats Game::quitGame() { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); endStats = *(world.getStats()); - NetworkManager &networkManager= NetworkManager::getInstance(); + //NetworkManager &networkManager= NetworkManager::getInstance(); if(this->masterserverMode == true) { endStats.setIsMasterserverMode(true); } @@ -2813,6 +2812,11 @@ void Game::render2d(){ str+= "Log buffer count: " + intToStr(SystemFlags::getLogEntryBufferCount())+"\n"; } + str+= "UnitRangeCellsLookupItemCache: " + world.getUnitUpdater()->getUnitRangeCellsLookupItemCacheStats()+"\n"; + str+= "ExploredCellsLookupItemCache: " + world.getExploredCellsLookupItemCacheStats()+"\n"; + str+= "FowAlphaCellsLookupItemCache: " + world.getFowAlphaCellsLookupItemCacheStats()+"\n"; + //str+= "AllFactionsCacheStats: " + world.getAllFactionsCacheStats()+"\n"; + //str+= "AttackWarningCount: " + intToStr(world.getUnitUpdater()->getAttackWarningCount()) + "\n"; str+= "Map: " + gameSettings.getMap() +"\n"; @@ -2831,15 +2835,15 @@ void Game::render2d(){ for(int i= 0; i<4; ++i){ str+= "(" + intToStr(visibleQuad.p[i].x) + "," +intToStr(visibleQuad.p[i].y) + ") "; } - str+= "\n"; - str+= "Visible quad camera: "; - for(int i= 0; i<4; ++i){ - str+= "(" + intToStr(visibleQuadCamera.p[i].x) + "," +intToStr(visibleQuadCamera.p[i].y) + ") "; - } +// str+= "\n"; +// str+= "Visible quad camera: "; +// for(int i= 0; i<4; ++i){ +// str+= "(" + intToStr(visibleQuadCamera.p[i].x) + "," +intToStr(visibleQuadCamera.p[i].y) + ") "; +// } str+= "\n"; str+= "Visible quad area: " + floatToStr(visibleQuad.area()) +"\n"; - str+= "Visible quad camera area: " + floatToStr(visibleQuadCamera.area()) +"\n"; +// str+= "Visible quad camera area: " + floatToStr(visibleQuadCamera.area()) +"\n"; // Rect2i boundingRect= visibleQuad.computeBoundingRect(); // Rect2i scaledRect= boundingRect/Map::cellScale; @@ -2898,7 +2902,7 @@ void Game::render2d(){ if(renderer.getShowDebugUI() == true) { const Metrics &metrics= Metrics::getInstance(); //int mx= metrics.getMinimapX(); - int my= metrics.getMinimapY(); + //int my= metrics.getMinimapY(); //int mw= metrics.getMinimapW(); int mh= metrics.getMinimapH(); const Vec4f fontColor=getGui()->getDisplay()->getColor(); diff --git a/source/glest_game/game/game.h b/source/glest_game/game/game.h index 400fb271..e7bb44cf 100644 --- a/source/glest_game/game/game.h +++ b/source/glest_game/game/game.h @@ -154,13 +154,14 @@ public: Game(Program *program, const GameSettings *gameSettings, bool masterserverMode); ~Game(); + bool isMasterserverMode() const { return masterserverMode; } //get GameSettings *getGameSettings() {return &gameSettings;} void setGameSettings(GameSettings *settings) { gameSettings = *settings;} const GameSettings *getReadOnlyGameSettings() const {return &gameSettings;} const GameCamera *getGameCamera() const {return &gameCamera;} - GameCamera *getGameCamera() {return &gameCamera;} + GameCamera *getGameCameraPtr() {return &gameCamera;} const Commander *getCommander() const {return &commander;} Gui *getGui() {return &gui;} const Gui *getGui() const {return &gui;} diff --git a/source/glest_game/game/game_camera.cpp b/source/glest_game/game/game_camera.cpp index d7c42c53..69a78c6a 100644 --- a/source/glest_game/game/game_camera.cpp +++ b/source/glest_game/game/game_camera.cpp @@ -30,7 +30,7 @@ namespace Glest { namespace Game { // class GameCamera // ===================================================== -static std::map > > cacheVisibleQuad; +//static std::map > > cacheVisibleQuad; // ================== PUBLIC ===================== @@ -187,7 +187,7 @@ void GameCamera::update(){ } } -Quad2i GameCamera::computeVisibleQuad() const { +Quad2i GameCamera::computeVisibleQuad() { //printf("\n@@@ hAng [%f] vAng [%f] fov [%f]\n",hAng,vAng,fov); if(MaxVisibleQuadItemCache != 0) { diff --git a/source/glest_game/game/game_camera.h b/source/glest_game/game/game_camera.h index 76e48244..f252d233 100644 --- a/source/glest_game/game/game_camera.h +++ b/source/glest_game/game/game_camera.h @@ -85,6 +85,7 @@ private: float calculatedDefault; + std::map > > cacheVisibleQuad; int MaxVisibleQuadItemCache; public: @@ -117,7 +118,7 @@ public: //other void update(); - Quad2i computeVisibleQuad() const; + Quad2i computeVisibleQuad(); void switchState(); void resetPosition(); diff --git a/source/glest_game/game/script_manager.cpp b/source/glest_game/game/script_manager.cpp index ee256412..3c28b7c7 100644 --- a/source/glest_game/game/script_manager.cpp +++ b/source/glest_game/game/script_manager.cpp @@ -62,7 +62,20 @@ const int ScriptManager::messageWrapCount= 30; const int ScriptManager::displayTextWrapCount= 64; ScriptManager::ScriptManager() { - + world = NULL; + gameCamera = NULL; + lastCreatedUnitId = -1; + lastDeadUnitId = 0; + lastDeadUnitCauseOfDeath = 0; + lastDeadUnitKillerId = 0; + lastAttackedUnitId = 0; + lastAttackingUnitId = 0; + gameOver = false; + gameWon = false; + currentTimerTriggeredEventId = 0; + currentCellTriggeredEventId = 0; + currentEventId = 0; + inCellTriggerEvent = false; } ScriptManager::~ScriptManager() { diff --git a/source/glest_game/global/core_data.cpp b/source/glest_game/global/core_data.cpp index b19163be..e1c8a731 100644 --- a/source/glest_game/global/core_data.cpp +++ b/source/glest_game/global/core_data.cpp @@ -78,6 +78,10 @@ CoreData::CoreData() { } CoreData::~CoreData() { + cleanup(); +} + +void CoreData::cleanup() { deleteValues(waterSounds.getSoundsPtr()->begin(), waterSounds.getSoundsPtr()->end()); waterSounds.getSoundsPtr()->clear(); } @@ -167,7 +171,7 @@ void CoreData::load() { } } - if(logoTextureList.size() == 0) { + if(logoTextureList.empty() == true) { logosPath= data_path + "data/core/menu/textures/logo*.*"; vector logoFilenames; findAll(logosPath, logoFilenames, false, false); @@ -200,7 +204,7 @@ void CoreData::load() { } //} } - if(miscTextureList.size() == 0) { + if(miscTextureList.empty() == true) { introPath= data_path + "data/core/menu/textures/intro*.*"; vector introFilenames; findAll(introPath, introFilenames, false, false); diff --git a/source/glest_game/global/core_data.h b/source/glest_game/global/core_data.h index 34f8bba8..89f7604d 100644 --- a/source/glest_game/global/core_data.h +++ b/source/glest_game/global/core_data.h @@ -88,6 +88,7 @@ public: static CoreData &getInstance(); void load(); + void cleanup(); void loadFonts(); Texture2D *getBackgroundTexture() const {return backgroundTexture;} diff --git a/source/glest_game/graphics/particle_type.cpp b/source/glest_game/graphics/particle_type.cpp index 308cd013..109da64b 100644 --- a/source/glest_game/graphics/particle_type.cpp +++ b/source/glest_game/graphics/particle_type.cpp @@ -300,6 +300,12 @@ void ParticleSystemType::setValues(AttackParticleSystem *ats){ // class ParticleSystemTypeProjectile // =========================================================== +ParticleSystemTypeProjectile::ParticleSystemTypeProjectile() : ParticleSystemType() { + trajectorySpeed = 0.0f; + trajectoryScale = 0.0f; + trajectoryFrequency = 0.0f; +} + void ParticleSystemTypeProjectile::load(const XmlNode* particleFileNode, const string &dir, const string &path, RendererInterface *renderer, std::map > > &loadedFileList, string parentLoader, string techtreePath) { @@ -373,6 +379,14 @@ ProjectileParticleSystem *ParticleSystemTypeProjectile::create() { // class ParticleSystemTypeSplash // =========================================================== +ParticleSystemTypeSplash::ParticleSystemTypeSplash() { + emissionRateFade = 0.0f; + verticalSpreadA = 0.0f; + verticalSpreadB = 0.0f; + horizontalSpreadA = 0.0f; + horizontalSpreadB = 0.0f; +} + void ParticleSystemTypeSplash::load(const XmlNode* particleFileNode, const string &dir, const string &path, RendererInterface *renderer, std::map > > &loadedFileList, string parentLoader, string techtreePath) { diff --git a/source/glest_game/graphics/particle_type.h b/source/glest_game/graphics/particle_type.h index b8382275..e1d3696b 100644 --- a/source/glest_game/graphics/particle_type.h +++ b/source/glest_game/graphics/particle_type.h @@ -121,6 +121,7 @@ private: float trajectoryFrequency; public: + ParticleSystemTypeProjectile(); void load(const XmlNode *particleFileNode, const string &dir, const string &path, RendererInterface *renderer, std::map > > &loadedFileList, string parentLoader, string techtreePath); @@ -134,6 +135,8 @@ public: class ParticleSystemTypeSplash: public ParticleSystemType { public: + + ParticleSystemTypeSplash(); void load(const XmlNode *particleFileNode, const string &dir, const string &path, RendererInterface *renderer, std::map > > &loadedFileList, string parentLoader, string techtreePath); diff --git a/source/glest_game/graphics/renderer.cpp b/source/glest_game/graphics/renderer.cpp index 488262f4..1fddacbe 100644 --- a/source/glest_game/graphics/renderer.cpp +++ b/source/glest_game/graphics/renderer.cpp @@ -162,6 +162,7 @@ Renderer::Renderer(bool masterserverMode) : BaseRenderer() { this->allowRenderUnitTitles = false; this->menu = NULL; this->game = NULL; + this->gameCamera = NULL; showDebugUI = false; showDebugUILevel = debugui_fps; modelRenderer = NULL; @@ -173,6 +174,9 @@ Renderer::Renderer(bool masterserverMode) : BaseRenderer() { visibleFrameUnitList.clear(); visibleFrameUnitListCameraKey = ""; + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustrumData(); + lastRenderFps=MIN_FPS_NORMAL_RENDERING; shadowsOffDueToMinRender=false; shadowMapHandle=0; @@ -282,8 +286,12 @@ Renderer::~Renderer() { cleanupScreenshotThread(); mapSurfaceData.clear(); + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustrumData(); + this->menu = NULL; this->game = NULL; + this->gameCamera = NULL; } void Renderer::simpleTask(BaseThread *callingThread) { @@ -368,9 +376,10 @@ void Renderer::init() { } -void Renderer::initGame(const Game *game){ +void Renderer::initGame(const Game *game, GameCamera *gameCamera) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + this->gameCamera = gameCamera; VisibleQuadContainerCache::enableFrustumCalcs = Config::getInstance().getBool("EnableFrustrumCalcs","true"); quadCache = VisibleQuadContainerCache(); quadCache.clearFrustrumData(); @@ -501,6 +510,9 @@ void Renderer::reset3dMenu() { // ==================== end ==================== void Renderer::end() { + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustrumData(); + if(Renderer::rendererEnded == true) { return; } @@ -536,7 +548,10 @@ void Renderer::end() { } void Renderer::endScenario() { - game= NULL; + this->game= NULL; + this->gameCamera = NULL; + quadCache = VisibleQuadContainerCache(); + quadCache.clearFrustrumData(); if(this->masterserverMode == true) { return; @@ -565,7 +580,8 @@ void Renderer::endScenario() { } void Renderer::endGame(bool isFinalEnd) { - game= NULL; + this->game= NULL; + this->gameCamera = NULL; quadCache = VisibleQuadContainerCache(); quadCache.clearFrustrumData(); @@ -1287,8 +1303,7 @@ bool Renderer::CubeInFrustum(vector > &frustum, float x, float y, } void Renderer::computeVisibleQuad() { - const GameCamera *gameCamera = game->getGameCamera(); - visibleQuad = gameCamera->computeVisibleQuad(); + visibleQuad = this->gameCamera->computeVisibleQuad(); //Matrix4 LookAt( gameCamera->getPos(), gameCamera->getPos(), Vector3 up ); //gluLookAt @@ -1391,7 +1406,7 @@ void Renderer::computeVisibleQuad() { } if((tl.y > bl.y) || (tr.y > br.y)) { - visibleQuad = game->getGameCamera()->computeVisibleQuad(); + visibleQuad = this->gameCamera->computeVisibleQuad(); if(debug) printf("Swap Y???\n"); @@ -1446,7 +1461,7 @@ void Renderer::computeVisibleQuad() { catch(PROJECTION_TO_INFINITY e) { if(debug) printf("hmm staring at the horizon %d\n",(int)e); // use historic code solution - visibleQuad = game->getGameCamera()->computeVisibleQuad(); + visibleQuad = this->gameCamera->computeVisibleQuad(); } } } @@ -5411,7 +5426,7 @@ void Renderer::renderMenuBackground(Camera *camera, float fade, Model *mainModel } //characters - if(characterModels.size() > 0) { + if(characterModels.empty() == false) { float dist= characterPosition.dist(cameraPosition); float minDist= 3.f; if(dist < minDist) { diff --git a/source/glest_game/graphics/renderer.h b/source/glest_game/graphics/renderer.h index 334cccc9..1e2953ff 100644 --- a/source/glest_game/graphics/renderer.h +++ b/source/glest_game/graphics/renderer.h @@ -55,6 +55,7 @@ using namespace Shared::PlatformCommon; //non shared classes class Config; class Game; +class GameCamera; class MainMenu; class Console; class MenuBackground; @@ -67,11 +68,14 @@ class SurfaceCell; // class MeshCallbackTeamColor // ===================================================== -class MeshCallbackTeamColor: public MeshCallback{ +class MeshCallbackTeamColor: public MeshCallback { private: const Texture *teamTexture; public: + MeshCallbackTeamColor() : MeshCallback() { + teamTexture = NULL; + } void setTeamTexture(const Texture *teamTexture) {this->teamTexture= teamTexture;} virtual void execute(const Mesh *mesh); @@ -97,6 +101,7 @@ protected: frustumData = obj.frustumData; proj = obj.proj; modl = obj.modl; + frustumDataCache = obj.frustumDataCache; } public: @@ -234,6 +239,7 @@ private: //game const Game *game; + GameCamera *gameCamera; const MainMenu *menu; //misc @@ -379,7 +385,7 @@ public: //init void init(); - void initGame(const Game *game); + void initGame(const Game *game, GameCamera *gameCamera); void initMenu(const MainMenu *mm); void reset3d(); void reset2d(); diff --git a/source/glest_game/gui/gui.cpp b/source/glest_game/gui/gui.cpp index 74df52ab..6ea5010a 100644 --- a/source/glest_game/gui/gui.cpp +++ b/source/glest_game/gui/gui.cpp @@ -124,7 +124,7 @@ Gui::Gui(){ void Gui::init(Game *game){ this->commander= game->getCommander(); - this->gameCamera= game->getGameCamera(); + this->gameCamera= game->getGameCameraPtr(); this->console= game->getConsole(); this->world= game->getWorld(); this->game=game; diff --git a/source/glest_game/gui/selection.h b/source/glest_game/gui/selection.h index a2b93a3b..39f418d8 100644 --- a/source/glest_game/gui/selection.h +++ b/source/glest_game/gui/selection.h @@ -28,7 +28,7 @@ class Gui; /// List of selected units and groups // ===================================================== -class Selection: public UnitObserver{ +class Selection: public UnitObserver { public: typedef vector UnitContainer; typedef UnitContainer::const_iterator UnitIterator; @@ -45,6 +45,11 @@ private: Gui *gui; public: + Selection() : UnitObserver() { + factionIndex = 0; + teamIndex = 0; + gui = NULL; + } void init(Gui *gui, int factionIndex, int teamIndex); virtual ~Selection(); diff --git a/source/glest_game/main/intro.cpp b/source/glest_game/main/intro.cpp index cf7bf0cb..0fe3b064 100644 --- a/source/glest_game/main/intro.cpp +++ b/source/glest_game/main/intro.cpp @@ -297,12 +297,18 @@ Intro::Intro(Program *program): } - int textureWidth = logoTexture->getTextureWidth(); + int textureWidth = 256; + if(logoTexture != NULL) { + textureWidth = logoTexture->getTextureWidth(); + } if(lang.hasString(introTagTextureWidthName,"",true) == true) { textureWidth = strToInt(lang.get(introTagTextureWidthName,"",true)); } - int textureHeight = logoTexture->getTextureHeight(); + int textureHeight = 128; + if(logoTexture != NULL) { + textureHeight = logoTexture->getTextureHeight(); + } if(lang.hasString(introTagTextureHeightName,"",true) == true) { textureHeight = strToInt(lang.get(introTagTextureHeightName,"",true)); } @@ -559,7 +565,7 @@ void Intro::renderModelBackground() { // Black background glClearColor(0, 0, 0, 1); - if(models.size() > 0) { + if(models.empty() == false) { int difTime= 1000 * timer / GameConstants::updateFps - modelShowTime; int totalModelShowTime = Intro::introTime - modelShowTime; int individualModelShowTime = totalModelShowTime / models.size(); @@ -569,7 +575,7 @@ void Intro::renderModelBackground() { //int difTime= 1; if(difTime > 0) { if(difTime > ((modelIndex+1) * individualModelShowTime)) { - int oldmodelIndex = modelIndex; + //int oldmodelIndex = modelIndex; if(modelIndex+1 < models.size()) { modelIndex++; @@ -750,8 +756,8 @@ void Intro::render() { if(Renderer::renderText3DEnabled) { const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - int h= metrics.getVirtualH(); + //int w= metrics.getVirtualW(); + //int h= metrics.getVirtualH(); renderer.renderText3D( timingText, coreData.getMenuFontVeryBig3D(), 1, @@ -759,8 +765,8 @@ void Intro::render() { } else { const Metrics &metrics= Metrics::getInstance(); - int w= metrics.getVirtualW(); - int h= metrics.getVirtualH(); + //int w= metrics.getVirtualW(); + //int h= metrics.getVirtualH(); renderer.renderText( timingText, coreData.getMenuFontVeryBig(), 1, diff --git a/source/glest_game/main/main.cpp b/source/glest_game/main/main.cpp index 349d56dd..af26e7a4 100644 --- a/source/glest_game/main/main.cpp +++ b/source/glest_game/main/main.cpp @@ -151,7 +151,11 @@ static void cleanupProcessObjects() { //SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(Renderer::isEnded() == false) Renderer::getInstance().end(); + if(Renderer::isEnded() == false) { + Renderer::getInstance().end(); + CoreData &coreData= CoreData::getInstance(); + coreData.cleanup(); + } if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); @@ -663,6 +667,7 @@ MainWindow::MainWindow(Program *program) : WindowGl() { this->popupMenu.setVisible(false); this->triggerLanguageToggle = false; this->triggerLanguage = ""; + this->cancelLanguageSelection = -1; } MainWindow::~MainWindow(){ @@ -2850,7 +2855,7 @@ int glestMain(int argc, char** argv) { } if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_MASTERSERVER_MODE])) == true) { - Renderer &renderer= Renderer::getInstance(true); + Renderer::getInstance(true); } if(hasCommandArgument(argc, argv,GAME_ARGS[GAME_ARG_USE_PORTS]) == true) { @@ -3212,7 +3217,7 @@ int glestMain(int argc, char** argv) { string autoloadMapName = paramPartTokens[1]; GameSettings *gameSettings = &startupGameSettings; - int factionCount= 0; + //int factionCount= 0; gameSettings->setMap(autoloadMapName); gameSettings->setTileset("forest"); gameSettings->setTech("megapack"); diff --git a/source/glest_game/main/program.cpp b/source/glest_game/main/program.cpp index 0299b814..71089b8b 100644 --- a/source/glest_game/main/program.cpp +++ b/source/glest_game/main/program.cpp @@ -82,7 +82,7 @@ bool ProgramState::canRender(bool sleepIfCannotRender) { if(lastFps > maxFPSCap) { if(sleepIfCannotRender == true) { sleep(sleepMillis); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sleeping because lastFps = %d, maxFPSCap = %d sleepMillis = %d\n",__FILE__,__FUNCTION__,__LINE__,lastFps,maxFPSCap,sleepMillis); + //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] sleeping because lastFps = %d, maxFPSCap = %d sleepMillis = %d\n",__FILE__,__FUNCTION__,__LINE__,lastFps,maxFPSCap,sleepMillis); } return false; } @@ -246,6 +246,8 @@ Program::~Program(){ if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); Renderer::getInstance().end(); + CoreData &coreData= CoreData::getInstance(); + coreData.cleanup(); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); diff --git a/source/glest_game/menu/menu_state_connected_game.cpp b/source/glest_game/menu/menu_state_connected_game.cpp index 9f2c008e..d79ed11d 100644 --- a/source/glest_game/menu/menu_state_connected_game.cpp +++ b/source/glest_game/menu/menu_state_connected_game.cpp @@ -124,7 +124,7 @@ MenuStateConnectedGame::MenuStateConnectedGame(Program *program, MainMenu *mainM int aHeadPos=240; int aPos=aHeadPos-labelOffset; int networkHeadPos=700; - int networkPos=networkHeadPos-labelOffset; + //int networkPos=networkHeadPos-labelOffset; int xoffset=0; //state @@ -1100,8 +1100,8 @@ void MenuStateConnectedGame::updateResourceMultiplier(const int index) { void MenuStateConnectedGame::mouseClickAdmin(int x, int y, MouseButton mouseButton) { try { - CoreData &coreData= CoreData::getInstance(); - SoundRenderer &soundRenderer= SoundRenderer::getInstance(); + //CoreData &coreData= CoreData::getInstance(); + //SoundRenderer &soundRenderer= SoundRenderer::getInstance(); //int oldListBoxMapfilterIndex=listBoxMapFilter.getSelectedItemIndex(); if(buttonPlayNow.mouseClick(x,y) && buttonPlayNow.getEnabled()) { @@ -1316,7 +1316,7 @@ void MenuStateConnectedGame::mouseClickAdmin(int x, int y, MouseButton mouseButt //} //ensure thet only 1 human player is present - int oldSelectedIndex = listBoxControls[i].getSelectedItemIndex(); + //int oldSelectedIndex = listBoxControls[i].getSelectedItemIndex(); if(clientInterface != NULL && clientInterface->getGameSettings() != NULL && clientInterface->getGameSettings()->getStartLocationIndex(clientInterface->getGameSettings()->getThisFactionIndex()) != i && listBoxControls[i].mouseClick(x, y)) { @@ -3708,7 +3708,7 @@ void MenuStateConnectedGame::FTPClient_CallbackEvent(string itemName, // Reload tilesets for the UI findDirs(Config::getInstance().getPathListForType(ptTechs), techTreeFiles); - int initialTechSelection=0; + //int initialTechSelection=0; std::vector techsFormatted = techTreeFiles; for(int i= 0; i < techsFormatted.size(); i++){ techsFormatted.at(i)= formatString(techsFormatted.at(i)); diff --git a/source/glest_game/menu/menu_state_custom_game.cpp b/source/glest_game/menu/menu_state_custom_game.cpp index e80c2392..e0de0ff6 100644 --- a/source/glest_game/menu/menu_state_custom_game.cpp +++ b/source/glest_game/menu/menu_state_custom_game.cpp @@ -1682,7 +1682,7 @@ void MenuStateCustomGame::render() { // START - this code ensure player title and player names don't overlap int offsetPosition=0; for(int i=0; i < GameConstants::maxPlayers; ++i) { - const Metrics &metrics= Metrics::getInstance(); + //const Metrics &metrics= Metrics::getInstance(); FontMetrics *fontMetrics= NULL; if(Renderer::renderText3DEnabled == false) { fontMetrics = labelPlayers[i].getFont()->getMetrics(); diff --git a/source/glest_game/menu/menu_state_graphic_info.cpp b/source/glest_game/menu/menu_state_graphic_info.cpp index 46e6f654..8909e866 100644 --- a/source/glest_game/menu/menu_state_graphic_info.cpp +++ b/source/glest_game/menu/menu_state_graphic_info.cpp @@ -134,7 +134,7 @@ void MenuStateGraphicInfo::mouseMove(int x, int y, const MouseState *ms){ void MenuStateGraphicInfo::render(){ Renderer &renderer= Renderer::getInstance(); - Lang &lang= Lang::getInstance(); + //Lang &lang= Lang::getInstance(); renderer.renderButton(&buttonReturn); renderer.renderLabel(&labelInfo); diff --git a/source/glest_game/menu/menu_state_mods.cpp b/source/glest_game/menu/menu_state_mods.cpp index 5df77666..bb2a2f0d 100644 --- a/source/glest_game/menu/menu_state_mods.cpp +++ b/source/glest_game/menu/menu_state_mods.cpp @@ -957,7 +957,7 @@ string MenuStateMods::refreshMapModInfo(string mapInfo) { std::vector mapInfoList; Tokenize(mapInfo,mapInfoList,"|"); if(mapInfoList.size() >= 5) { - Config &config = Config::getInstance(); + //Config &config = Config::getInstance(); ModInfo modinfo; modinfo.name = mapInfoList[0]; modinfo.count = mapInfoList[1]; @@ -977,7 +977,7 @@ string MenuStateMods::getMapCRC(string mapName) { Config &config = Config::getInstance(); vector mappaths=config.getPathListForType(ptMaps,""); string result=""; - if(mappaths.size()>0 ){ + if(mappaths.empty() == false) { Checksum checksum; string itemPath = mappaths[1] + "/" + mapName; if (fileExists(itemPath)){ diff --git a/source/glest_game/network/connection_slot.cpp b/source/glest_game/network/connection_slot.cpp index 8eef0b23..acf6edfb 100644 --- a/source/glest_game/network/connection_slot.cpp +++ b/source/glest_game/network/connection_slot.cpp @@ -33,6 +33,7 @@ namespace Glest{ namespace Game{ // ===================================================== ConnectionSlotThread::ConnectionSlotThread(int slotIndex) : BaseThread() { + this->triggerIdMutex = new Mutex(); this->slotIndex = slotIndex; this->slotInterface = NULL; //this->event = NULL; @@ -41,12 +42,18 @@ ConnectionSlotThread::ConnectionSlotThread(int slotIndex) : BaseThread() { } ConnectionSlotThread::ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface,int slotIndex) : BaseThread() { + this->triggerIdMutex = new Mutex(); this->slotIndex = slotIndex; this->slotInterface = slotInterface; //this->event = NULL; eventList.clear(); } +ConnectionSlotThread::~ConnectionSlotThread() { + delete triggerIdMutex; + triggerIdMutex = NULL; +} + void ConnectionSlotThread::setQuitStatus(bool value) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); @@ -60,7 +67,7 @@ void ConnectionSlotThread::setQuitStatus(bool value) { void ConnectionSlotThread::signalUpdate(ConnectionSlotEvent *event) { if(event != NULL) { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); eventList.push_back(*event); safeMutex.ReleaseLock(); } @@ -69,7 +76,7 @@ void ConnectionSlotThread::signalUpdate(ConnectionSlotEvent *event) { void ConnectionSlotThread::setTaskCompleted(int eventId) { if(eventId > 0) { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); //event->eventCompleted = true; for(int i = 0; i < eventList.size(); ++i) { ConnectionSlotEvent &slotEvent = eventList[i]; @@ -84,13 +91,13 @@ void ConnectionSlotThread::setTaskCompleted(int eventId) { } void ConnectionSlotThread::purgeAllEvents() { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); eventList.clear(); safeMutex.ReleaseLock(); } void ConnectionSlotThread::setAllEventsCompleted() { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); for(int i = 0; i < eventList.size(); ++i) { ConnectionSlotEvent &slotEvent = eventList[i]; if(slotEvent.eventCompleted == false) { @@ -101,7 +108,7 @@ void ConnectionSlotThread::setAllEventsCompleted() { } void ConnectionSlotThread::purgeCompletedEvents() { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); //event->eventCompleted = true; for(int i = eventList.size() - 1; i >= 0; i--) { ConnectionSlotEvent &slotEvent = eventList[i]; @@ -123,7 +130,7 @@ bool ConnectionSlotThread::canShutdown(bool deleteSelfIfShutdownDelayed) { } bool ConnectionSlotThread::isSignalCompleted(ConnectionSlotEvent *event) { - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); bool result = false; if(event != NULL) { for(int i = 0; i < eventList.size(); ++i) { @@ -177,7 +184,7 @@ void ConnectionSlotThread::execute() { break; } - MutexSafeWrapper safeMutex(&triggerIdMutex,CODE_AT_LINE); + MutexSafeWrapper safeMutex(triggerIdMutex,CODE_AT_LINE); int eventCount = eventList.size(); if(eventCount > 0) { ConnectionSlotEvent eventCopy; @@ -233,9 +240,12 @@ void ConnectionSlotThread::execute() { // ===================================================== ConnectionSlot::ConnectionSlot(ServerInterface* serverInterface, int playerIndex) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); + this->mutexSocket = new Mutex(); + this->mutexCloseConnection = new Mutex(); + this->mutexPendingNetworkCommandList = new Mutex(); + this->socketSynchAccessor = new Mutex(); this->connectedRemoteIPAddress = 0; this->sessionKey = 0; this->serverInterface = serverInterface; @@ -283,6 +293,18 @@ ConnectionSlot::~ConnectionSlot() { } slotThreadWorker = NULL; + delete socketSynchAccessor; + socketSynchAccessor = NULL; + + delete mutexPendingNetworkCommandList; + mutexPendingNetworkCommandList = NULL; + + delete mutexCloseConnection; + mutexCloseConnection = NULL; + + delete mutexSocket; + mutexSocket = NULL; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] END\n",__FILE__,__FUNCTION__); } @@ -372,7 +394,7 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { //printf("Got new connection for slot = %d\n",playerIndex); - MutexSafeWrapper safeMutex(&mutexCloseConnection,CODE_AT_LINE); + MutexSafeWrapper safeMutex(mutexCloseConnection,CODE_AT_LINE); this->setSocket(newSocket); safeMutex.ReleaseLock(); @@ -390,7 +412,7 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); - MutexSafeWrapper safeMutexSlot1(&mutexPendingNetworkCommandList,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot1(mutexPendingNetworkCommandList,CODE_AT_LINE); this->vctPendingNetworkCommandList.clear(); safeMutexSlot1.ReleaseLock(); @@ -545,7 +567,7 @@ void ConnectionSlot::update(bool checkForNewClients,int lockedSlotIndex) { lastReceiveCommandListTime = time(NULL); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] currentFrameCount = %d\n",__FILE__,__FUNCTION__,__LINE__,currentFrameCount); - MutexSafeWrapper safeMutexSlot(&mutexPendingNetworkCommandList,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); for(int i = 0; i < networkMessageCommandList.getCommandCount(); ++i) { vctPendingNetworkCommandList.push_back(*networkMessageCommandList.getCommand(i)); } @@ -1026,7 +1048,7 @@ void ConnectionSlot::close() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - MutexSafeWrapper safeMutex(&mutexCloseConnection,CODE_AT_LINE); + MutexSafeWrapper safeMutex(mutexCloseConnection,CODE_AT_LINE); bool updateServerListener = (this->getSocket() != NULL); this->deleteSocket(); @@ -1066,7 +1088,7 @@ bool ConnectionSlot::updateCompleted(ConnectionSlotEvent *event) { } void ConnectionSlot::sendMessage(const NetworkMessage* networkMessage) { - MutexSafeWrapper safeMutex(&socketSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(socketSynchAccessor,CODE_AT_LINE); // Skip text messages not intended for the players preferred language const NetworkMessageText *textMsg = dynamic_cast(networkMessage); @@ -1088,7 +1110,7 @@ string ConnectionSlot::getHumanPlayerName(int index) { vector ConnectionSlot::getPendingNetworkCommandList(bool clearList) { vector ret; - MutexSafeWrapper safeMutexSlot(&mutexPendingNetworkCommandList,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); if(vctPendingNetworkCommandList.empty() == false) { ret = vctPendingNetworkCommandList; if(clearList == true) { @@ -1101,7 +1123,7 @@ vector ConnectionSlot::getPendingNetworkCommandList(bool clearLi } void ConnectionSlot::clearPendingNetworkCommandList() { - MutexSafeWrapper safeMutexSlot(&mutexPendingNetworkCommandList,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexPendingNetworkCommandList,CODE_AT_LINE); if(vctPendingNetworkCommandList.empty() == false) { vctPendingNetworkCommandList.clear(); } @@ -1112,7 +1134,7 @@ bool ConnectionSlot::hasValidSocketId() { //bool result = (this->getSocket() != NULL && this->getSocket()->getSocketId() > 0); //return result; bool result = false; - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); if(socket != NULL && socket->getSocketId() > 0) { result = true; } @@ -1122,7 +1144,7 @@ bool ConnectionSlot::hasValidSocketId() { bool ConnectionSlot::isConnected() { bool result = false; - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); if(socket != NULL && socket->isConnected() == true) { result = true; } @@ -1131,7 +1153,7 @@ bool ConnectionSlot::isConnected() { PLATFORM_SOCKET ConnectionSlot::getSocketId() { PLATFORM_SOCKET result = 0; - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); if(socket != NULL) { result = socket->getSocketId(); } @@ -1140,7 +1162,7 @@ PLATFORM_SOCKET ConnectionSlot::getSocketId() { pair ConnectionSlot::getSocketInfo() { pair result; - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); result.first = (socket != NULL && socket->isConnected()); result.second = socket; @@ -1151,25 +1173,25 @@ pair ConnectionSlot::getSocketInfo() { Socket* ConnectionSlot::getSocket(bool mutexLock) { MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE); if(mutexLock == true) { - safeMutexSlot.setMutex(&mutexSocket,CODE_AT_LINE); + safeMutexSlot.setMutex(mutexSocket,CODE_AT_LINE); } return socket; } void ConnectionSlot::setSocket(Socket *newSocket) { - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); socket = newSocket; } void ConnectionSlot::deleteSocket() { - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); delete socket; socket = NULL; } bool ConnectionSlot::hasDataToRead() { bool result = false; - MutexSafeWrapper safeMutexSlot(&mutexSocket,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(mutexSocket,CODE_AT_LINE); if(socket != NULL && socket->hasDataToRead() == true) { result = true; diff --git a/source/glest_game/network/connection_slot.h b/source/glest_game/network/connection_slot.h index dfebcf82..3e11046e 100644 --- a/source/glest_game/network/connection_slot.h +++ b/source/glest_game/network/connection_slot.h @@ -75,7 +75,7 @@ protected: ConnectionSlotCallbackInterface *slotInterface; Semaphore semTaskSignalled; - Mutex triggerIdMutex; + Mutex *triggerIdMutex; vector eventList; int slotIndex; @@ -88,6 +88,8 @@ protected: public: ConnectionSlotThread(int slotIndex); ConnectionSlotThread(ConnectionSlotCallbackInterface *slotInterface,int slotIndex); + virtual ~ConnectionSlotThread(); + virtual void execute(); void signalUpdate(ConnectionSlotEvent *event); bool isSignalCompleted(ConnectionSlotEvent *event); @@ -106,7 +108,7 @@ class ConnectionSlot: public NetworkInterface { private: ServerInterface* serverInterface; - Mutex mutexSocket; + Mutex *mutexSocket; Socket* socket; int playerIndex; string name; @@ -116,9 +118,9 @@ private: time_t connectedTime; bool gotIntro; - Mutex mutexCloseConnection; + Mutex *mutexCloseConnection; - Mutex mutexPendingNetworkCommandList; + Mutex *mutexPendingNetworkCommandList; vector vctPendingNetworkCommandList; ConnectionSlotThread* slotThreadWorker; int currentFrameCount; @@ -199,7 +201,7 @@ protected: Mutex * getServerSynchAccessor(); std::vector threadErrorList; - Mutex socketSynchAccessor; + Mutex *socketSynchAccessor; void setSocket(Socket *newSocket); void deleteSocket(); diff --git a/source/glest_game/network/network_message.cpp b/source/glest_game/network/network_message.cpp index e1b7dfb9..daec86a7 100644 --- a/source/glest_game/network/network_message.cpp +++ b/source/glest_game/network/network_message.cpp @@ -402,7 +402,7 @@ void NetworkMessageCommandList::send(Socket* socket) const { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] nmtCommandList, frameCount = %d, data.header.commandCount = %d, data.header.messageType = %d\n",__FILE__,__FUNCTION__,__LINE__,data.header.frameCount,data.header.commandCount,data.header.messageType); assert(data.header.messageType==nmtCommandList); - int totalMsgSize = commandListHeaderSize + (sizeof(NetworkCommand) * data.header.commandCount); + //int totalMsgSize = commandListHeaderSize + (sizeof(NetworkCommand) * data.header.commandCount); //NetworkMessage::send(socket, &data, totalMsgSize); NetworkMessage::send(socket, &data.header, commandListHeaderSize); if(data.header.commandCount > 0) { diff --git a/source/glest_game/network/server_interface.cpp b/source/glest_game/network/server_interface.cpp index 68f981a5..a0efbee1 100644 --- a/source/glest_game/network/server_interface.cpp +++ b/source/glest_game/network/server_interface.cpp @@ -47,6 +47,15 @@ const int MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS = 30; ServerInterface::ServerInterface(bool publishEnabled) :GameNetworkInterface() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + serverSynchAccessor = new Mutex(); + for(int i= 0; i < GameConstants::maxPlayers; ++i) { + slotAccessorMutexes[i] = new Mutex(); + } + masterServerThreadAccessor = new Mutex(); + textMessageQueueThreadAccessor = new Mutex(); + broadcastMessageQueueThreadAccessor = new Mutex(); + inBroadcastMessageThreadAccessor = new Mutex(); + nextEventId = 1; gameHasBeenInitiated = false; exitServer = false; @@ -169,7 +178,7 @@ ServerInterface::~ServerInterface() { exitServer = true; for(int i= 0; i < GameConstants::maxPlayers; ++i) { if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); delete slots[i]; slots[i]=NULL; } @@ -187,7 +196,7 @@ ServerInterface::~ServerInterface() { delete ftpServer; ftpServer = NULL; } - MutexSafeWrapper safeMutex(&masterServerThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); delete publishToMasterserverThread; publishToMasterserverThread = NULL; safeMutex.ReleaseLock(); @@ -196,6 +205,27 @@ ServerInterface::~ServerInterface() { if(needToRepublishToMasterserver == true) { simpleTask(NULL); } + + for(int i= 0; i < GameConstants::maxPlayers; ++i) { + delete slotAccessorMutexes[i]; + slotAccessorMutexes[i] = NULL; + } + + delete textMessageQueueThreadAccessor; + textMessageQueueThreadAccessor = NULL; + + delete broadcastMessageQueueThreadAccessor; + broadcastMessageQueueThreadAccessor = NULL; + + delete inBroadcastMessageThreadAccessor; + inBroadcastMessageThreadAccessor = NULL; + + delete serverSynchAccessor; + serverSynchAccessor = NULL; + + delete masterServerThreadAccessor; + masterServerThreadAccessor = NULL; + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); } @@ -203,7 +233,7 @@ int ServerInterface::isValidClientType(uint32 clientIp) { int result = 0; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { if(slots[i] != NULL) { - MutexSafeWrapper safeMutex(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); Socket *socket = slots[i]->getSocket(); if(socket != NULL) { @@ -275,14 +305,14 @@ void ServerInterface::addClientToServerIPAddress(uint32 clientIp, uint32 ServerI void ServerInterface::addSlot(int playerIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); assert(playerIndex >= 0 && playerIndex < GameConstants::maxPlayers); - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); if(serverSocket.isPortBound() == false) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); serverSocket.bind(serverSocket.getBindPort()); } if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); ConnectionSlot *slot = slots[playerIndex]; if(slot != NULL) { @@ -308,9 +338,9 @@ bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { return false; } - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[fromPlayerIndex],CODE_AT_LINE_X(fromPlayerIndex)); - MutexSafeWrapper safeMutexSlot2(&slotAccessorMutexes[toPlayerIndex],CODE_AT_LINE_X(toPlayerIndex)); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[fromPlayerIndex],CODE_AT_LINE_X(fromPlayerIndex)); + MutexSafeWrapper safeMutexSlot2(slotAccessorMutexes[toPlayerIndex],CODE_AT_LINE_X(toPlayerIndex)); if(slots[toPlayerIndex] != NULL && slots[toPlayerIndex] != NULL && slots[toPlayerIndex]->isConnected() == false) { slots[fromPlayerIndex]->setPlayerIndex(toPlayerIndex); @@ -338,11 +368,11 @@ bool ServerInterface::switchSlot(int fromPlayerIndex, int toPlayerIndex) { void ServerInterface::removeSlot(int playerIndex, int lockedSlotIndex) { Lang &lang= Lang::getInstance(); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(playerIndex)); if(playerIndex != lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] playerIndex = %d, lockedSlotIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,playerIndex,lockedSlotIndex); - safeMutexSlot.setMutex(&slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); + safeMutexSlot.setMutex(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(playerIndex)); } ConnectionSlot *slot = slots[playerIndex]; bool notifyDisconnect = false; @@ -398,14 +428,14 @@ void ServerInterface::removeSlot(int playerIndex, int lockedSlotIndex) { } ConnectionSlot *ServerInterface::getSlot(int playerIndex) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[playerIndex],CODE_AT_LINE_X(i)); ConnectionSlot *result = slots[playerIndex]; return result; } bool ServerInterface::isClientConnected(int index) { bool result = false; - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[index],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[index],CODE_AT_LINE_X(i)); if(slots[index] != NULL && slots[index]->isConnected() == true) { result = true; } @@ -426,7 +456,7 @@ bool ServerInterface::hasClientConnection() { int ServerInterface::getConnectedSlotCount() { int connectedSlotCount = 0; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); if(slots[i] != NULL) { ++connectedSlotCount; } @@ -476,7 +506,7 @@ void ServerInterface::slotUpdateTask(ConnectionSlotEvent *event) { // // //printf("===> START slot %d [%d][%p] - About to updateSlot\n",event->triggerId,event->eventId,slots[event->triggerId]); // -// safeMutexSlot.setMutex(&slotAccessorMutexes[event->triggerId],CODE_AT_LINE_X(event->triggerId)); +// safeMutexSlot.setMutex(slotAccessorMutexes[event->triggerId],CODE_AT_LINE_X(event->triggerId)); // connectionSlot = slots[event->triggerId]; // } // else { @@ -708,7 +738,7 @@ bool ServerInterface::signalClientReceiveCommands(ConnectionSlot *connectionSlot void ServerInterface::updateSocketTriggeredList(std::map & socketTriggeredList) { for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL) { PLATFORM_SOCKET clientSocket = connectionSlot->getSocketId(); @@ -721,7 +751,7 @@ void ServerInterface::updateSocketTriggeredList(std::map & void ServerInterface::validateConnectedClients() { for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot = slots[i]; if(connectionSlot != NULL) { connectionSlot->validateConnection(); @@ -734,7 +764,7 @@ void ServerInterface::signalClientsToRecieveData(std::map std::map & mapSlotSignalledList) { //bool checkForNewClients = true; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot = slots[i]; bool socketTriggered = false; @@ -764,7 +794,7 @@ void ServerInterface::checkForCompletedClients(std::map & mapSlotSigna //printf("===> START slot %d [%p] - About to checkForCompletedClients\n",i,slots[i]); - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); //printf("===> IN slot %d - About to checkForCompletedClients\n",i); @@ -824,7 +854,7 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle threadsDone = true; // Examine all threads for completion of delegation for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot = slots[i]; if(connectionSlot != NULL && mapSlotSignalledList[i] == true && slotsCompleted.find(i) == slotsCompleted.end()) { @@ -937,7 +967,7 @@ void ServerInterface::checkForLaggingClients(std::map &mapSlotSignalle void ServerInterface::executeNetworkCommandsFromClients() { if(gameHasBeenInitiated == true) { for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { vector pendingList = connectionSlot->getPendingNetworkCommandList(true); @@ -954,7 +984,7 @@ void ServerInterface::executeNetworkCommandsFromClients() { void ServerInterface::dispatchPendingChatMessages(std::vector &errorMsgList) { for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->getChatTextList(false).empty() == false) { @@ -1284,7 +1314,7 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { vector waitingForHosts; allReady= true; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { if(connectionSlot->isReady() == false) { @@ -1363,7 +1393,7 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { uint32 loadingStatus = nmls_NONE; //send ready message after, so clients start delayed for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { switch(i) { @@ -1421,7 +1451,7 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { // send loading status message for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { NetworkMessageLoadingStatus networkMessageLoadingStatus(loadingStatus); @@ -1457,7 +1487,7 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { try { //send ready message after, so clients start delayed for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected() == true) { NetworkMessageReady networkMessageReady(checksum->getSum()); @@ -1476,7 +1506,7 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { } void ServerInterface::processBroadCastMessageQueue() { - MutexSafeWrapper safeMutexSlot(&broadcastMessageQueueThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); if(broadcastMessageQueue.empty() == false) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] broadcastMessageQueue.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,broadcastMessageQueue.size()); for(int i = 0; i < broadcastMessageQueue.size(); ++i) { @@ -1492,7 +1522,7 @@ void ServerInterface::processBroadCastMessageQueue() { } void ServerInterface::queueBroadcastMessage(const NetworkMessage *networkMessage, int excludeSlot) { - MutexSafeWrapper safeMutexSlot(&broadcastMessageQueueThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(broadcastMessageQueueThreadAccessor,CODE_AT_LINE); pair item; item.first = networkMessage; item.second = excludeSlot; @@ -1500,7 +1530,7 @@ void ServerInterface::queueBroadcastMessage(const NetworkMessage *networkMessage } void ServerInterface::processTextMessageQueue() { - MutexSafeWrapper safeMutexSlot(&textMessageQueueThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); if(textMessageQueue.empty() == false) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] textMessageQueue.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,textMessageQueue.size()); for(int i = 0; i < textMessageQueue.size(); ++i) { @@ -1516,7 +1546,7 @@ void ServerInterface::queueTextMessage(const string & text, int teamIndex, //printf("Line: %d text [%s]\n",__LINE__,text.c_str()); - MutexSafeWrapper safeMutexSlot(&textMessageQueueThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlot(textMessageQueueThreadAccessor,CODE_AT_LINE); TextMessageQueue item; item.text = text; item.teamIndex = teamIndex; @@ -1559,7 +1589,7 @@ string ServerInterface::getNetworkStatus() { Lang &lang = Lang::getInstance(); string str=""; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot* connectionSlot= slots[i]; str+= intToStr(i)+ ": "; @@ -1588,7 +1618,7 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { bool bOkToStart = true; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot= slots[i]; if(connectionSlot != NULL && (connectionSlot->getAllowDownloadDataSynch() == true || connectionSlot->getAllowGameDataSynchCheck() == true) && @@ -1608,7 +1638,7 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { if(useInGameBlockingClientSockets == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); for(int i= 0; i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot= slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected()) { connectionSlot->getSocket()->setBlock(true); @@ -1627,7 +1657,7 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] needToRepublishToMasterserver = %d\n",__FILE__,__FUNCTION__,__LINE__,needToRepublishToMasterserver); - MutexSafeWrapper safeMutex(&masterServerThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); delete publishToMasterserverThread; publishToMasterserverThread = NULL; lastMasterserverHeartbeatTime = 0; @@ -1662,7 +1692,7 @@ bool ServerInterface::launchGame(const GameSettings *gameSettings) { void ServerInterface::broadcastGameSetup(const GameSettings *gameSettings) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); NetworkMessageLaunch networkMessageLaunch(gameSettings, nmtBroadCastSetup); broadcastMessage(&networkMessageLaunch); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); @@ -1672,7 +1702,7 @@ void ServerInterface::broadcastMessage(const NetworkMessage *networkMessage, int try { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - MutexSafeWrapper safeMutexSlotBroadCastAccessor(&inBroadcastMessageThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlotBroadCastAccessor(inBroadcastMessageThreadAccessor,CODE_AT_LINE); if(inBroadcastMessage == true && dynamic_cast(networkMessage) != NULL) { safeMutexSlotBroadCastAccessor.ReleaseLock(); const NetworkMessageText *txtMsg = dynamic_cast(networkMessage); @@ -1689,7 +1719,7 @@ void ServerInterface::broadcastMessage(const NetworkMessage *networkMessage, int MutexSafeWrapper safeMutexSlot(NULL,CODE_AT_LINE_X(i)); if(i != lockedSlotIndex) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] i = %d, lockedSlotIndex = %d\n",__FILE__,__FUNCTION__,__LINE__,i,lockedSlotIndex); - safeMutexSlot.setMutex(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + safeMutexSlot.setMutex(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); } ConnectionSlot* connectionSlot= slots[i]; @@ -1724,7 +1754,7 @@ void ServerInterface::broadcastMessage(const NetworkMessage *networkMessage, int SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] ERROR [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); - MutexSafeWrapper safeMutexSlotBroadCastAccessor(&inBroadcastMessageThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSlotBroadCastAccessor(inBroadcastMessageThreadAccessor,CODE_AT_LINE); inBroadcastMessage = false; safeMutexSlotBroadCastAccessor.ReleaseLock(); @@ -1737,7 +1767,7 @@ void ServerInterface::broadcastMessageToConnectedClients(const NetworkMessage *n if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",__FILE__,__FUNCTION__,__LINE__); try { for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot= slots[i]; if(i != excludeSlot && connectionSlot != NULL) { @@ -1761,7 +1791,7 @@ void ServerInterface::updateListen() { } int openSlotCount = 0; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - //MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); + //MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); bool isSlotOpen = (slots[i] != NULL && slots[i]->isConnected() == false); if(isSlotOpen == true) { @@ -1774,7 +1804,7 @@ void ServerInterface::updateListen() { int ServerInterface::getOpenSlotCount() { int openSlotCount = 0; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - //MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); + //MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],intToStr(__LINE__) + "_" + intToStr(i)); bool isSlotOpen = (slots[i] != NULL && slots[i]->isConnected() == false); if(isSlotOpen == true) { @@ -1786,7 +1816,7 @@ int ServerInterface::getOpenSlotCount() { int ServerInterface::getGameSettingsUpdateCount() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START gameSettingsUpdateCount = %d\n",__FILE__,__FUNCTION__,gameSettingsUpdateCount); - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); int result = gameSettingsUpdateCount; safeMutex.ReleaseLock(); @@ -1795,7 +1825,7 @@ int ServerInterface::getGameSettingsUpdateCount() { void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool waitForClientAck) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START gameSettingsUpdateCount = %d, waitForClientAck = %d\n",__FILE__,__FUNCTION__,gameSettingsUpdateCount,waitForClientAck); - MutexSafeWrapper safeMutex(&serverSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); string mapFile = serverGameSettings->getMap(); if(find(mapFiles.begin(),mapFiles.end(),mapFile) == mapFiles.end()) { @@ -1834,7 +1864,7 @@ void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool wai for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { //printf("===> START slot %d - About to setGameSettings #1\n",i); - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot = slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected()) { if(connectionSlot->getReceivedNetworkGameStatus() == false) { @@ -1850,7 +1880,7 @@ void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool wai } for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot = slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected()) { connectionSlot->setReceivedNetworkGameStatus(false); @@ -1870,7 +1900,7 @@ void ServerInterface::setGameSettings(GameSettings *serverGameSettings, bool wai for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { //printf("===> START slot %d - About to setGameSettings 2\n",i); - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); ConnectionSlot *connectionSlot = slots[i]; if(connectionSlot != NULL && connectionSlot->isConnected()) { if(connectionSlot->getReceivedNetworkGameStatus() == false) { @@ -1921,7 +1951,7 @@ std::map ServerInterface::publishToMasterserver() { std::map < string, string > publishToServerInfo; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { - MutexSafeWrapper safeMutexSlot(&slotAccessorMutexes[i],CODE_AT_LINE_X(i)); + MutexSafeWrapper safeMutexSlot(slotAccessorMutexes[i],CODE_AT_LINE_X(i)); if(slots[i] != NULL) { slotCountUsed++; slotCountHumans++; @@ -1955,7 +1985,7 @@ std::map ServerInterface::publishToMasterserver() { } void ServerInterface::simpleTask(BaseThread *callingThread) { - MutexSafeWrapper safeMutex(&masterServerThreadAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutex(masterServerThreadAccessor,CODE_AT_LINE); if(difftime(time(NULL),lastMasterserverHeartbeatTime) >= MASTERSERVER_HEARTBEAT_GAME_STATUS_SECONDS) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line %d]\n",__FILE__,__FUNCTION__,__LINE__); diff --git a/source/glest_game/network/server_interface.h b/source/glest_game/network/server_interface.h index 8bfb9ea3..6ed2f569 100644 --- a/source/glest_game/network/server_interface.h +++ b/source/glest_game/network/server_interface.h @@ -48,13 +48,13 @@ public: private: ConnectionSlot* slots[GameConstants::maxPlayers]; - Mutex slotAccessorMutexes[GameConstants::maxPlayers]; + Mutex *slotAccessorMutexes[GameConstants::maxPlayers]; ServerSocket serverSocket; bool gameHasBeenInitiated; int gameSettingsUpdateCount; SwitchSetupRequest* switchSetupRequests[GameConstants::maxPlayers]; - Mutex serverSynchAccessor; + Mutex *serverSynchAccessor; int currentFrameCount; time_t gameStartTime; @@ -62,7 +62,7 @@ private: time_t lastGlobalLagCheckTime; SimpleTaskThread *publishToMasterserverThread; - Mutex masterServerThreadAccessor; + Mutex *masterServerThreadAccessor; time_t lastMasterserverHeartbeatTime; bool needToRepublishToMasterserver; @@ -70,13 +70,13 @@ private: bool exitServer; int64 nextEventId; - Mutex textMessageQueueThreadAccessor; + Mutex *textMessageQueueThreadAccessor; vector textMessageQueue; - Mutex broadcastMessageQueueThreadAccessor; + Mutex *broadcastMessageQueueThreadAccessor; vector > broadcastMessageQueue; - Mutex inBroadcastMessageThreadAccessor; + Mutex *inBroadcastMessageThreadAccessor; bool inBroadcastMessage; bool masterserverAdminRequestLaunch; @@ -184,7 +184,7 @@ public: public: Mutex *getServerSynchAccessor() { - return &serverSynchAccessor; + return serverSynchAccessor; } virtual void simpleTask(BaseThread *callingThread); diff --git a/source/glest_game/type_instances/faction.cpp b/source/glest_game/type_instances/faction.cpp index 41948dd8..bb74a50f 100644 --- a/source/glest_game/type_instances/faction.cpp +++ b/source/glest_game/type_instances/faction.cpp @@ -213,9 +213,15 @@ void Faction::sortUnitsByCommandGroups() { // ===================================================== FactionThread::FactionThread(Faction *faction) : BaseThread() { + this->triggerIdMutex = new Mutex(); this->faction = faction; } +FactionThread::~FactionThread() { + delete triggerIdMutex; + triggerIdMutex = NULL; +} + void FactionThread::setQuitStatus(bool value) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s] Line: %d value = %d\n",__FILE__,__FUNCTION__,__LINE__,value); @@ -230,7 +236,7 @@ void FactionThread::setQuitStatus(bool value) { void FactionThread::signalPathfinder(int frameIndex) { if(frameIndex >= 0) { static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&triggerIdMutex,mutexOwnerId); + MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); this->frameIndex.first = frameIndex; this->frameIndex.second = false; @@ -242,7 +248,7 @@ void FactionThread::signalPathfinder(int frameIndex) { void FactionThread::setTaskCompleted(int frameIndex) { if(frameIndex >= 0) { static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&triggerIdMutex,mutexOwnerId); + MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); if(this->frameIndex.first == frameIndex) { this->frameIndex.second = true; } @@ -265,7 +271,7 @@ bool FactionThread::isSignalPathfinderCompleted(int frameIndex) { return true; } static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&triggerIdMutex,mutexOwnerId); + MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); //bool result = (event != NULL ? event->eventCompleted : true); bool result = (this->frameIndex.first == frameIndex && this->frameIndex.second == true); @@ -297,7 +303,7 @@ void FactionThread::execute() { } static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&triggerIdMutex,mutexOwnerId); + MutexSafeWrapper safeMutex(triggerIdMutex,mutexOwnerId); bool executeTask = (frameIndex.first >= 0); //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] frameIndex = %d this = %p executeTask = %d\n",__FILE__,__FUNCTION__,__LINE__,frameIndex.first, this, executeTask); @@ -309,7 +315,7 @@ void FactionThread::execute() { World *world = faction->getWorld(); - Config &config= Config::getInstance(); + //Config &config= Config::getInstance(); //bool sortedUnitsAllowed = config.getBool("AllowGroupedUnitCommands","true"); bool sortedUnitsAllowed = false; if(sortedUnitsAllowed) { @@ -375,6 +381,7 @@ Faction::Faction() { teamIndex=0; startLocationIndex=0; thisFaction=false; + currentSwitchTeamVoteFactionIndex = -1; } Faction::~Faction() { @@ -1574,7 +1581,7 @@ int Faction::getFrameCount() { const SwitchTeamVote * Faction::getFirstSwitchTeamVote() const { const SwitchTeamVote *vote = NULL; - if(switchTeamVotes.size() > 0) { + if(switchTeamVotes.empty() == false) { for(std::map::const_iterator iterMap = switchTeamVotes.begin(); iterMap != switchTeamVotes.end(); ++iterMap) { const SwitchTeamVote &curVote = iterMap->second; @@ -1657,6 +1664,64 @@ bool Faction::canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProdu return foundUnit; } +uint64 Faction::getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size) { + uint64 cache1Count = 0; + uint64 cache2Count = 0; + + //std::map cacheResourceTargetList; + for(std::map::iterator iterMap1 = cacheResourceTargetList.begin(); + iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { + cache1Count++; + } + //std::map cachedCloseResourceTargetLookupList; + for(std::map::iterator iterMap1 = cachedCloseResourceTargetLookupList.begin(); + iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { + cache2Count++; + } + + if(cache1Size) { + *cache1Size = cache1Count; + } + if(cache2Size) { + *cache2Size = cache2Count; + } + + uint64 totalBytes = cache1Count * sizeof(int); + totalBytes += cache2Count * sizeof(bool); + + totalBytes /= 1000; + + return totalBytes; +} + +string Faction::getCacheStats() { + string result = ""; + + int cache1Count = 0; + int cache2Count = 0; + + //std::map cacheResourceTargetList; + for(std::map::iterator iterMap1 = cacheResourceTargetList.begin(); + iterMap1 != cacheResourceTargetList.end(); ++iterMap1) { + cache1Count++; + } + //std::map cachedCloseResourceTargetLookupList; + for(std::map::iterator iterMap1 = cachedCloseResourceTargetLookupList.begin(); + iterMap1 != cachedCloseResourceTargetLookupList.end(); ++iterMap1) { + cache2Count++; + } + + uint64 totalBytes = cache1Count * sizeof(int); + totalBytes += cache2Count * sizeof(bool); + + totalBytes /= 1000; + + char szBuf[1024]=""; + sprintf(szBuf,"cache1Count [%d] cache2Count [%d] total KB: %s",cache1Count,cache2Count,formatNumber(totalBytes).c_str()); + result = szBuf; + return result; +} + std::string Faction::toString() const { std::string result = ""; diff --git a/source/glest_game/type_instances/faction.h b/source/glest_game/type_instances/faction.h index 4af5c966..cc64d653 100644 --- a/source/glest_game/type_instances/faction.h +++ b/source/glest_game/type_instances/faction.h @@ -66,7 +66,7 @@ protected: Faction *faction; Semaphore semTaskSignalled; - Mutex triggerIdMutex; + Mutex *triggerIdMutex; std::pair frameIndex; virtual void setQuitStatus(bool value); @@ -75,6 +75,7 @@ protected: public: FactionThread(Faction *faction); + virtual ~FactionThread(); virtual void execute(); void signalPathfinder(int frameIndex); bool isSignalPathfinderCompleted(int frameIndex); @@ -250,6 +251,9 @@ public: bool canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProduce, bool checkMorph) const; + string getCacheStats(); + uint64 getCacheKBytes(uint64 *cache1Size, uint64 *cache2Size); + std::string toString() const; private: diff --git a/source/glest_game/type_instances/unit.cpp b/source/glest_game/type_instances/unit.cpp index d76840de..891265d3 100644 --- a/source/glest_game/type_instances/unit.cpp +++ b/source/glest_game/type_instances/unit.cpp @@ -131,7 +131,10 @@ void UnitPathBasic::addToLastPathCache(const Vec2i &path) { } } - lastPathCacheQueue.push_back(path); + const bool tryLastPathCache = Config::getInstance().getBool("EnablePathfinderCache","false"); + if(tryLastPathCache == true) { + lastPathCacheQueue.push_back(path); + } } Vec2i UnitPathBasic::pop(bool removeFrontPos) { @@ -286,6 +289,7 @@ Unit::Unit(int id, UnitPathInterface *unitpath, const Vec2i &pos, const UnitType Unit::mapMemoryList[this]=true; #endif + mutexCommands = new Mutex(); changedActiveCommand = false; lastSynchDataString=""; modelFacing = CardinalDir::NORTH; @@ -339,6 +343,10 @@ Unit::Unit(int id, UnitPathInterface *unitpath, const Vec2i &pos, const UnitType showUnitParticles = config.getBool("UnitParticles","true"); maxQueuedCommandDisplayCount = config.getInt("MaxQueuedCommandDisplayCount","15"); + if(Renderer::getInstance().isMasterserverMode() == true) { + showUnitParticles = false; + } + lastPos= pos; progress= 0; lastAnimProgress= 0; @@ -405,7 +413,7 @@ Unit::~Unit() { //remove commands static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); changedActiveCommand = false; while(commands.empty() == false) { @@ -459,6 +467,9 @@ Unit::~Unit() { //MutexSafeWrapper safeMutex1(&mutexDeletedUnits,string(__FILE__) + "_" + intToStr(__LINE__)); //deletedUnits[this]=true; + delete mutexCommands; + mutexCommands=NULL; + #ifdef LEAK_CHECK_UNITS Unit::mapMemoryList.erase(this); #endif @@ -1100,7 +1111,7 @@ bool Unit::anyCommand(bool validateCommandtype) const { //return current command, assert that there is always one command Command *Unit::getCurrrentCommandThreadSafe() { static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); if(commands.empty() == false) { return commands.front(); @@ -1119,7 +1130,7 @@ Command *Unit::getCurrCommand() const { void Unit::replaceCurrCommand(Command *cmd) { static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); assert(commands.empty() == false); commands.front() = cmd; @@ -1191,7 +1202,7 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) { SystemFlags::OutputDebug(SystemFlags::debugUnitCommands,"In [%s::%s Line: %d] Deleting lower priority command [%s]\n",__FILE__,__FUNCTION__,__LINE__,(*i)->toString().c_str()); static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); deleteQueuedCommand(*i); i= commands.erase(i); @@ -1226,7 +1237,7 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) { // clearCommands(); // changedActiveCommand = willChangedActiveCommand; - bool willChangedActiveCommand= (commands.size() > 0); + bool willChangedActiveCommand= (commands.empty() == false); if(willChangedActiveCommand){ CommandClass currCommandClass=getCurrCommand()->getCommandType()->getClass(); CommandClass commandClass=command->getCommandType()->getClass(); @@ -1271,7 +1282,7 @@ CommandResult Unit::giveCommand(Command *command, bool tryQueue) { //push back command if(result == crSuccess) { static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); commands.push_back(command); @@ -1300,7 +1311,7 @@ CommandResult Unit::finishCommand() { //pop front static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); delete commands.front(); commands.erase(commands.begin()); @@ -1341,7 +1352,7 @@ CommandResult Unit::cancelCommand() { //delete ans pop command static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); delete commands.back(); commands.pop_back(); @@ -2590,7 +2601,7 @@ void Unit::clearCommands() { undoCommand(commands.back()); static string mutexOwnerId = string(__FILE__) + string("_") + intToStr(__LINE__); - MutexSafeWrapper safeMutex(&mutexCommands,mutexOwnerId); + MutexSafeWrapper safeMutex(mutexCommands,mutexOwnerId); delete commands.back(); commands.pop_back(); diff --git a/source/glest_game/type_instances/unit.h b/source/glest_game/type_instances/unit.h index 1caad09a..8da54448 100644 --- a/source/glest_game/type_instances/unit.h +++ b/source/glest_game/type_instances/unit.h @@ -404,7 +404,7 @@ private: std::vector currentAttackBoostEffects; - Mutex mutexCommands; + Mutex *mutexCommands; //static Mutex mutexDeletedUnits; //static std::map deletedUnits; diff --git a/source/glest_game/types/command_type.cpp b/source/glest_game/types/command_type.cpp index b31958c7..ae57f7f1 100644 --- a/source/glest_game/types/command_type.cpp +++ b/source/glest_game/types/command_type.cpp @@ -851,7 +851,7 @@ void SwitchTeamCommandType::load(int id, const XmlNode *n, const string &dir, string SwitchTeamCommandType::getDesc(const TotalUpgrade *totalUpgrade) const{ string str= name+"\n"; - Lang &lang= Lang::getInstance(); + //Lang &lang= Lang::getInstance(); //prod speed //str+= lang.get("MorphSpeed")+": "+ intToStr(morphSkillType->getSpeed())+"\n"; diff --git a/source/glest_game/types/damage_multiplier.h b/source/glest_game/types/damage_multiplier.h index 3e1e60e6..3b712f11 100644 --- a/source/glest_game/types/damage_multiplier.h +++ b/source/glest_game/types/damage_multiplier.h @@ -29,6 +29,9 @@ private: int id; public: + AttackType() { + id = -1; + } int getId() const {return id;} const string &getName() const {return name;} @@ -40,12 +43,15 @@ public: // class ArmorType // =============================== -class ArmorType{ +class ArmorType { private: string name; int id; public: + ArmorType() { + id = -1; + } int getId() const {return id;} const string &getName() const {return name;} diff --git a/source/glest_game/types/object_type.h b/source/glest_game/types/object_type.h index 1d490f93..8d05cfde 100644 --- a/source/glest_game/types/object_type.h +++ b/source/glest_game/types/object_type.h @@ -35,7 +35,7 @@ using Shared::Graphics::Vec3f; typedef vector ObjectParticleSystemTypes; typedef vector ObjectParticleVector; -class ObjectType{ +class ObjectType { private: typedef vector ModelTypes; private: @@ -51,6 +51,11 @@ private: int height; public: + ObjectType() { + objectClass = -1; + walkable = false; + height = 0; + } ~ObjectType(); void init(int modelCount, int objectClass, bool walkable, int height); diff --git a/source/glest_game/types/tileset_model_type.h b/source/glest_game/types/tileset_model_type.h index 347a5011..f25ffbb6 100644 --- a/source/glest_game/types/tileset_model_type.h +++ b/source/glest_game/types/tileset_model_type.h @@ -33,7 +33,7 @@ using Shared::Graphics::Vec3f; typedef vector ModelParticleSystemTypes; -class TilesetModelType{ +class TilesetModelType { private: Model *model; ModelParticleSystemTypes particleTypes; @@ -41,6 +41,11 @@ private: bool rotationAllowed; public: + TilesetModelType() { + model = NULL; + height = 0; + rotationAllowed = false; + } ~TilesetModelType(); void addParticleSystem(ObjectParticleSystemType *particleSystem); diff --git a/source/glest_game/types/unit_type.cpp b/source/glest_game/types/unit_type.cpp index 827d02e7..cca3b3a1 100644 --- a/source/glest_game/types/unit_type.cpp +++ b/source/glest_game/types/unit_type.cpp @@ -131,7 +131,7 @@ void UnitType::load(int id,const string &dir, const TechTree *techTree, this->id= id; try { - Lang &lang= Lang::getInstance(); + //Lang &lang= Lang::getInstance(); char szBuf[1024]=""; sprintf(szBuf,Lang::getInstance().get("LogScreenGameLoadingUnitType","",true).c_str(),formatString(name).c_str()); diff --git a/source/glest_game/types/unit_type.h b/source/glest_game/types/unit_type.h index 16ccf956..dfc2268c 100644 --- a/source/glest_game/types/unit_type.h +++ b/source/glest_game/types/unit_type.h @@ -46,6 +46,9 @@ private: int kills; public: + Level() { + kills = 0; + } void init(string name, int kills); const string &getName() const {return name;} diff --git a/source/glest_game/world/tileset.h b/source/glest_game/world/tileset.h index e99e2eb0..869bb02a 100644 --- a/source/glest_game/world/tileset.h +++ b/source/glest_game/world/tileset.h @@ -72,6 +72,17 @@ private: StaticSound nightStart; public: + AmbientSounds() { + enabledDay = false; + enabledNight = false; + enabledRain = false; + enabledSnow = false; + enabledDayStart = false; + enabledNightStart = false; + alwaysPlayDay = false; + alwaysPlayNight = false; + } + bool isEnabledDay() const {return enabledDay;} bool isEnabledNight() const {return enabledNight;} bool isEnabledRain() const {return enabledRain;} @@ -131,6 +142,13 @@ private: Checksum checksumValue; public: + Tileset() { + waterTex = NULL; + waterEffects = false; + fog = false; + fogMode = 0; + fogDensity = 0.0f; + } ~Tileset(); Checksum loadTileset(const vector pathList, const string &tilesetName, Checksum* checksum, std::map > > &loadedFileList); diff --git a/source/glest_game/world/time_flow.h b/source/glest_game/world/time_flow.h index dc2ef4ba..91d0d21f 100644 --- a/source/glest_game/world/time_flow.h +++ b/source/glest_game/world/time_flow.h @@ -29,7 +29,7 @@ using Shared::Sound::StaticSound; /// Raises time related events (day/night cycle) // ===================================================== -class TimeFlow{ +class TimeFlow { public: static const float dusk; static const float dawn; @@ -42,6 +42,13 @@ private: float timeInc; public: + TimeFlow() { + firstTime = false; + tileset = NULL; + time = 0.0f; + lastTime = 0.0f; + timeInc = 0.0f; + } void init(Tileset *tileset); float getTime() const {return time;} diff --git a/source/glest_game/world/unit_updater.cpp b/source/glest_game/world/unit_updater.cpp index f060653f..d6bab191 100644 --- a/source/glest_game/world/unit_updater.cpp +++ b/source/glest_game/world/unit_updater.cpp @@ -1277,7 +1277,7 @@ void UnitUpdater::updateHarvest(Unit *unit, int frameIndex) { if (r->decAmount(1)) { const ResourceType *rt = r->getType(); sc->deleteResource(); - unit->getFaction()->removeResourceTargetFromCache(unitTargetPos); + world->removeResourceTargetFromCache(unitTargetPos); switch(this->game->getGameSettings()->getPathFinderType()) { case pfBasic: @@ -2178,26 +2178,28 @@ bool UnitUpdater::findCachedCellsEnemies(Vec2i center, int range, int size, vect bool result = false; //return result; - MutexSafeWrapper safeMutex(&mutexUnitRangeCellsLookupItemCache,string(__FILE__) + "_" + intToStr(__LINE__)); - std::map > >::iterator iterFind = UnitRangeCellsLookupItemCache.find(center); + if(game->isMasterserverMode() == false) { + MutexSafeWrapper safeMutex(&mutexUnitRangeCellsLookupItemCache,string(__FILE__) + "_" + intToStr(__LINE__)); + std::map > >::iterator iterFind = UnitRangeCellsLookupItemCache.find(center); - if(iterFind != UnitRangeCellsLookupItemCache.end()) { - std::map >::iterator iterFind3 = iterFind->second.find(size); - if(iterFind3 != iterFind->second.end()) { - std::map::iterator iterFind4 = iterFind3->second.find(range); - if(iterFind4 != iterFind3->second.end()) { - result = true; + if(iterFind != UnitRangeCellsLookupItemCache.end()) { + std::map >::iterator iterFind3 = iterFind->second.find(size); + if(iterFind3 != iterFind->second.end()) { + std::map::iterator iterFind4 = iterFind3->second.find(range); + if(iterFind4 != iterFind3->second.end()) { + result = true; - std::vector &cellList = iterFind4->second.rangeCellList; - for(int idx = 0; idx < cellList.size(); ++idx) { - Cell *cell = cellList[idx]; + std::vector &cellList = iterFind4->second.rangeCellList; + for(int idx = 0; idx < cellList.size(); ++idx) { + Cell *cell = cellList[idx]; - findEnemiesForCell(ast,cell,unit,commandTarget,enemies); + findEnemiesForCell(ast,cell,unit,commandTarget,enemies); + } } } } + safeMutex.ReleaseLock(); } - safeMutex.ReleaseLock(); return result; } @@ -2299,7 +2301,7 @@ bool UnitUpdater::unitOnRange(const Unit *unit, int range, Unit **rangedPtr, } // Ok update our caches with the latest info - if(cacheItem.rangeCellList.size() > 0) { + if(cacheItem.rangeCellList.empty() == false) { MutexSafeWrapper safeMutex(&mutexUnitRangeCellsLookupItemCache,string(__FILE__) + "_" + intToStr(__LINE__)); //cacheItem.UnitRangeCellsLookupItemCacheTimerCountIndex = UnitRangeCellsLookupItemCacheTimerCount++; @@ -2483,7 +2485,7 @@ vector UnitUpdater::enemyUnitsOnRange(const Unit *unit,const AttackSkillT } // Ok update our caches with the latest info - if(cacheItem.rangeCellList.size() > 0) { + if(cacheItem.rangeCellList.empty() == false) { MutexSafeWrapper safeMutex(&mutexUnitRangeCellsLookupItemCache,string(__FILE__) + "_" + intToStr(__LINE__)); //cacheItem.UnitRangeCellsLookupItemCacheTimerCountIndex = UnitRangeCellsLookupItemCacheTimerCount++; @@ -2537,6 +2539,41 @@ vector UnitUpdater::findUnitsInRange(const Unit *unit, int radius) { return units; } +string UnitUpdater::getUnitRangeCellsLookupItemCacheStats() { + string result = ""; + + int posCount = 0; + int sizeCount = 0; + int rangeCount = 0; + int rangeCountCellCount = 0; + + Mutex mutexUnitRangeCellsLookupItemCache; + //std::map > > UnitRangeCellsLookupItemCache; + for(std::map > >::iterator iterMap1 = UnitRangeCellsLookupItemCache.begin(); + iterMap1 != UnitRangeCellsLookupItemCache.end(); ++iterMap1) { + posCount++; + + for(std::map >::iterator iterMap2 = iterMap1->second.begin(); + iterMap2 != iterMap1->second.end(); ++iterMap2) { + sizeCount++; + + for(std::map::iterator iterMap3 = iterMap2->second.begin(); + iterMap3 != iterMap2->second.end(); ++iterMap3) { + rangeCount++; + + rangeCountCellCount += iterMap3->second.rangeCellList.size(); + } + } + } + + uint64 totalBytes = rangeCountCellCount * sizeof(Cell *); + totalBytes /= 1000; + + char szBuf[1024]=""; + sprintf(szBuf,"pos [%d] size [%d] range [%d][%d] total KB: %s",posCount,sizeCount,rangeCount,rangeCountCellCount,formatNumber(totalBytes).c_str()); + result = szBuf; + return result; +} // ===================================================== // class ParticleDamager // ===================================================== diff --git a/source/glest_game/world/unit_updater.h b/source/glest_game/world/unit_updater.h index 5fe80950..4b5e9cfc 100644 --- a/source/glest_game/world/unit_updater.h +++ b/source/glest_game/world/unit_updater.h @@ -126,6 +126,8 @@ public: void findUnitsForCell(Cell *cell, const Unit *unit,vector &units); vector findUnitsInRange(const Unit *unit, int radius); + string getUnitRangeCellsLookupItemCacheStats(); + private: //attack void hit(Unit *attacker); diff --git a/source/glest_game/world/world.cpp b/source/glest_game/world/world.cpp index 25943011..43372661 100644 --- a/source/glest_game/world/world.cpp +++ b/source/glest_game/world/world.cpp @@ -325,7 +325,7 @@ Checksum World::loadScenario(const string &path, Checksum *checksum, bool resetC if(resetCurrentScenario == true) { scenario = Scenario(); - scriptManager->init(this, this->getGame()->getGameCamera()); + scriptManager->init(this, this->getGame()->getGameCameraPtr()); } scenarioChecksum = scenario.load(path); @@ -1436,7 +1436,8 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) { //bool cacheLookupSightResult = false; // cache lookup of previously calculated cells + sight range - if(MaxExploredCellsLookupItemCache > 0) { + if(MaxExploredCellsLookupItemCache > 0 && game->isMasterserverMode() == false) { + //if(MaxExploredCellsLookupItemCache > 0) { if(difftime(time(NULL),ExploredCellsLookupItem::lastDebug) >= 10) { ExploredCellsLookupItem::lastDebug = time(NULL); //printf("In [%s::%s Line: %d] ExploredCellsLookupItemCache.size() = %d\n",__FILE__,__FUNCTION__,__LINE__,ExploredCellsLookupItemCache.size()); @@ -1540,7 +1541,7 @@ void World::exploreCells(const Vec2i &newPos, int sightRange, int teamIndex) { // Ok update our caches with the latest info for this position, sight and team if(MaxExploredCellsLookupItemCache > 0) { - if(item.exploredCellList.size() > 0 || item.visibleCellList.size() > 0) { + if(item.exploredCellList.empty() == false || item.visibleCellList.empty() == false) { //ExploredCellsLookupItemCache.push_back(item); item.ExploredCellsLookupItemCacheTimerCountIndex = ExploredCellsLookupItemCacheTimerCount++; ExploredCellsLookupItemCache[newPos][sightRange] = item; @@ -1701,7 +1702,9 @@ void World::computeFow(int factionIdxToTick) { } //compute texture - if(fogOfWar) { + //printf("Masterserver = %d\n",game->isMasterserverMode()); + + if(fogOfWar == true && game->isMasterserverMode() == false) { for(int i=0; igetTeam() == thisTeamIndex) { @@ -1758,7 +1761,7 @@ void World::computeFow(int factionIdxToTick) { itemCache.alphaList.push_back(alpha); } - if(itemCache.surfPosList.size() > 0) { + if(itemCache.surfPosList.empty() == false) { FowAlphaCellsLookupItemCache[unit->getPos()][sightRange] = itemCache; } } @@ -1796,6 +1799,98 @@ int World::getNextCommandGroupId() { return ++nextCommandGroupId; } +void World::removeResourceTargetFromCache(const Vec2i &pos) { + for(int i= 0; i < factions.size(); ++i) { + factions[i]->removeResourceTargetFromCache(pos); + } +} + +string World::getExploredCellsLookupItemCacheStats() { + string result = ""; + + int posCount = 0; + int sightCount = 0; + int exploredCellCount = 0; + int visibleCellCount = 0; + + //std::map > ExploredCellsLookupItemCache; + for(std::map >::iterator iterMap1 = ExploredCellsLookupItemCache.begin(); + iterMap1 != ExploredCellsLookupItemCache.end(); ++iterMap1) { + posCount++; + + for(std::map::iterator iterMap2 = iterMap1->second.begin(); + iterMap2 != iterMap1->second.end(); ++iterMap2) { + sightCount++; + + exploredCellCount += iterMap2->second.exploredCellList.size(); + visibleCellCount += iterMap2->second.visibleCellList.size(); + } + } + + uint64 totalBytes = exploredCellCount * sizeof(SurfaceCell *); + totalBytes += visibleCellCount * sizeof(SurfaceCell *); + + totalBytes /= 1000; + + char szBuf[1024]=""; + sprintf(szBuf,"pos [%d] sight [%d] [%d][%d] total KB: %s",posCount,sightCount,exploredCellCount,visibleCellCount,formatNumber(totalBytes).c_str()); + result = szBuf; + return result; +} + +string World::getFowAlphaCellsLookupItemCacheStats() { + string result = ""; + + int posCount = 0; + int sightCount = 0; + int surfPosCount = 0; + int alphaListCount = 0; + + //std::map > FowAlphaCellsLookupItemCache; + for(std::map >::iterator iterMap1 = FowAlphaCellsLookupItemCache.begin(); + iterMap1 != FowAlphaCellsLookupItemCache.end(); ++iterMap1) { + posCount++; + + for(std::map::iterator iterMap2 = iterMap1->second.begin(); + iterMap2 != iterMap1->second.end(); ++iterMap2) { + sightCount++; + + surfPosCount += iterMap2->second.surfPosList.size(); + alphaListCount += iterMap2->second.alphaList.size(); + } + } + + uint64 totalBytes = surfPosCount * sizeof(Vec2i); + totalBytes += alphaListCount * sizeof(float); + + totalBytes /= 1000; + + char szBuf[1024]=""; + sprintf(szBuf,"pos [%d] sight [%d] [%d][%d] total KB: %s",posCount,sightCount,surfPosCount,alphaListCount,formatNumber(totalBytes).c_str()); + result = szBuf; + return result; +} + +string World::getAllFactionsCacheStats() { + string result = ""; + + uint64 totalBytes = 0; + uint64 totalCache1Size = 0; + uint64 totalCache2Size = 0; + for(int i = 0; i < getFactionCount(); ++i) { + uint64 cache1Size = 0; + uint64 cache2Size = 0; + totalBytes += getFaction(i)->getCacheKBytes(&cache1Size, &cache2Size); + totalCache1Size += cache1Size; + totalCache2Size += cache2Size; + } + + char szBuf[1024]=""; + sprintf(szBuf,"totalCache1Size [%lu] totalCache1Size [%lu] total KB: %s",totalCache1Size,totalCache2Size,formatNumber(totalBytes).c_str()); + result = szBuf; + return result; +} + std::string World::DumpWorldToLog(bool consoleBasicInfoOnly) const { string debugWorldLogFile = Config::getInstance().getString("DebugWorldLogFile","debugWorld.log"); diff --git a/source/glest_game/world/world.h b/source/glest_game/world/world.h index 2a83afe1..d9b17716 100644 --- a/source/glest_game/world/world.h +++ b/source/glest_game/world/world.h @@ -82,7 +82,7 @@ public: static time_t lastDebug; }; -class World{ +class World { private: typedef vector Factions; @@ -258,6 +258,12 @@ public: UnitUpdater * getUnitUpdater() { return &unitUpdater; } + void removeResourceTargetFromCache(const Vec2i &pos); + + string getExploredCellsLookupItemCacheStats(); + string getFowAlphaCellsLookupItemCacheStats(); + string getAllFactionsCacheStats(); + private: void initCells(bool fogOfWar); diff --git a/source/shared_lib/include/platform/posix/socket.h b/source/shared_lib/include/platform/posix/socket.h index 8e164ac5..de41b0f6 100644 --- a/source/shared_lib/include/platform/posix/socket.h +++ b/source/shared_lib/include/platform/posix/socket.h @@ -120,10 +120,10 @@ protected: time_t lastThreadedPing; //Mutex pingThreadAccessor; - Mutex dataSynchAccessorRead; - Mutex dataSynchAccessorWrite; + Mutex *dataSynchAccessorRead; + Mutex *dataSynchAccessorWrite; - Mutex inSocketDestructorSynchAccessor; + Mutex *inSocketDestructorSynchAccessor; bool inSocketDestructor; public: @@ -214,7 +214,7 @@ protected: class BroadCastSocketThread : public BaseThread { private: - Mutex mutexPauseBroadcast; + Mutex *mutexPauseBroadcast; bool pauseBroadcast; public: diff --git a/source/shared_lib/include/util/conversion.h b/source/shared_lib/include/util/conversion.h index 2c430b16..f0b62264 100644 --- a/source/shared_lib/include/util/conversion.h +++ b/source/shared_lib/include/util/conversion.h @@ -38,6 +38,8 @@ string doubleToStr(double f,int precsion=2); bool IsNumeric(const char *p, bool allowNegative=true); +string formatNumber(uint64 f); + }}//end namespace #endif diff --git a/source/shared_lib/sources/feathery_ftp/ftpAccount.c b/source/shared_lib/sources/feathery_ftp/ftpAccount.c index c388e6eb..cabe03ac 100644 --- a/source/shared_lib/sources/feathery_ftp/ftpAccount.c +++ b/source/shared_lib/sources/feathery_ftp/ftpAccount.c @@ -119,13 +119,14 @@ int ftpCreateAccount(const char* name, const char* passw, const char* root, int */ int ftpFindAccount(const char* name) { - int n; - - if(name[0] != '\0') - for(n = 0; n < MAX_USERS; n++) - if(!strncmp(ftpUsers[n].name, name, MAXLEN_USERNAME)) + if(name[0] != '\0') { + int n; + for(n = 0; n < MAX_USERS; n++) { + if(!strncmp(ftpUsers[n].name, name, MAXLEN_USERNAME)) { return n + 1; - + } + } + } return 0; } diff --git a/source/shared_lib/sources/feathery_ftp/ftpCmds.c b/source/shared_lib/sources/feathery_ftp/ftpCmds.c index e6637779..687aa3b9 100644 --- a/source/shared_lib/sources/feathery_ftp/ftpCmds.c +++ b/source/shared_lib/sources/feathery_ftp/ftpCmds.c @@ -276,7 +276,6 @@ LOCAL int ftpCmdAbor(int sessionId, const char* args, int len) #define MLSD 8 LOCAL int sendListing(socket_t dataSocket, int sessionId, const char* path, int format) { - int haveAnySuccessfulFiles = 0; void *dir; const char monName[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", @@ -286,11 +285,12 @@ LOCAL int sendListing(socket_t dataSocket, int sessionId, const char* path, int dir = ftpOpenDir(path); if(dir) { - const char* dirEntry; - int len; + const char* dirEntry = NULL; + int len = 0; int err = 0; ftpTime_S currTime = {0}; ftpPathInfo_S fileInfo; + int haveAnySuccessfulFiles = 0; ftpGetLocalTime(&currTime); ftpSendMsg(MSG_NORMAL, sessionId, 150, ftpMsg010); @@ -1023,7 +1023,6 @@ void ftpParseCmd(int sessionId) { ftpSession_S *pSession; int len; - int c; socket_t ctrlSocket; pSession = ftpGetSession(sessionId); @@ -1033,6 +1032,7 @@ void ftpParseCmd(int sessionId) if((pSession->rxBuf[len - 1] == '\n') && (pSession->rxBuf[len - 2] == '\r') ) // command correctly terminated? { + int c = 0; pSession->rxBuf[len - 2] = '\0'; pSession->rxBufWriteIdx = 0; diff --git a/source/shared_lib/sources/feathery_ftp/ftpTargetWin32.c b/source/shared_lib/sources/feathery_ftp/ftpTargetWin32.c index da037271..211540fb 100644 --- a/source/shared_lib/sources/feathery_ftp/ftpTargetWin32.c +++ b/source/shared_lib/sources/feathery_ftp/ftpTargetWin32.c @@ -548,8 +548,8 @@ int getLastSocketError() { const char * getLastSocketErrorText(int *errNumber) { int errId = (errNumber != NULL ? *errNumber : getLastSocketError()); - //return WSAGetLastErrorMessage("",errId); - return "?"; + return WSAGetLastErrorMessage("",errId); + //return "?"; } #endif diff --git a/source/shared_lib/sources/graphics/gl/font_text_freetypegl.cpp b/source/shared_lib/sources/graphics/gl/font_text_freetypegl.cpp index 70d8711e..06e397c7 100644 --- a/source/shared_lib/sources/graphics/gl/font_text_freetypegl.cpp +++ b/source/shared_lib/sources/graphics/gl/font_text_freetypegl.cpp @@ -68,7 +68,8 @@ void TextFreetypeGL::init(string fontName, int fontSize) { this->font = texture_font_new( atlas, fontFile, (float)fontFaceSize ); //font = texture_font_new( atlas, font_manager_match_description( 0, "Verdana", minsize, bold, italic ), minsize ); - int missed = texture_font_cache_glyphs( font, cache ); + //int missed = texture_font_cache_glyphs( font, cache ); + texture_font_cache_glyphs( font, cache ); free((void*)this->fontFile); this->fontFile = NULL; @@ -113,7 +114,7 @@ void TextFreetypeGL::Render(const char* str, const int len) { for(int i = 0; (len < 0 && *ustr) || (len >= 0 && i < len); i++) { unsigned int prevChar = (i > 0 ? *ustr-1 : 0); unsigned int thisChar = *ustr++; - unsigned int nextChar = *ustr; + //unsigned int nextChar = *ustr; // Get glyph (build it if needed TextureGlyph *glyph = texture_font_get_glyph( this->font, thisChar ); diff --git a/source/shared_lib/sources/graphics/md5/Md5Model.cpp b/source/shared_lib/sources/graphics/md5/Md5Model.cpp index 76d360dc..3bb99ebd 100644 --- a/source/shared_lib/sources/graphics/md5/Md5Model.cpp +++ b/source/shared_lib/sources/graphics/md5/Md5Model.cpp @@ -1037,7 +1037,7 @@ Md5Model::Md5Model (const string &filename) while (!ifs.eof ()) { string token, buffer; - int version; + int version = 0; // Read next token ifs >> token; @@ -1377,8 +1377,8 @@ Md5Animation::Md5Animation (const string &filename) while (!ifs.eof ()) { string token, buffer; - int version; - int i; + int version = 0;; + int i = 0; // Read next token ifs >> token; diff --git a/source/shared_lib/sources/map/map_preview.cpp b/source/shared_lib/sources/map/map_preview.cpp index bb2c7851..f2169d99 100644 --- a/source/shared_lib/sources/map/map_preview.cpp +++ b/source/shared_lib/sources/map/map_preview.cpp @@ -717,7 +717,7 @@ void MapPreview::loadFromFile(const string &path) { #else FILE *f1 = fopen(path.c_str(), "rb"); #endif - int fileErrno = errno; + //int fileErrno = errno; if (f1 != NULL) { //read header diff --git a/source/shared_lib/sources/platform/common/simple_threads.cpp b/source/shared_lib/sources/platform/common/simple_threads.cpp index a9fd23da..f4e9e42b 100644 --- a/source/shared_lib/sources/platform/common/simple_threads.cpp +++ b/source/shared_lib/sources/platform/common/simple_threads.cpp @@ -202,12 +202,12 @@ void FileCRCPreCacheThread::execute() { string &techPath = techDataPaths[idx]; endPathWithSlash(techPath); findAll(techPath + techName + "/factions/*.", results, false, false); - if(results.size() > 0) { + if(results.empty() == false) { break; } } - if(results.size() == 0) { + if(results.empty() == true) { for(unsigned int factionIdx = 0; factionIdx < results.size(); ++factionIdx) { string factionName = results[factionIdx]; int32 factionCRC = 0; diff --git a/source/shared_lib/sources/platform/miniupnpc/miniwget.c b/source/shared_lib/sources/platform/miniupnpc/miniwget.c index 87f61556..f84f5f95 100644 --- a/source/shared_lib/sources/platform/miniupnpc/miniwget.c +++ b/source/shared_lib/sources/platform/miniupnpc/miniwget.c @@ -76,6 +76,7 @@ getHTTPResponse(int s, int * size) int chunksize_buf_index; header_buf = malloc(header_buf_len); + header_buf[0] = '\0'; content_buf = malloc(content_buf_len); chunksize_buf[0] = '\0'; chunksize_buf_index = 0; diff --git a/source/shared_lib/sources/platform/posix/socket.cpp b/source/shared_lib/sources/platform/posix/socket.cpp index a80030ae..6a5a02da 100644 --- a/source/shared_lib/sources/platform/posix/socket.cpp +++ b/source/shared_lib/sources/platform/posix/socket.cpp @@ -785,15 +785,19 @@ bool Socket::isSocketValid(const PLATFORM_SOCKET *validateSocket) { } Socket::Socket(PLATFORM_SOCKET sock) { - MutexSafeWrapper safeMutexSocketDestructorFlag(&inSocketDestructorSynchAccessor,CODE_AT_LINE); - inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); + dataSynchAccessorRead = new Mutex(); + dataSynchAccessorWrite = new Mutex(); + inSocketDestructorSynchAccessor = new Mutex(); + + MutexSafeWrapper safeMutexSocketDestructorFlag(inSocketDestructorSynchAccessor,CODE_AT_LINE); + inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); this->inSocketDestructor = false; //safeMutexSocketDestructorFlag.ReleaseLock(); //this->pingThread = NULL; //pingThreadAccessor.setOwnerId(CODE_AT_LINE); - dataSynchAccessorRead.setOwnerId(CODE_AT_LINE); - dataSynchAccessorWrite.setOwnerId(CODE_AT_LINE); + dataSynchAccessorRead->setOwnerId(CODE_AT_LINE); + dataSynchAccessorWrite->setOwnerId(CODE_AT_LINE); @@ -802,8 +806,12 @@ Socket::Socket(PLATFORM_SOCKET sock) { } Socket::Socket() { - MutexSafeWrapper safeMutexSocketDestructorFlag(&inSocketDestructorSynchAccessor,CODE_AT_LINE); - inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); + dataSynchAccessorRead = new Mutex(); + dataSynchAccessorWrite = new Mutex(); + inSocketDestructorSynchAccessor = new Mutex(); + + MutexSafeWrapper safeMutexSocketDestructorFlag(inSocketDestructorSynchAccessor,CODE_AT_LINE); + inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); this->inSocketDestructor = false; //safeMutexSocketDestructorFlag.ReleaseLock(); @@ -906,12 +914,12 @@ void Socket::simpleTask(BaseThread *callingThread) { */ Socket::~Socket() { - MutexSafeWrapper safeMutexSocketDestructorFlag(&inSocketDestructorSynchAccessor,CODE_AT_LINE); + MutexSafeWrapper safeMutexSocketDestructorFlag(inSocketDestructorSynchAccessor,CODE_AT_LINE); if(this->inSocketDestructor == true) { SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); return; } - inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); + inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); this->inSocketDestructor = true; if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] START closing socket = %d...\n",__FILE__,__FUNCTION__,sock); @@ -922,9 +930,10 @@ Socket::~Socket() { // Allow other callers with a lock on the mutexes to let them go for(time_t elapsed = time(NULL); - (dataSynchAccessorRead.getRefCount() > 0 || - dataSynchAccessorWrite.getRefCount() > 0) && - difftime(time(NULL),elapsed) <= 5;) { + (dataSynchAccessorRead->getRefCount() > 0 || + dataSynchAccessorWrite->getRefCount() > 0) && + difftime(time(NULL),elapsed) <= 2;) { + printf("Waiting in socket destructor\n"); //sleep(0); } @@ -933,6 +942,13 @@ Socket::~Socket() { //delete pingThread; //pingThread = NULL; safeMutexSocketDestructorFlag.ReleaseLock(); + + delete dataSynchAccessorRead; + dataSynchAccessorRead = NULL; + delete dataSynchAccessorWrite; + dataSynchAccessorWrite = NULL; + delete inSocketDestructorSynchAccessor; + inSocketDestructorSynchAccessor = NULL; } void Socket::disconnectSocket() { @@ -941,8 +957,8 @@ void Socket::disconnectSocket() { if(isSocketValid() == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] calling shutdown and close for socket = %d...\n",__FILE__,__FUNCTION__,sock); - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); - MutexSafeWrapper safeMutex1(&dataSynchAccessorWrite,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex1(dataSynchAccessorWrite,CODE_AT_LINE); ::shutdown(sock,2); #ifndef WIN32 ::close(sock); @@ -1180,10 +1196,10 @@ int Socket::send(const void *data, int dataSize) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); - MutexSafeWrapper safeMutex(&dataSynchAccessorWrite,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorWrite,CODE_AT_LINE); #ifdef __APPLE__ bytesSent = ::send(sock, (const char *)data, dataSize, SO_NOSIGPIPE); @@ -1218,10 +1234,10 @@ int Socket::send(const void *data, int dataSize) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); - MutexSafeWrapper safeMutex(&dataSynchAccessorWrite,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorWrite,CODE_AT_LINE); #ifdef __APPLE__ bytesSent = ::send(sock, (const char *)data, dataSize, SO_NOSIGPIPE); #else @@ -1267,10 +1283,10 @@ int Socket::send(const void *data, int dataSize) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); - MutexSafeWrapper safeMutex(&dataSynchAccessorWrite,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorWrite,CODE_AT_LINE); const char *sendBuf = (const char *)data; #ifdef __APPLE__ bytesSent = ::send(sock, &sendBuf[totalBytesSent], dataSize - totalBytesSent, SO_NOSIGPIPE); @@ -1332,10 +1348,10 @@ int Socket::receive(void *data, int dataSize, bool tryReceiveUntilDataSizeMet) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); bytesReceived = recv(sock, reinterpret_cast(data), dataSize, 0); safeMutex.ReleaseLock(); } @@ -1361,10 +1377,10 @@ int Socket::receive(void *data, int dataSize, bool tryReceiveUntilDataSizeMet) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); bytesReceived = recv(sock, reinterpret_cast(data), dataSize, 0); safeMutex.ReleaseLock(); @@ -1410,7 +1426,7 @@ int Socket::peek(void *data, int dataSize,bool mustGetData) { const int MAX_PEEK_WAIT_SECONDS = 3; - ssize_t err = 0; + int err = 0; if(isSocketValid() == true) { //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); @@ -1419,17 +1435,19 @@ int Socket::peek(void *data, int dataSize,bool mustGetData) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); //MutexSafeWrapper safeMutex(&dataSynchAccessor,CODE_AT_LINE + "_" + intToStr(sock) + "_" + intToStr(dataSize)); - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); err = recv(sock, reinterpret_cast(data), dataSize, MSG_PEEK); safeMutex.ReleaseLock(); + //printf("Peek #1 err = %d\n",err); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) if(chrono.getMillis() > 1) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); } //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); @@ -1441,6 +1459,8 @@ int Socket::peek(void *data, int dataSize,bool mustGetData) { else if(err < 0 && getLastSocketError() == PLATFORM_SOCKET_TRY_AGAIN && mustGetData == true) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] #1 ERROR EAGAIN during peek, trying again...\n",__FILE__,__FUNCTION__,__LINE__); + //printf("Peek #2 err = %d\n",err); + time_t tStartTimer = time(NULL); while((err < 0 && getLastSocketError() == PLATFORM_SOCKET_TRY_AGAIN) && (difftime(time(NULL),tStartTimer) <= MAX_PEEK_WAIT_SECONDS)) { @@ -1458,11 +1478,11 @@ int Socket::peek(void *data, int dataSize,bool mustGetData) { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return -1; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); // safeMutexSocketDestructorFlag.ReleaseLock(); //MutexSafeWrapper safeMutex(&dataSynchAccessor,CODE_AT_LINE + "_" + intToStr(sock) + "_" + intToStr(dataSize)); - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); err = recv(sock, reinterpret_cast(data), dataSize, MSG_PEEK); safeMutex.ReleaseLock(); @@ -1477,6 +1497,7 @@ int Socket::peek(void *data, int dataSize,bool mustGetData) { //if(chrono.getMillis() > 1) printf("In [%s::%s Line: %d] action running for msecs: %lld\n",__FILE__,__FUNCTION__,__LINE__,(long long int)chrono.getMillis()); if(err <= 0) { + //printf("Peek #3 err = %d\n",err); if(mustGetData == true || getLastSocketError() != PLATFORM_SOCKET_TRY_AGAIN) { int iErr = getLastSocketError(); disconnectSocket(); @@ -1537,7 +1558,7 @@ bool Socket::isReadable() { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return false; //} - //inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); + //inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); //safeMutexSocketDestructorFlag.ReleaseLock(); //MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); @@ -1574,7 +1595,7 @@ bool Socket::isWritable() { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return false; //} - //inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); + //inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); //safeMutexSocketDestructorFlag.ReleaseLock(); //MutexSafeWrapper safeMutex(&dataSynchAccessorWrite,CODE_AT_LINE); @@ -1607,7 +1628,7 @@ bool Socket::isConnected() { // SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] this->inSocketDestructor == true\n",__FILE__,__FUNCTION__,__LINE__); // return false; // } -// inSocketDestructorSynchAccessor.setOwnerId(CODE_AT_LINE); +// inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); //if the socket is not writable then it is not conencted if(isWritable() == false) { @@ -1618,9 +1639,10 @@ bool Socket::isConnected() { if(isReadable()) { char tmp=0; int err = peek(&tmp, 1, false); - if(err <= 0 && err != PLATFORM_SOCKET_TRY_AGAIN) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"[%s::%s Line: %d] ERROR Peek failed, err = %d, error = %s\n",__FILE__,__FUNCTION__,__LINE__,err,getLastSocketErrorFormattedText().c_str()); - if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugError,"SOCKET DISCONNECTED In [%s::%s Line: %d] ERROR Peek failed, err = %d, error = %s\n",__FILE__,__FUNCTION__,__LINE__,err,getLastSocketErrorFormattedText().c_str()); + //if(err <= 0 && err != PLATFORM_SOCKET_TRY_AGAIN) { + if(err <= 0) { + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"[%s::%s Line: %d] ERROR Peek failed, err = %d for socket: %d, error = %s\n",__FILE__,__FUNCTION__,__LINE__,err,sock,getLastSocketErrorFormattedText().c_str()); + if(SystemFlags::VERBOSE_MODE_ENABLED) SystemFlags::OutputDebug(SystemFlags::debugError,"SOCKET DISCONNECTED In [%s::%s Line: %d] ERROR Peek failed, err = %d for socket: %d, error = %s\n",__FILE__,__FUNCTION__,__LINE__,err,sock,getLastSocketErrorFormattedText().c_str()); return false; } } @@ -1757,7 +1779,7 @@ void ClientSocket::connect(const Ip &ip, int port) FD_SET(sock, &myset); { - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); err = select((int)sock + 1, NULL, &myset, NULL, &tv); //safeMutex.ReleaseLock(); } @@ -2175,7 +2197,7 @@ Socket *ServerSocket::accept() { struct sockaddr_in cli_addr; socklen_t clilen = sizeof(cli_addr); char client_host[100]=""; - MutexSafeWrapper safeMutex(&dataSynchAccessorRead,CODE_AT_LINE); + MutexSafeWrapper safeMutex(dataSynchAccessorRead,CODE_AT_LINE); PLATFORM_SOCKET newSock= ::accept(sock, (struct sockaddr *) &cli_addr, &clilen); safeMutex.ReleaseLock(); @@ -2549,23 +2571,27 @@ void UPNP_Tools::NETremRedirects(int ext_port) { // BroadCastSocketThread::BroadCastSocketThread() : BaseThread() { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + mutexPauseBroadcast = new Mutex(); setPauseBroadcast(false); //printf("new broadcast thread [%p]\n",this); } BroadCastSocketThread::~BroadCastSocketThread() { //printf("delete broadcast thread [%p]\n",this); + + delete mutexPauseBroadcast; + mutexPauseBroadcast = NULL; } bool BroadCastSocketThread::getPauseBroadcast() { - MutexSafeWrapper safeMutexSocketDestructorFlag(&mutexPauseBroadcast,CODE_AT_LINE); - mutexPauseBroadcast.setOwnerId(CODE_AT_LINE); + MutexSafeWrapper safeMutexSocketDestructorFlag(mutexPauseBroadcast,CODE_AT_LINE); + mutexPauseBroadcast->setOwnerId(CODE_AT_LINE); return pauseBroadcast; } void BroadCastSocketThread::setPauseBroadcast(bool value) { - MutexSafeWrapper safeMutexSocketDestructorFlag(&mutexPauseBroadcast,CODE_AT_LINE); - mutexPauseBroadcast.setOwnerId(CODE_AT_LINE); + MutexSafeWrapper safeMutexSocketDestructorFlag(mutexPauseBroadcast,CODE_AT_LINE); + mutexPauseBroadcast->setOwnerId(CODE_AT_LINE); pauseBroadcast = value; } @@ -2592,7 +2618,7 @@ void BroadCastSocketThread::execute() { short port=0; // The port for the broadcast. struct sockaddr_in bcLocal[MAX_NIC_COUNT]; // local socket address for the broadcast. PLATFORM_SOCKET bcfd[MAX_NIC_COUNT]; // The socket used for the broadcast. - bool one = true; // Parameter for "setscokopt". + int one = 1; // Parameter for "setscokopt". int pn=0; // The number of the packet broadcasted. const int buffMaxSize=1024; char buff[buffMaxSize]=""; // Buffers the data to be broadcasted. diff --git a/source/shared_lib/sources/platform/sdl/thread.cpp b/source/shared_lib/sources/platform/sdl/thread.cpp index 64b97cdf..c2ff4bdb 100644 --- a/source/shared_lib/sources/platform/sdl/thread.cpp +++ b/source/shared_lib/sources/platform/sdl/thread.cpp @@ -94,29 +94,38 @@ void Thread::resume() { class SDLMutexSafeWrapper { protected: - SDL_mutex *mutex; + SDL_mutex **mutex; + bool destroyMutexInDestructor; public: - SDLMutexSafeWrapper(SDL_mutex *mutex) { + SDLMutexSafeWrapper(SDL_mutex **mutex, bool destroyMutexInDestructor=false) { this->mutex = mutex; + this->destroyMutexInDestructor = destroyMutexInDestructor; Lock(); } ~SDLMutexSafeWrapper() { - ReleaseLock(); + bool keepMutex = (this->destroyMutexInDestructor == true && mutex != NULL && *mutex != NULL); + ReleaseLock(keepMutex); + + if(this->destroyMutexInDestructor == true && mutex != NULL && *mutex != NULL) { + SDL_DestroyMutex(*mutex); + *mutex = NULL; + mutex = NULL; + } } void Lock() { - if(this->mutex != NULL) { - SDL_mutexP(this->mutex); + if(mutex != NULL && *mutex != NULL) { + SDL_mutexP(*mutex); } } void ReleaseLock(bool keepMutex=false) { - if(this->mutex != NULL) { - SDL_mutexV(this->mutex); + if(mutex != NULL && *mutex != NULL) { + SDL_mutexV(*mutex); if(keepMutex == false) { - this->mutex = NULL; + mutex = NULL; } } } @@ -124,7 +133,7 @@ public: Mutex::Mutex(string ownerId) { mutexAccessor = SDL_CreateMutex(); - SDLMutexSafeWrapper safeMutex(mutexAccessor); + SDLMutexSafeWrapper safeMutex(&mutexAccessor); refCount=0; this->ownerId = ownerId; mutex = SDL_CreateMutex(); @@ -138,7 +147,7 @@ Mutex::Mutex(string ownerId) { } Mutex::~Mutex() { - SDLMutexSafeWrapper safeMutex(mutexAccessor); + SDLMutexSafeWrapper safeMutex(&mutexAccessor,true); if(mutex == NULL) { char szBuf[1024]=""; snprintf(szBuf,1023,"In [%s::%s Line: %d] mutex == NULL refCount = %d owner [%s] deleteownerId [%s]",__FILE__,__FUNCTION__,__LINE__,refCount,ownerId.c_str(),deleteownerId.c_str()); diff --git a/source/shared_lib/sources/util/conversion.cpp b/source/shared_lib/sources/util/conversion.cpp index c565e185..181ae2f4 100644 --- a/source/shared_lib/sources/util/conversion.cpp +++ b/source/shared_lib/sources/util/conversion.cpp @@ -15,6 +15,9 @@ #include #include #include "platform_common.h" +#include +#include +#include #include "leak_dumper.h" using namespace std; @@ -145,4 +148,21 @@ bool IsNumeric(const char *p, bool allowNegative) { return true; } +class Comma: public numpunct// own facet class +{ + protected: + char do_thousands_sep() const { return ','; }// use the comma + string do_grouping() const { return "\3"; }//group 3 digits +}; +string formatNumber(uint64 f) { + + locale myloc( locale(), // C++ default locale + new Comma);// Own numeric facet + + ostringstream out; + out.imbue(myloc); + out << f; + return out.str(); +} + }}//end namespace