CMap.cpp 16 KB

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