From b9d6b38e8f90e2d4a9f626b3c2085f27f0731217 Mon Sep 17 00:00:00 2001 From: SoftCoder Date: Fri, 13 Dec 2013 23:04:12 -0800 Subject: [PATCH] - coverity based bug fixes - round #1 --- source/glest_game/ai/ai.cpp | 9 +- source/glest_game/ai/ai_rule.cpp | 29 +- source/glest_game/ai/path_finder.cpp | 4 +- source/glest_game/game/game.cpp | 16 +- source/glest_game/game/script_manager.cpp | 3 + source/glest_game/global/core_data.cpp | 2 +- source/glest_game/global/lang.cpp | 8 +- source/glest_game/graphics/renderer.cpp | 424 +++++++++--------- source/glest_game/main/main.cpp | 7 +- source/glest_game/menu/menu_background.cpp | 2 +- .../menu/menu_state_connected_game.cpp | 6 +- .../menu/menu_state_custom_game.cpp | 10 +- .../menu/menu_state_masterserver.cpp | 1 + .../menu/menu_state_options_graphics.cpp | 4 +- .../glest_game/network/client_interface.cpp | 32 +- source/glest_game/network/network_manager.cpp | 1 - source/glest_game/network/network_message.cpp | 89 +++- source/glest_game/network/network_message.h | 4 +- .../glest_game/network/network_protocol.cpp | 2 +- source/glest_game/network/network_types.cpp | 4 +- .../glest_game/network/server_interface.cpp | 31 +- source/glest_game/type_instances/faction.cpp | 61 ++- source/glest_game/type_instances/faction.h | 3 + source/glest_game/type_instances/object.cpp | 3 + source/glest_game/type_instances/unit.cpp | 3 + source/glest_game/types/faction_type.cpp | 24 +- source/glest_game/types/unit_type.cpp | 12 +- source/glest_game/types/upgrade_type.cpp | 2 + source/glest_game/world/map.cpp | 9 +- source/glest_game/world/minimap.cpp | 3 +- source/glest_game/world/unit_updater.cpp | 5 +- .../include/graphics/gl/text_renderer_gl.h | 14 +- source/shared_lib/include/graphics/model.h | 1 - source/shared_lib/include/util/gen_uuid.h | 2 +- .../sources/compression/compression_utils.cpp | 3 + .../sources/feathery_ftp/ftpTargetPosix.c | 7 +- source/shared_lib/sources/graphics/font.cpp | 5 +- .../sources/graphics/gl/font_textFTGL.cpp | 7 +- source/shared_lib/sources/graphics/model.cpp | 31 +- .../shared_lib/sources/graphics/particle.cpp | 1 + source/shared_lib/sources/graphics/pixmap.cpp | 6 +- .../shared_lib/sources/graphics/texture.cpp | 3 +- source/shared_lib/sources/miniz/miniz.c | 10 +- .../platform/common/platform_common.cpp | 6 +- .../sources/platform/posix/miniftpclient.cpp | 2 +- .../sources/platform/posix/socket.cpp | 40 +- .../sources/platform/sdl/platform_util.cpp | 41 +- .../sources/platform/sdl/thread.cpp | 5 +- .../sound/openal/sound_player_openal.cpp | 1 + source/shared_lib/sources/sound/sound.cpp | 10 +- source/shared_lib/sources/util/properties.cpp | 10 +- source/shared_lib/sources/util/util.cpp | 29 +- .../tests/shared_lib/xml/xml_parser_test.cpp | 20 +- 53 files changed, 651 insertions(+), 416 deletions(-) diff --git a/source/glest_game/ai/ai.cpp b/source/glest_game/ai/ai.cpp index b7325a0d0..1d35d37e8 100644 --- a/source/glest_game/ai/ai.cpp +++ b/source/glest_game/ai/ai.cpp @@ -788,8 +788,9 @@ void Ai::sendScoutPatrol(){ std::vector warningEnemyList = aiInterface->getEnemyWarningPositionList(); if( (possibleTargetFound == false) && (warningEnemyList.empty() == false)) { - for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) { - Vec2i &checkPos = warningEnemyList[i]; + //for(int i = (int)warningEnemyList.size() - 1; i <= 0; --i) { + //Vec2i &checkPos = warningEnemyList[i]; + Vec2i &checkPos = warningEnemyList[0]; if (random.randRange(0, 1) == 1 ) { pos = checkPos; possibleTargetFound = true; @@ -797,8 +798,8 @@ void Ai::sendScoutPatrol(){ } else { aiInterface->removeEnemyWarningPositionFromList(checkPos); } - break; - } + //break; + //} } if(possibleTargetFound == false){ diff --git a/source/glest_game/ai/ai_rule.cpp b/source/glest_game/ai/ai_rule.cpp index 0095086f1..4894c8f83 100644 --- a/source/glest_game/ai/ai_rule.cpp +++ b/source/glest_game/ai/ai_rule.cpp @@ -592,24 +592,30 @@ bool AiRuleProduceResourceProducer::test(){ if(factionUsesResourceType == true && rt->getClass() == rcConsumable) { // The consumable balance is negative if(r->getBalance() < 0) { - if(newResourceBehaviour==true) + if(newResourceBehaviour == true) { interval = shortInterval; - else + } + else { interval = longInterval; + } + return true; } // If the consumable balance is down to 1/3 of what we need else { if(r->getBalance() * 3 + r->getAmount() < 0) { - if(newResourceBehaviour==true) - interval = shortInterval; - else - interval = longInterval; + if(newResourceBehaviour == true) { + interval = shortInterval; + } + else { + interval = longInterval; + } + return true; } } - } - } + } + } int targetStaticResourceCount = minStaticResources; if(aiInterface->getMyFactionType()->getAIBehaviorStaticOverideValue(aibsvcMinStaticResourceCount) != INT_MAX) { @@ -749,9 +755,9 @@ bool AiRuleProduce::canUnitTypeOfferResourceType(const UnitType *ut, const Resou } } - if(aiInterface->isLogLevelEnabled(4) == true) { + if(aiInterface != NULL && aiInterface->isLogLevelEnabled(4) == true) { char szBuf[8096]=""; - snprintf(szBuf,8096,"canUnitTypeOfferResourceType for unit type [%s] for resource type [%s] returned: %d",ut->getName(false).c_str(),rt->getName(false).c_str(),unitTypeOffersResourceType); + snprintf(szBuf,8096,"canUnitTypeOfferResourceType for unit type [%s] for resource type [%s] returned: %d",(ut != NULL ? ut->getName(false).c_str() : "n/a"),(rt != NULL ? rt->getName(false).c_str() : "n/a"),unitTypeOffersResourceType); aiInterface->printLog(4, szBuf); } @@ -1157,6 +1163,9 @@ void AiRuleProduce::produceSpecific(const ProduceTask *pt){ if(ctypeForCostCheck == NULL || ct->getClass() == ccMorph) { if(ctypeForCostCheck != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); + if(mct == NULL) { + throw megaglest_runtime_error("mct == NULL"); + } if(mct->getIgnoreResourceRequirements() == true) { ctypeForCostCheck= ct; } diff --git a/source/glest_game/ai/path_finder.cpp b/source/glest_game/ai/path_finder.cpp index 97393bab8..c916c97e0 100644 --- a/source/glest_game/ai/path_finder.cpp +++ b/source/glest_game/ai/path_finder.cpp @@ -398,7 +398,7 @@ TravelState PathFinder::findPath(Unit *unit, const Vec2i &finalPos, bool *wasStu if(dynamic_cast(path) != NULL) { UnitPathBasic *basicPath = dynamic_cast(path); Vec2i pos; - if(frameIndex < 0) { + if(frameIndex < 0 && basicPath != NULL) { pos = basicPath->pop(frameIndex < 0); } else { @@ -809,7 +809,7 @@ TravelState PathFinder::aStar(Unit *unit, const Vec2i &targetPos, bool inBailout if(faction.closedNodesList.empty() == false) { float bestHeuristic = faction.closedNodesList.begin()->first; - if(bestHeuristic < lastNode->heuristic) { + if(lastNode != NULL && bestHeuristic < lastNode->heuristic) { lastNode= faction.closedNodesList.begin()->second[0]; } } diff --git a/source/glest_game/game/game.cpp b/source/glest_game/game/game.cpp index 2ec691ec4..a05f3b845 100644 --- a/source/glest_game/game/game.cpp +++ b/source/glest_game/game/game.cpp @@ -5350,14 +5350,14 @@ string Game::getDebugStats(std::map &factionDebugInfo) { factionInfo += " [" + formatString(this->gameSettings.getFactionTypeName(i)) + " team: " + intToStr(this->gameSettings.getTeam(i)) + "]"; - bool showResourceDebugInfo = false; - if(showResourceDebugInfo == true) { - factionInfo +=" res: "; - for(int j = 0; j < world.getTechTree()->getResourceTypeCount(); ++j) { - factionInfo += intToStr(world.getFaction(i)->getResource(j)->getAmount()); - factionInfo += " "; - } - } +// bool showResourceDebugInfo = false; +// if(showResourceDebugInfo == true) { +// factionInfo +=" res: "; +// for(int j = 0; j < world.getTechTree()->getResourceTypeCount(); ++j) { +// factionInfo += intToStr(world.getFaction(i)->getResource(j)->getAmount()); +// factionInfo += " "; +// } +// } factionDebugInfo[i] = factionInfo; } diff --git a/source/glest_game/game/script_manager.cpp b/source/glest_game/game/script_manager.cpp index 9306777db..c27be0993 100644 --- a/source/glest_game/game/script_manager.cpp +++ b/source/glest_game/game/script_manager.cpp @@ -1662,6 +1662,9 @@ int ScriptManager::isFreeCellsOrHasUnit(int field, int unitId, Vec2i pos) { Unit* unit= world->findUnitById(unitId); + if(unit == NULL) { + throw megaglest_runtime_error("unit == NULL"); + } int result = world->getMap()->isFreeCellsOrHasUnit(pos,unit->getType()->getSize(),static_cast(field),unit,NULL,true); if(SystemFlags::getSystemSettingType(SystemFlags::debugLUA).enabled) SystemFlags::OutputDebug(SystemFlags::debugLUA,"In [%s] unitId = %d, [%s] pos [%s] field = %d result = %d\n",__FUNCTION__,unitId,unit->getType()->getName(false).c_str(),pos.getString().c_str(),field,result); diff --git a/source/glest_game/global/core_data.cpp b/source/glest_game/global/core_data.cpp index 2da9f5a3d..e3fb222db 100644 --- a/source/glest_game/global/core_data.cpp +++ b/source/glest_game/global/core_data.cpp @@ -242,7 +242,7 @@ void CoreData::loadTextures(string data_path) { message(ex.what(), GlobalStaticFlags::getIsNonGraphicalModeEnabled(), tempDataLocation); - cleanupTexture (&fireTexture); + cleanupTexture (&teamColorTexture); } } snowTexture = renderer.newTexture2D(rsGlobal); diff --git a/source/glest_game/global/lang.cpp b/source/glest_game/global/lang.cpp index 791c563bd..02bd588b7 100644 --- a/source/glest_game/global/lang.cpp +++ b/source/glest_game/global/lang.cpp @@ -505,7 +505,7 @@ string Lang::getString(const string &s, string uselanguage, bool fallbackToDefau return getString(s, DEFAULT_LANGUAGE, false); } - return "???" + s + "???"; + //return "???" + s + "???"; } return "???" + s + "???"; } @@ -540,8 +540,8 @@ bool Lang::hasScenarioString(const string &s) { string Lang::getTechTreeString(const string &s,const char *defaultValue) { try{ - string default_language = "default"; string result = ""; + string default_language = "default"; //printf("Line: %d techNameLoaded = %s s = %s this->language = %s\n",__LINE__,techNameLoaded.c_str(),s.c_str(),this->language.c_str()); @@ -579,7 +579,7 @@ string Lang::getTechTreeString(const string &s,const char *defaultValue) { if(techTreeStringsAllLanguages[techNameLoaded][this->language].getpath() != "") { SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); } - return "???" + s + "???"; + //return "???" + s + "???"; } return "???" + s + "???"; } @@ -609,7 +609,7 @@ string Lang::getTilesetString(const string &s,const char *defaultValue) { if(tilesetStrings.getpath() != "") { SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",__FILE__,__FUNCTION__,__LINE__,ex.what()); } - return "???" + s + "???"; + //return "???" + s + "???"; } return "???" + s + "???"; } diff --git a/source/glest_game/graphics/renderer.cpp b/source/glest_game/graphics/renderer.cpp index a307966ba..52283cf71 100644 --- a/source/glest_game/graphics/renderer.cpp +++ b/source/glest_game/graphics/renderer.cpp @@ -597,7 +597,7 @@ void Renderer::manageDeferredParticleSystems() { } if(dynamic_cast(ps) != NULL) { GameParticleSystem *gps = dynamic_cast(ps); - if(gps->getModelFileLoadDeferred() != "" && gps->getModel() == NULL) { + if(gps != NULL && gps->getModelFileLoadDeferred() != "" && gps->getModel() == NULL) { std::map > > loadedFileList; Model *model= newModel(rsGame, gps->getModelFileLoadDeferred(), false, &loadedFileList, NULL); if(model) @@ -3988,12 +3988,14 @@ void Renderer::MapRenderer::load(float coordStep) { } template void* _bindVBO(GLuint vbo,std::vector buf,int target=GL_ARRAY_BUFFER_ARB) { + void* result = NULL; if(vbo) { glBindBuffer(target,vbo); - return NULL; - } else { - return &buf[0]; } + else { + result = &buf[0]; + } + return result; } void Renderer::MapRenderer::Layer::renderVisibleLayer() { @@ -4273,13 +4275,13 @@ void Renderer::renderSurface(const int renderFps) { else if(qCache.visibleScaledCellList.empty() == false) { int lastTex=-1; - int currTex=-1; + //int currTex=-1; Quad2i snapshotOfvisibleQuad = visibleQuad; //bool useVertexArrayRendering = getVBOSupported(); - bool useVertexArrayRendering = false; - if(useVertexArrayRendering == false) { + //bool useVertexArrayRendering = false; + //if(useVertexArrayRendering == false) { //printf("\LEGACY qCache.visibleScaledCellList.size() = %d \n",qCache.visibleScaledCellList.size()); Vec2f texCoords[4]; @@ -4330,7 +4332,7 @@ void Renderer::renderSurface(const int renderFps) { if(tc00->getSurfaceTexture() == NULL) { throw megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); } - currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); + int currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); if(currTex != lastTex) { lastTex = currTex; //glBindTexture(GL_TEXTURE_2D, lastTex); @@ -4411,204 +4413,204 @@ void Renderer::renderSurface(const int renderFps) { glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); - } - else { - const bool useVBOs = false; - const bool useSurfaceCache = false; - - std::vector surfaceData; - bool recalcSurface = false; - - if(useSurfaceCache == true) { - std::map > >::iterator iterFind = mapSurfaceData.find(snapshotOfvisibleQuad.getString()); - if(iterFind == mapSurfaceData.end()) { - recalcSurface = true; - //printf("#1 Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); - } -/* - else if(iterFind->second.first.getMillis() >= 250) { - recalcSurface = true; - mapSurfaceData.erase(snapshotOfvisibleQuad.getString()); - //printf("#2 RE-Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); - } -*/ - } - else { - recalcSurface = true; - } - - if(recalcSurface == true) { - //printf("Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); - - std::vector *surface = &surfaceData; - if(useSurfaceCache == true) { - std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; - surface = &surfaceCacheEntity.second; - //surface.reserve(qCache.visibleScaledCellList.size()); - } - surface->reserve(qCache.visibleScaledCellList.size()); - - int lastSurfaceDataIndex = -1; - for(int visibleIndex = 0; - visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { - Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; - - SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); - SurfaceCell *tc10= map->getSurfaceCell(pos.x+1, pos.y); - SurfaceCell *tc01= map->getSurfaceCell(pos.x, pos.y+1); - SurfaceCell *tc11= map->getSurfaceCell(pos.x+1, pos.y+1); - - if(tc00 == NULL) { - throw megaglest_runtime_error("tc00 == NULL"); - } - if(tc10 == NULL) { - throw megaglest_runtime_error("tc10 == NULL"); - } - if(tc01 == NULL) { - throw megaglest_runtime_error("tc01 == NULL"); - } - if(tc11 == NULL) { - throw megaglest_runtime_error("tc11 == NULL"); - } - - triangleCount+= 2; - pointCount+= 4; - - //set texture - if(tc00->getSurfaceTexture() == NULL) { - throw megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); - } - - int surfaceDataIndex = -1; - currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); - if(currTex != lastTex) { - lastTex = currTex; - } - else { - surfaceDataIndex = lastSurfaceDataIndex; - } - - if(surfaceDataIndex < 0) { - SurfaceData newData; - newData.uniqueId = SurfaceData::nextUniqueId; - SurfaceData::nextUniqueId++; - newData.bufferCount=0; - newData.textureHandle = currTex; - surface->push_back(newData); - - surfaceDataIndex = (int)surface->size() - 1; - } - - lastSurfaceDataIndex = surfaceDataIndex; - - SurfaceData *cellData = &(*surface)[surfaceDataIndex]; - - const Vec2f &surfCoord= tc00->getSurfTexCoord(); - - cellData->texCoords.push_back(tc01->getFowTexCoord()); - cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y + coordStep)); - cellData->vertices.push_back(tc01->getVertex()); - cellData->normals.push_back(tc01->getNormal()); - cellData->bufferCount++; - - cellData->texCoords.push_back(tc00->getFowTexCoord()); - cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y)); - cellData->vertices.push_back(tc00->getVertex()); - cellData->normals.push_back(tc00->getNormal()); - cellData->bufferCount++; - - cellData->texCoords.push_back(tc11->getFowTexCoord()); - cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y+coordStep)); - cellData->vertices.push_back(tc11->getVertex()); - cellData->normals.push_back(tc11->getNormal()); - cellData->bufferCount++; - - cellData->texCoords.push_back(tc10->getFowTexCoord()); - cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y)); - cellData->vertices.push_back(tc10->getVertex()); - cellData->normals.push_back(tc10->getNormal()); - cellData->bufferCount++; - } - } - - std::vector *surface = &surfaceData; - if(useSurfaceCache == true) { - std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; - surface = &surfaceCacheEntity.second; - } - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - - for(int i = 0; i < (int)surface->size(); ++i) { - SurfaceData &data = (*surface)[i]; - - if(useVBOs == true) { - VisibleQuadContainerVBOCache *vboCache = GetSurfaceVBOs(&data); - - //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - glClientActiveTexture(fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOFowTexCoords); - glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL); - - glBindTexture(GL_TEXTURE_2D, data.textureHandle); - glClientActiveTexture(baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOSurfaceTexCoords); - glTexCoordPointer(2, GL_FLOAT, 0, (char *) NULL); - - glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOVertices); - glVertexPointer(3, GL_FLOAT, 0, (char *) NULL); - - glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBONormals); - glNormalPointer(GL_FLOAT, 0, (char *) NULL); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); - - glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); - - glClientActiveTexture(fowTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - } - else { - Vec2f *texCoords = &data.texCoords[0]; - Vec2f *texCoordsSurface = &data.texCoordsSurface[0]; - Vec3f *vertices = &data.vertices[0]; - Vec3f *normals = &data.normals[0]; - - //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); - glClientActiveTexture(fowTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0,texCoords); - - glBindTexture(GL_TEXTURE_2D, data.textureHandle); - glClientActiveTexture(baseTexUnit); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - glTexCoordPointer(2, GL_FLOAT, 0, texCoordsSurface); - - glVertexPointer(3, GL_FLOAT, 0, vertices); - glNormalPointer(GL_FLOAT, 0, normals); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); - - glClientActiveTexture(fowTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glClientActiveTexture(baseTexUnit); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - } - } - - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - - //printf("Surface Render before [%d] after [%d]\n",qCache.visibleScaledCellList.size(),surface.size()); - } +// } +// else { +// const bool useVBOs = false; +// const bool useSurfaceCache = false; +// +// std::vector surfaceData; +// bool recalcSurface = false; +// +// if(useSurfaceCache == true) { +// std::map > >::iterator iterFind = mapSurfaceData.find(snapshotOfvisibleQuad.getString()); +// if(iterFind == mapSurfaceData.end()) { +// recalcSurface = true; +// //printf("#1 Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); +// } +///* +// else if(iterFind->second.first.getMillis() >= 250) { +// recalcSurface = true; +// mapSurfaceData.erase(snapshotOfvisibleQuad.getString()); +// //printf("#2 RE-Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); +// } +//*/ +// } +// else { +// recalcSurface = true; +// } +// +// if(recalcSurface == true) { +// //printf("Calculating surface for Rendering using VA's [%s]\n",snapshotOfvisibleQuad.getString().c_str()); +// +// std::vector *surface = &surfaceData; +// if(useSurfaceCache == true) { +// std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; +// surface = &surfaceCacheEntity.second; +// //surface.reserve(qCache.visibleScaledCellList.size()); +// } +// surface->reserve(qCache.visibleScaledCellList.size()); +// +// int lastSurfaceDataIndex = -1; +// for(int visibleIndex = 0; +// visibleIndex < (int)qCache.visibleScaledCellList.size(); ++visibleIndex) { +// Vec2i &pos = qCache.visibleScaledCellList[visibleIndex]; +// +// SurfaceCell *tc00= map->getSurfaceCell(pos.x, pos.y); +// SurfaceCell *tc10= map->getSurfaceCell(pos.x+1, pos.y); +// SurfaceCell *tc01= map->getSurfaceCell(pos.x, pos.y+1); +// SurfaceCell *tc11= map->getSurfaceCell(pos.x+1, pos.y+1); +// +// if(tc00 == NULL) { +// throw megaglest_runtime_error("tc00 == NULL"); +// } +// if(tc10 == NULL) { +// throw megaglest_runtime_error("tc10 == NULL"); +// } +// if(tc01 == NULL) { +// throw megaglest_runtime_error("tc01 == NULL"); +// } +// if(tc11 == NULL) { +// throw megaglest_runtime_error("tc11 == NULL"); +// } +// +// triangleCount+= 2; +// pointCount+= 4; +// +// //set texture +// if(tc00->getSurfaceTexture() == NULL) { +// throw megaglest_runtime_error("tc00->getSurfaceTexture() == NULL"); +// } +// +// int surfaceDataIndex = -1; +// currTex= static_cast(tc00->getSurfaceTexture())->getHandle(); +// if(currTex != lastTex) { +// lastTex = currTex; +// } +// else { +// surfaceDataIndex = lastSurfaceDataIndex; +// } +// +// if(surfaceDataIndex < 0) { +// SurfaceData newData; +// newData.uniqueId = SurfaceData::nextUniqueId; +// SurfaceData::nextUniqueId++; +// newData.bufferCount=0; +// newData.textureHandle = currTex; +// surface->push_back(newData); +// +// surfaceDataIndex = (int)surface->size() - 1; +// } +// +// lastSurfaceDataIndex = surfaceDataIndex; +// +// SurfaceData *cellData = &(*surface)[surfaceDataIndex]; +// +// const Vec2f &surfCoord= tc00->getSurfTexCoord(); +// +// cellData->texCoords.push_back(tc01->getFowTexCoord()); +// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y + coordStep)); +// cellData->vertices.push_back(tc01->getVertex()); +// cellData->normals.push_back(tc01->getNormal()); +// cellData->bufferCount++; +// +// cellData->texCoords.push_back(tc00->getFowTexCoord()); +// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x, surfCoord.y)); +// cellData->vertices.push_back(tc00->getVertex()); +// cellData->normals.push_back(tc00->getNormal()); +// cellData->bufferCount++; +// +// cellData->texCoords.push_back(tc11->getFowTexCoord()); +// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y+coordStep)); +// cellData->vertices.push_back(tc11->getVertex()); +// cellData->normals.push_back(tc11->getNormal()); +// cellData->bufferCount++; +// +// cellData->texCoords.push_back(tc10->getFowTexCoord()); +// cellData->texCoordsSurface.push_back(Vec2f(surfCoord.x+coordStep, surfCoord.y)); +// cellData->vertices.push_back(tc10->getVertex()); +// cellData->normals.push_back(tc10->getNormal()); +// cellData->bufferCount++; +// } +// } +// +// std::vector *surface = &surfaceData; +// if(useSurfaceCache == true) { +// std::pair > &surfaceCacheEntity = mapSurfaceData[snapshotOfvisibleQuad.getString()]; +// surface = &surfaceCacheEntity.second; +// } +// +// glEnableClientState(GL_VERTEX_ARRAY); +// glEnableClientState(GL_NORMAL_ARRAY); +// +// for(int i = 0; i < (int)surface->size(); ++i) { +// SurfaceData &data = (*surface)[i]; +// +// if(useVBOs == true) { +// VisibleQuadContainerVBOCache *vboCache = GetSurfaceVBOs(&data); +// +// //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); +// glClientActiveTexture(fowTexUnit); +// glEnableClientState(GL_TEXTURE_COORD_ARRAY); +// +// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOFowTexCoords); +// glTexCoordPointer(2, GL_FLOAT, 0,(char *) NULL); +// +// glBindTexture(GL_TEXTURE_2D, data.textureHandle); +// glClientActiveTexture(baseTexUnit); +// glEnableClientState(GL_TEXTURE_COORD_ARRAY); +// +// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOSurfaceTexCoords); +// glTexCoordPointer(2, GL_FLOAT, 0, (char *) NULL); +// +// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBOVertices); +// glVertexPointer(3, GL_FLOAT, 0, (char *) NULL); +// +// glBindBufferARB( GL_ARRAY_BUFFER_ARB, vboCache->m_nVBONormals); +// glNormalPointer(GL_FLOAT, 0, (char *) NULL); +// +// glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); +// +// glBindBufferARB( GL_ARRAY_BUFFER_ARB, 0 ); +// +// glClientActiveTexture(fowTexUnit); +// glDisableClientState(GL_TEXTURE_COORD_ARRAY); +// glClientActiveTexture(baseTexUnit); +// glDisableClientState(GL_TEXTURE_COORD_ARRAY); +// +// } +// else { +// Vec2f *texCoords = &data.texCoords[0]; +// Vec2f *texCoordsSurface = &data.texCoordsSurface[0]; +// Vec3f *vertices = &data.vertices[0]; +// Vec3f *normals = &data.normals[0]; +// +// //glBindTexture(GL_TEXTURE_2D, static_cast(fowTex)->getHandle()); +// glClientActiveTexture(fowTexUnit); +// glEnableClientState(GL_TEXTURE_COORD_ARRAY); +// glTexCoordPointer(2, GL_FLOAT, 0,texCoords); +// +// glBindTexture(GL_TEXTURE_2D, data.textureHandle); +// glClientActiveTexture(baseTexUnit); +// glEnableClientState(GL_TEXTURE_COORD_ARRAY); +// glTexCoordPointer(2, GL_FLOAT, 0, texCoordsSurface); +// +// glVertexPointer(3, GL_FLOAT, 0, vertices); +// glNormalPointer(GL_FLOAT, 0, normals); +// +// glDrawArrays(GL_TRIANGLE_STRIP, 0, data.bufferCount); +// +// glClientActiveTexture(fowTexUnit); +// glDisableClientState(GL_TEXTURE_COORD_ARRAY); +// glClientActiveTexture(baseTexUnit); +// glDisableClientState(GL_TEXTURE_COORD_ARRAY); +// } +// } +// +// glDisableClientState(GL_NORMAL_ARRAY); +// glDisableClientState(GL_VERTEX_ARRAY); +// +// //printf("Surface Render before [%d] after [%d]\n",qCache.visibleScaledCellList.size(),surface.size()); +// } } //Restore @@ -4619,7 +4621,10 @@ void Renderer::renderSurface(const int renderFps) { glPopAttrib(); //assert - glGetError(); //remove when first mtex problem solved + GLenum glresult = glGetError(); //remove when first mtex problem solved + if(glresult) { + assertGl(); + } assertGl(); IF_DEBUG_EDITION( @@ -5349,8 +5354,9 @@ void Renderer::renderSelectionEffects() { (showDebugUILevel & debugui_unit_titles) == debugui_unit_titles) { const UnitPathInterface *path= unit->getPath(); - if(path != NULL && dynamic_cast(path)) { - vector pathList = dynamic_cast(path)->getQueue(); + const UnitPathBasic *pathfinder = (path == NULL ? NULL : dynamic_cast(path)); + if(pathfinder != NULL) { + vector pathList = pathfinder->getQueue(); Vec2i lastPosValue; for(int i = 0; i < (int)pathList.size(); ++i) { diff --git a/source/glest_game/main/main.cpp b/source/glest_game/main/main.cpp index ffb63ff25..3d92043c9 100644 --- a/source/glest_game/main/main.cpp +++ b/source/glest_game/main/main.cpp @@ -3256,7 +3256,10 @@ void CheckForDuplicateData() { oldFile = newFile + "/" + tilesetName + ".xml"; newFile = newFile + "/" + tilesetName + "_custom.xml"; - rename(oldFile.c_str(),newFile.c_str()); + bool rename_result = rename(oldFile.c_str(),newFile.c_str()); + if(rename_result == false) { + printf("Error renaming [%s] to [%s]\n",oldFile.c_str(),newFile.c_str()); + } } errorMsg += szBuf; } @@ -4712,7 +4715,7 @@ int glestMain(int argc, char** argv) { printf("Running in auto test mode\n"); } if(hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST])) == true) { - Config::getInstance().setBool("AutoTest","true",true); + Config::getInstance().setBool("AutoTest",true,true); int foundParamIndIndex = -1; hasCommandArgument(argc, argv,string(GAME_ARGS[GAME_ARG_AUTO_TEST]) + string("="),&foundParamIndIndex); diff --git a/source/glest_game/menu/menu_background.cpp b/source/glest_game/menu/menu_background.cpp index 93c3aa12b..d4128c432 100644 --- a/source/glest_game/menu/menu_background.cpp +++ b/source/glest_game/menu/menu_background.cpp @@ -116,7 +116,7 @@ MenuBackground::MenuBackground() : rps(NULL) { aboutPosition.x= positionNode->getAttribute("x")->getFloatValue(); aboutPosition.y= positionNode->getAttribute("y")->getFloatValue(); aboutPosition.z= positionNode->getAttribute("z")->getFloatValue(); - rotationNode= cameraNode->getChild("about-rotation"); + //rotationNode= cameraNode->getChild("about-rotation"); targetCamera= NULL; t= 0.f; diff --git a/source/glest_game/menu/menu_state_connected_game.cpp b/source/glest_game/menu/menu_state_connected_game.cpp index 817ea1ea3..9e357f270 100644 --- a/source/glest_game/menu/menu_state_connected_game.cpp +++ b/source/glest_game/menu/menu_state_connected_game.cpp @@ -1287,7 +1287,9 @@ void MenuStateConnectedGame::mouseClick(int x, int y, MouseButton mouseButton){ getMissingTechtreeFromFTPServerLastPrompted = 0; ClientInterface *clientInterface = networkManager.getClientInterface(); - + if(clientInterface == NULL) { + throw megaglest_runtime_error("clientInterface == NULL"); + } if(getInProgressSavedGameFromFTPServerInProgress == true) { if(clientInterface != NULL) { clientInterface->close(); @@ -2777,7 +2779,7 @@ void MenuStateConnectedGame::update() { techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + gameSettings->getTech() + string("/*"), ".xml", NULL); //clientInterface->sendTextMessage("#1 TechCRC = " + intToStr(techCRC) + " remoteCRC = " + intToStr(gameSettings->getTechCRC()),-1, true, ""); - if(techCRC == 0 || tilesetCRC != gameSettings->getTechCRC()) { + if(techCRC == 0 || techCRC != gameSettings->getTechCRC()) { techCRC = getFolderTreeContentsCheckSumRecursively(config.getPathListForType(ptTechs,""), string("/") + gameSettings->getTech() + string("/*"), ".xml", NULL, true); //clientInterface->sendTextMessage("#2 TechCRC = " + intToStr(techCRC) + " remoteCRC = " + intToStr(gameSettings->getTechCRC()),-1, true, ""); } diff --git a/source/glest_game/menu/menu_state_custom_game.cpp b/source/glest_game/menu/menu_state_custom_game.cpp index f39cb32ee..f5c308c4e 100644 --- a/source/glest_game/menu/menu_state_custom_game.cpp +++ b/source/glest_game/menu/menu_state_custom_game.cpp @@ -909,7 +909,7 @@ void MenuStateCustomGame::cleanupThread(SimpleTaskThread **thread) { //printf("LINE: %d *thread = %p\n",__LINE__,*thread); } threadPtr = NULL; - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1e cleanupThread callingThread [%p]\n",*thread); + //if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1e cleanupThread callingThread [%p]\n",*thread); } else { if(SystemFlags::VERBOSE_MODE_ENABLED) printf("\n\n#1f cleanupThread callingThread [%p]\n",*thread); @@ -2406,6 +2406,9 @@ void MenuStateCustomGame::update() { if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took msecs: %lld\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) chrono.start(); + if(this->headlessServerMode == true && serverInterface == NULL) { + throw megaglest_runtime_error("serverInterface == NULL"); + } if(this->headlessServerMode == true && serverInterface->getGameSettingsUpdateCount() > lastMasterServerSettingsUpdateCount && serverInterface->getGameSettings() != NULL) { const GameSettings *settings = serverInterface->getGameSettings(); @@ -3434,8 +3437,9 @@ void MenuStateCustomGame::loadGameSettings(GameSettings *gameSettings,bool force ControlType ct= static_cast(listBoxControls[i].getSelectedItemIndex()); if(forceCloseUnusedSlots == true && (ct == ctNetworkUnassigned || ct == ctNetwork)) { - if(serverInterface->getSlot(i) == NULL || - serverInterface->getSlot(i)->isConnected() == false) { + if(serverInterface != NULL && + (serverInterface->getSlot(i) == NULL || + serverInterface->getSlot(i)->isConnected() == false)) { if(checkBoxScenario.getValue() == false) { //printf("Closed A [%d] [%s]\n",i,labelPlayerNames[i].getText().c_str()); diff --git a/source/glest_game/menu/menu_state_masterserver.cpp b/source/glest_game/menu/menu_state_masterserver.cpp index 3748ffa1c..c93630a7d 100644 --- a/source/glest_game/menu/menu_state_masterserver.cpp +++ b/source/glest_game/menu/menu_state_masterserver.cpp @@ -1087,6 +1087,7 @@ void MenuStateMasterserver::rebuildServerLines(const string &serverInfo) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); serverLines.push_back(new ServerLine( masterServerInfo, i, serverLinesYBase, serverLinesLineHeight, containerName)); + delete masterServerInfo; } else { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); diff --git a/source/glest_game/menu/menu_state_options_graphics.cpp b/source/glest_game/menu/menu_state_options_graphics.cpp index bd220305b..464252bf5 100644 --- a/source/glest_game/menu/menu_state_options_graphics.cpp +++ b/source/glest_game/menu/menu_state_options_graphics.cpp @@ -592,7 +592,9 @@ void MenuStateOptionsGraphics::mouseClick(int x, int y, MouseButton mouseButton) selectedMode = &(*it); } } - + if(selectedMode == NULL) { + throw megaglest_runtime_error("selectedMode == NULL"); + } WindowGl *window = this->program->getWindow(); window->ChangeVideoMode(true, selectedMode->width, diff --git a/source/glest_game/network/client_interface.cpp b/source/glest_game/network/client_interface.cpp index 41bbaf546..119bc0404 100644 --- a/source/glest_game/network/client_interface.cpp +++ b/source/glest_game/network/client_interface.cpp @@ -199,7 +199,13 @@ ClientInterface::ClientInterface() : GameNetworkInterface() { setQuitThread(false); playerIndex= -1; + gameSettingsReceivedCount=0; setGameSettingsReceived(false); + gameSettingsReceivedCount=0; + connectedTime = 0; + port = 0; + serverFTPPort = 0; + gotIntro = false; lastNetworkCommandListSendTime = 0; currentFrameCount = 0; @@ -211,7 +217,6 @@ ClientInterface::ClientInterface() : GameNetworkInterface() { networkGameDataSynchCheckOkTech = false; this->setNetworkGameDataSynchCheckTechMismatchReport(""); this->setReceivedDataSynchCheck(false); - } void ClientInterface::shutdownNetworkCommandListThread(MutexSafeWrapper &safeMutexWrapper) { @@ -1491,16 +1496,16 @@ void ClientInterface::updateKeyframe(int frameCount) { if(getQuit() == false && getQuitThread() == false) { //bool testThreaded = Config::getInstance().getBool("ThreadedNetworkClient","true"); - bool testThreaded = true; - if(testThreaded == false) { - updateFrame(&frameCount); - Commands &frameCmdList = cachedPendingCommands[frameCount]; - for(int i= 0; i < (int)frameCmdList.size(); ++i) { - pendingCommands.push_back(frameCmdList[i]); - } - cachedPendingCommands.erase(frameCount); - } - else { +// bool testThreaded = true; +// if(testThreaded == false) { +// updateFrame(&frameCount); +// Commands &frameCmdList = cachedPendingCommands[frameCount]; +// for(int i= 0; i < (int)frameCmdList.size(); ++i) { +// pendingCommands.push_back(frameCmdList[i]); +// } +// cachedPendingCommands.erase(frameCount); +// } +// else { if(networkCommandListThread == NULL) { static string mutexOwnerId = string(extractFileFromDirectoryPath(__FILE__).c_str()) + string("_") + intToStr(__LINE__); // networkCommandListThread = new SimpleTaskThread(this,0,0); @@ -1514,7 +1519,7 @@ void ClientInterface::updateKeyframe(int frameCount) { } getNetworkCommand(frameCount,cachedPendingCommandsIndex); - } + //} } if(SystemFlags::getSystemSettingType(SystemFlags::debugPerformance).enabled && chrono.getMillis() > 0) SystemFlags::OutputDebug(SystemFlags::debugPerformance,"In [%s::%s Line: %d] took %lld msecs\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,chrono.getMillis()); @@ -1556,6 +1561,9 @@ void ClientInterface::waitUntilReady(Checksum* checksum) { uint64 waitLoopIterationCount = 0; uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 100; MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkClientLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + MAX_LOOP_COUNT_BEFORE_SLEEP = 1; + } int sleepMillis = Config::getInstance().getInt("NetworkClientLoopGameLoadingCapSleepMillis","10"); //wait until we get a ready message from the server diff --git a/source/glest_game/network/network_manager.cpp b/source/glest_game/network/network_manager.cpp index 1b4987007..6ecc6aedb 100644 --- a/source/glest_game/network/network_manager.cpp +++ b/source/glest_game/network/network_manager.cpp @@ -28,7 +28,6 @@ NetworkManager &NetworkManager::getInstance(){ NetworkManager::NetworkManager() { if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] this->networkRole = %d gameNetworkInterface [%p]\n",__FILE__,__FUNCTION__,__LINE__,this->networkRole,gameNetworkInterface); gameNetworkInterface= NULL; networkRole= nrIdle; diff --git a/source/glest_game/network/network_message.cpp b/source/glest_game/network/network_message.cpp index 9f1a50004..54ff57035 100644 --- a/source/glest_game/network/network_message.cpp +++ b/source/glest_game/network/network_message.cpp @@ -144,6 +144,14 @@ unsigned int NetworkMessageIntro::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.externalIp = 0; + packedData.ftpPort = 0; + packedData.gameInProgress = 0; + packedData.gameState = 0; + packedData.messageType = nmtIntro; + packedData.playerIndex = 0; + packedData.sessionId = 0; + unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -290,7 +298,9 @@ void NetworkMessageIntro::fromEndian() { // ===================================================== NetworkMessagePing::NetworkMessagePing(){ - data.messageType= nmtPing; + data.messageType = nmtPing; + data.pingFrequency = 0; + data.pingTime = 0; pingReceivedLocalTime = 0; } @@ -395,6 +405,7 @@ void NetworkMessagePing::fromEndian() { NetworkMessageReady::NetworkMessageReady() { data.messageType= nmtReady; + data.checksum= 0; } NetworkMessageReady::NetworkMessageReady(uint32 checksum) { @@ -641,6 +652,39 @@ unsigned int NetworkMessageLaunch::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.aiAcceptSwitchTeamPercentChance = 0; + packedData.allowObservers = 0; + packedData.cpuReplacementMultiplier = 0; + packedData.defaultResources = 0; + packedData.defaultUnits = 0; + packedData.defaultVictoryConditions = 0; + packedData.enableObserverModeAtEndGame = 0; + packedData.enableServerControlledAI = 0; + for(unsigned int index =0; index < maxFactionCRCCount; ++index) { + packedData.factionCRCList[index] = 0; + } + for(unsigned int index =0; index < GameConstants::maxPlayers; ++index) { + packedData.factionControls[index] = 0; + packedData.networkPlayerStatuses[index] = 0; + packedData.resourceMultiplierIndex[index] = 0; + packedData.startLocationIndex[index] = 0; + packedData.teams[index] = 0; + } + packedData.factionCount = 0; + packedData.flagTypes1 = 0; + packedData.fogOfWar = 0; + packedData.mapCRC = 0; + packedData.masterserver_admin = 0; + packedData.masterserver_admin_factionIndex = 0; + packedData.messageType = 0; + packedData.networkAllowNativeLanguageTechtree = 0; + packedData.networkFramePeriod = 0; + packedData.networkPauseGameForLaggedClients = 0; + packedData.pathFinderType = 0; + packedData.techCRC = 0; + packedData.thisFactionIndex = 0; + packedData.tilesetCRC = 0; + unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -1619,6 +1663,9 @@ unsigned int NetworkMessageText::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.messageType = nmtText; + packedData.playerIndex = 0; + packedData.teamIndex = 0; unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -1956,6 +2003,9 @@ unsigned int NetworkMessageSynchNetworkGameData::getPackedSizeDetail() { static unsigned int result = 0; if(result == 0) { DataDetail packedData; + for(unsigned int index = 0; index < maxFileCRCCount; ++index) { + packedData.techCRCFileCRCList[index] = 0; + } unsigned char *buf = new unsigned char[sizeof(DataDetail)*3]; for(unsigned int i = 0; i < (unsigned int)maxFileCRCCount; ++i) { @@ -2325,7 +2375,8 @@ void NetworkMessageSynchNetworkGameDataStatus::fromEndianDetail() { // class NetworkMessageSynchNetworkGameDataFileCRCCheck // ===================================================== -NetworkMessageSynchNetworkGameDataFileCRCCheck::NetworkMessageSynchNetworkGameDataFileCRCCheck(uint32 totalFileCount, uint32 fileIndex, uint32 fileCRC, const string fileName) +NetworkMessageSynchNetworkGameDataFileCRCCheck::NetworkMessageSynchNetworkGameDataFileCRCCheck( + uint32 totalFileCount, uint32 fileIndex, uint32 fileCRC, const string fileName) { data.messageType= nmtSynchNetworkGameDataFileCRCCheck; @@ -2343,6 +2394,11 @@ unsigned int NetworkMessageSynchNetworkGameDataFileCRCCheck::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.fileCRC = 0; + packedData.fileIndex = 0; + packedData.messageType = nmtSynchNetworkGameDataFileCRCCheck; + packedData.totalFileCount = 0; + unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -2445,6 +2501,7 @@ unsigned int NetworkMessageSynchNetworkGameDataFileGet::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.messageType = nmtSynchNetworkGameDataFileGet; unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -2554,6 +2611,13 @@ unsigned int SwitchSetupRequest::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.currentSlotIndex = 0; + packedData.messageType = nmtSwitchSetupRequest; + packedData.networkPlayerStatus = 0; + packedData.switchFlags = 0; + packedData.toSlotIndex = 0; + packedData.toTeam = 0; + unsigned char *buf = new unsigned char[sizeof(Data)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -2870,6 +2934,12 @@ unsigned int NetworkMessageMarkCell::getPackedSize() { static unsigned int result = 0; if(result == 0) { Data packedData; + packedData.factionIndex = 0; + packedData.messageType = nmtMarkCell; + packedData.playerIndex = 0; + packedData.targetX = 0; + packedData.targetY = 0; + unsigned char *buf = new unsigned char[sizeof(packedData)*3]; result = pack(buf, getPackedMessageFormat(), packedData.messageType, @@ -2966,6 +3036,13 @@ void NetworkMessageMarkCell::fromEndian() { // class NetworkMessageUnMarkCell // ===================================================== +NetworkMessageUnMarkCell::NetworkMessageUnMarkCell() { + data.messageType = nmtUnMarkCell; + data.targetX = 0; + data.targetY = 0; + data.factionIndex = 0; +} + NetworkMessageUnMarkCell::NetworkMessageUnMarkCell(Vec2i target, int factionIndex) { data.messageType = nmtUnMarkCell; data.targetX = target.x; @@ -3078,8 +3155,14 @@ void NetworkMessageUnMarkCell::fromEndian() { // class NetworkMessageHighlightCell // ===================================================== -NetworkMessageHighlightCell::NetworkMessageHighlightCell(Vec2i target, int factionIndex) { +NetworkMessageHighlightCell::NetworkMessageHighlightCell() { + data.messageType = nmtHighlightCell; + data.targetX = 0; + data.targetY = 0; + data.factionIndex = 0; +} +NetworkMessageHighlightCell::NetworkMessageHighlightCell(Vec2i target, int factionIndex) { data.messageType = nmtHighlightCell; data.targetX = target.x; data.targetY = target.y; diff --git a/source/glest_game/network/network_message.h b/source/glest_game/network/network_message.h index f571d2119..8b14bc807 100644 --- a/source/glest_game/network/network_message.h +++ b/source/glest_game/network/network_message.h @@ -1011,7 +1011,7 @@ protected: virtual unsigned char * packMessage(); public: - NetworkMessageUnMarkCell(){} + NetworkMessageUnMarkCell(); NetworkMessageUnMarkCell(Vec2i target, int factionIndex); virtual size_t getDataSize() const { return sizeof(Data); } @@ -1058,7 +1058,7 @@ protected: virtual unsigned char * packMessage(); public: - NetworkMessageHighlightCell(){} + NetworkMessageHighlightCell(); NetworkMessageHighlightCell(Vec2i target, int factionIndex); virtual size_t getDataSize() const { return sizeof(Data); } diff --git a/source/glest_game/network/network_protocol.cpp b/source/glest_game/network/network_protocol.cpp index ab5c3a22c..615067101 100644 --- a/source/glest_game/network/network_protocol.cpp +++ b/source/glest_game/network/network_protocol.cpp @@ -58,7 +58,7 @@ unsigned long long int pack754(long double f, unsigned bits, unsigned expbits) significand = fnorm * ((1LL<targetId = targetId >= 0 ? targetId : facing; diff --git a/source/glest_game/network/server_interface.cpp b/source/glest_game/network/server_interface.cpp index 0b364cc59..03f0eb13b 100644 --- a/source/glest_game/network/server_interface.cpp +++ b/source/glest_game/network/server_interface.cpp @@ -1844,6 +1844,9 @@ void ServerInterface::waitUntilReady(Checksum *checksum) { uint64 waitLoopIterationCount = 0; uint64 MAX_LOOP_COUNT_BEFORE_SLEEP = 10; MAX_LOOP_COUNT_BEFORE_SLEEP = Config::getInstance().getInt("NetworkServerLoopGameLoadingCap",intToStr(MAX_LOOP_COUNT_BEFORE_SLEEP).c_str()); + if(MAX_LOOP_COUNT_BEFORE_SLEEP == 0) { + MAX_LOOP_COUNT_BEFORE_SLEEP = 1; + } int sleepMillis = Config::getInstance().getInt("NetworkServerLoopGameLoadingCapSleepMillis","10"); int64 lastStatusUpdate = 0; @@ -2365,19 +2368,17 @@ void ServerInterface::checkListenerSlots() { void ServerInterface::broadcastGameSetup(GameSettings *gameSettingsBuffer, bool setGameSettingsBuffer) { if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s] Line: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__); - if(gameSettingsBuffer != NULL) { - for(unsigned int i = 0; i < (unsigned int)gameSettingsBuffer->getFactionCount(); ++i) { - int slotIndex = gameSettingsBuffer->getStartLocationIndex(i); - if(gameSettingsBuffer->getFactionControl(i) == ctNetwork && - isClientConnected(slotIndex) == false) { - gameSettingsBuffer->setNetworkPlayerName(i,GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); - } + if(gameSettingsBuffer == NULL) { + throw megaglest_runtime_error("gameSettingsBuffer == NULL"); + } + for(unsigned int i = 0; i < (unsigned int)gameSettingsBuffer->getFactionCount(); ++i) { + int slotIndex = gameSettingsBuffer->getStartLocationIndex(i); + if(gameSettingsBuffer->getFactionControl(i) == ctNetwork && + isClientConnected(slotIndex) == false) { + gameSettingsBuffer->setNetworkPlayerName(i,GameConstants::NETWORK_SLOT_UNCONNECTED_SLOTNAME); } } if(setGameSettingsBuffer == true) { - if(gameSettingsBuffer == NULL) { - throw megaglest_runtime_error("gameSettingsBuffer == NULL"); - } validateGameSettings(gameSettingsBuffer); //setGameSettings(gameSettingsBuffer,false); MutexSafeWrapper safeMutex(serverSynchAccessor,CODE_AT_LINE); @@ -2398,8 +2399,10 @@ void ServerInterface::broadcastMessage(NetworkMessage *networkMessage, int exclu if(inBroadcastMessage == true && dynamic_cast(networkMessage) != NULL) { safeMutexSlotBroadCastAccessor.ReleaseLock(); NetworkMessageText *txtMsg = dynamic_cast(networkMessage); - NetworkMessageText *msgCopy = txtMsg->getCopy(); - queueBroadcastMessage(msgCopy, excludeSlot); + if(txtMsg != NULL) { + NetworkMessageText *msgCopy = txtMsg->getCopy(); + queueBroadcastMessage(msgCopy, excludeSlot); + } return; } else { @@ -3132,7 +3135,6 @@ bool ServerInterface::getPauseForInGameConnection() { bool ServerInterface::getUnPauseForInGameConnection() { - bool allResumeClientsReady = false; bool result = false; for(int i= 0; exitServer == false && i < GameConstants::maxPlayers; ++i) { if(slots[i] != NULL) { @@ -3153,9 +3155,8 @@ bool ServerInterface::getUnPauseForInGameConnection() { } } } - if(allResumeClientsReady == true) { + if(result == true) { resumeGameStartTime = time(NULL); - result = true; } return result; } diff --git a/source/glest_game/type_instances/faction.cpp b/source/glest_game/type_instances/faction.cpp index 3a4c8b0cb..40bacfdbd 100644 --- a/source/glest_game/type_instances/faction.cpp +++ b/source/glest_game/type_instances/faction.cpp @@ -909,7 +909,9 @@ bool Faction::applyCosts(const ProducibleType *p,const CommandType *ct) { bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -935,8 +937,7 @@ bool Faction::applyCosts(const ProducibleType *p,const CommandType *ct) { throw megaglest_runtime_error(szBuf); } int cost= r->getAmount(); - if((cost > 0 || (rt->getClass() != rcStatic)) && rt->getClass() != rcConsumable) - { + if((cost > 0 || (rt->getClass() != rcStatic)) && rt->getClass() != rcConsumable) { incResourceAmount(rt, -(cost)); } @@ -968,7 +969,9 @@ void Faction::applyStaticCosts(const ProducibleType *p,const CommandType *ct) { bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -996,7 +999,9 @@ void Faction::applyStaticProduction(const ProducibleType *p,const CommandType *c bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -1021,7 +1026,9 @@ void Faction::deApplyCosts(const ProducibleType *p,const CommandType *ct) { bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -1044,7 +1051,9 @@ void Faction::deApplyStaticCosts(const ProducibleType *p,const CommandType *ct) bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -1069,7 +1078,9 @@ void Faction::deApplyStaticConsumption(const ProducibleType *p,const CommandType bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } } if(ignoreResourceCosts == false) { @@ -1162,7 +1173,9 @@ bool Faction::checkCosts(const ProducibleType *pt,const CommandType *ct) { bool ignoreResourceCosts = false; if(ct != NULL && ct->getClass() == ccMorph) { const MorphCommandType *mct = dynamic_cast(ct); - ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + if(mct != NULL) { + ignoreResourceCosts = mct->getIgnoreResourceRequirements(); + } //printf("Checking costs = %d for commandtype:\n%s\n",ignoreResourceCosts,mct->getDesc(NULL).c_str()); } @@ -1959,27 +1972,31 @@ bool Faction::canCreateUnit(const UnitType *ut, bool checkBuild, bool checkProdu // Check if this is a build command else if(checkBuild == true && cmdType->getClass() == ccBuild) { const BuildCommandType *build = dynamic_cast(cmdType); - for(int k = 0; k < build->getBuildingCount() && foundUnit == false; ++k) { - const UnitType *buildUnit = build->getBuilding(k); + if(build != NULL) { + for(int k = 0; k < build->getBuildingCount() && foundUnit == false; ++k) { + const UnitType *buildUnit = build->getBuilding(k); - if( buildUnit != NULL && - ut->getId() != unitType2->getId() && - ut->getName(false) == buildUnit->getName(false)) { - foundUnit = true; - break; + if( buildUnit != NULL && + ut->getId() != unitType2->getId() && + ut->getName(false) == buildUnit->getName(false)) { + foundUnit = true; + break; + } } } } // Check if this is a morph command else if(checkMorph == true && cmdType->getClass() == ccMorph) { const MorphCommandType *morph = dynamic_cast(cmdType); - const UnitType *morphUnit = morph->getMorphUnit(); + if(morph != NULL) { + const UnitType *morphUnit = morph->getMorphUnit(); - if( morphUnit != NULL && - ut->getId() != unitType2->getId() && - ut->getName(false) == morphUnit->getName(false)) { - foundUnit = true; - break; + if( morphUnit != NULL && + ut->getId() != unitType2->getId() && + ut->getName(false) == morphUnit->getName(false)) { + foundUnit = true; + break; + } } } } diff --git a/source/glest_game/type_instances/faction.h b/source/glest_game/type_instances/faction.h index 2b8d09ff4..b799bba49 100644 --- a/source/glest_game/type_instances/faction.h +++ b/source/glest_game/type_instances/faction.h @@ -61,6 +61,9 @@ public: class ExploredCellsLookupItem { public: + ExploredCellsLookupItem() { + ExploredCellsLookupItemCacheTimerCountIndex = 0; + } int ExploredCellsLookupItemCacheTimerCountIndex; std::vector exploredCellList; std::vector visibleCellList; diff --git a/source/glest_game/type_instances/object.cpp b/source/glest_game/type_instances/object.cpp index f3cb709f5..4bafffb73 100644 --- a/source/glest_game/type_instances/object.cpp +++ b/source/glest_game/type_instances/object.cpp @@ -57,6 +57,9 @@ Object::Object(ObjectType *objectType, const Vec3f &pos, const Vec2i &mapPos) : } animated=tmt->getAnimSpeed()>0; } + else { + variation=0; + } visible=false; animProgress=0.0f; } diff --git a/source/glest_game/type_instances/unit.cpp b/source/glest_game/type_instances/unit.cpp index 4cd386917..b34e57bab 100644 --- a/source/glest_game/type_instances/unit.cpp +++ b/source/glest_game/type_instances/unit.cpp @@ -3338,6 +3338,9 @@ bool Unit::morph(const MorphCommandType *mct) { UnitAttackBoostEffect *effect = currentAttackBoostEffects[i]; if(effect != NULL) { Unit *sourceUnit = game->getWorld()->findUnitById(effect->source->getId()); + if(sourceUnit == NULL) { + throw megaglest_runtime_error("sourceUnit == NULL"); + } sourceUnit->morphAttackBoosts(this); } } diff --git a/source/glest_game/types/faction_type.cpp b/source/glest_game/types/faction_type.cpp index 362b7354a..f5be6762a 100644 --- a/source/glest_game/types/faction_type.cpp +++ b/source/glest_game/types/faction_type.cpp @@ -427,10 +427,12 @@ std::vector FactionType::validateFactionType() { const CommandType *cmdType2 = unitType2.getCommandType(m); if(cmdType2 != NULL && dynamic_cast(cmdType2) != NULL) { const UpgradeCommandType *uct = dynamic_cast(cmdType2); - const UpgradeType *upgradeType2 = uct->getProducedUpgrade(); - if(upgradeType2 != NULL && upgradeType2->getName() == upgradeType->getName()) { - foundUpgraderUnit = true; - break; + if(uct != NULL) { + const UpgradeType *upgradeType2 = uct->getProducedUpgrade(); + if(upgradeType2 != NULL && upgradeType2->getName() == upgradeType->getName()) { + foundUpgraderUnit = true; + break; + } } } } @@ -481,6 +483,9 @@ std::vector FactionType::validateFactionType() { // exist in this faction if(cmdType->getClass() == ccRepair) { const RepairCommandType *repair = dynamic_cast(cmdType); + if(repair == NULL) { + throw megaglest_runtime_error("repair == NULL"); + } for(int k = 0; k < repair->getRepairCount(); ++k) { const UnitType *repairUnit = repair->getRepair(k); @@ -586,6 +591,9 @@ std::vector FactionType::validateFactionType() { // Check if this is a build command if(cmdType->getClass() == ccBuild) { const BuildCommandType *build = dynamic_cast(cmdType); + if(build == NULL) { + throw megaglest_runtime_error("build == NULL"); + } for(int k = 0; k < build->getBuildingCount() && foundUnit == false; ++k) { const UnitType *buildUnit = build->getBuilding(k); @@ -603,6 +611,9 @@ std::vector FactionType::validateFactionType() { // Check if this is a morph command if(cmdType->getClass() == ccMorph) { const MorphCommandType *morph = dynamic_cast(cmdType); + if(morph == NULL) { + throw megaglest_runtime_error("morph == NULL"); + } const UnitType *morphUnit = morph->getMorphUnit(); if( morphUnit != NULL && @@ -644,7 +655,7 @@ std::vector FactionType::validateFactionType() { const SkillType *st = unitType.getSkillType(j); if(st != NULL && dynamic_cast(st) != NULL) { const AttackSkillType *ast = dynamic_cast(st); - if(ast->getAttackVar() < 0) { + if(ast != NULL && ast->getAttackVar() < 0) { char szBuf[8096]=""; snprintf(szBuf,8096,"The Unit [%s] in Faction [%s] has the skill [%s] with an INVALID attack var value which is < 0 [%d]!",unitType.getName().c_str(),this->getName().c_str(),ast->getName().c_str(),ast->getAttackVar()); results.push_back(szBuf); @@ -738,6 +749,9 @@ std::vector FactionType::validateFactionTypeResourceTypes(vectorgetClass() == ccHarvest) { const HarvestCommandType *harvest = dynamic_cast(cmdType); + if(harvest == NULL) { + throw megaglest_runtime_error("harvest == NULL"); + } for(int k = 0; k < harvest->getHarvestedResourceCount(); ++k) { const ResourceType *harvestResource = harvest->getHarvestedResource(k); diff --git a/source/glest_game/types/unit_type.cpp b/source/glest_game/types/unit_type.cpp index 26c39d68f..486918669 100644 --- a/source/glest_game/types/unit_type.cpp +++ b/source/glest_game/types/unit_type.cpp @@ -787,7 +787,7 @@ const AttackCommandType *UnitType::getFirstAttackCommand(Field field) const{ //printf("$$$ Unit [%s] i = %d, commandTypes[i] [%s]\n",this->getName().c_str(),(int)i, commandTypes[i]->toString().c_str()); if(commandTypes[i]->getClass()== ccAttack){ const AttackCommandType *act= dynamic_cast(commandTypes[i]); - if(act->getAttackSkillType()->getAttackField(field)) { + if(act != NULL && act->getAttackSkillType()->getAttackField(field)) { //printf("## Unit [%s] i = %d, is found\n",this->getName().c_str(),(int)i); return act; } @@ -808,7 +808,7 @@ const AttackStoppedCommandType *UnitType::getFirstAttackStoppedCommand(Field fie //printf("$$$ Unit [%s] i = %d, commandTypes[i] [%s]\n",this->getName().c_str(),(int)i, commandTypes[i]->toString().c_str()); if(commandTypes[i]->getClass()== ccAttackStopped){ const AttackStoppedCommandType *act= dynamic_cast(commandTypes[i]); - if(act->getAttackSkillType()->getAttackField(field)) { + if(act != NULL && act->getAttackSkillType()->getAttackField(field)) { //printf("## Unit [%s] i = %d, is found\n",this->getName().c_str(),(int)i); return act; } @@ -1036,13 +1036,13 @@ void UnitType::computeFirstCtOfClass() { const CommandType* UnitType::findCommandTypeById(int id) const{ const HarvestEmergencyReturnCommandType *result = dynamic_cast(ctHarvestEmergencyReturnCommandType.get()); - if(id == result->getId()) { + if(result != NULL && id == result->getId()) { return result; } - for(int i=0; igetId()==id){ + for(int i=0; i < getCommandTypeCount(); ++i) { + const CommandType *commandType= getCommandType(i); + if(commandType->getId() == id){ return commandType; } } diff --git a/source/glest_game/types/upgrade_type.cpp b/source/glest_game/types/upgrade_type.cpp index 3ca8a9bb9..fbc95d54d 100644 --- a/source/glest_game/types/upgrade_type.cpp +++ b/source/glest_game/types/upgrade_type.cpp @@ -851,6 +851,8 @@ void TotalUpgrade::sum(const UpgradeTypeBase *ut, const Unit *unit) { if(ut->getMaxEpIsMultiplier() == true) { maxEp += ((double)unit->getEp() * ((double)ut->getMaxEp() / (double)100)); + // TODO: SoftCoder - Fix the bug below on next major release + // if(ut->getMaxEpRegeneration() != 0) { if(ut->getMaxHpRegeneration() != 0) { maxEpRegeneration += ((double)unit->getType()->getEpRegeneration() + ((double)max(maxEp,unit->getEp()) * ((double)ut->getMaxEpRegeneration() / (double)100))); } diff --git a/source/glest_game/world/map.cpp b/source/glest_game/world/map.cpp index ff36aa502..4ab4c9c5e 100644 --- a/source/glest_game/world/map.cpp +++ b/source/glest_game/world/map.cpp @@ -913,7 +913,7 @@ bool Map::canMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, std::m } //} - if(unit == NULL || isBadHarvestPos == true) { + if(isBadHarvestPos == true) { if(lookupCache != NULL) { (*lookupCache)[pos1][pos2][size][field]=false; } @@ -1084,8 +1084,13 @@ bool Map::aproxCanMove(const Unit *unit, const Vec2i &pos1, const Vec2i &pos2, s Vec2i Map::computeRefPos(const Selection *selection) const { Vec2i total= Vec2i(0); + + if(selection == NULL) { + throw megaglest_runtime_error("selection == NULL"); + } + for(int i = 0; i < selection->getCount(); ++i) { - if(selection == NULL || selection->getUnit(i) == NULL) { + if(selection->getUnit(i) == NULL) { throw megaglest_runtime_error("selection == NULL || selection->getUnit(i) == NULL"); } total = total + selection->getUnit(i)->getPosNotThreadSafe(); diff --git a/source/glest_game/world/minimap.cpp b/source/glest_game/world/minimap.cpp index 20d4a1b93..e8533e3bb 100644 --- a/source/glest_game/world/minimap.cpp +++ b/source/glest_game/world/minimap.cpp @@ -99,7 +99,8 @@ void Minimap::init(int w, int h, const World *world, bool fogOfWar) { if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d] scaledW = %d, scaledH = %d, potW = %d, potH = %d\n",__FILE__,__FUNCTION__,__LINE__,scaledW,scaledH,potW,potH); fowTex->getPixmap()->init(potW, potH, 1); - fowTex->getPixmap()->setPixels(&f); + const float *fPtr = &f; + fowTex->getPixmap()->setPixels(fPtr); } if(SystemFlags::getSystemSettingType(SystemFlags::debugSystem).enabled) SystemFlags::OutputDebug(SystemFlags::debugSystem,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); diff --git a/source/glest_game/world/unit_updater.cpp b/source/glest_game/world/unit_updater.cpp index af71c3a62..9e2080a8b 100644 --- a/source/glest_game/world/unit_updater.cpp +++ b/source/glest_game/world/unit_updater.cpp @@ -212,7 +212,7 @@ bool UnitUpdater::updateUnit(Unit *unit) { else if(unit->getCommandSize() > 0) { Command *command= unit->getCurrCommand(); if(command != NULL) { - const CommandType *ct = (command != NULL ? command->getCommandType() : NULL); + const CommandType *ct = command->getCommandType(); const AttackCommandType *act= dynamic_cast(command->getCommandType()); if( act != NULL && act->getAttackSkillType() != NULL && @@ -1279,6 +1279,9 @@ void UnitUpdater::updateHarvest(Unit *unit, int frameIndex) { } const HarvestCommandType *hct= dynamic_cast(command->getCommandType()); + if(hct == NULL) { + throw megaglest_runtime_error("hct == NULL"); + } Vec2i targetPos(-1); //TravelState tsValue = tsImpossible; diff --git a/source/shared_lib/include/graphics/gl/text_renderer_gl.h b/source/shared_lib/include/graphics/gl/text_renderer_gl.h index 856ac645c..f17744a71 100644 --- a/source/shared_lib/include/graphics/gl/text_renderer_gl.h +++ b/source/shared_lib/include/graphics/gl/text_renderer_gl.h @@ -87,13 +87,17 @@ public: void begin() { if(this->renderer != NULL) { - if(dynamic_cast(renderer) != NULL) { - dynamic_cast(renderer)->begin(dynamic_cast(this->font)); + TextRenderer2DGl *txtrender2d = dynamic_cast(renderer); + if(txtrender2d != NULL) { + txtrender2d->begin(dynamic_cast(this->font)); mustEnd = true; } - if(dynamic_cast(renderer) != NULL) { - mustEnd = true; - dynamic_cast(renderer)->begin(dynamic_cast(this->font)); + else { + TextRenderer3DGl *txtrender3d = dynamic_cast(renderer); + if(txtrender3d != NULL) { + mustEnd = true; + txtrender3d->begin(dynamic_cast(this->font)); + } } } } diff --git a/source/shared_lib/include/graphics/model.h b/source/shared_lib/include/graphics/model.h index 47d75399f..e5323852f 100644 --- a/source/shared_lib/include/graphics/model.h +++ b/source/shared_lib/include/graphics/model.h @@ -298,7 +298,6 @@ private: static unsigned char nextColorID[COLOR_COMPONENTS]; static unsigned int nextColorRGB; static const unsigned int k, p; - //static Mutex mutexNextColorID; static bool using_loop_method; diff --git a/source/shared_lib/include/util/gen_uuid.h b/source/shared_lib/include/util/gen_uuid.h index 45dad2d8b..6ccce0bd3 100644 --- a/source/shared_lib/include/util/gen_uuid.h +++ b/source/shared_lib/include/util/gen_uuid.h @@ -176,7 +176,7 @@ inline static void get_random_info(char seed[16]) { seed[i++] = myrand >> 8; } while (i < 14); - fclose(fp); + if(fp != NULL) fclose(fp); } #endif diff --git a/source/shared_lib/sources/compression/compression_utils.cpp b/source/shared_lib/sources/compression/compression_utils.cpp index 53f1bd55b..b3818108d 100644 --- a/source/shared_lib/sources/compression/compression_utils.cpp +++ b/source/shared_lib/sources/compression/compression_utils.cpp @@ -254,6 +254,9 @@ int zipfile_tool(int argc, const char *argv[]) { } else { if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Invalid mode!\n"); + + if(pInfile) fclose(pInfile); + if(pOutfile) fclose(pOutfile); return EXIT_FAILURE; } diff --git a/source/shared_lib/sources/feathery_ftp/ftpTargetPosix.c b/source/shared_lib/sources/feathery_ftp/ftpTargetPosix.c index c1b483183..4c70986c5 100644 --- a/source/shared_lib/sources/feathery_ftp/ftpTargetPosix.c +++ b/source/shared_lib/sources/feathery_ftp/ftpTargetPosix.c @@ -300,6 +300,7 @@ socket_t ftpEstablishDataConnection(int passive, ip_t *ip, port_t *port, int ses myAddr.sin_family = AF_INET; myAddr.sin_addr.s_addr = INADDR_ANY; myAddr.sin_port = htons(passivePort); + myAddr.sin_zero[0] = 0; //myAddr.sin_port = htons(ftpGetPassivePort() + sessionId); if(setsockopt(dataSocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) @@ -396,6 +397,7 @@ socket_t ftpCreateServerSocket(int portNumber) struct sockaddr_in serverinfo; unsigned len; int val = 1; + int opt_result = 0; theServer = socket(AF_INET, SOCK_STREAM, 0); if(theServer < 0) @@ -404,13 +406,14 @@ socket_t ftpCreateServerSocket(int portNumber) serverinfo.sin_family = AF_INET; serverinfo.sin_addr.s_addr = INADDR_ANY; serverinfo.sin_port = htons(portNumber); + serverinfo.sin_zero[0] = 0; len = sizeof(serverinfo); - setsockopt(theServer, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); + opt_result = setsockopt(theServer, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); if(bind(theServer, (struct sockaddr *)&serverinfo, len)) { - if(VERBOSE_MODE_ENABLED) printf("\nERROR In ftpCreateServerSocket bind FAILED about to close listener socket = %d\n",theServer); + if(VERBOSE_MODE_ENABLED) printf("\nERROR In ftpCreateServerSocket bind FAILED about to close listener socket = %d opt_result = %d\n",theServer,opt_result); ftpUntrackSocket(theServer); ftpCloseSocket(&theServer); diff --git a/source/shared_lib/sources/graphics/font.cpp b/source/shared_lib/sources/graphics/font.cpp index 4e2cea080..2b62e8055 100644 --- a/source/shared_lib/sources/graphics/font.cpp +++ b/source/shared_lib/sources/graphics/font.cpp @@ -605,7 +605,7 @@ string findFontFamily(const char* font, const char *fontFamily) { fs = FcFontSetCreate(); match = FcFontMatch(0, pat, &result); - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Trying fontconfig for fontfamily [%s]\n",(fontFamily != NULL ? fontFamily : "null")); + if(SystemFlags::VERBOSE_MODE_ENABLED) printf("Trying fontconfig for fontfamily [%s]\n",fontFamily); if (match) FcFontSetAdd(fs, match); if (pat) FcPatternDestroy(pat); @@ -649,8 +649,9 @@ void CHECK_FONT_PATH(const char *filename,const char *fontFamily,const char **fo *font = strdup(*path); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 candidate font file has been set[%s]\n",(*font != NULL ? *font : "null")); } + *path = NULL; } - if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 Searching for font family [%s] result [%s]\n",(fontFamily != NULL ? fontFamily : "null"),(*font != NULL ? *font : "null")); + if(SystemFlags::VERBOSE_MODE_ENABLED) printf("#2 Searching for font family [%s] result [%s]\n",fontFamily,(*font != NULL ? *font : "null")); } } diff --git a/source/shared_lib/sources/graphics/gl/font_textFTGL.cpp b/source/shared_lib/sources/graphics/gl/font_textFTGL.cpp index 6ac066e95..4875f8e59 100644 --- a/source/shared_lib/sources/graphics/gl/font_textFTGL.cpp +++ b/source/shared_lib/sources/graphics/gl/font_textFTGL.cpp @@ -70,11 +70,12 @@ TextFTGL::TextFTGL(FontTextHandlerType type) : Text(type) { } if(ftFont->Error()) { - printf("FTGL: error loading font: %s\n", fontFile); + string fontFileName = (fontFile != NULL ? fontFile : "n/a"); + printf("FTGL: error loading font: %s\n", fontFileName.c_str()); delete ftFont; ftFont = NULL; - free((void*)fontFile); + if(fontFile != NULL) free((void*)fontFile); fontFile = NULL; - throw megaglest_runtime_error(string("FTGL: error loading font: ") + string(fontFile)); + throw megaglest_runtime_error(string("FTGL: error loading font: ") + fontFileName); } free((void*)fontFile); fontFile = NULL; diff --git a/source/shared_lib/sources/graphics/model.cpp b/source/shared_lib/sources/graphics/model.cpp index 4dc926796..7c0e61fab 100644 --- a/source/shared_lib/sources/graphics/model.cpp +++ b/source/shared_lib/sources/graphics/model.cpp @@ -537,7 +537,12 @@ void Mesh::loadV2(int meshIndex, const string &dir, FILE *f, TextureManager *tex } opacity = Shared::PlatformByteOrder::fromCommonEndian(opacity); - fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR); + int seek_result = fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR); + if(seek_result != 0) { + char szBuf[8096]=""; + snprintf(szBuf,8096,"fseek returned failure = %d [%u] on line: %d.",seek_result,indexCount,__LINE__); + throw megaglest_runtime_error(szBuf); + } readBytes = fread(indices, sizeof(uint32)*indexCount, 1, f); if(readBytes != 1 && indexCount != 0) { char szBuf[8096]=""; @@ -677,7 +682,13 @@ void Mesh::loadV3(int meshIndex, const string &dir, FILE *f, } opacity = Shared::PlatformByteOrder::fromCommonEndian(opacity); - fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR); + int seek_result = fseek(f, sizeof(Vec4f)*(meshHeader.colorFrameCount-1), SEEK_CUR); + if(seek_result != 0) { + char szBuf[8096]=""; + snprintf(szBuf,8096,"fseek returned failure = %d [%u] on line: %d.",seek_result,indexCount,__LINE__); + throw megaglest_runtime_error(szBuf); + } + readBytes = fread(indices, sizeof(uint32)*indexCount, 1, f); if(readBytes != 1 && indexCount != 0) { char szBuf[8096]=""; @@ -798,7 +809,10 @@ void Mesh::load(int meshIndex, const string &dir, FILE *f, TextureManager *textu } Shared::PlatformByteOrder::fromEndianTypeArray(cMapPath, mapPathSize); - string mapPath= toLower(reinterpret_cast(cMapPath)); + char mapPathString[mapPathSize+1]=""; + memset(&mapPathString[0],0,mapPathSize); + memcpy(&mapPathString[0],reinterpret_cast(cMapPath),mapPathSize); + string mapPath= toLower(mapPathString); if(SystemFlags::VERBOSE_MODE_ENABLED) printf("mapPath [%s] meshHeader.textures = %d flag = %d (meshHeader.textures & flag) = %d meshIndex = %d i = %d\n",mapPath.c_str(),meshHeader.textures,flag,(meshHeader.textures & flag),meshIndex,i); @@ -1074,6 +1088,7 @@ Model::Model() { meshCount = 0; meshes = NULL; + fileVersion = 0; textureManager = NULL; lastTData = -1; lastCycleData = false; @@ -1199,7 +1214,10 @@ void Model::loadG3d(const string &path, bool deletePixMapAfterLoad, if(strncmp(reinterpret_cast(fileHeader.id), "G3D", 3) != 0) { fclose(f); f = NULL; - printf("In [%s::%s] file = [%s] fileheader.id = [%s][%c]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,path.c_str(),reinterpret_cast(fileHeader.id),fileHeader.id[0]); + char fileType[4]=""; + memset(&fileType[0],0,4); + memcpy(&fileType[0],fileHeader.id,4); + printf("In [%s::%s] file = [%s] fileheader.id = [%s][%c]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,path.c_str(),fileType,fileHeader.id[0]); throw megaglest_runtime_error("Not a valid G3D model",true); } fileVersion= fileHeader.version; @@ -1833,7 +1851,6 @@ const unsigned int BaseColorPickEntity::p = 64007; const unsigned int BaseColorPickEntity::k = 43067; unsigned int BaseColorPickEntity::nextColorRGB = BaseColorPickEntity::k; -//Mutex BaseColorPickEntity::mutexNextColorID; unsigned char BaseColorPickEntity::nextColorID[COLOR_COMPONENTS] = { 1, 1, 1, 0 }; auto_ptr BaseColorPickEntity::pbo; @@ -1853,7 +1870,6 @@ BaseColorPickEntity::BaseColorPickEntity() { } bool BaseColorPickEntity::get_next_assign_color(unsigned char *assign_to) { - //MutexSafeWrapper safeMutex(&mutexNextColorID); if(assign_to == NULL) { throw megaglest_runtime_error("assign_to == NULL"); @@ -1969,7 +1985,6 @@ void BaseColorPickEntity::assign_color_using_loop(unsigned char *assign_to) { } void BaseColorPickEntity::recycleUniqueColor() { - //MutexSafeWrapper safeMutex(&mutexNextColorID); vector reUseColor; reUseColor.push_back(uniqueColorID[0]); @@ -1993,8 +2008,6 @@ void BaseColorPickEntity::recycleUniqueColor() { } void BaseColorPickEntity::resetUniqueColors() { - //MutexSafeWrapper safeMutex(&mutexNextColorID); - BaseColorPickEntity::nextColorRGB = BaseColorPickEntity::k; BaseColorPickEntity::nextColorID[0] = 1; diff --git a/source/shared_lib/sources/graphics/particle.cpp b/source/shared_lib/sources/graphics/particle.cpp index ca33174a0..11bab51eb 100644 --- a/source/shared_lib/sources/graphics/particle.cpp +++ b/source/shared_lib/sources/graphics/particle.cpp @@ -124,6 +124,7 @@ ParticleSystem::ParticleSystem(int particleCount) { particleSystemStartDelay= 0; this->particleOwner = NULL; + this->particleSize = 0.0f; } ParticleSystem::~ParticleSystem() { diff --git a/source/shared_lib/sources/graphics/pixmap.cpp b/source/shared_lib/sources/graphics/pixmap.cpp index c910e0073..80f480994 100644 --- a/source/shared_lib/sources/graphics/pixmap.cpp +++ b/source/shared_lib/sources/graphics/pixmap.cpp @@ -802,7 +802,7 @@ void Pixmap1D::init(int w, int components){ } uint64 Pixmap1D::getPixelByteCount() const { - return (w * components); + return ((uint64)w * (uint64)components); } void Pixmap1D::deletePixels() { @@ -955,7 +955,7 @@ void Pixmap2D::init(int w, int h, int components) { } uint64 Pixmap2D::getPixelByteCount() const { - return (h * w * components); + return ((uint64)h * (uint64)w * (uint64)components); } void Pixmap2D::deletePixels() { @@ -1456,7 +1456,7 @@ void Pixmap3D::init(int w, int h, int d, int components){ } uint64 Pixmap3D::getPixelByteCount() const { - return (h * w * d * components); + return ((uint64)h * (uint64)w * (uint64)d * (uint64)components); } void Pixmap3D::init(int d, int components){ diff --git a/source/shared_lib/sources/graphics/texture.cpp b/source/shared_lib/sources/graphics/texture.cpp index 412d6bb5e..fc8766f43 100644 --- a/source/shared_lib/sources/graphics/texture.cpp +++ b/source/shared_lib/sources/graphics/texture.cpp @@ -108,7 +108,7 @@ std::pair Texture2D::CreateSDLSurface(bool newPixel delete[] surfData; result.second = NULL; } - + else { // SDL_Surface *prepGLTexture(SDL_Surface *surface, GLfloat *texCoords = NULL, const bool // freeSource = false) { /* Use the surface width and height expanded to powers of 2 */ @@ -208,6 +208,7 @@ std::pair Texture2D::CreateSDLSurface(bool newPixel result.first = image; // } + } return result; } diff --git a/source/shared_lib/sources/miniz/miniz.c b/source/shared_lib/sources/miniz/miniz.c index 9b56d9ee9..9b83c3236 100644 --- a/source/shared_lib/sources/miniz/miniz.c +++ b/source/shared_lib/sources/miniz/miniz.c @@ -3264,8 +3264,10 @@ mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_ MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; - if (MZ_FSEEK64(pFile, 0, SEEK_END)) + if (MZ_FSEEK64(pFile, 0, SEEK_END)) { + MZ_FCLOSE(pFile); return MZ_FALSE; + } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { @@ -4379,8 +4381,10 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, if (uncomp_size <= 3) level = 0; - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) - return MZ_FALSE; + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); diff --git a/source/shared_lib/sources/platform/common/platform_common.cpp b/source/shared_lib/sources/platform/common/platform_common.cpp index afaae0163..de23be57c 100644 --- a/source/shared_lib/sources/platform/common/platform_common.cpp +++ b/source/shared_lib/sources/platform/common/platform_common.cpp @@ -145,7 +145,7 @@ Chrono::Chrono(bool autoStart) { lastResult = 0; lastMultiplier = 0; lastStopped = false; - + startCount = 0; if(autoStart == true) { start(); } @@ -204,11 +204,11 @@ int64 Chrono::queryCounter(int multiplier) { int64 result = 0; if(stopped) { - result = multiplier*accumCount/freq; + result = (int64)multiplier * (int64)(accumCount / freq); } else { Uint32 endCount = SDL_GetTicks(); - result = multiplier*(accumCount+endCount-startCount)/freq; + result = (int64)multiplier * (int64)((accumCount + endCount - startCount) / freq); lastTickCount = endCount; } diff --git a/source/shared_lib/sources/platform/posix/miniftpclient.cpp b/source/shared_lib/sources/platform/posix/miniftpclient.cpp index 8e3e0ab97..adcd6acfd 100644 --- a/source/shared_lib/sources/platform/posix/miniftpclient.cpp +++ b/source/shared_lib/sources/platform/posix/miniftpclient.cpp @@ -1203,7 +1203,7 @@ void FTPClientThread::execute() { getTempFileFromServer(file); } else { - safeMutex5.ReleaseLock(); + safeMutex6.ReleaseLock(); } if(this->getQuitStatus() == false) { diff --git a/source/shared_lib/sources/platform/posix/socket.cpp b/source/shared_lib/sources/platform/posix/socket.cpp index 7727ff12a..9de53f26c 100644 --- a/source/shared_lib/sources/platform/posix/socket.cpp +++ b/source/shared_lib/sources/platform/posix/socket.cpp @@ -809,6 +809,8 @@ Socket::Socket() { dataSynchAccessorWrite = new Mutex(); inSocketDestructorSynchAccessor = new Mutex(); lastSocketError = 0; + lastDebugEvent = 0; + lastThreadedPing = 0; MutexSafeWrapper safeMutexSocketDestructorFlag(inSocketDestructorSynchAccessor,CODE_AT_LINE); inSocketDestructorSynchAccessor->setOwnerId(CODE_AT_LINE); @@ -1466,6 +1468,7 @@ int Socket::receive(void *data, int dataSize, bool tryReceiveUntilDataSizeMet) { SafeSocketBlockToggleWrapper::SafeSocketBlockToggleWrapper(Socket *socket, bool toggle) { this->socket = socket; + if(this->socket != NULL) { this->originallyBlocked = socket->getBlock(); this->newBlocked = toggle; @@ -1474,6 +1477,10 @@ SafeSocketBlockToggleWrapper::SafeSocketBlockToggleWrapper(Socket *socket, bool socket->setBlock(this->newBlocked); } } + else { + this->originallyBlocked = false; + this->newBlocked = false; + } } void SafeSocketBlockToggleWrapper::Restore() { @@ -2068,15 +2075,15 @@ void BroadCastClientSocketThread::execute() { int val = 1; #ifndef WIN32 - setsockopt(bcfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); + int opt_result = setsockopt(bcfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); #else - setsockopt(bcfd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val)); + int opt_result = setsockopt(bcfd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val)); #endif if(::bind( bcfd, (struct sockaddr *)&bcaddr, sizeof(bcaddr) ) < 0 ) { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"bind failed: %s\n", Socket::getLastSocketErrorFormattedText().c_str()); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"bind failed: %s opt_result = %d\n", Socket::getLastSocketErrorFormattedText().c_str(),opt_result); } else { - if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d]\n",__FILE__,__FUNCTION__,__LINE__); + if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"In [%s::%s Line: %d] opt_result = %d\n",__FILE__,__FUNCTION__,__LINE__,opt_result); Socket::setBlock(false, bcfd); @@ -2314,19 +2321,20 @@ void ServerSocket::bind(int port) { addr.sin_addr.s_addr= INADDR_ANY; } addr.sin_port= htons(port); + addr.sin_zero[0] = 0; int val = 1; #ifndef WIN32 - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); + int opt_result = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)); #else - setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val)); + int opt_result = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val)); #endif int err= ::bind(sock, reinterpret_cast(&addr), sizeof(addr)); if(err < 0) { char szBuf[8096]=""; - snprintf(szBuf, 8096,"In [%s::%s] Error binding socket sock = " PLATFORM_SOCKET_FORMAT_TYPE ", address [%s] port = %d err = %d, error = %s\n",__FILE__,__FUNCTION__,sock,this->bindSpecificAddress.c_str(),port,err,getLastSocketErrorFormattedText().c_str()); + snprintf(szBuf, 8096,"In [%s::%s] Error binding socket sock = " PLATFORM_SOCKET_FORMAT_TYPE ", address [%s] port = %d err = %d, error = %s opt_result = %d\n",__FILE__,__FUNCTION__,sock,this->bindSpecificAddress.c_str(),port,err,getLastSocketErrorFormattedText().c_str(),opt_result); if(SystemFlags::getSystemSettingType(SystemFlags::debugNetwork).enabled) SystemFlags::OutputDebug(SystemFlags::debugNetwork,"%s",szBuf); snprintf(szBuf, 8096,"Error binding socket sock = %d, address [%s] port = %d err = %d, error = %s\n",sock,this->bindSpecificAddress.c_str(),port,err,getLastSocketErrorFormattedText().c_str()); @@ -2399,8 +2407,8 @@ Socket *ServerSocket::accept(bool errorOnFail) { PLATFORM_SOCKET newSock=0; char client_host[100]=""; - const int max_attempts = 100; - for(int attempt = 0; attempt < max_attempts; ++attempt) { + //const int max_attempts = 100; + //for(int attempt = 0; attempt < max_attempts; ++attempt) { struct sockaddr_in cli_addr; socklen_t clilen = sizeof(cli_addr); client_host[0]='\0'; @@ -2415,12 +2423,12 @@ Socket *ServerSocket::accept(bool errorOnFail) { int lastSocketError = getLastSocketError(); if(lastSocketError == PLATFORM_SOCKET_TRY_AGAIN) { - if(attempt+1 >= max_attempts) { - return NULL; - } - else { + //if(attempt+1 >= max_attempts) { + // return NULL; + //} + //else { sleep(0); - } + //} } if(errorOnFail == true) { throwException(szBuf); @@ -2448,8 +2456,8 @@ Socket *ServerSocket::accept(bool errorOnFail) { return NULL; } - break; - } + //break; + //} Socket *result = new Socket(newSock); result->setIpAddress((client_host[0] != '\0' ? client_host : "")); return result; diff --git a/source/shared_lib/sources/platform/sdl/platform_util.cpp b/source/shared_lib/sources/platform/sdl/platform_util.cpp index 4885df6a2..69bd92a3a 100644 --- a/source/shared_lib/sources/platform/sdl/platform_util.cpp +++ b/source/shared_lib/sources/platform/sdl/platform_util.cpp @@ -68,32 +68,33 @@ const char * getDialogCommand() { } bool showMessage(std::string warning,string writepath) { - bool guiMessage = false; - const char * dialogCommand = getDialogCommand(); - if (dialogCommand) { - std::string command = dialogCommand; + bool guiMessage = false; + const char * dialogCommand = getDialogCommand(); + if (dialogCommand) { + std::string command = dialogCommand; - string text_file = writepath + "/mg_dialog_text.txt"; - { - FILE *fp = fopen(text_file.c_str(),"wt"); - if (fp != NULL) { - fputs(warning.c_str(),fp); - fclose(fp); + string text_file = writepath + "/mg_dialog_text.txt"; + { + FILE *fp = fopen(text_file.c_str(),"wt"); + if (fp != NULL) { + fputs(warning.c_str(),fp); + fclose(fp); + } } - } - //command += " --title \"Error\" --msgbox \"`printf \"" + warning + "\"`\""; - command += " --title \"Error\" --text-info --filename=" + text_file; + //command += " --title \"Error\" --msgbox \"`printf \"" + warning + "\"`\""; + command += " --title \"Error\" --text-info --filename=" + text_file; - //printf("\n\n\nzenity command [%s]\n\n\n",command.c_str()); + //printf("\n\n\nzenity command [%s]\n\n\n",command.c_str()); - FILE *fp = popen(command.c_str(),"r"); - if (fp != 0) - guiMessage = true; - pclose(fp); - } + FILE *fp = popen(command.c_str(),"r"); + if (fp != 0) { + guiMessage = true; + pclose(fp); + } + } - return guiMessage; + return guiMessage; } void message(string message, bool isNonGraphicalModeEnabled,string writepath) { diff --git a/source/shared_lib/sources/platform/sdl/thread.cpp b/source/shared_lib/sources/platform/sdl/thread.cpp index 9cddeaf74..dc434dd87 100644 --- a/source/shared_lib/sources/platform/sdl/thread.cpp +++ b/source/shared_lib/sources/platform/sdl/thread.cpp @@ -107,7 +107,7 @@ public: sleep(10); if(base_thread->getRunningStatus() == true || base_thread->getExecutingTask() == true) { - if(Thread::getEnableVerboseMode()) printf("\n\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$ cleanupPendingThread Line: %d thread = %p [%s]\n",__LINE__,thread,(base_thread != NULL ? base_thread->getUniqueID().c_str() : "n/a")); + if(Thread::getEnableVerboseMode()) printf("\n\n\n$$$$$$$$$$$$$$$$$$$$$$$$$$$ cleanupPendingThread Line: %d thread = %p [%s]\n",__LINE__,thread,base_thread->getUniqueID().c_str()); char szBuf[8096]=""; snprintf(szBuf,8095,"In [%s::%s Line: %d] cannot delete active thread: getRunningStatus(): %d getExecutingTask: %d\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,base_thread->getRunningStatus(),base_thread->getExecutingTask()); @@ -118,8 +118,9 @@ public: if(Thread::getEnableVerboseMode()) printf("!!!! cleanupPendingThread Line: %d thread = %p [%s]\n",__LINE__,thread,(base_thread != NULL ? base_thread->getUniqueID().c_str() : "n/a")); delete thread; + thread = NULL; - if(Thread::getEnableVerboseMode()) printf("!!!! cleanupPendingThread Line: %d thread = %p [%s]\n",__LINE__,thread,(base_thread != NULL ? base_thread->getUniqueID().c_str() : "n/a")); + if(Thread::getEnableVerboseMode()) printf("!!!! cleanupPendingThread Line: %d thread = NULL [%s]\n",__LINE__,(base_thread != NULL ? base_thread->getUniqueID().c_str() : "n/a")); } } diff --git a/source/shared_lib/sources/sound/openal/sound_player_openal.cpp b/source/shared_lib/sources/sound/openal/sound_player_openal.cpp index 511e28667..cdc18c62b 100644 --- a/source/shared_lib/sources/sound/openal/sound_player_openal.cpp +++ b/source/shared_lib/sources/sound/openal/sound_player_openal.cpp @@ -182,6 +182,7 @@ StreamSoundSource::StreamSoundSource() sound = 0; fadeState = NoFading; format = 0; + fade = 0; alGenBuffers(STREAMFRAGMENTS, buffers); SoundPlayerOpenAL::checkAlError(string(__FILE__) + string(" ") + string(__FUNCTION__) + string(" ") + intToStr(__LINE__)); } diff --git a/source/shared_lib/sources/sound/sound.cpp b/source/shared_lib/sources/sound/sound.cpp index 4a47cca88..2dbb2ced7 100644 --- a/source/shared_lib/sources/sound/sound.cpp +++ b/source/shared_lib/sources/sound/sound.cpp @@ -81,16 +81,16 @@ void StaticSound::load(const string &path) { string ext= path.substr(path.find_last_of('.')+1); soundFileLoader= SoundFileLoaderFactory::getInstance()->newInstance(ext); + if(soundFileLoader == NULL) { + throw megaglest_runtime_error("soundFileLoader == NULL"); + } soundFileLoader->open(path, &info); samples= new int8[info.getSize()]; soundFileLoader->read(samples, info.getSize()); soundFileLoader->close(); - if(soundFileLoader!=NULL){ - soundFileLoader->close(); - delete soundFileLoader; - soundFileLoader= NULL; - } + delete soundFileLoader; + soundFileLoader= NULL; } // ===================================================== diff --git a/source/shared_lib/sources/util/properties.cpp b/source/shared_lib/sources/util/properties.cpp index 8c8162d06..3e7411fc2 100644 --- a/source/shared_lib/sources/util/properties.cpp +++ b/source/shared_lib/sources/util/properties.cpp @@ -426,15 +426,16 @@ int Properties::getInt(const string &key, int min, int max,const char *defaultVa } float Properties::getFloat(const string &key, const char *defaultValueIfNotFound) const{ + float result = 0.0; try{ - return strToFloat(getString(key,defaultValueIfNotFound)); + result = strToFloat(getString(key,defaultValueIfNotFound)); } catch(exception &e){ SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); //throw megaglest_runtime_error("Error accessing value: " + key + " in: " + path + "\n[" + e.what() + "]"); throw runtime_error("Error accessing value: " + key + " in: " + path + "\n[" + e.what() + "]"); } - return 0.0; + return result; } float Properties::getFloat(const string &key, float min, float max, const char *defaultValueIfNotFound) const{ @@ -543,15 +544,16 @@ int Properties::getInt(const char *key,const char *defaultValueIfNotFound) const } float Properties::getFloat(const char *key, const char *defaultValueIfNotFound) const{ + float result = 0.0; try{ - return strToFloat(getString(key,defaultValueIfNotFound)); + result = strToFloat(getString(key,defaultValueIfNotFound)); } catch(exception &e){ SystemFlags::OutputDebug(SystemFlags::debugError,"In [%s::%s Line: %d] Error [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,e.what()); //throw megaglest_runtime_error("Error accessing value: " + string(key) + " in: " + path + "\n[" + e.what() + "]"); throw runtime_error("Error accessing value: " + string(key) + " in: " + path + "\n[" + e.what() + "]"); } - return 0.0; + return result; } const string Properties::getString(const char *key, const char *defaultValueIfNotFound) const{ diff --git a/source/shared_lib/sources/util/util.cpp b/source/shared_lib/sources/util/util.cpp index 731670091..fca042a4c 100644 --- a/source/shared_lib/sources/util/util.cpp +++ b/source/shared_lib/sources/util/util.cpp @@ -378,7 +378,10 @@ void SystemFlags::Close() { SystemFlags::lockFileCountIndex = -1; if(SystemFlags::lockfilename != "") { - remove(SystemFlags::lockfilename.c_str()); + bool remove_result = remove(SystemFlags::lockfilename.c_str()); + + if(SystemFlags::VERBOSE_MODE_ENABLED) printf("In [%s::%s Line: %d] remove_result = %d for file [%s]\n",extractFileFromDirectoryPath(__FILE__).c_str(),__FUNCTION__,__LINE__,remove_result,SystemFlags::lockfilename.c_str()); + SystemFlags::lockfilename = ""; } } @@ -468,18 +471,20 @@ void SystemFlags::logDebugEntry(DebugType type, string debugEntry, time_t debugT // If the file is already open (shared) by another debug type // do not over-write the file but share the stream pointer - for(std::map::iterator iterMap = SystemFlags::debugLogFileList->begin(); - iterMap != SystemFlags::debugLogFileList->end(); ++iterMap) { - SystemFlags::SystemFlagsType ¤tDebugLog2 = iterMap->second; + if(SystemFlags::debugLogFileList != NULL) { + for(std::map::iterator iterMap = SystemFlags::debugLogFileList->begin(); + iterMap != SystemFlags::debugLogFileList->end(); ++iterMap) { + SystemFlags::SystemFlagsType ¤tDebugLog2 = iterMap->second; - if( iterMap->first != type && - currentDebugLog.debugLogFileName == currentDebugLog2.debugLogFileName && - currentDebugLog2.fileStream != NULL) { - currentDebugLog.fileStream = currentDebugLog2.fileStream; - currentDebugLog.fileStreamOwner = false; - currentDebugLog.mutex = currentDebugLog2.mutex; - break; - } + if( iterMap->first != type && + currentDebugLog.debugLogFileName == currentDebugLog2.debugLogFileName && + currentDebugLog2.fileStream != NULL) { + currentDebugLog.fileStream = currentDebugLog2.fileStream; + currentDebugLog.fileStreamOwner = false; + currentDebugLog.mutex = currentDebugLog2.mutex; + break; + } + } } string debugLog = currentDebugLog.debugLogFileName; diff --git a/source/tests/shared_lib/xml/xml_parser_test.cpp b/source/tests/shared_lib/xml/xml_parser_test.cpp index 3267dcf6e..ca94e4f31 100644 --- a/source/tests/shared_lib/xml/xml_parser_test.cpp +++ b/source/tests/shared_lib/xml/xml_parser_test.cpp @@ -104,7 +104,8 @@ public: CPPUNIT_ASSERT_EQUAL( false, newInstance.isInitialized() ); } void test_load_file_missing() { - XmlIo::getInstance().load("/some/path/that/does/not exist", std::map()); + XmlNode *rootNode = XmlIo::getInstance().load("/some/path/that/does/not exist", std::map()); + delete rootNode; } void test_load_file_valid() { const string test_filename = "xml_test_valid.xml"; @@ -115,13 +116,16 @@ public: CPPUNIT_ASSERT( rootNode != NULL ); CPPUNIT_ASSERT_EQUAL( string("menu"), rootNode->getName() ); + + delete rootNode; } void test_load_file_malformed_content() { const string test_filename = "xml_test_malformed.xml"; createMalformedXMLTestFile(test_filename); SafeRemoveTestFile deleteFile(test_filename); - XmlIo::getInstance().load(test_filename, std::map()); + XmlNode *rootNode = XmlIo::getInstance().load(test_filename, std::map()); + delete rootNode; } void test_save_file_null_node() { @@ -139,6 +143,8 @@ public: XmlIo::getInstance().save(test_filename_save,rootNode); SafeRemoveTestFile deleteFile2(test_filename_save); + + delete rootNode; } }; @@ -174,7 +180,8 @@ public: CPPUNIT_ASSERT_EQUAL( false, newInstance.isInitialized() ); } void test_load_file_missing() { - XmlIoRapid::getInstance().load("/some/path/that/does/not exist", std::map()); + XmlNode *rootNode = XmlIoRapid::getInstance().load("/some/path/that/does/not exist", std::map()); + delete rootNode; } void test_load_file_valid() { const string test_filename = "xml_test_valid.xml"; @@ -185,12 +192,15 @@ public: CPPUNIT_ASSERT( rootNode != NULL ); CPPUNIT_ASSERT_EQUAL( string("menu"), rootNode->getName() ); + + delete rootNode; } void test_load_file_malformed_content() { const string test_filename = "xml_test_malformed.xml"; createMalformedXMLTestFile(test_filename); SafeRemoveTestFile deleteFile(test_filename); - XmlIoRapid::getInstance().load(test_filename, std::map()); + XmlNode *rootNode = XmlIoRapid::getInstance().load(test_filename, std::map()); + delete rootNode; } void test_save_file_null_node() { @@ -208,6 +218,8 @@ public: XmlIoRapid::getInstance().save(test_filename_save,rootNode); SafeRemoveTestFile deleteFile2(test_filename_save); + + delete rootNode; } };