CMap.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 "../CTownHandler.h"
  16. #include "../CHeroHandler.h"
  17. #include "../RiverHandler.h"
  18. #include "../RoadHandler.h"
  19. #include "../TerrainHandler.h"
  20. #include "../mapObjects/CObjectClassesHandler.h"
  21. #include "../mapObjects/CGHeroInstance.h"
  22. #include "../CGeneralTextHandler.h"
  23. #include "../spells/CSpellHandler.h"
  24. #include "../CSkillHandler.h"
  25. #include "CMapEditManager.h"
  26. #include "../serializer/JsonSerializeFormat.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. SHeroName::SHeroName() : heroId(-1)
  29. {
  30. }
  31. PlayerInfo::PlayerInfo(): canHumanPlay(false), canComputerPlay(false),
  32. aiTactic(EAiTactic::RANDOM), isFactionRandom(false), hasRandomHero(false), mainCustomHeroPortrait(-1), mainCustomHeroId(-1), hasMainTown(false),
  33. generateHeroAtMainTown(false), posOfMainTown(-1), team(TeamID::NO_TEAM), /* following are unused */ generateHero(false), p7(0), powerPlaceholders(-1)
  34. {
  35. allowedFactions = VLC->townh->getAllowedFactions();
  36. }
  37. si8 PlayerInfo::defaultCastle() const
  38. {
  39. //if random allowed set it as default
  40. if(isFactionRandom)
  41. return -1;
  42. if(!allowedFactions.empty())
  43. return *allowedFactions.begin();
  44. // fall back to random
  45. return -1;
  46. }
  47. si8 PlayerInfo::defaultHero() const
  48. {
  49. // we will generate hero in front of main town
  50. if((generateHeroAtMainTown && hasMainTown) || hasRandomHero)
  51. {
  52. //random hero
  53. return -1;
  54. }
  55. return -2;
  56. }
  57. bool PlayerInfo::canAnyonePlay() const
  58. {
  59. return canHumanPlay || canComputerPlay;
  60. }
  61. bool PlayerInfo::hasCustomMainHero() const
  62. {
  63. return !mainCustomHeroName.empty() && mainCustomHeroPortrait != -1;
  64. }
  65. EventCondition::EventCondition(EWinLoseType condition):
  66. object(nullptr),
  67. metaType(EMetaclass::INVALID),
  68. value(-1),
  69. objectType(-1),
  70. objectSubtype(-1),
  71. position(-1, -1, -1),
  72. condition(condition)
  73. {
  74. }
  75. EventCondition::EventCondition(EWinLoseType condition, si32 value, si32 objectType, int3 position):
  76. object(nullptr),
  77. metaType(EMetaclass::INVALID),
  78. value(value),
  79. objectType(objectType),
  80. objectSubtype(-1),
  81. position(position),
  82. condition(condition)
  83. {}
  84. void Rumor::serializeJson(JsonSerializeFormat & handler)
  85. {
  86. handler.serializeString("name", name);
  87. handler.serializeString("text", text);
  88. }
  89. DisposedHero::DisposedHero() : heroId(0), portrait(255), players(0)
  90. {
  91. }
  92. CMapEvent::CMapEvent() : players(0), humanAffected(0), computerAffected(0),
  93. firstOccurence(0), nextOccurence(0)
  94. {
  95. }
  96. bool CMapEvent::earlierThan(const CMapEvent & other) const
  97. {
  98. return firstOccurence < other.firstOccurence;
  99. }
  100. bool CMapEvent::earlierThanOrEqual(const CMapEvent & other) const
  101. {
  102. return firstOccurence <= other.firstOccurence;
  103. }
  104. CCastleEvent::CCastleEvent() : town(nullptr)
  105. {
  106. }
  107. TerrainTile::TerrainTile():
  108. terType(nullptr),
  109. terView(0),
  110. riverType(VLC->riverTypeHandler->getById(River::NO_RIVER)),
  111. riverDir(0),
  112. roadType(VLC->roadTypeHandler->getById(Road::NO_ROAD)),
  113. roadDir(0),
  114. extTileFlags(0),
  115. visitable(false),
  116. blocked(false)
  117. {
  118. }
  119. bool TerrainTile::entrableTerrain(const TerrainTile * from) const
  120. {
  121. return entrableTerrain(from ? from->terType->isLand() : true, from ? from->terType->isWater() : true);
  122. }
  123. bool TerrainTile::entrableTerrain(bool allowLand, bool allowSea) const
  124. {
  125. return terType->isPassable()
  126. && ((allowSea && terType->isWater()) || (allowLand && terType->isLand()));
  127. }
  128. bool TerrainTile::isClear(const TerrainTile * from) const
  129. {
  130. return entrableTerrain(from) && !blocked;
  131. }
  132. Obj TerrainTile::topVisitableId(bool excludeTop) const
  133. {
  134. return topVisitableObj(excludeTop) ? topVisitableObj(excludeTop)->ID : Obj(Obj::NO_OBJ);
  135. }
  136. CGObjectInstance * TerrainTile::topVisitableObj(bool excludeTop) const
  137. {
  138. if(visitableObjects.empty() || (excludeTop && visitableObjects.size() == 1))
  139. return nullptr;
  140. if(excludeTop)
  141. return visitableObjects[visitableObjects.size()-2];
  142. return visitableObjects.back();
  143. }
  144. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  145. {
  146. if(terType->isWater() || !terType->isPassable())
  147. return EDiggingStatus::WRONG_TERRAIN;
  148. int allowedBlocked = excludeTop ? 1 : 0;
  149. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  150. return EDiggingStatus::TILE_OCCUPIED;
  151. else
  152. return EDiggingStatus::CAN_DIG;
  153. }
  154. bool TerrainTile::hasFavorableWinds() const
  155. {
  156. return extTileFlags & 128;
  157. }
  158. bool TerrainTile::isWater() const
  159. {
  160. return terType->isWater();
  161. }
  162. void CMapHeader::setupEvents()
  163. {
  164. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  165. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  166. defeatCondition.value = 7;
  167. //Victory condition - defeat all
  168. TriggeredEvent standardVictory;
  169. standardVictory.effect.type = EventEffect::VICTORY;
  170. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  171. standardVictory.identifier = "standardVictory";
  172. standardVictory.description.clear(); // TODO: display in quest window
  173. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  174. standardVictory.trigger = EventExpression(victoryCondition);
  175. //Loss condition - 7 days without town
  176. TriggeredEvent standardDefeat;
  177. standardDefeat.effect.type = EventEffect::DEFEAT;
  178. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  179. standardDefeat.identifier = "standardDefeat";
  180. standardDefeat.description.clear(); // TODO: display in quest window
  181. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  182. standardDefeat.trigger = EventExpression(defeatCondition);
  183. triggeredEvents.push_back(standardVictory);
  184. triggeredEvents.push_back(standardDefeat);
  185. victoryIconIndex = 11;
  186. victoryMessage = VLC->generaltexth->victoryConditions[0];
  187. defeatIconIndex = 3;
  188. defeatMessage = VLC->generaltexth->lossCondtions[0];
  189. }
  190. CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
  191. twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
  192. {
  193. setupEvents();
  194. allowedHeroes = VLC->heroh->getDefaultAllowed();
  195. players.resize(PlayerColor::PLAYER_LIMIT_I);
  196. }
  197. CMapHeader::~CMapHeader()
  198. {
  199. }
  200. ui8 CMapHeader::levels() const
  201. {
  202. return (twoLevel ? 2 : 1);
  203. }
  204. CMap::CMap()
  205. : checksum(0), grailPos(-1, -1, -1), grailRadius(0), terrain(nullptr),
  206. guardingCreaturePositions(nullptr),
  207. uidCounter(0)
  208. {
  209. allHeroes.resize(allowedHeroes.size());
  210. allowedAbilities = VLC->skillh->getDefaultAllowed();
  211. allowedArtifact = VLC->arth->getDefaultAllowed();
  212. allowedSpell = VLC->spellh->getDefaultAllowed();
  213. }
  214. CMap::~CMap()
  215. {
  216. getEditManager()->getUndoManager().clearAll();
  217. if(terrain)
  218. {
  219. for(int z = 0; z < levels(); z++)
  220. {
  221. for(int x = 0; x < width; x++)
  222. {
  223. delete[] terrain[z][x];
  224. delete[] guardingCreaturePositions[z][x];
  225. }
  226. delete[] terrain[z];
  227. delete[] guardingCreaturePositions[z];
  228. }
  229. delete [] terrain;
  230. delete [] guardingCreaturePositions;
  231. }
  232. for(auto obj : objects)
  233. obj.dellNull();
  234. for(auto quest : quests)
  235. quest.dellNull();
  236. resetStaticData();
  237. }
  238. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  239. {
  240. const int zVal = obj->pos.z;
  241. for(int fx = 0; fx < obj->getWidth(); ++fx)
  242. {
  243. int xVal = obj->pos.x - fx;
  244. for(int fy = 0; fy < obj->getHeight(); ++fy)
  245. {
  246. int yVal = obj->pos.y - fy;
  247. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  248. {
  249. TerrainTile & curt = terrain[zVal][xVal][yVal];
  250. if(total || obj->visitableAt(xVal, yVal))
  251. {
  252. curt.visitableObjects -= obj;
  253. curt.visitable = curt.visitableObjects.size();
  254. }
  255. if(total || obj->blockingAt(xVal, yVal))
  256. {
  257. curt.blockingObjects -= obj;
  258. curt.blocked = curt.blockingObjects.size();
  259. }
  260. }
  261. }
  262. }
  263. }
  264. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  265. {
  266. const int zVal = obj->pos.z;
  267. for(int fx = 0; fx < obj->getWidth(); ++fx)
  268. {
  269. int xVal = obj->pos.x - fx;
  270. for(int fy = 0; fy < obj->getHeight(); ++fy)
  271. {
  272. int yVal = obj->pos.y - fy;
  273. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  274. {
  275. TerrainTile & curt = terrain[zVal][xVal][yVal];
  276. if(obj->visitableAt(xVal, yVal))
  277. {
  278. curt.visitableObjects.push_back(obj);
  279. curt.visitable = true;
  280. }
  281. if(obj->blockingAt(xVal, yVal))
  282. {
  283. curt.blockingObjects.push_back(obj);
  284. curt.blocked = true;
  285. }
  286. }
  287. }
  288. }
  289. }
  290. void CMap::calculateGuardingGreaturePositions()
  291. {
  292. int levels = twoLevel ? 2 : 1;
  293. for(int z = 0; z < levels; z++)
  294. {
  295. for(int x = 0; x < width; x++)
  296. {
  297. for(int y = 0; y < height; y++)
  298. {
  299. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  300. }
  301. }
  302. }
  303. }
  304. CGHeroInstance * CMap::getHero(int heroID)
  305. {
  306. for(auto & elem : heroesOnMap)
  307. if(elem->subID == heroID)
  308. return elem;
  309. return nullptr;
  310. }
  311. bool CMap::isCoastalTile(const int3 & pos) const
  312. {
  313. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  314. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  315. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  316. if(!isInTheMap(pos))
  317. {
  318. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  319. return false;
  320. }
  321. if(isWaterTile(pos))
  322. return false;
  323. for (auto & dir : dirs)
  324. {
  325. const int3 hlp = pos + dir;
  326. if(!isInTheMap(hlp))
  327. continue;
  328. const TerrainTile &hlpt = getTile(hlp);
  329. if(hlpt.isWater())
  330. return true;
  331. }
  332. return false;
  333. }
  334. bool CMap::isInTheMap(const int3 & pos) const
  335. {
  336. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  337. || pos.z > (twoLevel ? 1 : 0))
  338. {
  339. return false;
  340. }
  341. else
  342. {
  343. return true;
  344. }
  345. }
  346. TerrainTile & CMap::getTile(const int3 & tile)
  347. {
  348. assert(isInTheMap(tile));
  349. return terrain[tile.z][tile.x][tile.y];
  350. }
  351. const TerrainTile & CMap::getTile(const int3 & tile) const
  352. {
  353. assert(isInTheMap(tile));
  354. return terrain[tile.z][tile.x][tile.y];
  355. }
  356. bool CMap::isWaterTile(const int3 &pos) const
  357. {
  358. return isInTheMap(pos) && getTile(pos).isWater();
  359. }
  360. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  361. {
  362. const TerrainTile * dstTile = &getTile(dst);
  363. const TerrainTile * srcTile = &getTile(src);
  364. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  365. }
  366. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  367. {
  368. if (!pom->entrableTerrain()) //rock is never accessible
  369. return false;
  370. for (auto obj : pom->visitableObjects) //checking destination tile
  371. {
  372. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  373. continue;
  374. if (!obj->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  375. return false;
  376. }
  377. return true;
  378. }
  379. int3 CMap::guardingCreaturePosition (int3 pos) const
  380. {
  381. const int3 originalPos = pos;
  382. // Give monster at position priority.
  383. if (!isInTheMap(pos))
  384. return int3(-1, -1, -1);
  385. const TerrainTile &posTile = getTile(pos);
  386. if (posTile.visitable)
  387. {
  388. for (CGObjectInstance* obj : posTile.visitableObjects)
  389. {
  390. if(obj->blockVisit)
  391. {
  392. if (obj->ID == Obj::MONSTER) // Monster
  393. return pos;
  394. else
  395. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  396. }
  397. }
  398. }
  399. // See if there are any monsters adjacent.
  400. bool water = posTile.isWater();
  401. pos -= int3(1, 1, 0); // Start with top left.
  402. for (int dx = 0; dx < 3; dx++)
  403. {
  404. for (int dy = 0; dy < 3; dy++)
  405. {
  406. if (isInTheMap(pos))
  407. {
  408. const auto & tile = getTile(pos);
  409. if (tile.visitable && (tile.isWater() == water))
  410. {
  411. for (CGObjectInstance* obj : tile.visitableObjects)
  412. {
  413. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  414. {
  415. return pos;
  416. }
  417. }
  418. }
  419. }
  420. pos.y++;
  421. }
  422. pos.y -= 3;
  423. pos.x++;
  424. }
  425. return int3(-1, -1, -1);
  426. }
  427. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  428. {
  429. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  430. {
  431. if (object->ID == type)
  432. return object;
  433. }
  434. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  435. // Try to workaround that and find closest object that we can use
  436. logGlobal->error("Failed to find object of type %d at %s", int(type), pos.toString());
  437. logGlobal->error("Will try to find closest matching object");
  438. CGObjectInstance * bestMatch = nullptr;
  439. for (CGObjectInstance * object : objects)
  440. {
  441. if (object && object->ID == type)
  442. {
  443. if (bestMatch == nullptr)
  444. bestMatch = object;
  445. else
  446. {
  447. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  448. bestMatch = object;// closer than one we already found
  449. }
  450. }
  451. }
  452. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  453. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
  454. return bestMatch;
  455. }
  456. void CMap::checkForObjectives()
  457. {
  458. // NOTE: probably should be moved to MapFormatH3M.cpp
  459. for (TriggeredEvent & event : triggeredEvents)
  460. {
  461. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  462. {
  463. switch (cond.condition)
  464. {
  465. case EventCondition::HAVE_ARTIFACT:
  466. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->objects[cond.objectType]->getNameTranslated());
  467. break;
  468. case EventCondition::HAVE_CREATURES:
  469. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->objects[cond.objectType]->getNameSingularTranslated());
  470. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  471. break;
  472. case EventCondition::HAVE_RESOURCES:
  473. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  474. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  475. break;
  476. case EventCondition::HAVE_BUILDING:
  477. if (isInTheMap(cond.position))
  478. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  479. break;
  480. case EventCondition::CONTROL:
  481. if (isInTheMap(cond.position))
  482. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  483. if (cond.object)
  484. {
  485. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  486. if (town)
  487. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  488. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  489. if (hero)
  490. boost::algorithm::replace_first(event.onFulfill, "%s", hero->getNameTranslated());
  491. }
  492. break;
  493. case EventCondition::DESTROY:
  494. if (isInTheMap(cond.position))
  495. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  496. if (cond.object)
  497. {
  498. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  499. if (hero)
  500. boost::algorithm::replace_first(event.onFulfill, "%s", hero->getNameTranslated());
  501. }
  502. break;
  503. case EventCondition::TRANSPORT:
  504. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  505. break;
  506. //break; case EventCondition::DAYS_PASSED:
  507. //break; case EventCondition::IS_HUMAN:
  508. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  509. //break; case EventCondition::STANDARD_WIN:
  510. //TODO: support new condition format
  511. case EventCondition::HAVE_0:
  512. break;
  513. case EventCondition::DESTROY_0:
  514. break;
  515. case EventCondition::HAVE_BUILDING_0:
  516. break;
  517. }
  518. return cond;
  519. };
  520. event.trigger = event.trigger.morph(patcher);
  521. }
  522. }
  523. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  524. {
  525. art->id = ArtifactInstanceID((si32)artInstances.size());
  526. artInstances.push_back(art);
  527. }
  528. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  529. {
  530. //TODO: handle for artifacts removed in map editor
  531. assert(artInstances[art->id.getNum()] == art);
  532. artInstances[art->id.getNum()].dellNull();
  533. }
  534. void CMap::addNewQuestInstance(CQuest* quest)
  535. {
  536. quest->qid = static_cast<si32>(quests.size());
  537. quests.push_back(quest);
  538. }
  539. void CMap::removeQuestInstance(CQuest * quest)
  540. {
  541. //TODO: should be called only by map editor.
  542. //During game, completed quests or quests from removed objects stay forever
  543. //Shift indexes
  544. auto iter = std::next(quests.begin(), quest->qid);
  545. iter = quests.erase(iter);
  546. for (int i = quest->qid; iter != quests.end(); ++i, ++iter)
  547. {
  548. (*iter)->qid = i;
  549. }
  550. }
  551. void CMap::setUniqueInstanceName(CGObjectInstance * obj)
  552. {
  553. //this gives object unique name even if objects are removed later
  554. auto uid = uidCounter++;
  555. boost::format fmt("%s_%d");
  556. fmt % obj->typeName % uid;
  557. obj->instanceName = fmt.str();
  558. }
  559. void CMap::addNewObject(CGObjectInstance * obj)
  560. {
  561. if(obj->id != ObjectInstanceID((si32)objects.size()))
  562. throw std::runtime_error("Invalid object instance id");
  563. if(obj->instanceName.empty())
  564. throw std::runtime_error("Object instance name missing");
  565. if (vstd::contains(instanceNames, obj->instanceName))
  566. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  567. objects.push_back(obj);
  568. instanceNames[obj->instanceName] = obj;
  569. addBlockVisTiles(obj);
  570. //TODO: how about defeated heroes recruited again?
  571. obj->afterAddToMap(this);
  572. }
  573. void CMap::moveObject(CGObjectInstance * obj, const int3 & pos)
  574. {
  575. removeBlockVisTiles(obj);
  576. obj->pos = pos;
  577. addBlockVisTiles(obj);
  578. }
  579. void CMap::removeObject(CGObjectInstance * obj)
  580. {
  581. removeBlockVisTiles(obj);
  582. instanceNames.erase(obj->instanceName);
  583. //update indeces
  584. auto iter = std::next(objects.begin(), obj->id.getNum());
  585. iter = objects.erase(iter);
  586. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  587. {
  588. (*iter)->id = ObjectInstanceID(i);
  589. }
  590. obj->afterRemoveFromMap(this);
  591. //TOOD: Clean artifact instances (mostly worn by hero?) and quests related to this object
  592. }
  593. void CMap::initTerrain()
  594. {
  595. int level = levels();
  596. terrain = new TerrainTile**[level];
  597. guardingCreaturePositions = new int3**[level];
  598. for(int z = 0; z < level; ++z)
  599. {
  600. terrain[z] = new TerrainTile*[width];
  601. guardingCreaturePositions[z] = new int3*[width];
  602. for(int x = 0; x < width; ++x)
  603. {
  604. terrain[z][x] = new TerrainTile[height];
  605. guardingCreaturePositions[z][x] = new int3[height];
  606. }
  607. }
  608. }
  609. CMapEditManager * CMap::getEditManager()
  610. {
  611. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  612. return editManager.get();
  613. }
  614. void CMap::resetStaticData()
  615. {
  616. CGKeys::reset();
  617. CGMagi::reset();
  618. CGObelisk::reset();
  619. CGTownInstance::reset();
  620. }
  621. VCMI_LIB_NAMESPACE_END