2
0

CMap.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. /*
  2. * CMap.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CMap.h"
  12. #include "../CArtHandler.h"
  13. #include "../GameLibrary.h"
  14. #include "../CCreatureHandler.h"
  15. #include "../GameSettings.h"
  16. #include "../RiverHandler.h"
  17. #include "../RoadHandler.h"
  18. #include "../TerrainHandler.h"
  19. #include "../entities/hero/CHeroHandler.h"
  20. #include "../mapObjects/CGHeroInstance.h"
  21. #include "../mapObjects/CGTownInstance.h"
  22. #include "../mapObjects/CQuest.h"
  23. #include "../mapObjects/ObjectTemplate.h"
  24. #include "../texts/CGeneralTextHandler.h"
  25. #include "../spells/CSpellHandler.h"
  26. #include "../CSkillHandler.h"
  27. #include "CMapEditManager.h"
  28. #include "CMapOperation.h"
  29. #include "../serializer/JsonSerializeFormat.h"
  30. #include <vstd/RNG.h>
  31. VCMI_LIB_NAMESPACE_BEGIN
  32. void Rumor::serializeJson(JsonSerializeFormat & handler)
  33. {
  34. handler.serializeString("name", name);
  35. handler.serializeStruct("text", text);
  36. }
  37. CMapEvent::CMapEvent()
  38. : humanAffected(false)
  39. , computerAffected(false)
  40. , firstOccurrence(0)
  41. , nextOccurrence(0)
  42. {
  43. }
  44. bool CMapEvent::occursToday(int currentDay) const
  45. {
  46. if (currentDay == firstOccurrence + 1)
  47. return true;
  48. if (nextOccurrence == 0)
  49. return false;
  50. if (currentDay < firstOccurrence)
  51. return false;
  52. return (currentDay - firstOccurrence - 1) % nextOccurrence == 0;
  53. }
  54. bool CMapEvent::affectsPlayer(PlayerColor color, bool isHuman) const
  55. {
  56. if (players.count(color) == 0)
  57. return false;
  58. if (!isHuman && !computerAffected)
  59. return false;
  60. if (isHuman && !humanAffected)
  61. return false;
  62. return true;
  63. }
  64. void CMapEvent::serializeJson(JsonSerializeFormat & handler)
  65. {
  66. handler.serializeString("name", name);
  67. handler.serializeStruct("message", message);
  68. if (!handler.saving && handler.getCurrent()["players"].isNumber())
  69. {
  70. // compatibility for old maps
  71. int playersMask = 0;
  72. handler.serializeInt("players", playersMask);
  73. for (int i = 0; i < 8; ++i)
  74. if ((playersMask & (1 << i)) != 0)
  75. players.insert(PlayerColor(i));
  76. }
  77. else
  78. {
  79. handler.serializeIdArray("players", players);
  80. }
  81. handler.serializeInt("humanAffected", humanAffected);
  82. handler.serializeInt("computerAffected", computerAffected);
  83. handler.serializeInt("firstOccurrence", firstOccurrence);
  84. handler.serializeInt("nextOccurrence", nextOccurrence);
  85. resources.serializeJson(handler, "resources");
  86. auto deletedObjects = handler.enterArray("deletedObjectsInstances");
  87. deletedObjects.serializeArray(deletedObjectsInstances);
  88. }
  89. void CCastleEvent::serializeJson(JsonSerializeFormat & handler)
  90. {
  91. CMapEvent::serializeJson(handler);
  92. // TODO: handler.serializeIdArray("buildings", buildings);
  93. {
  94. std::vector<BuildingID> temp(buildings.begin(), buildings.end());
  95. auto a = handler.enterArray("buildings");
  96. a.syncSize(temp);
  97. for(int i = 0; i < temp.size(); ++i)
  98. {
  99. int buildingID = temp[i].getNum();
  100. a.serializeInt(i, buildingID);
  101. buildings.insert(buildingID);
  102. }
  103. }
  104. {
  105. auto a = handler.enterArray("creatures");
  106. a.syncSize(creatures);
  107. for(int i = 0; i < creatures.size(); ++i)
  108. a.serializeInt(i, creatures[i]);
  109. }
  110. }
  111. TerrainTile::TerrainTile():
  112. riverType(River::NO_RIVER),
  113. roadType(Road::NO_ROAD),
  114. terView(0),
  115. riverDir(0),
  116. roadDir(0),
  117. extTileFlags(0)
  118. {
  119. }
  120. bool TerrainTile::isClear(const TerrainTile * from) const
  121. {
  122. return entrableTerrain(from) && !blocked();
  123. }
  124. ObjectInstanceID TerrainTile::topVisitableObj(bool excludeTop) const
  125. {
  126. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  127. return {};
  128. if(excludeTop)
  129. return visitableObjects[visitableObjects.size()-2];
  130. return visitableObjects.back();
  131. }
  132. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  133. {
  134. if(isWater() || !getTerrain()->isPassable())
  135. return EDiggingStatus::WRONG_TERRAIN;
  136. int allowedBlocked = excludeTop ? 1 : 0;
  137. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  138. return EDiggingStatus::TILE_OCCUPIED;
  139. else
  140. return EDiggingStatus::CAN_DIG;
  141. }
  142. CMap::CMap(IGameCallback * cb)
  143. : GameCallbackHolder(cb)
  144. , grailPos(-1, -1, -1)
  145. , grailRadius(0)
  146. , waterMap(false)
  147. , uidCounter(0)
  148. {
  149. heroesPool.resize(LIBRARY->heroh->size());
  150. allowedAbilities = LIBRARY->skillh->getDefaultAllowed();
  151. allowedArtifact = LIBRARY->arth->getDefaultAllowed();
  152. allowedSpells = LIBRARY->spellh->getDefaultAllowed();
  153. gameSettings = std::make_unique<GameSettings>();
  154. gameSettings->loadBase(LIBRARY->settingsHandler->getFullConfig());
  155. }
  156. CMap::~CMap() = default;
  157. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  158. {
  159. const int zVal = obj->anchorPos().z;
  160. for(int fx = 0; fx < obj->getWidth(); ++fx)
  161. {
  162. int xVal = obj->anchorPos().x - fx;
  163. for(int fy = 0; fy < obj->getHeight(); ++fy)
  164. {
  165. int yVal = obj->anchorPos().y - fy;
  166. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  167. {
  168. TerrainTile & curt = terrain[zVal][xVal][yVal];
  169. if(total || obj->visitableAt(int3(xVal, yVal, zVal)))
  170. curt.visitableObjects -= obj->id;
  171. if(total || obj->blockingAt(int3(xVal, yVal, zVal)))
  172. curt.blockingObjects -= obj->id;
  173. }
  174. }
  175. }
  176. }
  177. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  178. {
  179. const int zVal = obj->anchorPos().z;
  180. for(int fx = 0; fx < obj->getWidth(); ++fx)
  181. {
  182. int xVal = obj->anchorPos().x - fx;
  183. for(int fy = 0; fy < obj->getHeight(); ++fy)
  184. {
  185. int yVal = obj->anchorPos().y - fy;
  186. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  187. {
  188. TerrainTile & curt = terrain[zVal][xVal][yVal];
  189. if(obj->visitableAt(int3(xVal, yVal, zVal)))
  190. curt.visitableObjects.push_back(obj->id);
  191. if(obj->blockingAt(int3(xVal, yVal, zVal)))
  192. curt.blockingObjects.push_back(obj->id);
  193. }
  194. }
  195. }
  196. }
  197. void CMap::calculateGuardingGreaturePositions()
  198. {
  199. int levels = twoLevel ? 2 : 1;
  200. for(int z = 0; z < levels; z++)
  201. {
  202. for(int x = 0; x < width; x++)
  203. {
  204. for(int y = 0; y < height; y++)
  205. {
  206. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  207. }
  208. }
  209. }
  210. }
  211. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  212. {
  213. for (const auto & objectID : heroesOnMap)
  214. {
  215. const auto hero = std::dynamic_pointer_cast<CGHeroInstance>(objects.at(objectID.getNum()));
  216. if (hero->getHeroTypeID() == heroID)
  217. return hero.get();
  218. }
  219. return nullptr;
  220. }
  221. bool CMap::isCoastalTile(const int3 & pos) const
  222. {
  223. //todo: refactoring: extract neighbour tile iterator and use it in GameState
  224. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  225. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  226. if(!isInTheMap(pos))
  227. {
  228. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  229. return false;
  230. }
  231. if(getTile(pos).isWater())
  232. return false;
  233. for(const auto & dir : dirs)
  234. {
  235. const int3 hlp = pos + dir;
  236. if(!isInTheMap(hlp))
  237. continue;
  238. const TerrainTile &hlpt = getTile(hlp);
  239. if(hlpt.isWater())
  240. return true;
  241. }
  242. return false;
  243. }
  244. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  245. {
  246. const TerrainTile * dstTile = &getTile(dst);
  247. const TerrainTile * srcTile = &getTile(src);
  248. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  249. }
  250. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  251. {
  252. if (!pom->entrableTerrain()) //rock is never accessible
  253. return false;
  254. for(const auto & objID : pom->visitableObjects) //checking destination tile
  255. {
  256. if(!vstd::contains(pom->blockingObjects, objID)) //this visitable object is not blocking, ignore
  257. continue;
  258. if (!getObject(objID)->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  259. return false;
  260. }
  261. return true;
  262. }
  263. int3 CMap::guardingCreaturePosition (int3 pos) const
  264. {
  265. const int3 originalPos = pos;
  266. // Give monster at position priority.
  267. if (!isInTheMap(pos))
  268. return int3(-1, -1, -1);
  269. const TerrainTile &posTile = getTile(pos);
  270. if (posTile.visitable())
  271. {
  272. for (const auto & objID : posTile.visitableObjects)
  273. {
  274. const auto * object = getObject(objID);
  275. if (object->ID == Obj::MONSTER)
  276. return pos;
  277. }
  278. }
  279. // See if there are any monsters adjacent.
  280. bool water = posTile.isWater();
  281. pos -= int3(1, 1, 0); // Start with top left.
  282. for (int dx = 0; dx < 3; dx++)
  283. {
  284. for (int dy = 0; dy < 3; dy++)
  285. {
  286. if (isInTheMap(pos))
  287. {
  288. const auto & tile = getTile(pos);
  289. if (tile.visitable() && (tile.isWater() == water))
  290. {
  291. for (const auto & objID : tile.visitableObjects)
  292. {
  293. const auto * object = getObject(objID);
  294. if (object->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  295. return pos;
  296. }
  297. }
  298. }
  299. pos.y++;
  300. }
  301. pos.y -= 3;
  302. pos.x++;
  303. }
  304. return int3(-1, -1, -1);
  305. }
  306. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  307. {
  308. for(const auto & objID : getTile(pos).visitableObjects)
  309. {
  310. const auto * object = getObject(objID);
  311. if (object->ID == type)
  312. return object;
  313. }
  314. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  315. // Try to workaround that and find closest object that we can use
  316. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  317. logGlobal->error("Will try to find closest matching object");
  318. CGObjectInstance * bestMatch = nullptr;
  319. for (const auto & object : objects)
  320. {
  321. if (object && object->ID == type)
  322. {
  323. if (bestMatch == nullptr)
  324. bestMatch = object.get();
  325. else
  326. {
  327. if (object->anchorPos().dist2dSQ(pos) < bestMatch->anchorPos().dist2dSQ(pos))
  328. bestMatch = object.get();// closer than one we already found
  329. }
  330. }
  331. }
  332. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  333. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->anchorPos().toString());
  334. return bestMatch;
  335. }
  336. void CMap::checkForObjectives()
  337. {
  338. // NOTE: probably should be moved to MapFormatH3M.cpp
  339. for (TriggeredEvent & event : triggeredEvents)
  340. {
  341. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  342. {
  343. switch (cond.condition)
  344. {
  345. case EventCondition::HAVE_ARTIFACT:
  346. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(LIBRARY)->getNameTextID());
  347. break;
  348. case EventCondition::HAVE_CREATURES:
  349. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(LIBRARY)->getNameSingularTextID());
  350. event.onFulfill.replaceNumber(cond.value);
  351. break;
  352. case EventCondition::HAVE_RESOURCES:
  353. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  354. event.onFulfill.replaceNumber(cond.value);
  355. break;
  356. case EventCondition::HAVE_BUILDING:
  357. if (isInTheMap(cond.position))
  358. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  359. break;
  360. case EventCondition::CONTROL:
  361. if (isInTheMap(cond.position))
  362. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  363. if (cond.objectID != ObjectInstanceID::NONE)
  364. {
  365. const auto * town = dynamic_cast<const CGTownInstance *>(objects[cond.objectID].get());
  366. if (town)
  367. event.onFulfill.replaceRawString(town->getNameTranslated());
  368. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  369. if (hero)
  370. event.onFulfill.replaceRawString(hero->getNameTranslated());
  371. }
  372. break;
  373. case EventCondition::DESTROY:
  374. if (isInTheMap(cond.position))
  375. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  376. if (cond.objectID != ObjectInstanceID::NONE)
  377. {
  378. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  379. if (hero)
  380. event.onFulfill.replaceRawString(hero->getNameTranslated());
  381. }
  382. break;
  383. case EventCondition::TRANSPORT:
  384. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  385. break;
  386. //break; case EventCondition::DAYS_PASSED:
  387. //break; case EventCondition::IS_HUMAN:
  388. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  389. //break; case EventCondition::STANDARD_WIN:
  390. }
  391. return cond;
  392. };
  393. event.trigger = event.trigger.morph(patcher);
  394. }
  395. }
  396. void CMap::eraseArtifactInstance(ArtifactInstanceID art)
  397. {
  398. //TODO: handle for artifacts removed in map editor
  399. artInstances[art.getNum()] = nullptr;
  400. }
  401. void CMap::moveArtifactInstance(
  402. CArtifactSet & srcSet, const ArtifactPosition & srcSlot,
  403. CArtifactSet & dstSet, const ArtifactPosition & dstSlot)
  404. {
  405. auto art = srcSet.getArt(srcSlot);
  406. removeArtifactInstance(srcSet, srcSlot);
  407. putArtifactInstance(dstSet, art->getId(), dstSlot);
  408. }
  409. void CMap::putArtifactInstance(CArtifactSet & set, ArtifactInstanceID artID, const ArtifactPosition & slot)
  410. {
  411. auto artifact = artInstances.at(artID.getNum());
  412. artifact->addPlacementMap(set.putArtifact(slot, artifact.get()));
  413. }
  414. void CMap::removeArtifactInstance(CArtifactSet & set, const ArtifactPosition & slot)
  415. {
  416. ArtifactInstanceID artID = set.getArtID(slot);
  417. auto artifact = artInstances.at(artID.getNum());
  418. assert(artifact);
  419. set.removeArtifact(slot);
  420. CArtifactSet::ArtPlacementMap partsMap;
  421. for(auto & part : artifact->getPartsInfo())
  422. {
  423. if(part.slot != ArtifactPosition::PRE_FIRST)
  424. partsMap.try_emplace(part.getArtifact(), ArtifactPosition::PRE_FIRST);
  425. }
  426. artifact->addPlacementMap(partsMap);
  427. }
  428. void CMap::generateUniqueInstanceName(CGObjectInstance * target)
  429. {
  430. //this gives object unique name even if objects are removed later
  431. auto uid = uidCounter++;
  432. boost::format fmt("%s_%d");
  433. fmt % target->getTypeName() % uid;
  434. target->instanceName = fmt.str();
  435. }
  436. void CMap::addNewObject(std::shared_ptr<CGObjectInstance> obj)
  437. {
  438. if (!obj->id.hasValue())
  439. obj->id = ObjectInstanceID(objects.size());
  440. if(obj->id != ObjectInstanceID(objects.size()) && objects.at(obj->id.getNum()) != nullptr)
  441. throw std::runtime_error("Invalid object instance id");
  442. if(obj->instanceName.empty())
  443. throw std::runtime_error("Object instance name missing");
  444. if (vstd::contains(instanceNames, obj->instanceName))
  445. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  446. if (obj->id == ObjectInstanceID(objects.size()))
  447. objects.emplace_back(obj);
  448. else
  449. objects[obj->id.getNum()] = obj;
  450. instanceNames[obj->instanceName] = obj;
  451. addBlockVisTiles(obj.get());
  452. //TODO: how about defeated heroes recruited again?
  453. obj->afterAddToMap(this);
  454. }
  455. void CMap::moveObject(ObjectInstanceID target, const int3 & dst)
  456. {
  457. auto obj = objects.at(target).get();
  458. removeBlockVisTiles(obj);
  459. obj->setAnchorPos(dst);
  460. addBlockVisTiles(obj);
  461. }
  462. std::shared_ptr<CGObjectInstance> CMap::removeObject(ObjectInstanceID oldObject)
  463. {
  464. auto obj = objects.at(oldObject);
  465. removeBlockVisTiles(obj.get());
  466. instanceNames.erase(obj->instanceName);
  467. obj->afterRemoveFromMap(this);
  468. //update indices
  469. auto iter = std::next(objects.begin(), obj->id.getNum());
  470. iter = objects.erase(iter);
  471. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  472. (*iter)->id = ObjectInstanceID(i);
  473. for (auto & town : towns)
  474. if (town.getNum() >= obj->id)
  475. town = ObjectInstanceID(town.getNum()-1);
  476. for (auto & hero : heroesOnMap)
  477. if (hero.getNum() >= obj->id)
  478. hero = ObjectInstanceID(hero.getNum()-1);
  479. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  480. {
  481. for (auto & objectID : tile->blockingObjects)
  482. if (objectID.getNum() >= obj->id)
  483. objectID = ObjectInstanceID(objectID.getNum()-1);
  484. for (auto & objectID : tile->visitableObjects)
  485. if (objectID.getNum() >= obj->id)
  486. objectID = ObjectInstanceID(objectID.getNum()-1);
  487. }
  488. //TODO: Clean artifact instances (mostly worn by hero?) and quests related to this object
  489. //This causes crash with undo/redo in editor
  490. return obj;
  491. }
  492. std::shared_ptr<CGObjectInstance> CMap::replaceObject(ObjectInstanceID oldObjectID, const std::shared_ptr<CGObjectInstance> & newObject)
  493. {
  494. auto oldObject = objects.at(oldObjectID.getNum());
  495. newObject->id = oldObjectID;
  496. removeBlockVisTiles(oldObject.get(), true);
  497. instanceNames.erase(oldObject->instanceName);
  498. objects.at(oldObjectID.getNum()) = newObject;
  499. addBlockVisTiles(newObject.get());
  500. instanceNames[newObject->instanceName] = newObject;
  501. oldObject->afterRemoveFromMap(this);
  502. newObject->afterAddToMap(this);
  503. return oldObject;
  504. }
  505. std::shared_ptr<CGObjectInstance> CMap::eraseObject(ObjectInstanceID oldObjectID)
  506. {
  507. auto oldObject = objects.at(oldObjectID.getNum());
  508. instanceNames.erase(oldObject->instanceName);
  509. objects.at(oldObjectID) = nullptr;
  510. removeBlockVisTiles(oldObject.get(), true);
  511. oldObject->afterRemoveFromMap(this);
  512. return oldObject;
  513. }
  514. void CMap::heroAddedToMap(const CGHeroInstance * hero)
  515. {
  516. assert(!vstd::contains(heroesOnMap, hero->id));
  517. heroesOnMap.push_back(hero->id);
  518. }
  519. void CMap::heroRemovedFromMap(const CGHeroInstance * hero)
  520. {
  521. assert(vstd::contains(heroesOnMap, hero->id));
  522. vstd::erase(heroesOnMap, hero->id);
  523. }
  524. void CMap::townAddedToMap(const CGTownInstance * town)
  525. {
  526. assert(!vstd::contains(towns, town->id));
  527. towns.push_back(town->id);
  528. }
  529. void CMap::townRemovedFromMap(const CGTownInstance * town)
  530. {
  531. assert(vstd::contains(towns, town->id));
  532. vstd::erase(towns, town->id);
  533. }
  534. bool CMap::isWaterMap() const
  535. {
  536. return waterMap;
  537. }
  538. bool CMap::calculateWaterContent()
  539. {
  540. size_t totalTiles = height * width * levels();
  541. size_t waterTiles = 0;
  542. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  543. {
  544. if (tile->isWater())
  545. {
  546. waterTiles++;
  547. }
  548. }
  549. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  550. {
  551. waterMap = true;
  552. }
  553. else
  554. {
  555. waterMap = false;
  556. }
  557. return waterMap;
  558. }
  559. void CMap::banWaterContent()
  560. {
  561. banWaterHeroes();
  562. banWaterArtifacts();
  563. banWaterSpells();
  564. banWaterSkills();
  565. }
  566. void CMap::banWaterSpells()
  567. {
  568. vstd::erase_if(allowedSpells, [&](SpellID spell)
  569. {
  570. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  571. });
  572. }
  573. void CMap::banWaterArtifacts()
  574. {
  575. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  576. {
  577. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  578. });
  579. }
  580. void CMap::banWaterSkills()
  581. {
  582. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  583. {
  584. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  585. });
  586. }
  587. void CMap::banWaterHeroes()
  588. {
  589. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  590. {
  591. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  592. });
  593. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  594. {
  595. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  596. });
  597. }
  598. void CMap::banHero(const HeroTypeID & id)
  599. {
  600. if (!vstd::contains(allowedHeroes, id))
  601. logGlobal->warn("Attempt to ban hero %s, who is already not allowed", id.encode(id));
  602. allowedHeroes.erase(id);
  603. }
  604. void CMap::unbanHero(const HeroTypeID & id)
  605. {
  606. if (vstd::contains(allowedHeroes, id))
  607. logGlobal->warn("Attempt to unban hero %s, who is already allowed", id.encode(id));
  608. allowedHeroes.insert(id);
  609. }
  610. void CMap::initTerrain()
  611. {
  612. terrain.resize(boost::extents[levels()][width][height]);
  613. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  614. }
  615. CMapEditManager * CMap::getEditManager()
  616. {
  617. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  618. return editManager.get();
  619. }
  620. void CMap::reindexObjects()
  621. {
  622. // Only reindex at editor / RMG operations
  623. auto oldIndex = objects;
  624. std::sort(objects.begin(), objects.end(), [](const auto & lhs, const auto & rhs)
  625. {
  626. // Obstacles first, then visitable, at the end - removable
  627. if (!lhs->isVisitable() && rhs->isVisitable())
  628. return true;
  629. if (lhs->isVisitable() && !rhs->isVisitable())
  630. return false;
  631. // Special case for Windomill - draw on top of other objects
  632. if (lhs->ID != Obj::WINDMILL && rhs->ID == Obj::WINDMILL)
  633. return true;
  634. if (lhs->ID == Obj::WINDMILL && rhs->ID != Obj::WINDMILL)
  635. return false;
  636. if (!lhs->isRemovable() && rhs->isRemovable())
  637. return true;
  638. if (lhs->isRemovable() && !rhs->isRemovable())
  639. return false;
  640. return lhs->anchorPos().y < rhs->anchorPos().y;
  641. });
  642. // instanceNames don't change
  643. for (size_t i = 0; i < objects.size(); ++i)
  644. objects[i]->id = ObjectInstanceID(i);
  645. for (auto & town : towns)
  646. town = oldIndex.at(town.getNum())->id;
  647. for (auto & hero : heroesOnMap)
  648. hero = oldIndex.at(hero.getNum())->id;
  649. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  650. {
  651. for (auto & objectID : tile->blockingObjects)
  652. objectID = oldIndex.at(objectID.getNum())->id;
  653. for (auto & objectID : tile->visitableObjects)
  654. objectID = oldIndex.at(objectID.getNum())->id;
  655. }
  656. }
  657. const IGameSettings & CMap::getSettings() const
  658. {
  659. return *gameSettings;
  660. }
  661. void CMap::overrideGameSetting(EGameSettings option, const JsonNode & input)
  662. {
  663. return gameSettings->addOverride(option, input);
  664. }
  665. void CMap::overrideGameSettings(const JsonNode & input)
  666. {
  667. return gameSettings->loadOverrides(input);
  668. }
  669. CArtifactInstance * CMap::createScroll(const SpellID & spellId)
  670. {
  671. return createArtifact(ArtifactID::SPELL_SCROLL, spellId);
  672. }
  673. CArtifactInstance * CMap::createSingleArtifact(const ArtifactID & artId, const SpellID & spellId)
  674. {
  675. auto newArtifact = artId.hasValue() ?
  676. std::make_shared<CArtifactInstance>(cb, artId.toArtifact()):
  677. std::make_shared<CArtifactInstance>(cb);
  678. newArtifact->setId(ArtifactInstanceID(artInstances.size()));
  679. artInstances.push_back(newArtifact);
  680. return newArtifact.get();
  681. }
  682. CArtifactInstance * CMap::createArtifact(const ArtifactID & artID, const SpellID & spellId)
  683. {
  684. if(!artID.hasValue())
  685. {
  686. // random, empty
  687. // TODO: make this illegal & remove? Such artifact can't be randomized as combined artifact later
  688. return createSingleArtifact(artID, spellId);
  689. }
  690. auto art = artID.toArtifact();
  691. auto artInst = createSingleArtifact(artID, spellId);
  692. if(art->isCombined() && !art->isFused())
  693. {
  694. for(const auto & part : art->getConstituents())
  695. artInst->addPart(createArtifact(part->getId(), spellId), ArtifactPosition::PRE_FIRST);
  696. }
  697. if(art->isGrowing())
  698. {
  699. auto bonus = std::make_shared<Bonus>();
  700. bonus->type = BonusType::LEVEL_COUNTER;
  701. bonus->val = 0;
  702. artInst->addNewBonus(bonus);
  703. }
  704. if(art->isScroll())
  705. {
  706. artInst->addNewBonus(std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::SPELL,
  707. BonusSource::ARTIFACT_INSTANCE, -1, BonusSourceID(ArtifactID(ArtifactID::SPELL_SCROLL)), BonusSubtypeID(spellId)));
  708. }
  709. return artInst;
  710. }
  711. CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID)
  712. {
  713. return artInstances.at(artifactID.getNum()).get();
  714. }
  715. const CArtifactInstance * CMap::getArtifactInstance(const ArtifactInstanceID & artifactID) const
  716. {
  717. return artInstances.at(artifactID.getNum()).get();
  718. }
  719. const std::vector<ObjectInstanceID> & CMap::getAllTowns()
  720. {
  721. return towns;
  722. }
  723. const std::vector<ObjectInstanceID> & CMap::getHeroesOnMap()
  724. {
  725. return heroesOnMap;
  726. }
  727. void CMap::postInitialize()
  728. {
  729. //TODO: check whether this is actually needed
  730. boost::range::sort(heroesOnMap, [this](const ObjectInstanceID & a, const ObjectInstanceID & b)
  731. {
  732. const auto aHero = std::dynamic_pointer_cast<const CGHeroInstance>(objects.at(a.getNum()));
  733. const auto bHero = std::dynamic_pointer_cast<const CGHeroInstance>(objects.at(b.getNum()));
  734. return aHero->getHeroTypeID() < bHero->getHeroTypeID();
  735. });
  736. }
  737. void CMap::addToHeroPool(std::shared_ptr<CGHeroInstance> hero)
  738. {
  739. assert(hero->getHeroTypeID().isValid());
  740. assert(!vstd::contains(heroesOnMap, hero->getHeroTypeID()));
  741. assert(heroesPool.at(hero->getHeroTypeID().getNum()) == nullptr);
  742. heroesPool.at(hero->getHeroTypeID().getNum()) = hero;
  743. if (!hero->id.hasValue())
  744. {
  745. // reserve ID for this new hero, if needed (but don't actually add it since hero is not present on map)
  746. hero->id = ObjectInstanceID(objects.size());
  747. objects.push_back(nullptr);
  748. }
  749. }
  750. CGHeroInstance * CMap::tryGetFromHeroPool(HeroTypeID hero)
  751. {
  752. return heroesPool.at(hero.getNum()).get();
  753. }
  754. std::shared_ptr<CGHeroInstance> CMap::tryTakeFromHeroPool(HeroTypeID hero)
  755. {
  756. auto result = heroesPool.at(hero.getNum());
  757. heroesPool.at(hero.getNum()) = nullptr;
  758. return result;
  759. }
  760. std::vector<HeroTypeID> CMap::getHeroesInPool() const
  761. {
  762. std::vector<HeroTypeID> result;
  763. for (const auto & hero : heroesPool)
  764. if (hero)
  765. result.push_back(hero->getHeroTypeID());
  766. return result;
  767. }
  768. CGObjectInstance * CMap::getObject(ObjectInstanceID obj)
  769. {
  770. return objects.at(obj).get();
  771. }
  772. const CGObjectInstance * CMap::getObject(ObjectInstanceID obj) const
  773. {
  774. return objects.at(obj).get();
  775. }
  776. VCMI_LIB_NAMESPACE_END