CMap.cpp 17 KB

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