CMap.cpp 25 KB

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