CMap.cpp 16 KB

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