CMap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. for(auto artInstance : artInstances)
  156. artInstance.dellNull();
  157. resetStaticData();
  158. }
  159. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  160. {
  161. const int zVal = obj->pos.z;
  162. for(int fx = 0; fx < obj->getWidth(); ++fx)
  163. {
  164. int xVal = obj->pos.x - fx;
  165. for(int fy = 0; fy < obj->getHeight(); ++fy)
  166. {
  167. int yVal = obj->pos.y - fy;
  168. if(xVal>=0 && xVal < width && yVal>=0 && yVal < height)
  169. {
  170. TerrainTile & curt = terrain[zVal][xVal][yVal];
  171. if(total || obj->visitableAt(xVal, yVal))
  172. {
  173. curt.visitableObjects -= obj;
  174. curt.visitable = curt.visitableObjects.size();
  175. }
  176. if(total || obj->blockingAt(xVal, yVal))
  177. {
  178. curt.blockingObjects -= obj;
  179. curt.blocked = curt.blockingObjects.size();
  180. }
  181. }
  182. }
  183. }
  184. }
  185. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  186. {
  187. const int zVal = obj->pos.z;
  188. for(int fx = 0; fx < obj->getWidth(); ++fx)
  189. {
  190. int xVal = obj->pos.x - fx;
  191. for(int fy = 0; fy < obj->getHeight(); ++fy)
  192. {
  193. int yVal = obj->pos.y - fy;
  194. if(xVal>=0 && xVal < width && yVal >= 0 && yVal < height)
  195. {
  196. TerrainTile & curt = terrain[zVal][xVal][yVal];
  197. if(obj->visitableAt(xVal, yVal))
  198. {
  199. curt.visitableObjects.push_back(obj);
  200. curt.visitable = true;
  201. }
  202. if(obj->blockingAt(xVal, yVal))
  203. {
  204. curt.blockingObjects.push_back(obj);
  205. curt.blocked = true;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. void CMap::calculateGuardingGreaturePositions()
  212. {
  213. int levels = twoLevel ? 2 : 1;
  214. for(int z = 0; z < levels; z++)
  215. {
  216. for(int x = 0; x < width; x++)
  217. {
  218. for(int y = 0; y < height; y++)
  219. {
  220. guardingCreaturePositions[z][x][y] = guardingCreaturePosition(int3(x, y, z));
  221. }
  222. }
  223. }
  224. }
  225. CGHeroInstance * CMap::getHero(HeroTypeID heroID)
  226. {
  227. for(auto & elem : heroesOnMap)
  228. if(elem->getHeroType() == heroID)
  229. return elem;
  230. return nullptr;
  231. }
  232. bool CMap::isCoastalTile(const int3 & pos) const
  233. {
  234. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  235. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  236. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  237. if(!isInTheMap(pos))
  238. {
  239. logGlobal->error("Coastal check outside of map: %s", pos.toString());
  240. return false;
  241. }
  242. if(isWaterTile(pos))
  243. return false;
  244. for(const auto & dir : dirs)
  245. {
  246. const int3 hlp = pos + dir;
  247. if(!isInTheMap(hlp))
  248. continue;
  249. const TerrainTile &hlpt = getTile(hlp);
  250. if(hlpt.isWater())
  251. return true;
  252. }
  253. return false;
  254. }
  255. bool CMap::isInTheMap(const int3 & pos) const
  256. {
  257. return pos.x >= 0 && pos.y >= 0 && pos.z >= 0 && pos.x < width && pos.y < height && pos.z <= (twoLevel ? 1 : 0);
  258. }
  259. TerrainTile & CMap::getTile(const int3 & tile)
  260. {
  261. assert(isInTheMap(tile));
  262. return terrain[tile.z][tile.x][tile.y];
  263. }
  264. const TerrainTile & CMap::getTile(const int3 & tile) const
  265. {
  266. assert(isInTheMap(tile));
  267. return terrain[tile.z][tile.x][tile.y];
  268. }
  269. bool CMap::isWaterTile(const int3 &pos) const
  270. {
  271. return isInTheMap(pos) && getTile(pos).isWater();
  272. }
  273. bool CMap::canMoveBetween(const int3 &src, const int3 &dst) const
  274. {
  275. const TerrainTile * dstTile = &getTile(dst);
  276. const TerrainTile * srcTile = &getTile(src);
  277. return checkForVisitableDir(src, dstTile, dst) && checkForVisitableDir(dst, srcTile, src);
  278. }
  279. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile * pom, const int3 & dst) const
  280. {
  281. if (!pom->entrableTerrain()) //rock is never accessible
  282. return false;
  283. for(auto * obj : pom->visitableObjects) //checking destination tile
  284. {
  285. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  286. continue;
  287. if (!obj->appearance->isVisitableFrom(src.x - dst.x, src.y - dst.y))
  288. return false;
  289. }
  290. return true;
  291. }
  292. int3 CMap::guardingCreaturePosition (int3 pos) const
  293. {
  294. const int3 originalPos = pos;
  295. // Give monster at position priority.
  296. if (!isInTheMap(pos))
  297. return int3(-1, -1, -1);
  298. const TerrainTile &posTile = getTile(pos);
  299. if (posTile.visitable)
  300. {
  301. for (CGObjectInstance* obj : posTile.visitableObjects)
  302. {
  303. if(obj->isBlockedVisitable())
  304. {
  305. if (obj->ID == Obj::MONSTER) // Monster
  306. return pos;
  307. else
  308. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  309. }
  310. }
  311. }
  312. // See if there are any monsters adjacent.
  313. bool water = posTile.isWater();
  314. pos -= int3(1, 1, 0); // Start with top left.
  315. for (int dx = 0; dx < 3; dx++)
  316. {
  317. for (int dy = 0; dy < 3; dy++)
  318. {
  319. if (isInTheMap(pos))
  320. {
  321. const auto & tile = getTile(pos);
  322. if (tile.visitable && (tile.isWater() == water))
  323. {
  324. for (CGObjectInstance* obj : tile.visitableObjects)
  325. {
  326. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  327. {
  328. return pos;
  329. }
  330. }
  331. }
  332. }
  333. pos.y++;
  334. }
  335. pos.y -= 3;
  336. pos.x++;
  337. }
  338. return int3(-1, -1, -1);
  339. }
  340. const CGObjectInstance * CMap::getObjectiveObjectFrom(const int3 & pos, Obj type)
  341. {
  342. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  343. {
  344. if (object->ID == type)
  345. return object;
  346. }
  347. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  348. // Try to workaround that and find closest object that we can use
  349. logGlobal->error("Failed to find object of type %d at %s", type.getNum(), pos.toString());
  350. logGlobal->error("Will try to find closest matching object");
  351. CGObjectInstance * bestMatch = nullptr;
  352. for (CGObjectInstance * object : objects)
  353. {
  354. if (object && object->ID == type)
  355. {
  356. if (bestMatch == nullptr)
  357. bestMatch = object;
  358. else
  359. {
  360. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  361. bestMatch = object;// closer than one we already found
  362. }
  363. }
  364. }
  365. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  366. logGlobal->error("Will use %s from %s", bestMatch->getObjectName(), bestMatch->pos.toString());
  367. return bestMatch;
  368. }
  369. void CMap::checkForObjectives()
  370. {
  371. // NOTE: probably should be moved to MapFormatH3M.cpp
  372. for (TriggeredEvent & event : triggeredEvents)
  373. {
  374. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  375. {
  376. switch (cond.condition)
  377. {
  378. case EventCondition::HAVE_ARTIFACT:
  379. event.onFulfill.replaceTextID(cond.objectType.as<ArtifactID>().toEntity(VLC)->getNameTextID());
  380. break;
  381. case EventCondition::HAVE_CREATURES:
  382. event.onFulfill.replaceTextID(cond.objectType.as<CreatureID>().toEntity(VLC)->getNameSingularTextID());
  383. event.onFulfill.replaceNumber(cond.value);
  384. break;
  385. case EventCondition::HAVE_RESOURCES:
  386. event.onFulfill.replaceName(cond.objectType.as<GameResID>());
  387. event.onFulfill.replaceNumber(cond.value);
  388. break;
  389. case EventCondition::HAVE_BUILDING:
  390. if (isInTheMap(cond.position))
  391. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  392. break;
  393. case EventCondition::CONTROL:
  394. if (isInTheMap(cond.position))
  395. cond.object = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>());
  396. if (cond.object)
  397. {
  398. const auto * town = dynamic_cast<const CGTownInstance *>(cond.object);
  399. if (town)
  400. event.onFulfill.replaceRawString(town->getNameTranslated());
  401. const auto * hero = dynamic_cast<const CGHeroInstance *>(cond.object);
  402. if (hero)
  403. event.onFulfill.replaceRawString(hero->getNameTranslated());
  404. }
  405. break;
  406. case EventCondition::DESTROY:
  407. if (isInTheMap(cond.position))
  408. cond.object = getObjectiveObjectFrom(cond.position, cond.objectType.as<MapObjectID>());
  409. if (cond.object)
  410. {
  411. const auto * hero = dynamic_cast<const CGHeroInstance *>(cond.object);
  412. if (hero)
  413. event.onFulfill.replaceRawString(hero->getNameTranslated());
  414. }
  415. break;
  416. case EventCondition::TRANSPORT:
  417. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  418. break;
  419. //break; case EventCondition::DAYS_PASSED:
  420. //break; case EventCondition::IS_HUMAN:
  421. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  422. //break; case EventCondition::STANDARD_WIN:
  423. }
  424. return cond;
  425. };
  426. event.trigger = event.trigger.morph(patcher);
  427. }
  428. }
  429. void CMap::addNewArtifactInstance(ConstTransitivePtr<CArtifactInstance> art)
  430. {
  431. art->setId(static_cast<ArtifactInstanceID>(artInstances.size()));
  432. artInstances.emplace_back(art);
  433. }
  434. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  435. {
  436. //TODO: handle for artifacts removed in map editor
  437. assert(artInstances[art->getId().getNum()] == art);
  438. artInstances[art->getId().getNum()].dellNull();
  439. }
  440. void CMap::addNewQuestInstance(CQuest* quest)
  441. {
  442. quest->qid = static_cast<si32>(quests.size());
  443. quests.emplace_back(quest);
  444. }
  445. void CMap::removeQuestInstance(CQuest * quest)
  446. {
  447. //TODO: should be called only by map editor.
  448. //During game, completed quests or quests from removed objects stay forever
  449. //Shift indexes
  450. auto iter = std::next(quests.begin(), quest->qid);
  451. iter = quests.erase(iter);
  452. for (int i = quest->qid; iter != quests.end(); ++i, ++iter)
  453. {
  454. (*iter)->qid = i;
  455. }
  456. }
  457. void CMap::setUniqueInstanceName(CGObjectInstance * obj)
  458. {
  459. //this gives object unique name even if objects are removed later
  460. auto uid = uidCounter++;
  461. boost::format fmt("%s_%d");
  462. fmt % obj->typeName % uid;
  463. obj->instanceName = fmt.str();
  464. }
  465. void CMap::addNewObject(CGObjectInstance * obj)
  466. {
  467. if(obj->id != ObjectInstanceID(static_cast<si32>(objects.size())))
  468. throw std::runtime_error("Invalid object instance id");
  469. if(obj->instanceName.empty())
  470. throw std::runtime_error("Object instance name missing");
  471. if (vstd::contains(instanceNames, obj->instanceName))
  472. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  473. objects.emplace_back(obj);
  474. instanceNames[obj->instanceName] = obj;
  475. addBlockVisTiles(obj);
  476. //TODO: how about defeated heroes recruited again?
  477. obj->afterAddToMap(this);
  478. }
  479. void CMap::moveObject(CGObjectInstance * obj, const int3 & pos)
  480. {
  481. removeBlockVisTiles(obj);
  482. obj->pos = pos;
  483. addBlockVisTiles(obj);
  484. }
  485. void CMap::removeObject(CGObjectInstance * obj)
  486. {
  487. removeBlockVisTiles(obj);
  488. instanceNames.erase(obj->instanceName);
  489. //update indeces
  490. auto iter = std::next(objects.begin(), obj->id.getNum());
  491. iter = objects.erase(iter);
  492. for(int i = obj->id.getNum(); iter != objects.end(); ++i, ++iter)
  493. {
  494. (*iter)->id = ObjectInstanceID(i);
  495. }
  496. obj->afterRemoveFromMap(this);
  497. //TOOD: Clean artifact instances (mostly worn by hero?) and quests related to this object
  498. }
  499. bool CMap::isWaterMap() const
  500. {
  501. return waterMap;
  502. }
  503. bool CMap::calculateWaterContent()
  504. {
  505. size_t totalTiles = height * width * levels();
  506. size_t waterTiles = 0;
  507. for(auto tile = terrain.origin(); tile < (terrain.origin() + terrain.num_elements()); ++tile)
  508. {
  509. if (tile->isWater())
  510. {
  511. waterTiles++;
  512. }
  513. }
  514. if (waterTiles >= totalTiles / 100) //At least 1% of area is water
  515. {
  516. waterMap = true;
  517. }
  518. return waterMap;
  519. }
  520. void CMap::banWaterContent()
  521. {
  522. banWaterHeroes();
  523. banWaterArtifacts();
  524. banWaterSpells();
  525. banWaterSkills();
  526. }
  527. void CMap::banWaterSpells()
  528. {
  529. vstd::erase_if(allowedSpells, [&](SpellID spell)
  530. {
  531. return spell.toSpell()->onlyOnWaterMap && !isWaterMap();
  532. });
  533. }
  534. void CMap::banWaterArtifacts()
  535. {
  536. vstd::erase_if(allowedArtifact, [&](ArtifactID artifact)
  537. {
  538. return artifact.toArtifact()->onlyOnWaterMap && !isWaterMap();
  539. });
  540. }
  541. void CMap::banWaterSkills()
  542. {
  543. vstd::erase_if(allowedAbilities, [&](SecondarySkill skill)
  544. {
  545. return skill.toSkill()->onlyOnWaterMap && !isWaterMap();
  546. });
  547. }
  548. void CMap::banWaterHeroes()
  549. {
  550. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  551. {
  552. return hero.toHeroType()->onlyOnWaterMap && !isWaterMap();
  553. });
  554. vstd::erase_if(allowedHeroes, [&](HeroTypeID hero)
  555. {
  556. return hero.toHeroType()->onlyOnMapWithoutWater && isWaterMap();
  557. });
  558. }
  559. void CMap::banHero(const HeroTypeID & id)
  560. {
  561. allowedHeroes.erase(id);
  562. }
  563. void CMap::initTerrain()
  564. {
  565. terrain.resize(boost::extents[levels()][width][height]);
  566. guardingCreaturePositions.resize(boost::extents[levels()][width][height]);
  567. }
  568. CMapEditManager * CMap::getEditManager()
  569. {
  570. if(!editManager) editManager = std::make_unique<CMapEditManager>(this);
  571. return editManager.get();
  572. }
  573. void CMap::resetStaticData()
  574. {
  575. CGKeys::reset();
  576. CGMagi::reset();
  577. CGObelisk::reset();
  578. CGTownInstance::reset();
  579. }
  580. VCMI_LIB_NAMESPACE_END