Browse Source

* Code convention updates * Default values for CMap types * Updated BinaryReader c-tor * Converted "bool" int types to bool in CMap classes * Removed map event operators in favor of member methods

beegee1 13 years ago
parent
commit
105083dd70

+ 6 - 6
AI/VCAI/VCAI.cpp

@@ -2749,7 +2749,7 @@ TSubgoal CGoal::whatToDoToAchieve()
 			switch(cond)
 			{
 			case EVictoryConditionType::ARTIFACT:
-				return CGoal(GET_ART_TYPE).setaid(vc.ID);
+                return CGoal(GET_ART_TYPE).setaid(vc.objectId);
 			case EVictoryConditionType::BEATHERO:
 				return CGoal(GET_OBJ).setobjid(vc.obj->id);
 			case EVictoryConditionType::BEATMONSTER:
@@ -2800,12 +2800,12 @@ TSubgoal CGoal::whatToDoToAchieve()
 			case EVictoryConditionType::CAPTURECITY:
 				return CGoal(GET_OBJ).setobjid(vc.obj->id);
 			case EVictoryConditionType::GATHERRESOURCE:
-				return CGoal(COLLECT_RES).setresID(vc.ID).setvalue(vc.count);
+                return CGoal(COLLECT_RES).setresID(vc.objectId).setvalue(vc.count);
 				//TODO mines? piles? marketplace?
 				//save?
 				break;
 			case EVictoryConditionType::GATHERTROOP:
-				return CGoal(GATHER_TROOPS).setobjid(vc.ID).setvalue(vc.count);
+                return CGoal(GATHER_TROOPS).setobjid(vc.objectId).setvalue(vc.count);
 				break;
 			case EVictoryConditionType::TAKEDWELLINGS:
 				break;
@@ -3422,7 +3422,7 @@ bool CGoal::invalid() const
 
 bool isBlockedBorderGate(int3 tileToHit)
 {
-	return cb->getTile(tileToHit)->topVisitableID() == Obj::BORDER_GATE
+    return cb->getTile(tileToHit)->topVisitableId() == Obj::BORDER_GATE
 		&& cb->getPathInfo(tileToHit)->accessible != CGPathNode::ACCESSIBLE;
 }
 
@@ -3480,7 +3480,7 @@ bool canBeEmbarkmentPoint(const TerrainTile *t)
 {
 	//tile must be free of with unoccupied boat
 	return !t->blocked
-		|| (t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT);
+        || (t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT);
 }
 
 void SectorMap::exploreNewSector(crint3 pos, int num)
@@ -3726,7 +3726,7 @@ int3 SectorMap::firstTileToGet(HeroPtr h, crint3 dst)
 				auto firstEP = boost::find_if(src->embarkmentPoints, [=](crint3 pos) -> bool
 				{
 					const TerrainTile *t = cb->getTile(pos);
-					return t && t->visitableObjects.size() == 1 && t->topVisitableID() == Obj::BOAT
+                    return t && t->visitableObjects.size() == 1 && t->topVisitableId() == Obj::BOAT
 						&& retreiveTile(pos) == sectorToReach->id;
 				});
 

+ 2 - 2
client/AdventureMapClasses.cpp

@@ -370,9 +370,9 @@ const SDL_Color & CMinimapInstance::getTileColor(const int3 & pos)
 
 	// else - use terrain color (blocked version or normal)
 	if (tile->blocked && (!tile->visitable))
-		return parent->colors.find(tile->tertype)->second.second;
+		return parent->colors.find(tile->terType)->second.second;
 	else
-		return parent->colors.find(tile->tertype)->second.first;
+		return parent->colors.find(tile->terType)->second.first;
 }
 void CMinimapInstance::tileToPixels (const int3 &tile, int &x, int &y, int toX, int toY)
 {

+ 1 - 1
client/BattleInterface/CBattleInterface.cpp

@@ -458,7 +458,7 @@ CBattleInterface::~CBattleInterface()
 
 	if(adventureInt && adventureInt->selection)
 	{
-		int terrain = LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->tertype;
+		int terrain = LOCPLINT->cb->getTile(adventureInt->selection->visitablePos())->terType;
 		CCS->musich->playMusicFromSet("terrain", terrain, true);
 	}
 }

+ 2 - 2
client/CAdvmapInterface.cpp

@@ -988,7 +988,7 @@ void CAdvMapInt::select(const CArmedInstance *sel, bool centerView /*= true*/)
 		auto pos = sel->visitablePos();
 		auto tile = LOCPLINT->cb->getTile(pos);
 		if(tile)
-			CCS->musich->playMusicFromSet("terrain", tile->tertype, true);
+			CCS->musich->playMusicFromSet("terrain", tile->terType, true);
 	}
 	if(centerView)
 		centerOn(sel);
