CMap.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 "../VCMI_Lib.h"
  14. #include "../CCreatureHandler.h"
  15. #include "../CHeroHandler.h"
  16. #include "../GameSettings.h"
  17. #include "../RiverHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../TerrainHandler.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. DisposedHero::DisposedHero() : heroId(0), portrait(255)
  38. {
  39. }
  40. CMapEvent::CMapEvent()
  41. : humanAffected(false)
  42. , computerAffected(false)
  43. , firstOccurrence(0)
  44. , nextOccurrence(0)
  45. {
  46. }
  47. bool CMapEvent::occursToday(int currentDay) const
  48. {
  49. if (currentDay == firstOccurrence + 1)
  50. return true;
  51. if (nextOccurrence == 0)
  52. return false;
  53. if (currentDay < firstOccurrence)
  54. return false;
  55. return (currentDay - firstOccurrence - 1) % nextOccurrence == 0;
  56. }
  57. bool CMapEvent::affectsPlayer(PlayerColor color, bool isHuman) const
  58. {
  59. if (players.count(color) == 0)
  60. return false;
  61. if (!isHuman && !computerAffected)
  62. return false;
  63. if (isHuman && !humanAffected)
  64. return false;
  65. return true;
  66. }
  67. void CMapEvent::serializeJson(JsonSerializeFormat & handler)
  68. {
  69. handler.serializeString("name", name);
  70. handler.serializeStruct("message", message);
  71. if (!handler.saving && handler.getCurrent()["players"].isNumber())
  72. {
  73. // compatibility for old maps
  74. int playersMask = 0;
  75. handler.serializeInt("players", playersMask);
  76. for (int i = 0; i < 8; ++i)
  77. if ((playersMask & (1 << i)) != 0)
  78. players.insert(PlayerColor(i));
  79. }
  80. else
  81. {
  82. handler.serializeIdArray("players", players);
  83. }
  84. handler.serializeInt("humanAffected", humanAffected);
  85. handler.serializeInt("computerAffected", computerAffected);
  86. handler.serializeInt("firstOccurrence", firstOccurrence);
  87. handler.serializeInt("nextOccurrence", nextOccurrence);
  88. resources.serializeJson(handler, "resources");
  89. if(handler.saving)
  90. {
  91. JsonNode deletedObjectsJson;
  92. for(const auto & entry : deletedObjectsCoordinates)
  93. {
  94. JsonNode values;
  95. JsonNode valueX;
  96. JsonNode valueY;
  97. JsonNode valueZ;
  98. valueX.Float() = static_cast<int>(entry.x);
  99. valueY.Float() = static_cast<int>(entry.y);
  100. valueZ.Float() = static_cast<int>(entry.z);
  101. values.Vector().push_back(valueX);
  102. values.Vector().push_back(valueY);
  103. values.Vector().push_back(valueZ);
  104. deletedObjectsJson.Vector().push_back(values);
  105. }
  106. handler.serializeRaw("deletedObjectsCoordinates", deletedObjectsJson, std::nullopt);
  107. }
  108. else
  109. {
  110. JsonNode deletedObjectsJson = handler.getCurrent()["deletedObjectsCoordinates"];
  111. for(auto const & entry : deletedObjectsJson.Vector())
  112. {
  113. int3 position;
  114. position.x = static_cast<int>(entry[0].Float());
  115. position.y = static_cast<int>(entry[1].Float());
  116. position.z = static_cast<int>(entry[2].Float());
  117. deletedObjectsCoordinates.push_back(position);
  118. }
  119. }
  120. }
  121. void CCastleEvent::serializeJson(JsonSerializeFormat & handler)
  122. {
  123. CMapEvent::serializeJson(handler);
  124. // TODO: handler.serializeIdArray("buildings", buildings);
  125. {
  126. std::vector<BuildingID> temp(buildings.begin(), buildings.end());
  127. auto a = handler.enterArray("buildings");
  128. a.syncSize(temp);
  129. for(int i = 0; i < temp.size(); ++i)
  130. {
  131. int buildingID = temp[i].getNum();
  132. a.serializeInt(i, buildingID);
  133. buildings.insert(buildingID);
  134. }
  135. }
  136. {
  137. auto a = handler.enterArray("creatures");
  138. a.syncSize(creatures);
  139. for(int i = 0; i < creatures.size(); ++i)
  140. a.serializeInt(i, creatures[i]);
  141. }
  142. }
  143. TerrainTile::TerrainTile():
  144. terType(nullptr),
  145. riverType(VLC->riverTypeHandler->getById(River::NO_RIVER)),
  146. roadType(VLC->roadTypeHandler->getById(Road::NO_ROAD)),
  147. terView(0),
  148. riverDir(0),
  149. roadDir(0),
  150. extTileFlags(0),
  151. visitable(false),
  152. blocked(false)
  153. {
  154. }
  155. bool TerrainTile::entrableTerrain(const TerrainTile * from) const
  156. {
  157. return entrableTerrain(from ? from->terType->isLand() : true, from ? from->terType->isWater() : true);
  158. }
  159. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  160. {
  161. return terType->isPassable()
  162. && ((allowSea && terType->isWater()) || (allowLand && terType->isLand()));
  163. }
  164. bool TerrainTile::isClear(const TerrainTile * from) const
  165. {
  166. return entrableTerrain(from) && !blocked;
  167. }
  168. Obj TerrainTile::topVisitableId(bool excludeTop) const
  169. {
  170. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  171. }
  172. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  173. {
  174. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  175. return nullptr;
  176. if(excludeTop)
  177. return visitableObjects[visitableObjects.size()-2];
  178. return visitableObjects.back();
  179. }
  180. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  181. {
  182. if(terType->isWater() || !terType->isPassable())
  183. return EDiggingStatus::WRONG_TERRAIN;
  184. int allowedBlocked = excludeTop ? 1 : 0;
  185. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  186. return EDiggingStatus::TILE_OCCUPIED;
  187. else
  188. return EDiggingStatus::CAN_DIG;
  189. }
  190. bool TerrainTile::hasFavorableWinds() const
  191. {
  192. return extTileFlags & 128;
  193. }
  194. bool TerrainTile::isWater() const
  195. {
  196. return terType->isWater();
  197. }
  198. CMap::CMap(IGameCallback * cb)
  199. : GameCallbackHolder(cb)
  200. , checksum(0)
  201. , grailPos(-1, -1, -1)
  202. , grailRadius(0)
  203. , waterMap(false)
  204. , uidCounter(0)
  205. {
  206. allHeroes.resize(VLC->heroh->size());
  207. allowedAbilities = VLC->skillh->getDefaultAllowed();
  208. allowedArtifact = VLC->arth->getDefaultAllowed();
  209. allowedSpells = VLC->spellh->getDefaultAllowed();
  210. gameSettings = std::make_unique<GameSettings>();
  211. gameSettings->loadBase(VLC->settingsHandler->getFullConfig());
  212. }
  213. CMap::~CMap()
  214. {
  215. getEditManager()->getUndoManager().clearAll();
  216. for(auto obj : objects)
  217. obj.dellNull();
  218. for(auto quest : quests)
  219. quest.dellNull();
  220. for(auto artInstance : artInstances)
  221. artInstance.dellNull();
  222. resetStaticData();
  223. }
  224. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  225. {
  226. const int zVal = obj->pos.z;
  227. for(int fx = 0; fx < obj->getWidth(); ++fx)
  228. {
  229. int xVal = obj->pos.x - fx;
  230. for(int fy = 0; fy < obj->getHeight(); ++fy)
  231. {
  232. int yVal = obj->pos.y - fy;
  233. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  234. {
  235. TerrainTile & curt = terrain[zVal][xVal][yVal];
  236. if(total || obj->visitableAt(xVal, yVal))
  237. {
  238. curt.visitableObjects -= obj;
  239. curt.visitable = curt.visitableObjects.size();
  240. }
  241. if(total || obj->blockingAt(xVal, yVal))
  242. {
  243. curt.blockingObjects -= obj;
  244. curt.blocked = curt.blockingObjects.size();
  245. }
  246. }
  247. }
  248. }
  249. }
  250. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  251. {
  252. const int zVal = obj->pos.z;
  253. for(int fx = 0; fx < obj->getWidth(); ++fx)
  254. {
  255. int xVal = obj->pos.x - fx;
  256. for(int fy = 0; fy < obj->getHeight(); ++fy)
  257. {
  258. int yVal = obj->pos.y - fy;
  259. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  260. {
  261. TerrainTile & curt = terrain[zVal][xVal][yVal];
  262. if(obj->visitableAt(xVal, yVal))
  263. {
  264. curt.visitableObjects.push_back(obj);
  265. curt.visitable = true;
  266. }
  267. if(obj->blockingAt(xVal, yVal))
  268. {
  269. curt.blockingObjects.push_back(obj);
  270. curt.blocked = true;
  271. }
  272. }
  273. }
  274. }
  275. }
  276. void CMap::calculateGuardingGreaturePositions()
  277. {
  278. int levels = twoLevel ? 2 : 1;
  279. for(int z = 0; z < levels; z++)
  280. {
  281. for(int x = 0; x < width; x++)
  282. {
  283. for(int y = 0; y < height; y++)
  284. {
  285. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  286. }
  287. }
  288. }
  289. }
  290. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  291. {
  292. for(auto & elem : heroesOnMap)
  293. if(elem->getHeroType() == heroID)
  294. return elem;
  295. return nullptr;
  296. }
  297. bool CMap::isCoastalTile(const int3 & pos) const
  298. {
  299. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  300. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  301. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  302. if(!isInTheMap(pos))
  303. {
  304. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  305. return false;
  306. }
  307. if(isWaterTile(pos))
  308. return false;
  309. for(const auto & dir : dirs)
  310. {
  311. const int3 hlp = pos + dir;
  312. if(!isInTheMap(hlp))
  313. continue;
  314. const TerrainTile &hlpt = getTile(hlp);
  315. if(hlpt.isWater())
  316. return true;
  317. }
  318. return false;
  319. }
  320. TerrainTile & CMap::getTile(const int3 & tile)
  321. {
  322. assert(isInTheMap(tile));
  323. return terrain[tile.z][tile.x][tile.y];
  324. }
  325. const TerrainTile & CMap::getTile(const int3 & tile) const
  326. {
  327. assert(isInTheMap(tile));
  328. return terrain[tile.z][tile.x][tile.y];
  329. }
  330. bool CMap::isWaterTile(const int3 &pos) const
  331. {
  332. return isInTheMap(pos) && getTile(pos).isWater();
  333. }
  334. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  335. {
  336. const TerrainTile * dstTile = &getTile(dst);
  337. const TerrainTile * srcTile = &getTile(src);
  338. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  339. }
  340. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  341. {
  342. if (!pom->entrableTerrain()) //rock is never accessible
  343. return false;
  344. for(auto * obj : pom->visitableObjects) //checking destination tile
  345. {
  346. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  347. continue;
  348. if (!obj->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  349. return false;
  350. }
  351. return true;
  352. }
  353. int3 CMap::guardingCreaturePosition (int3 pos) const
  354. {
  355. const int3 originalPos = pos;
  356. // Give monster at position priority.
  357. if (!isInTheMap(pos))
  358. return int3(-1, -1, -1);
  359. const TerrainTile &posTile = getTile(pos);
  360. if (posTile.visitable)
  361. {
  362. for (CGObjectInstance* obj : posTile.visitableObjects)
  363. {
  364. if (obj->ID == Obj::MONSTER)
  365. return pos;
  366. }
  367. }
  368. // See if there are any monsters adjacent.
  369. bool water = posTile.isWater();
  370. pos -= int3(1, 1, 0); // Start with top left.
  371. for (int dx = 0; dx < 3; dx++)
  372. {
  373. for (int dy = 0; dy < 3; dy++)
  374. {
  375. if (isInTheMap(pos))
  376. {
  377. const auto & tile = getTile(pos);
  378. if (tile.visitable && (tile.isWater() == water))
  379. {
  380. for (CGObjectInstance* obj : tile.visitableObjects)
  381. {
  382. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  383. {
  384. return pos;
  385. }
  386. }
  387. }
  388. }
  389. pos.y++;
  390. }
  391. pos.y -= 3;
  392. pos.x++;
  393. }
  394. return int3(-1, -1, -1);
  395. }
  396. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  397. {
  398. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  399. {
  400. if (object->ID == type)
  401. return object;
  402. }
  403. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  404. // Try to workaround that and find closest object that we can use
  405. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  406. logGlobal->error("Will try to find closest matching object");
  407. CGObjectInstance * bestMatch = nullptr;
  408. for (CGObjectInstance * object : objects)
  409. {
  410. if (object && object->ID == type)
  411. {
  412. if (bestMatch == nullptr)
  413. bestMatch = object;
  414. else
  415. {
  416. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  417. bestMatch = object;// closer than one we already found
  418. }
  419. }
  420. }
  421. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  422. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
  423. return bestMatch;
  424. }
  425. const CGObjectInstance * CMap::getObjectFrom(const int3 & pos)
  426. {
  427. for(CGObjectInstance * object : objects)
  428. {
  429. if(object->pos == pos)
  430. return object;
  431. }
  432. return nullptr;
  433. }
  434. void CMap::checkForObjectives()
  435. {
  436. // NOTE: probably should be moved to MapFormatH3M.cpp
  437. for (TriggeredEvent & event : triggeredEvents)
  438. {
  439. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  440. {
  441. switch (cond.condition)
  442. {
  443. case EventCondition::HAVE_ARTIFACT:
  444. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(VLC)->getNameTextID());
  445. break;
  446. case EventCondition::HAVE_CREATURES:
  447. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(VLC)->getNameSingularTextID());
  448. event.onFulfill.replaceNumber(cond.value);
  449. break;
  450. case EventCondition::HAVE_RESOURCES:
  451. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  452. event.onFulfill.replaceNumber(cond.value);
  453. break;
  454. case EventCondition::HAVE_BUILDING:
  455. if (isInTheMap(cond.position))
  456. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  457. break;
  458. case EventCondition::CONTROL:
  459. if (isInTheMap(cond.position))
  460. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  461. if (cond.objectID != ObjectInstanceID::NONE)
  462. {
  463. const auto * town = dynamic_cast<const CGTownInstance *>(objects[cond.objectID].get());
  464. if (town)
  465. event.onFulfill.replaceRawString(town->getNameTranslated());
  466. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  467. if (hero)
  468. event.onFulfill.replaceRawString(hero->getNameTranslated());
  469. }
  470. break;
  471. case EventCondition::DESTROY:
  472. if (isInTheMap(cond.position))
  473. cond.objectID = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>())->id;
  474. if (cond.objectID != ObjectInstanceID::NONE)
  475. {
  476. const auto * hero = dynamic_cast<const CGHeroInstance *>(objects[cond.objectID].get());
  477. if (hero)
  478. event.onFulfill.replaceRawString(hero->getNameTranslated());
  479. }
  480. break;
  481. case EventCondition::TRANSPORT:
  482. cond.objectID = getObjectiveObjectFrom(cond.position, Obj::TOWN)->id;
  483. break;
  484. //break; case EventCondition::DAYS_PASSED:
  485. //break; case EventCondition::IS_HUMAN:
  486. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  487. //break; case EventCondition::STANDARD_WIN:
  488. }
  489. return cond;
  490. };
  491. event.trigger = event.trigger.morph(patcher);
  492. }
  493. }
  494. void CMap::addNewArtifactInstance(CArtifactSet & artSet)
  495. {
  496. for(const auto & [slot, slotInfo] : artSet.artifactsWorn)
  497. {
  498. if(!slotInfo.locked && slotInfo.getArt())
  499. addNewArtifactInstance(slotInfo.artifact);
  500. }
  501. for(const auto & slotInfo : artSet.artifactsInBackpack)
  502. addNewArtifactInstance(slotInfo.artifact);
  503. }
  504. void CMap::addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art)
  505. {
  506. assert(art);
  507. assert(art->getId() == -1);
  508. art->setId(static_cast<ArtifactInstanceID>(artInstances.size()));
  509. artInstances.emplace_back(art);
  510. for(const auto & partInfo : art->getPartsInfo())
  511. addNewArtifactInstance(partInfo.art);
  512. }
  513. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  514. {
  515. //TODO: handle for artifacts removed in map editor
  516. assert(artInstances[art->getId().getNum()] == art);
  517. artInstances[art->getId().getNum()].dellNull();
  518. }
  519. void CMap::addNewQuestInstance(CQuest* quest)
  520. {
  521. quest->qid = static_cast<si32>(quests.size());
  522. quests.emplace_back(quest);
  523. }
  524. void CMap::removeQuestInstance(CQuest * quest)
  525. {
  526. //TODO: should be called only by map editor.
  527. //During game, completed quests or quests from removed objects stay forever
  528. //Shift indexes
  529. auto iter = std::next(quests.begin(), quest->qid);
  530. iter = quests.erase(iter);
  531. for (int i = quest->qid; iter != quests.end(); ++i, ++iter)
  532. {
  533. (*iter)->qid = i;
  534. }
  535. }
  536. void CMap::setUniqueInstanceName(CGObjectInstance * obj)
  537. {
  538. //this gives object unique name even if objects are removed later
  539. auto uid = uidCounter++;
  540. boost::format fmt("%s_%d");
  541. fmt % obj->typeName % uid;
  542. obj->instanceName = fmt.str();
  543. }
  544. void CMap::addNewObject(CGObjectInstance * obj)
  545. {
  546. if(obj->id != ObjectInstanceID(static_cast<si32>(objects.size())))
  547. throw std::runtime_error("Invalid object instance id");
  548. if(obj->instanceName.empty())
  549. throw std::runtime_error("Object instance name missing");
  550. if (vstd::contains(instanceNames, obj->instanceName))
  551. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  552. objects.emplace_back(obj);
  553. instanceNames[obj->instanceName] = obj;
  554. addBlockVisTiles(obj);
  555. //TODO: how about defeated heroes recruited again?
  556. obj->afterAddToMap(this);
  557. }
  558. void CMap::moveObject(CGObjectInstance * obj, const int3 & pos)
  559. {
  560. removeBlockVisTiles(obj);
  561. obj->pos = pos;
  562. addBlockVisTiles(obj);
  563. }
  564. void CMap::removeObject(CGObjectInstance * obj)
  565. {
  566. removeBlockVisTiles(obj);
  567. instanceNames.erase(obj->instanceName);
  568. //update indices
  569. auto iter = std::next(objects.begin(), obj->id.getNum());
  570. iter = objects.erase(iter);
  571. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  572. {
  573. (*iter)->id = ObjectInstanceID(i);
  574. }
  575. obj->afterRemoveFromMap(this);
  576. //TODO: Clean artifact instances (mostly worn by hero?) and quests related to this object
  577. //This causes crash with undo/redo in editor
  578. }
  579. bool CMap::isWaterMap() const
  580. {
  581. return waterMap;
  582. }
  583. bool CMap::calculateWaterContent()
  584. {
  585. size_t totalTiles = height * width * levels();
  586. size_t waterTiles = 0;
  587. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  588. {
  589. if (tile->isWater())
  590. {
  591. waterTiles++;
  592. }
  593. }
  594. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  595. {
  596. waterMap = true;
  597. }
  598. else
  599. {
  600. waterMap = false;
  601. }
  602. return waterMap;
  603. }
  604. void CMap::banWaterContent()
  605. {
  606. banWaterHeroes();
  607. banWaterArtifacts();
  608. banWaterSpells();
  609. banWaterSkills();
  610. }
  611. void CMap::banWaterSpells()
  612. {
  613. vstd::erase_if(allowedSpells, [&](SpellID spell)
  614. {
  615. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  616. });
  617. }
  618. void CMap::banWaterArtifacts()
  619. {
  620. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  621. {
  622. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  623. });
  624. }
  625. void CMap::banWaterSkills()
  626. {
  627. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  628. {
  629. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  630. });
  631. }
  632. void CMap::banWaterHeroes()
  633. {
  634. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  635. {
  636. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  637. });
  638. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  639. {
  640. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  641. });
  642. }
  643. void CMap::banHero(const HeroTypeID & id)
  644. {
  645. if (!vstd::contains(allowedHeroes, id))
  646. logGlobal->warn("Attempt to ban hero %s, who is already not allowed", id.encode(id));
  647. allowedHeroes.erase(id);
  648. }
  649. void CMap::unbanHero(const HeroTypeID & id)
  650. {
  651. if (vstd::contains(allowedHeroes, id))
  652. logGlobal->warn("Attempt to unban hero %s, who is already allowed", id.encode(id));
  653. allowedHeroes.insert(id);
  654. }
  655. void CMap::initTerrain()
  656. {
  657. terrain.resize(boost::extents[levels()][width][height]);
  658. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  659. }
  660. CMapEditManager * CMap::getEditManager()
  661. {
  662. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  663. return editManager.get();
  664. }
  665. void CMap::resetStaticData()
  666. {
  667. obeliskCount = 0;
  668. obelisksVisited.clear();
  669. townMerchantArtifacts.clear();
  670. townUniversitySkills.clear();
  671. }
  672. void CMap::resolveQuestIdentifiers()
  673. {
  674. //FIXME: move to CMapLoaderH3M
  675. for (auto & quest : quests)
  676. {
  677. if (quest && quest->killTarget != ObjectInstanceID::NONE)
  678. quest->killTarget = questIdentifierToId[quest->killTarget.getNum()];
  679. }
  680. questIdentifierToId.clear();
  681. }
  682. void CMap::reindexObjects()
  683. {
  684. // Only reindex at editor / RMG operations
  685. std::sort(objects.begin(), objects.end(), [](const CGObjectInstance * lhs, const CGObjectInstance * rhs)
  686. {
  687. // Obstacles first, then visitable, at the end - removable
  688. if (!lhs->isVisitable() && rhs->isVisitable())
  689. return true;
  690. if (lhs->isVisitable() && !rhs->isVisitable())
  691. return false;
  692. // Special case for Windomill - draw on top of other objects
  693. if (lhs->ID != Obj::WINDMILL && rhs->ID == Obj::WINDMILL)
  694. return true;
  695. if (lhs->ID == Obj::WINDMILL && rhs->ID != Obj::WINDMILL)
  696. return false;
  697. if (!lhs->isRemovable() && rhs->isRemovable())
  698. return true;
  699. if (lhs->isRemovable() && !rhs->isRemovable())
  700. return false;
  701. return lhs->pos.y < rhs->pos.y;
  702. });
  703. // instanceNames don't change
  704. for (size_t i = 0; i < objects.size(); ++i)
  705. {
  706. objects[i]->id = ObjectInstanceID(i);
  707. }
  708. }
  709. const IGameSettings & CMap::getSettings() const
  710. {
  711. return *gameSettings;
  712. }
  713. void CMap::overrideGameSetting(EGameSettings option, const JsonNode & input)
  714. {
  715. return gameSettings->addOverride(option, input);
  716. }
  717. void CMap::overrideGameSettings(const JsonNode & input)
  718. {
  719. return gameSettings->loadOverrides(input);
  720. }
  721. VCMI_LIB_NAMESPACE_END