@@ -1385,7 +1385,7 @@ void CAdvMapInt::tileHovered(const int3 &mapPos)
 				{
 					if(pnode->land)
 					{
-                        if(LOCPLINT->cb->getTile(h->getPosition(false))->tertype != ETerrainType::WATER)
+                        if(LOCPLINT->cb->getTile(h->getPosition(false))->terType != ETerrainType::WATER)
 							CCS->curh->changeGraphic(0, 4 + turns*6);
 						else
 							CCS->curh->changeGraphic(0, 7 + turns*6); //anchor

+ 2 - 2
client/CPlayerInterface.cpp

@@ -256,7 +256,7 @@ void CPlayerInterface::heroMoved(const TryMoveHero & details)
 	if(makingTurn  &&  ho->tempOwner == playerID) //we are moving our hero - we may need to update assigned path
 	{
 		//We may need to change music - select new track, music handler will change it if needed
-		CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(ho->visitablePos())->tertype, true);
+		CCS->musich->playMusicFromSet("terrain", LOCPLINT->cb->getTile(ho->visitablePos())->terType, true);
 
 		if(details.result == TryMoveHero::TELEPORTATION)
 		{
@@ -1249,7 +1249,7 @@ bool CPlayerInterface::moveHero( const CGHeroInstance *h, CGPath path )
 					sh = CCS->soundh->playSound(soundBase::horseFlying, -1);
 #endif
 				{
-					newTerrain = cb->getTile(CGHeroInstance::convertPosition(path.nodes[i].coord, false))->tertype;
+					newTerrain = cb->getTile(CGHeroInstance::convertPosition(path.nodes[i].coord, false))->terType;
 
 					if (newTerrain != currentTerrain)
 					{

+ 2 - 2
client/CPreGame.cpp

@@ -2057,9 +2057,9 @@ void OptionsTab::recreate()
 	for(auto it = SEL->sInfo.playerInfos.begin(); it != SEL->sInfo.playerInfos.end(); ++it)
 	{
 		entries.insert(std::make_pair(it->first, new PlayerOptionsEntry(this, it->second)));
-		const std::vector<SheroName> &heroes = SEL->current->mapHeader->players[it->first].heroesNames;
+        const std::vector<SHeroName> &heroes = SEL->current->mapHeader->players[it->first].heroesNames;
 		for(size_t hi=0; hi<heroes.size(); hi++)
-			usedHeroes.insert(heroes[hi].heroID);
+            usedHeroes.insert(heroes[hi].heroId);
 	}
 
 }

+ 7 - 4
client/GUIClasses.cpp

@@ -5641,11 +5641,14 @@ CThievesGuildWindow::CThievesGuildWindow(const CGObjectInstance * _owner):
 	BOOST_FOREACH(auto & it, tgi.personality)
 	{
 		std::string text;
-		if(it.second == -1)
+        if(it.second == EAiTactic::NONE)
+        {
 			text = CGI->generaltexth->arraytxt[172];
-		else
-		if (it.second)
-			text = CGI->generaltexth->arraytxt[168 + it.second];
+        }
+        else if(it.second != EAiTactic::RANDOM)
+        {
+            text = CGI->generaltexth->arraytxt[168 + it.second];
+        }
 
 		new CLabel(283 + 66*counter, 459, FONT_SMALL, CENTER, Colors::Cornsilk, text);
 

+ 5 - 5
client/mapHandler.cpp

@@ -504,7 +504,7 @@ void CMapHandler::terrainRect( int3 top_tile, ui8 anim, const std::vector< std::
 			}
 			else //use default terrain graphic
 			{
-                blitterWithRotation(terrainGraphics[tinfo.tertype][tinfo.terview],rtile, extSurf, sr, tinfo.extTileFlags%4);
+                blitterWithRotation(terrainGraphics[tinfo.terType][tinfo.terView],rtile, extSurf, sr, tinfo.extTileFlags%4);
 			}
             if(tinfo.riverType) //print river if present
 			{
@@ -512,15 +512,15 @@ void CMapHandler::terrainRect( int3 top_tile, ui8 anim, const std::vector< std::
 			}
 
 			//Roads are shifted by 16 pixels to bottom. We have to draw both parts separately
-            if (pos.y > 0 && map->terrain[pos.x][pos.y-1][pos.z].roadType)
+            if (pos.y > 0 && map->terrain[pos.x][pos.y-1][pos.z].roadType != ERoadType::NO_ROAD)
 			{ //part from top tile
 				const TerrainTile &topTile = map->terrain[pos.x][pos.y-1][pos.z];
 				Rect source(0, 16, 32, 16);
 				Rect dest(sr.x, sr.y, sr.w, sr.h/2);
-                blitterWithRotationAndAlpha(roadDefs[topTile.roadType-1]->ourImages[topTile.roadDir].bitmap, source, extSurf, dest, (topTile.extTileFlags>>4)%4);
+                blitterWithRotationAndAlpha(roadDefs[topTile.roadType - 1]->ourImages[topTile.roadDir].bitmap, source, extSurf, dest, (topTile.extTileFlags>>4)%4);
 			}
 
-            if(tinfo.roadType) //print road from this tile
+            if(tinfo.roadType != ERoadType::NO_ROAD) //print road from this tile
 			{
 				Rect source(0, 0, 32, 32);
 				Rect dest(sr.x, sr.y+16, sr.w, sr.h/2);
@@ -1106,7 +1106,7 @@ void CMapHandler::getTerrainDescr( const int3 &pos, std::string & out, bool terN
 	if(t.hasFavourableWinds())
 		out = CGI->generaltexth->names[Obj::FAVORABLE_WINDS];
 	else if(terName)
-		out = CGI->generaltexth->terrainNames[t.tertype];
+        out = CGI->generaltexth->terrainNames[t.terType];
 }
 
 TerrainTile2::TerrainTile2()

+ 25 - 25
lib/CGameState.cpp

@@ -770,7 +770,7 @@ CGameState::~CGameState()
 BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
 {
 	const TerrainTile &t = map->getTile(tile);
-	int terrain = t.tertype;
+    int terrain = t.terType;
 	if(t.isCoastal() && !t.isWater()) 
         terrain = ETerrainType::SAND;
 
@@ -929,8 +929,8 @@ void CGameState::init(StartInfo * si)
  					const TerrainTile &t = map->terrain[i][j][k];
  					if(!t.blocked
 						&& !t.visitable
-                        && t.tertype != ETerrainType::WATER
-                        && t.tertype != ETerrainType::ROCK
+                        && t.terType != ETerrainType::WATER
+                        && t.terType != ETerrainType::ROCK
 						&& map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  						allowedPos.push_back(int3(i,j,k));
  				}
@@ -1209,7 +1209,7 @@ void CGameState::init(StartInfo * si)
 
 	for(ui32 i=0; i<map->disposedHeroes.size(); i++)
 	{
-		hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
+        hpool.pavailable[map->disposedHeroes[i].heroId] = map->disposedHeroes[i].players;
 	}
 
 	if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
@@ -1670,7 +1670,7 @@ int CGameState::battleGetBattlefieldType(int3 tile) const
 	if(!t.isWater() && t.isCoastal())
 		return 1; //sand/beach
 
-	switch(t.tertype)
+    switch(t.terType)
 	{
     case ETerrainType::DIRT:
 		return rand()%3+3;
@@ -1822,19 +1822,19 @@ void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<i
 // 			continue;
 // 		}
 
-        if(srct.tertype == ETerrainType::WATER && limitCoastSailing && hlpt.tertype == ETerrainType::WATER && dirs[i].x && dirs[i].y) //diagonal move through water
+        if(srct.terType == ETerrainType::WATER && limitCoastSailing && hlpt.terType == ETerrainType::WATER && dirs[i].x && dirs[i].y) //diagonal move through water
 		{
 			int3 hlp1 = tile,
 				hlp2 = tile;
 			hlp1.x += dirs[i].x;
 			hlp2.y += dirs[i].y;
 
-            if(map->getTile(hlp1).tertype != ETerrainType::WATER || map->getTile(hlp2).tertype != ETerrainType::WATER)
+            if(map->getTile(hlp1).terType != ETerrainType::WATER || map->getTile(hlp2).terType != ETerrainType::WATER)
 				continue;
 		}
 
-        if((indeterminate(onLand)  ||  onLand == (hlpt.tertype!=ETerrainType::WATER) )
-            && hlpt.tertype != ETerrainType::ROCK)
+        if((indeterminate(onLand)  ||  onLand == (hlpt.terType!=ETerrainType::WATER) )
+            && hlpt.terType != ETerrainType::ROCK)
 		{
 			vec.push_back(hlp);
 		}
@@ -1861,7 +1861,7 @@ int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const
 			ret *= 1.4; //40% penalty for movement over blocked tile
 		}
 	}
-    else if (d.tertype == ETerrainType::WATER)
+    else if (d.terType == ETerrainType::WATER)
 	{
 		if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
 			ret *= 0.666;
@@ -1885,7 +1885,7 @@ int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const
 	if(checkLast  &&  left > 0  &&  remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
 	{
 		std::vector<int3> vec;
-        getNeighbours(d, dest, vec, s.tertype != ETerrainType::WATER, true);
+        getNeighbours(d, dest, vec, s.terType != ETerrainType::WATER, true);
 		for(size_t i=0; i < vec.size(); i++)
 		{
 			int fcost = getMovementCost(h,dest,vec[i],left,false);
@@ -1955,7 +1955,7 @@ int3 CGameState::guardingCreaturePosition (int3 pos) const
 			if (map->isInTheMap(pos))
 			{
 				TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
-                if (tile.visitable && (tile.tertype == ETerrainType::WATER) == (posTile.tertype == ETerrainType::WATER))
+                if (tile.visitable && (tile.terType == ETerrainType::WATER) == (posTile.terType == ETerrainType::WATER))
 				{
 					BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
 					{
@@ -2081,7 +2081,7 @@ int CGameState::victoryCheck( ui8 player ) const
 		case EVictoryConditionType::ARTIFACT:
 			//check if any hero has winning artifact
 			for(size_t i = 0; i < p->heroes.size(); i++)
-				if(p->heroes[i]->hasArt(map->victoryCondition.ID))
+                if(p->heroes[i]->hasArt(map->victoryCondition.objectId))
 					return 1;
 
 			break;
@@ -2098,7 +2098,7 @@ int CGameState::victoryCheck( ui8 player ) const
 						&&  (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
 					{
 						for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
-							if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
+                            if(i->second->type->idNumber == map->victoryCondition.objectId) //it's searched creature
 								total += i->second->count;
 					}
 				}
@@ -2109,7 +2109,7 @@ int CGameState::victoryCheck( ui8 player ) const
 			break;
 
 		case EVictoryConditionType::GATHERRESOURCE:
-			if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
+            if(p->resources[map->victoryCondition.objectId] >= map->victoryCondition.count)
 				return 1;
 
 			break;
@@ -2117,7 +2117,7 @@ int CGameState::victoryCheck( ui8 player ) const
 		case EVictoryConditionType::BUILDCITY:
 			{
 				const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
-				if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
+                if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.objectId && t->hallLevel()-1 >= map->victoryCondition.count)
 					return 1;
 			}
 			break;
@@ -2176,8 +2176,8 @@ int CGameState::victoryCheck( ui8 player ) const
 		case EVictoryConditionType::TRANSPORTITEM:
 			{
 				const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
-				if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
-					|| (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
+                if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.objectId))
+                    || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.objectId)))
 				{
 					return 1;
 				}
@@ -2370,11 +2370,11 @@ void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
 				continue;
 			if(g->second.human)
 			{
-				tgi.personality[g->second.color] = -1;
+                tgi.personality[g->second.color] = EAiTactic::NONE;
 			}
 			else //AI
 			{
-				tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
+                tgi.personality[g->second.color] = map->players[g->second.color].aiTactic;
 			}
 
 		}
@@ -2931,7 +2931,7 @@ void CPathfinder::initializeGraph()
 				node.coord.x = i;
 				node.coord.y = j;
 				node.coord.z = k;
-                node.land = tinfo->tertype != ETerrainType::WATER;
+                node.land = tinfo->terType != ETerrainType::WATER;
 				node.theNodeBefore = NULL;
 			}
 		}
@@ -2988,7 +2988,7 @@ void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*=
 		neighbours.clear();
 
 		//handling subterranean gate => it's exit is the only neighbour
-		bool subterraneanEntry = (ct->topVisitableID() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
+        bool subterraneanEntry = (ct->topVisitableId() == Obj::SUBTERRANEAN_GATE && useSubterraneanGates);
 		if(subterraneanEntry)
 		{
 			//try finding the exit gate
@@ -3012,7 +3012,7 @@ void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*=
 			const int3 &n = neighbours[i]; //current neighbor
 			dp = getNode(n);
 			dt = &gs->map->getTile(n);
-			destTopVisObjID = dt->topVisitableID();
+            destTopVisObjID = dt->topVisitableId();
 
 			useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
 
@@ -3028,7 +3028,7 @@ void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*=
 				continue;
 
 			//special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
-			if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableID() == Obj::BOAT)
+            if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableId() == Obj::BOAT)
 				guardedSource = false;
 
 			int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
@@ -3104,7 +3104,7 @@ CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile
 	CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
 
 
-    if(tinfo->tertype == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
+    if(tinfo->terType == ETerrainType::ROCK || !FoW[curPos.x][curPos.y][curPos.z])
 		return CGPathNode::BLOCKED;
 
 	if(tinfo->visitable)

+ 1 - 1
lib/CGameState.h

@@ -149,7 +149,7 @@ struct DLL_LINKAGE SThievesGuildInfo
 
 	std::map<TPlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
 
-	std::map<TPlayerColor, si8> personality; // color to personality // -1 - human, AI -> (00 - random, 01 -  warrior, 02 - builder, 03 - explorer)
+    std::map<TPlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
 	std::map<TPlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
 
 // 	template <typename Handler> void serialize(Handler &h, const int version)

+ 6 - 6
lib/CObjectHandler.cpp

@@ -530,7 +530,7 @@ ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &fro
 	unsigned ret = 100;
 
 	//if there is road both on dest and src tiles - use road movement cost
-    if(dest.roadType && from.roadType)
+    if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
 	{
         int road = std::min(dest.roadType,from.roadType); //used road ID
 		switch(road)
@@ -563,14 +563,14 @@ ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &fro
 		{
 			int nativeTerrain = VLC->townh->factions[stack.second->type->faction].nativeTerrain;
 
-			if (nativeTerrain != -1 && nativeTerrain != from.tertype)
+            if (nativeTerrain != -1 && nativeTerrain != from.terType)
 			{
 				nativeArmy = false;
 				break;
 			}
 		}
 		if (!nativeArmy)
-			ret = VLC->heroh->terrCosts[from.tertype];
+            ret = VLC->heroh->terrCosts[from.terType];
  	}
 	return ret;
 }
@@ -1502,7 +1502,7 @@ CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
 {
 	if(movement < maxMovePoints(true))
 		return LACK_OF_MOVEMENT;
-    else if(cb->getTile(getPosition(false))->tertype == ETerrainType::WATER)
+    else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
 		return WRONG_TERRAIN;
 	else
 	{
@@ -6516,7 +6516,7 @@ void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
 //
 //	TerrainTile *tile;
 //	for(int i = 0; i < offsets.size(); i++)
-//		if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i]))  &&  tile->tertype == TerrainTile::water) //tile is in the map and is water
+//		if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i]))  &&  tile->terType == TerrainTile::water) //tile is in the map and is water
 //			return true;
 //	return false;
 //}
@@ -6530,7 +6530,7 @@ int3 IBoatGenerator::bestLocation() const
 	{
 		if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offsets[i], false)) //tile is in the map
 		{
-            if (tile->tertype == ETerrainType::WATER  &&  (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
+            if (tile->terType == ETerrainType::WATER  &&  (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
 				return o->pos + offsets[i];
 		}
 	}

+ 3 - 3
lib/Filesystem/CBinaryReader.cpp

@@ -27,7 +27,7 @@ CBinaryReader::CBinaryReader() : stream(nullptr)
 
 }
 
-CBinaryReader::CBinaryReader(CInputStream & stream) : stream(&stream)
+CBinaryReader::CBinaryReader(CInputStream * stream) : stream(stream)
 {
 
 }
@@ -37,9 +37,9 @@ CInputStream * CBinaryReader::getStream()
 	return stream;
 }
 
-void CBinaryReader::setStream(CInputStream & stream)
+void CBinaryReader::setStream(CInputStream * stream)
 {
-	this->stream = &stream;
+    this->stream = stream;
 }
 
 si64 CBinaryReader::read(ui8 * data, si64 size)

+ 12 - 12
lib/Filesystem/CBinaryReader.h

@@ -21,16 +21,6 @@ class CInputStream;
  */
 class DLL_LINKAGE CBinaryReader : public boost::noncopyable
 {
-	/**
-	 * Reads any integer. Advances the read pointer by its size.
-	 *
-	 * @return read integer.
-	 *
-	 * @throws std::runtime_error if the end of the stream was reached unexpectedly
-	 */
-	template <typename CData>
-	CData readInteger();
-
 public:
 	/**
 	 * Default c-tor.
@@ -42,7 +32,7 @@ public:
 	 *
 	 * @param stream The base stream object which serves as the reading input.
 	 */
-	CBinaryReader(CInputStream & stream);
+    CBinaryReader(CInputStream * stream);
 
 	/**
 	 * Gets the underlying stream.
@@ -56,7 +46,7 @@ public:
 	 *
 	 * @param stream The base stream to set
 	 */
-	void setStream(CInputStream & stream);
+    void setStream(CInputStream * stream);
 
 	/**
 	 * Reads n bytes from the stream into the data buffer.
@@ -84,6 +74,16 @@ public:
 	si64 readInt64();
 
 private:
+    /**
+     * Reads any integer. Advances the read pointer by its size.
+     *
+     * @return read integer.
+     *
+     * @throws std::runtime_error if the end of the stream was reached unexpectedly
+     */
+    template <typename CData>
+    CData readInteger();
+
 	/**
 	 * Gets a end of stream exception message.
 	 *

+ 1 - 0
lib/Filesystem/CFileInputStream.h

@@ -93,6 +93,7 @@ private:
 
 	si64 dataStart;
 	si64 dataSize;
+
 	/** Native c++ input file stream object. */
 	std::ifstream fileStream;
 };

+ 3 - 3
lib/Filesystem/CLodArchiveLoader.cpp

@@ -60,7 +60,7 @@ void CLodArchiveLoader::initLODArchive(CFileInputStream & fileStream)
 	};
 
 	// Read count of total files
-	CBinaryReader reader(fileStream);
+    CBinaryReader reader(&fileStream);
 
 	fileStream.seek(8);
 	ui32 totalFiles = reader.readUInt32();
@@ -98,7 +98,7 @@ void CLodArchiveLoader::initVIDArchive(CFileInputStream & fileStream)
 	};
 
 	// Read count of total files
-	CBinaryReader reader(fileStream);
+    CBinaryReader reader(&fileStream);
 	fileStream.seek(0);
 	ui32 totalFiles = reader.readUInt32();
 
@@ -146,7 +146,7 @@ void CLodArchiveLoader::initSNDArchive(CFileInputStream & fileStream)
 	};
 
 	// Read count of total files
-	CBinaryReader reader(fileStream);
+    CBinaryReader reader(&fileStream);
 	fileStream.seek(0);
 	ui32 totalFiles = reader.readUInt32();
 

+ 7 - 7
lib/IGameCallback.cpp

@@ -133,8 +133,8 @@ void CPrivilagedInfoCallback::getAllTiles (boost::unordered_set<int3, ShashInt3>
 		{
 			for (int yd = 0; yd < gs->map->height; yd++)
 			{
-				if ((getTile (int3 (xd,yd,zd))->tertype == 8 && water)
-					|| (getTile (int3 (xd,yd,zd))->tertype != 8 && land))
+				if ((getTile (int3 (xd,yd,zd))->terType == 8 && water)
+					|| (getTile (int3 (xd,yd,zd))->terType != 8 && land))
 					tiles.insert(int3(xd,yd,zd));
 			}
 		}
@@ -157,7 +157,7 @@ void CPrivilagedInfoCallback::getFreeTiles (std::vector<int3> &tiles) const
 			for (int yd = 0; yd < gs->map->height; yd++)
 			{
 				tinfo = getTile(int3 (xd,yd,zd));
-				if (tinfo->tertype != 8 && !tinfo->blocked) //land and free
+				if (tinfo->terType != 8 && !tinfo->blocked) //land and free
 					tiles.push_back (int3 (xd,yd,zd));
 			}
 		}
@@ -430,9 +430,9 @@ bool CGameInfoCallback::verifyPath(CPath * path, bool blockSea) const
 				continue;
 
 			const TerrainTile *prev = getTile(path->nodes[i-1].coord); //tile of previous node on the path
-            if ((   t->tertype == ETerrainType::WATER  &&  prev->tertype != ETerrainType::WATER)
-                || (t->tertype != ETerrainType::WATER  &&  prev->tertype == ETerrainType::WATER)
-                ||  prev->tertype == ETerrainType::ROCK
+            if ((   t->terType == ETerrainType::WATER  &&  prev->terType != ETerrainType::WATER)
+                || (t->terType != ETerrainType::WATER  &&  prev->terType == ETerrainType::WATER)
+                ||  prev->terType == ETerrainType::ROCK
 				)
 				return false;
 		}
@@ -594,7 +594,7 @@ int CGameInfoCallback::canBuildStructure( const CGTownInstance *t, int ID )
 	{
 		const TerrainTile *tile = getTile(t->bestLocation(), false);
 		
-        if(!tile || tile->tertype != ETerrainType::WATER)
+        if(!tile || tile->terType != ETerrainType::WATER)
 			return EBuildingState::NO_WATER; //lack of water
 	}
 

+ 120 - 82
lib/Map/CMap.cpp

@@ -5,10 +5,15 @@
 #include "../CArtHandler.h"
 #include "../CDefObjInfoHandler.h"
 
-PlayerInfo::PlayerInfo(): p7(0), p8(0), p9(0), canHumanPlay(0), canComputerPlay(0),
-    AITactic(0), isFactionRandom(0),
-    mainHeroPortrait(0), hasMainTown(0), generateHeroAtMainTown(0),
-    team(255), generateHero(0)
+SHeroName::SHeroName() : heroId(-1)
+{
+
+}
+
+PlayerInfo::PlayerInfo(): p7(0), p8(0), p9(0), powerPlaceholders(-1),
+    canHumanPlay(false), canComputerPlay(false),
+    aiTactic(EAiTactic::RANDOM), isFactionRandom(false), mainHeroPortrait(0), hasMainTown(false),
+    generateHeroAtMainTown(false), team(255), generateHero(false)
 {
 
 }
@@ -39,10 +44,93 @@ si8 PlayerInfo::defaultHero() const
     return -2;
 }
 
-CMapHeader::CMapHeader() : version(EMapFormat::INVALID)
+LossCondition::LossCondition() : typeOfLossCon(ELossConditionType::LOSSSTANDARD),
+    pos(int3(-1, -1, -1)), timeLimit(-1), obj(nullptr)
+{
+
+}
+
+VictoryCondition::VictoryCondition() : condition(EVictoryConditionType::WINSTANDARD),
+    allowNormalVictory(false), appliesToAI(false), pos(int3(-1, -1, -1)), objectId(0),
+    count(0), obj(nullptr)
+{
+
+}
+
+DisposedHero::DisposedHero() : heroId(0), portrait(255), players(0)
+{
+
+}
+
+CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
+    firstOccurence(0), nextOccurence(0)
+{
+
+}
+
+bool CMapEvent::earlierThan(const CMapEvent & other) const
+{
+    return firstOccurence < other.firstOccurence;
+}
+
+bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
+{
+    return firstOccurence <= other.firstOccurence;
+}
+
+CCastleEvent::CCastleEvent() : town(nullptr)
 {
-    areAnyPLayers = difficulty = levelLimit = howManyTeams = 0;
-    height = width = twoLevel = -1;
+
+}
+
+TerrainTile::TerrainTile() : terType(ETerrainType::BORDER), terView(0), riverType(ERiverType::NO_RIVER),
+    riverDir(0), roadType(ERoadType::NO_ROAD), roadDir(0), extTileFlags(0), visitable(false),
+    blocked(false)
+{
+
+}
+
+bool TerrainTile::entrableTerrain(const TerrainTile * from /*= NULL*/) const
+{
+    return entrableTerrain(from ? from->terType != ETerrainType::WATER : true, from ? from->terType == ETerrainType::WATER : true);
+}
+
+bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
+{
+    return terType != ETerrainType::ROCK
+        && ((allowSea && terType == ETerrainType::WATER)  ||  (allowLand && terType != ETerrainType::WATER));
+}
+
+bool TerrainTile::isClear(const TerrainTile *from /*= NULL*/) const
+{
+    return entrableTerrain(from) && !blocked;
+}
+
+int TerrainTile::topVisitableId() const
+{
+    return visitableObjects.size() ? visitableObjects.back()->ID : -1;
+}
+
+bool TerrainTile::isCoastal() const
+{
+    return extTileFlags & 64;
+}
+
+bool TerrainTile::hasFavourableWinds() const
+{
+    return extTileFlags & 128;
+}
+
+bool TerrainTile::isWater() const
+{
+    return terType == ETerrainType::WATER;
+}
+
+CMapHeader::CMapHeader() : version(EMapFormat::INVALID), areAnyPlayers(false),
+    height(-1), width(-1), twoLevel(-1), difficulty(0), levelLimit(0),
+    howManyTeams(0)
+{
+
 }
 
 CMapHeader::~CMapHeader()
@@ -50,6 +138,30 @@ CMapHeader::~CMapHeader()
 
 }
 
+CMap::CMap() : checksum(0), terrain(nullptr), grailRadious(0)
+{
+
+}
+
+CMap::~CMap()
+{
+    if(terrain)
+    {
+        for(int ii=0;ii<width;ii++)
+        {
+            for(int jj=0;jj<height;jj++)
+                delete [] terrain[ii][jj];
+            delete [] terrain[ii];
+        }
+        delete [] terrain;
+    }
+
+    for(std::list<ConstTransitivePtr<CMapEvent> >::iterator i = events.begin(); i != events.end(); i++)
+    {
+        i->dellNull();
+    }
+}
+
 void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
 {
     for(int fx=0; fx<8; ++fx)
@@ -103,30 +215,6 @@ void CMap::addBlockVisTiles(CGObjectInstance * obj)
     }
 }
 
-CMap::CMap() : terrain(nullptr)
-{
-
-}
-
-CMap::~CMap()
-{
-    if(terrain)
-    {
-        for(int ii=0;ii<width;ii++)
-        {
-            for(int jj=0;jj<height;jj++)
-                delete [] terrain[ii][jj];
-            delete [] terrain[ii];
-        }
-        delete [] terrain;
-    }
-
-    for(std::list<ConstTransitivePtr<CMapEvent> >::iterator i = events.begin(); i != events.end(); i++)
-    {
-        i->dellNull();
-    }
-}
-
 CGHeroInstance * CMap::getHero(int heroID)
 {
     for(ui32 i=0; i<heroes.size();i++)
@@ -154,7 +242,7 @@ const TerrainTile & CMap::getTile( const int3 & tile ) const
 
 bool CMap::isWaterTile(const int3 &pos) const
 {
-    return isInTheMap(pos) && getTile(pos).tertype == ETerrainType::WATER;
+    return isInTheMap(pos) && getTile(pos).terType == ETerrainType::WATER;
 }
 
 const CGObjectInstance *CMap::getObjectiveObjectFrom(int3 pos, bool lookForHero)
@@ -190,53 +278,3 @@ void CMap::eraseArtifactInstance(CArtifactInstance *art)
     assert(artInstances[art->id] == art);
     artInstances[art->id].dellNull();
 }
-
-LossCondition::LossCondition()
-{
-    obj = NULL;
-    timeLimit = -1;
-    pos = int3(-1,-1,-1);
-}
-
-VictoryCondition::VictoryCondition()
-{
-    pos = int3(-1,-1,-1);
-    obj = NULL;
-    ID = allowNormalVictory = appliesToAI = count = 0;
-}
-
-bool TerrainTile::entrableTerrain(const TerrainTile * from /*= NULL*/) const
-{
-    return entrableTerrain(from ? from->tertype != ETerrainType::WATER : true, from ? from->tertype == ETerrainType::WATER : true);
-}
-
-bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
-{
-    return tertype != ETerrainType::ROCK
-        && ((allowSea && tertype == ETerrainType::WATER)  ||  (allowLand && tertype != ETerrainType::WATER));
-}
-
-bool TerrainTile::isClear(const TerrainTile *from /*= NULL*/) const
-{
-    return entrableTerrain(from) && !blocked;
-}
-
-int TerrainTile::topVisitableID() const
-{
-    return visitableObjects.size() ? visitableObjects.back()->ID : -1;
-}
-
-bool TerrainTile::isCoastal() const
-{
-    return extTileFlags & 64;
-}
-
-bool TerrainTile::hasFavourableWinds() const
-{
-    return extTileFlags & 128;
-}
-
-bool TerrainTile::isWater() const
-{
-    return tertype == ETerrainType::WATER;
-}

+ 250 - 206
lib/Map/CMap.h

@@ -33,149 +33,18 @@ class IModableArt;
 class IQuestObject;
 class CInputStream;
 
-namespace ETerrainType
-{
-    enum ETerrainType
-    {
-        BORDER = -1, DIRT, SAND, GRASS, SNOW, SWAMP,
-        ROUGH, SUBTERRANEAN, LAVA, WATER, ROCK
-    };
-}
-
-namespace ERiverType
-{
-    enum ERiverType
-    {
-        NO_RIVER = 0, CLEAR_RIVER, ICY_RIVER, MUDDY_RIVER, LAVA_RIVER
-    };
-}
-
-namespace ERoadType
-{
-    enum ERoadType
-    {
-        DIRT_ROAD = 1, GRAVEL_ROAD, COBBLESTONE_ROAD
-    };
-}
-
 /**
- * The terrain tile describes the terrain type and the visual representation of the terrain.
- * Furthermore the struct defines whether the tile is visitable or/and blocked and which objects reside in it.
+ * The hero name struct consists of the hero id and the hero name.
  */
-struct DLL_LINKAGE TerrainTile
+struct DLL_LINKAGE SHeroName
 {
-    /** the type of terrain */
-    ETerrainType::ETerrainType tertype;
-
-    /** the visual representation of the terrain */
-    ui8 terview;
-
-    /** the type of the river. 0 if there is no river */
-    ERiverType::ERiverType riverType;
-
-    /** the direction of the river */
-    ui8 riverDir;
-
-    /** the type of the road. 0 if there is no river */
-    ERoadType::ERoadType roadType;
-
-    /** the direction of the road */
-    ui8 roadDir;
-
-    /**
-     * first two bits - how to rotate terrain graphic (next two - river graphic, next two - road);
-     * 7th bit - whether tile is coastal (allows disembarking if land or block movement if water); 8th bit - Favourable Winds effect
-     */
-    ui8 extTileFlags;
-
-    /** true if it is visitable, false if not */
-    bool visitable;
-
-    /** true if it is blocked, false if not */
-    bool blocked;
-
-    /** pointers to objects which the hero can visit while being on this tile */
-    std::vector <CGObjectInstance *> visitableObjects;
-
-    /** pointers to objects that are blocking this tile */
-    std::vector <CGObjectInstance *> blockingObjects;
-
     /**
-     * Gets true if the terrain is not a rock. If from is water/land, same type is also required.
-     *
-     * @param from
-     * @return
-     */
-    bool entrableTerrain(const TerrainTile * from = NULL) const;
-
-    /**
-     * Gets true if the terrain is not a rock. If from is water/land, same type is also required.
-     *
-     * @param allowLand
-     * @param allowSea
-     * @return
-     */
-    bool entrableTerrain(bool allowLand, bool allowSea) const;
-
-    /**
-     * Checks for blocking objects and terraint type (water / land).
-     *
-     * @param from
-     * @return
-     */
-    bool isClear(const TerrainTile * from = NULL) const;
-
-    /**
-     * Gets the ID of the top visitable object or -1 if there is none.
-     *
-     * @return the ID of the top visitable object or -1 if there is none
+     * Default c-tor.
      */
-    int topVisitableID() const;
+    SHeroName();
 
-    /**
-     * Gets true if the terrain type is water.
-     *
-     * @return true if the terrain type is water
-     */
-    bool isWater() const;
-
-    /**
-     * Gets true if the terrain tile is coastal.
-     *
-     * @return true if the terrain tile is coastal
-     */
-    bool isCoastal() const;
-
-    /**
-     * Gets true if the terrain tile has favourable winds.
-     *
-     * @return true if the terrain tile has favourable winds
-     */
-    bool hasFavourableWinds() const;
-
-    /**
-     * Serialize method.
-     */
-    template <typename Handler>
-    void serialize(Handler & h, const int version)
-    {
-        h & tertype & terview & riverType & riverDir & roadType &roadDir & extTileFlags & blocked;
-
-        if(!h.saving)
-        {
-            visitable = false;
-            //these flags (and obj vectors) will be restored in map serialization
-        }
-    }
-};
-
-/**
- * The hero name struct consists of the hero id and name.
- */
-struct DLL_LINKAGE SheroName
-{
     /** the id of the hero */
-    int heroID;
+    int heroId;
 
     /** the name of the hero */
     std::string heroName;
@@ -186,16 +55,47 @@ struct DLL_LINKAGE SheroName
     template <typename Handler>
     void serialize(Handler & h, const int version)
     {
-        h & heroID & heroName;
+        h & heroId & heroName;
     }
 };
 
+namespace EAiTactic
+{
+    enum EAiTactic
+    {
+        NONE = -1,
+        RANDOM,
+        WARRIOR,
+        BUILDER,
+        EXPLORER
+    };
+}
+
 /**
  * The player info constains data about which factions are allowed, AI tactical settings,
- * main hero name, where to generate the hero, whether faction is random,...
+ * the main hero name, where to generate the hero, whether the faction should be selected randomly,...
  */
 struct DLL_LINKAGE PlayerInfo
 {
+    /**
+     * Default constructor.
+     */
+    PlayerInfo();
+
+    /**
+     * Gets the default faction id or -1 for a random faction.
+     *
+     * @return the default faction id or -1 for a random faction
+     */
+    si8 defaultCastle() const;
+
+    /**
+     * Gets -1 for random hero.
+     *
+     * @return -1 for random hero
+     */
+    si8 defaultHero() const;
+
     /** unknown, unused */
     si32 p7;
 
@@ -205,23 +105,23 @@ struct DLL_LINKAGE PlayerInfo
     /** TODO ? */
     si32 p9;
 
-    /** TODO unused, q-ty of hero placeholders containing hero type, WARNING: powerPlacehodlers sometimes gives false 0 (eg. even if there is one placeholder), maybe different meaning??? */
-    ui8 powerPlacehodlers;
+    /** TODO unused, q-ty of hero placeholders containing hero type, WARNING: powerPlaceholders sometimes gives false 0 (eg. even if there is one placeholder), maybe different meaning??? */
+    ui8 powerPlaceholders;
 
-    /** player can be played by a human */
-    ui8 canHumanPlay;
+    /** true if player can be played by a human */
+    bool canHumanPlay;
 
-    /** player can be played by the computer */
-    ui8 canComputerPlay;
+    /** true if player can be played by the computer */
+    bool canComputerPlay;
 
-    /** defines the tactical setting of the AI: 0 - random, 1 -  warrior, 2 - builder, 3 - explorer */
-    ui32 AITactic;
+    /** defines the tactical setting of the AI */
+    EAiTactic::EAiTactic aiTactic;
 
     /** IDs of allowed factions */
     std::set<ui32> allowedFactions;
 
     /** unused. is the faction random */
-    ui8 isFactionRandom;
+    bool isFactionRandom;
 
     /** specifies the ID of hero with chosen portrait; 255 if standard */
     ui32 mainHeroPortrait;
@@ -230,13 +130,13 @@ struct DLL_LINKAGE PlayerInfo
     std::string mainHeroName;
 
     /** list of available heroes */
-    std::vector<SheroName> heroesNames;
+    std::vector<SHeroName> heroesNames;
 
-    /** has the player a main town */
-    ui8 hasMainTown;
+    /** true if the player has a main town */
+    bool hasMainTown;
 
-    /** generates the hero at the main town */
-    ui8 generateHeroAtMainTown;
+    /** true if the hero should be generated at the main town */
+    bool generateHeroAtMainTown;
 
     /** the position of the main town */
     int3 posOfMainTown;
@@ -244,27 +144,8 @@ struct DLL_LINKAGE PlayerInfo
     /** the team id to which the player belongs to */
     ui8 team;
 
-    /** unused. generates a hero */
-    ui8 generateHero;
-
-    /**
-     * Default constructor.
-     */
-    PlayerInfo();
-
-    /**
-     * Gets the default faction id or -1 for a random faction.
-     *
-     * @return the default faction id or -1 for a random faction
-     */
-    si8 defaultCastle() const;
-
-    /**
-     * Gets -1 for random hero.
-     *
-     * @return -1 for random hero
-     */
-    si8 defaultHero() const;
+    /** unused. true if a hero should be generated */
+    bool generateHero;
 
     /**
      * Serialize method.
@@ -272,7 +153,7 @@ struct DLL_LINKAGE PlayerInfo
     template <typename Handler>
     void serialize(Handler & h, const int version)
     {
-        h & p7 & p8 & p9 & canHumanPlay & canComputerPlay & AITactic & allowedFactions & isFactionRandom &
+        h & p7 & p8 & p9 & canHumanPlay & canComputerPlay & aiTactic & allowedFactions & isFactionRandom &
             mainHeroPortrait & mainHeroName & heroesNames & hasMainTown & generateHeroAtMainTown &
             posOfMainTown & team & generateHero;
     }
@@ -283,6 +164,11 @@ struct DLL_LINKAGE PlayerInfo
  */
 struct DLL_LINKAGE LossCondition
 {
+    /**
+     * Default constructor.
+     */
+    LossCondition();
+
     /** specifies the condition type */
     ELossConditionType::ELossConditionType typeOfLossCon;
 
@@ -295,11 +181,6 @@ struct DLL_LINKAGE LossCondition
     /** set during map parsing: hero/town (depending on typeOfLossCon); nullptr if not used */
     const CGObjectInstance * obj;
 
-    /**
-     * Default constructor.
-     */
-    LossCondition();
-
     /**
      * Serialize method.
      */
@@ -316,20 +197,25 @@ struct DLL_LINKAGE LossCondition
  */
 struct DLL_LINKAGE VictoryCondition
 {
+    /**
+     * Default constructor.
+     */
+    VictoryCondition();
+
     /** specifies the condition type */
     EVictoryConditionType::EVictoryConditionType condition;
 
     /** true if a normal victory is allowed (defeat all enemy towns, heroes) */
-    ui8 allowNormalVictory;
+    bool allowNormalVictory;
 
     /** true if this victory condition also applies to the AI */
-    ui8 appliesToAI;
+    bool appliesToAI;
 
     /** pos of city to upgrade (3); pos of town to build grail, {-1,-1,-1} if not relevant (4); hero pos (5); town pos(6); monster pos (7); destination pos(8) */
     int3 pos;
 
     /** artifact ID (0); monster ID (1); resource ID (2); needed fort level in upgraded town (3); artifact ID (8) */
-    si32 ID;
+    si32 objectId;
 
     /** needed count for creatures (1) / resource (2); upgraded town hall level (3);  */
     si32 count;
@@ -337,18 +223,13 @@ struct DLL_LINKAGE VictoryCondition
     /** object of specific monster / city / hero instance (NULL if not used); set during map parsing */
     const CGObjectInstance * obj;
 
-    /**
-     * Default constructor.
-     */
-    VictoryCondition();
-
     /**
      * Serialize method.
      */
     template <typename Handler>
     void serialize(Handler & h, const int version)
     {
-        h & condition & allowNormalVictory & appliesToAI & pos & ID & count & obj;
+        h & condition & allowNormalVictory & appliesToAI & pos & objectId & count & obj;
     }
 };
 
@@ -378,8 +259,13 @@ struct DLL_LINKAGE Rumor
  */
 struct DLL_LINKAGE DisposedHero
 {
+    /**
+     * Default c-tor.
+     */
+    DisposedHero();
+
     /** the id of the hero */
-    ui32 ID;
+    ui32 heroId;
 
     /** the portrait id of the hero, 0xFF is default */
     ui16 portrait;
@@ -396,7 +282,7 @@ struct DLL_LINKAGE DisposedHero
     template <typename Handler>
     void serialize(Handler & h, const int version)
     {
-        h & ID & portrait & name & players;
+        h & heroId & portrait & name & players;
     }
 };
 
@@ -409,6 +295,27 @@ struct DLL_LINKAGE DisposedHero
 class DLL_LINKAGE CMapEvent
 {
 public:
+    /**
+     * Default c-tor.
+     */
+    CMapEvent();
+
+    /**
+     * Returns true if this map event occurs earlier than the other map event for the first time.
+     *
+     * @param other the other map event to compare with
+     * @return true if this event occurs earlier than the other map event, false if not
+     */
+    bool earlierThan(const CMapEvent & other) const;
+
+    /**
+     * Returns true if this map event occurs earlier than or at the same day than the other map event for the first time.
+     *
+     * @param other the other map event to compare with
+     * @return true if this event occurs earlier than or at the same day than the other map event, false if not
+     */
+    bool earlierThanOrEqual(const CMapEvent & other) const;
+
     /** the name of the event */
     std::string name;
 
@@ -427,21 +334,12 @@ public:
     /** affacted computer players */
     ui8 computerAffected;
 
-    /** the day counted continously where the event happens */
+    /** the day counted continously when the event happens */
     ui32 firstOccurence;
 
     /** specifies after how many days the event will occur the next time; 0 if event occurs only one time */
     ui32 nextOccurence;
 
-    bool operator<(const CMapEvent &b) const
-    {
-        return firstOccurence < b.firstOccurence;
-    }
-    bool operator<=(const CMapEvent &b) const
-    {
-        return firstOccurence <= b.firstOccurence;
-    }
-
     /**
      * Serialize method.
      */
@@ -459,6 +357,11 @@ public:
 class DLL_LINKAGE CCastleEvent: public CMapEvent
 {
 public:
+    /**
+     * Default c-tor.
+     */
+    CCastleEvent();
+
     /** build specific buildings */
     std::set<si32> buildings;
 
@@ -479,6 +382,147 @@ public:
     }
 };
 
+namespace ETerrainType
+{
+    enum ETerrainType
+    {
+        BORDER = -1, DIRT, SAND, GRASS, SNOW, SWAMP,
+        ROUGH, SUBTERRANEAN, LAVA, WATER, ROCK
+    };
+}
+
+namespace ERiverType
+{
+    enum ERiverType
+    {
+        NO_RIVER, CLEAR_RIVER, ICY_RIVER, MUDDY_RIVER, LAVA_RIVER
+    };
+}
+
+namespace ERoadType
+{
+    enum ERoadType
+    {
+        NO_ROAD, DIRT_ROAD, GRAVEL_ROAD, COBBLESTONE_ROAD
+    };
+}
+
+/**
+ * The terrain tile describes the terrain type and the visual representation of the terrain.
+ * Furthermore the struct defines whether the tile is visitable or/and blocked and which objects reside in it.
+ */
+struct DLL_LINKAGE TerrainTile
+{
+    /**
+     * Default c-tor.
+     */
+    TerrainTile();
+
+    /**
+     * Gets true if the terrain is not a rock. If from is water/land, same type is also required.
+     *
+     * @param from
+     * @return
+     */
+    bool entrableTerrain(const TerrainTile * from = NULL) const;
+
+    /**
+     * Gets true if the terrain is not a rock. If from is water/land, same type is also required.
+     *
+     * @param allowLand
+     * @param allowSea
+     * @return
+     */
+    bool entrableTerrain(bool allowLand, bool allowSea) const;
+
+    /**
+     * Checks for blocking objects and terraint type (water / land).
+     *
+     * @param from
+     * @return
+     */
+    bool isClear(const TerrainTile * from = NULL) const;
+
+    /**
+     * Gets the ID of the top visitable object or -1 if there is none.
+     *
+     * @return the ID of the top visitable object or -1 if there is none
+     */
+    int topVisitableId() const;
+
+    /**
+     * Gets true if the terrain type is water.
+     *
+     * @return true if the terrain type is water
+     */
+    bool isWater() const;
+
+    /**
+     * Gets true if the terrain tile is coastal.
+     *
+     * @return true if the terrain tile is coastal
+     */
+    bool isCoastal() const;
+
+    /**
+     * Gets true if the terrain tile has favourable winds.
+     *
+     * @return true if the terrain tile has favourable winds
+     */
+    bool hasFavourableWinds() const;
+
+    /** the type of terrain */
+    ETerrainType::ETerrainType terType;
+
+    /** the visual representation of the terrain */
+    ui8 terView;
+
+    /** the type of the river. 0 if there is no river */
+    ERiverType::ERiverType riverType;
+
+    /** the direction of the river */
+    ui8 riverDir;
+
+    /** the type of the road. 0 if there is no river */
+    ERoadType::ERoadType roadType;
+
+    /** the direction of the road */
+    ui8 roadDir;
+
+    /**
+     * first two bits - how to rotate terrain graphic (next two - river graphic, next two - road);
+     * 7th bit - whether tile is coastal (allows disembarking if land or block movement if water); 8th bit - Favourable Winds effect
+     */
+    ui8 extTileFlags;
+
+    /** true if it is visitable, false if not */
+    bool visitable;
+
+    /** true if it is blocked, false if not */
+    bool blocked;
+
+    /** pointers to objects which the hero can visit while being on this tile */
+    std::vector<CGObjectInstance *> visitableObjects;
+
+    /** pointers to objects that are blocking this tile */
+    std::vector<CGObjectInstance *> blockingObjects;
+
+    /**
+     * Serialize method.
+     */
+    template <typename Handler>
+    void serialize(Handler & h, const int version)
+    {
+        h & terType & terView & riverType & riverDir & roadType &roadDir & extTileFlags & blocked;
+
+        if(!h.saving)
+        {
+            visitable = false;
+            //these flags (and obj vectors) will be restored in map serialization
+        }
+    }
+};
+
 namespace EMapFormat
 {
     enum EMapFormat
@@ -507,8 +551,8 @@ public:
     /** the version of the map */
     EMapFormat::EMapFormat version;
 
-    /** if there are any playable players on the map */
-    ui8 areAnyPLayers;
+    /** unused. if there are any playable players on the map */
+    bool areAnyPlayers;
 
     /** the height of the map */
     si32 height;
@@ -555,7 +599,7 @@ public:
     template <typename Handler>
     void serialize(Handler & h, const int Version)
     {
-        h & version & name & description & width & height & twoLevel & difficulty & levelLimit & areAnyPLayers;
+        h & version & name & description & width & height & twoLevel & difficulty & levelLimit & areAnyPlayers;
         h & players & lossCondition & victoryCondition & howManyTeams & allowedHeroes;
     }
 };
@@ -633,10 +677,10 @@ public:
 
     /**
      * Gets the hero with the given id.
-     * @param heroID the hero id
+     * @param heroId the hero id
      * @return the hero with the given id
      */
-    CGHeroInstance * getHero(int heroID);
+    CGHeroInstance * getHero(int heroId);
 
     /**
      * Validates if the position is in the bounds of the map.
@@ -822,7 +866,7 @@ public:
 
                 vistile.x -= 2; //manifest pos
                 const TerrainTile & t = getTile(vistile);
-                if(t.tertype != ETerrainType::WATER) continue;
+                if(t.terType != ETerrainType::WATER) continue;
 
                 //hero stands on the water - he must be in the boat
                 for(ui32 j = 0; j < t.visitableObjects.size(); ++j)

+ 25 - 25
lib/Map/CMapService.cpp

@@ -51,7 +51,7 @@ std::unique_ptr<CInputStream> CMapService::getStreamFromMem(const ui8 * buffer,
 std::unique_ptr<IMapLoader> CMapService::getMapLoader(std::unique_ptr<CInputStream> & stream)
 {
     // Read map header
-    CBinaryReader reader(*stream.get());
+    CBinaryReader reader(stream.get());
     ui32 header = reader.readUInt32();
     reader.getStream()->seek(0);
 
@@ -205,7 +205,7 @@ void CMapLoaderH3M::readHeader()
     }
 
     // Read map name, description, dimensions,...
-    mapHeader->areAnyPLayers = readChar(buffer, pos); // Invalid on some maps
+    mapHeader->areAnyPlayers = static_cast<bool>(readChar(buffer, pos));
     mapHeader->height = mapHeader->width = (read_le_u32(buffer + pos));
     pos += 4;
     mapHeader->twoLevel = readChar(buffer, pos);
@@ -232,8 +232,8 @@ void CMapLoaderH3M::readPlayerInfo()
     mapHeader->players.resize(8);
     for(int i = 0; i < 8; ++i)
     {
-        mapHeader->players[i].canHumanPlay = buffer[pos++];
-        mapHeader->players[i].canComputerPlay = buffer[pos++];
+        mapHeader->players[i].canHumanPlay = static_cast<bool>(buffer[pos++]);
+        mapHeader->players[i].canComputerPlay = static_cast<bool>(buffer[pos++]);
 
         // If nobody can play with this player
         if((!(mapHeader->players[i].canHumanPlay || mapHeader->players[i].canComputerPlay)))
@@ -254,7 +254,7 @@ void CMapLoaderH3M::readPlayerInfo()
             continue;
         }
 
-        mapHeader->players[i].AITactic = buffer[pos++];
+        mapHeader->players[i].aiTactic = static_cast<EAiTactic::EAiTactic>(buffer[pos++]);
 
         if(mapHeader->version == EMapFormat::SOD || mapHeader->version == EMapFormat::WOG)
         {
@@ -280,14 +280,14 @@ void CMapLoaderH3M::readPlayerInfo()
             }
         }
 
-        mapHeader->players[i].isFactionRandom = buffer[pos++];
-        mapHeader->players[i].hasMainTown = buffer[pos++];
+        mapHeader->players[i].isFactionRandom = static_cast<bool>(buffer[pos++]);
+        mapHeader->players[i].hasMainTown = static_cast<bool>(buffer[pos++]);
         if(mapHeader->players[i].hasMainTown)
         {
             if(mapHeader->version != EMapFormat::ROE)
             {
-                mapHeader->players[i].generateHeroAtMainTown = buffer[pos++];
-                mapHeader->players[i].generateHero = buffer[pos++];
+                mapHeader->players[i].generateHeroAtMainTown = static_cast<bool>(buffer[pos++]);
+                mapHeader->players[i].generateHero = static_cast<bool>(buffer[pos++]);
             }
             else
             {
@@ -310,13 +310,13 @@ void CMapLoaderH3M::readPlayerInfo()
 
         if(mapHeader->version != EMapFormat::ROE)
         {
-            mapHeader->players[i].powerPlacehodlers = buffer[pos++]; //unknown byte
+            mapHeader->players[i].powerPlaceholders = buffer[pos++]; //unknown byte
             int heroCount = buffer[pos++];
             pos += 3;
             for(int pp = 0; pp < heroCount; ++pp)
             {
-                SheroName vv;
-                vv.heroID = buffer[pos++];
+                SHeroName vv;
+                vv.heroId = buffer[pos++];
                 int hnl = buffer[pos++];
                 pos += 3;
                 for(int zz = 0; zz < hnl; ++zz)
@@ -343,20 +343,20 @@ void CMapLoaderH3M::readVictoryLossConditions()
         {
         case EVictoryConditionType::ARTIFACT:
             {
-                mapHeader->victoryCondition.ID = buffer[pos + 2];
+                mapHeader->victoryCondition.objectId = buffer[pos + 2];
                 nr = (mapHeader->version == EMapFormat::ROE ? 1 : 2);
                 break;
             }
         case EVictoryConditionType::GATHERTROOP:
             {
-                mapHeader->victoryCondition.ID = buffer[pos + 2];
+                mapHeader->victoryCondition.objectId = buffer[pos + 2];
                 mapHeader->victoryCondition.count = read_le_u32(buffer + pos + (mapHeader->version == EMapFormat::ROE ? 3 : 4));
                 nr = (mapHeader->version == EMapFormat::ROE ? 5 : 6);
                 break;
             }
         case EVictoryConditionType::GATHERRESOURCE:
             {
-                mapHeader->victoryCondition.ID = buffer[pos + 2];
+                mapHeader->victoryCondition.objectId = buffer[pos + 2];
                 mapHeader->victoryCondition.count = read_le_u32(buffer + pos + 3);
                 nr = 5;
                 break;
@@ -367,7 +367,7 @@ void CMapLoaderH3M::readVictoryLossConditions()
                 mapHeader->victoryCondition.pos.y = buffer[pos + 3];
                 mapHeader->victoryCondition.pos.z = buffer[pos + 4];
                 mapHeader->victoryCondition.count = buffer[pos + 5];
-                mapHeader->victoryCondition.ID = buffer[pos + 6];
+                mapHeader->victoryCondition.objectId = buffer[pos + 6];
                 nr = 5;
                 break;
             }
@@ -404,7 +404,7 @@ void CMapLoaderH3M::readVictoryLossConditions()
             }
         case EVictoryConditionType::TRANSPORTITEM:
             {
-                mapHeader->victoryCondition.ID =  buffer[pos + 2];
+                mapHeader->victoryCondition.objectId =  buffer[pos + 2];
                 mapHeader->victoryCondition.pos.x = buffer[pos + 3];
                 mapHeader->victoryCondition.pos.y = buffer[pos + 4];
                 mapHeader->victoryCondition.pos.z = buffer[pos + 5];
@@ -414,8 +414,8 @@ void CMapLoaderH3M::readVictoryLossConditions()
         default:
             assert(0);
         }
-        mapHeader->victoryCondition.allowNormalVictory = buffer[pos++];
-        mapHeader->victoryCondition.appliesToAI = buffer[pos++];
+        mapHeader->victoryCondition.allowNormalVictory = static_cast<bool>(buffer[pos++]);
+        mapHeader->victoryCondition.appliesToAI = static_cast<bool>(buffer[pos++]);
         pos += nr;
     }
 
@@ -505,7 +505,7 @@ void CMapLoaderH3M::readDisposedHeroes()
         map->disposedHeroes.resize(disp);
         for(int g = 0; g < disp; ++g)
         {
-            map->disposedHeroes[g].ID = buffer[pos++];
+            map->disposedHeroes[g].heroId = buffer[pos++];
             map->disposedHeroes[g].portrait = buffer[pos++];
             int lenbuf = read_le_u32(buffer + pos);
             pos += 4;
@@ -572,7 +572,7 @@ void CMapLoaderH3M::readAllowedArtifacts()
     if(map->victoryCondition.condition == EVictoryConditionType::ARTIFACT
             || map->victoryCondition.condition == EVictoryConditionType::TRANSPORTITEM)
     {
-        map->allowedArtifact[map->victoryCondition.ID] = false;
+        map->allowedArtifact[map->victoryCondition.objectId] = false;
     }
 }
 
@@ -900,14 +900,14 @@ void CMapLoaderH3M::readTerrain()
         {
             for(int z = 0; z < map->height; z++)
             {
-                map->terrain[z][c][a].tertype = static_cast<ETerrainType::ETerrainType>(buffer[pos++]);
-                map->terrain[z][c][a].terview = buffer[pos++];
+                map->terrain[z][c][a].terType = static_cast<ETerrainType::ETerrainType>(buffer[pos++]);
+                map->terrain[z][c][a].terView = buffer[pos++];
                 map->terrain[z][c][a].riverType = static_cast<ERiverType::ERiverType>(buffer[pos++]);
                 map->terrain[z][c][a].riverDir = buffer[pos++];
                 map->terrain[z][c][a].roadType = static_cast<ERoadType::ERoadType>(buffer[pos++]);
                 map->terrain[z][c][a].roadDir = buffer[pos++];
                 map->terrain[z][c][a].extTileFlags = buffer[pos++];
-                map->terrain[z][c][a].blocked = (map->terrain[z][c][a].tertype == ETerrainType::ROCK ? 1 : 0); //underground tiles are always blocked
+                map->terrain[z][c][a].blocked = (map->terrain[z][c][a].terType == ETerrainType::ROCK ? 1 : 0); //underground tiles are always blocked
                 map->terrain[z][c][a].visitable = 0;
             }
         }
@@ -1819,7 +1819,7 @@ CGObjectInstance * CMapLoaderH3M::readHero(int idToBeGiven)
 
     for(int j = 0; j < map->disposedHeroes.size(); ++j)
     {
-        if(map->disposedHeroes[j].ID == nhi->subID)
+        if(map->disposedHeroes[j].heroId == nhi->subID)
         {
             nhi->name = map->disposedHeroes[j].name;
             nhi->portrait = map->disposedHeroes[j].portrait;

+ 1 - 1
lib/NetPacksLib.cpp

@@ -558,7 +558,7 @@ DLL_LINKAGE void NewObject::applyGs( CGameState *gs )
 			break;
 		case 124://hole
 			const TerrainTile &t = gs->map->getTile(pos);
-			o->defInfo = VLC->dobjinfo->gobjs[ID][t.tertype];
+			o->defInfo = VLC->dobjinfo->gobjs[ID][t.terType];
 			assert(o->defInfo);
 		break;
 	}

+ 12 - 12
server/CGameHandler.cpp

@@ -1078,7 +1078,7 @@ void CGameHandler::init(StartInfo *si)
 
 static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
 {
-	return *a < *b;
+    return a->earlierThan(*b);
 }
 
 void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
@@ -1229,7 +1229,7 @@ void CGameHandler::newTurn()
 
 			NewTurn::Hero hth;
 			hth.id = h->id;
-            hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != ETerrainType::WATER);
+            hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).terType != ETerrainType::WATER);
 
 			if(h->visitedTown && h->visitedTown->hasBuilt(EBuilding::MAGES_GUILD_1)) //if hero starts turn in town with mage guild
 				hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
@@ -1671,11 +1671,11 @@ bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*
 
 	//it's a rock or blocked and not visitable tile
 	//OR hero is on land and dest is water and (there is not present only one object - boat)
-    if(((t.tertype == ETerrainType::ROCK  ||  (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
+    if(((t.terType == ETerrainType::ROCK  ||  (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
 			&& complain("Cannot move hero, destination tile is blocked!"))
-        || ((!h->boat && !h->canWalkOnSea() && t.tertype == ETerrainType::WATER && (t.visitableObjects.size() < 1 ||  (t.visitableObjects.back()->ID != 8 && t.visitableObjects.back()->ID != Obj::HERO)))  //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land) -> we test back cause boat may be on top of another object (#276)
+        || ((!h->boat && !h->canWalkOnSea() && t.terType == ETerrainType::WATER && (t.visitableObjects.size() < 1 ||  (t.visitableObjects.back()->ID != 8 && t.visitableObjects.back()->ID != Obj::HERO)))  //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land) -> we test back cause boat may be on top of another object (#276)
 			&& complain("Cannot move hero, destination tile is on water!"))
-        || ((h->boat && t.tertype != ETerrainType::WATER && t.blocked)
+        || ((h->boat && t.terType != ETerrainType::WATER && t.blocked)
 			&& complain("Cannot disembark hero, tile is blocked!"))
 		|| ((h->movement < cost  &&  dst != h->pos  &&  !instant)
 			&& complain("Hero doesn't have any movement points left!"))
@@ -1697,7 +1697,7 @@ bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*
 		return true;
 	}
 	//hero leaves the boat
-    else if(h->boat && t.tertype != ETerrainType::WATER && !t.blocked)
+    else if(h->boat && t.terType != ETerrainType::WATER && !t.blocked)
 	{
 		//TODO? code similarity with the block above
 		tmh.result = TryMoveHero::DISEMBARK;
@@ -4720,7 +4720,7 @@ void CGameHandler::handleTimeEvents()
 
 			ev->firstOccurence += ev->nextOccurence;
 			std::list<ConstTransitivePtr<CMapEvent> >::iterator it = gs->map->events.begin();
-			while ( it !=gs->map->events.end() && **it <= *ev )
+            while ( it !=gs->map->events.end() && (*it)->earlierThanOrEqual(*ev))
 				it++;
 			gs->map->events.insert(it, ev);
 		}
@@ -4791,7 +4791,7 @@ void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n, std::map<
 
 			ev->firstOccurence += ev->nextOccurence;
 			std::list<CCastleEvent*>::iterator it = town->events.begin();
-			while ( it !=town->events.end() &&  **it <= *ev )
+            while ( it !=town->events.end() &&  (*it)->earlierThanOrEqual(*ev))
 				it++;
 			town->events.insert(it, ev);
 		}
@@ -5085,17 +5085,17 @@ void CGameHandler::getLossVicMessage( ui8 player, si8 standard, bool victory, In
 			{
 			case EVictoryConditionType::ARTIFACT:
 				out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
-				out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
+                out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.objectId); //artifact name
 				break;
 			case EVictoryConditionType::GATHERTROOP:
 				out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
 				out.text.addReplacement(gs->map->victoryCondition.count);
-				out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
+                out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.objectId);
 				break;
 			case EVictoryConditionType::GATHERRESOURCE:
 				out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
 				out.text.addReplacement(gs->map->victoryCondition.count);
-				out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
+                out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.objectId);
 				break;
 			case EVictoryConditionType::BUILDCITY:
 				out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
@@ -5196,7 +5196,7 @@ bool CGameHandler::dig( const CGHeroInstance *h )
 	NewObject no;
 	no.ID = Obj::HOLE;
 	no.pos = h->getPosition();
-	no.subID = getTile(no.pos)->tertype;
+	no.subID = getTile(no.pos)->terType;
 	sendAndApply(&no);
 
 	//take MPs