CMap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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(255), 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. bool TerrainTile::isCoastal() const
  115. {
  116. return extTileFlags & 64;
  117. }
  118. EDiggingStatus TerrainTile::getDiggingStatus(const bool excludeTop) const
  119. {
  120. if(terType == ETerrainType::WATER || terType == ETerrainType::ROCK)
  121. return EDiggingStatus::WRONG_TERRAIN;
  122. int allowedBlocked = excludeTop ? 1 : 0;
  123. if(blockingObjects.size() > allowedBlocked || topVisitableObj(excludeTop))
  124. return EDiggingStatus::TILE_OCCUPIED;
  125. else
  126. return EDiggingStatus::CAN_DIG;
  127. }
  128. bool TerrainTile::hasFavorableWinds() const
  129. {
  130. return extTileFlags & 128;
  131. }
  132. bool TerrainTile::isWater() const
  133. {
  134. return terType == ETerrainType::WATER;
  135. }
  136. const int CMapHeader::MAP_SIZE_SMALL = 36;
  137. const int CMapHeader::MAP_SIZE_MIDDLE = 72;
  138. const int CMapHeader::MAP_SIZE_LARGE = 108;
  139. const int CMapHeader::MAP_SIZE_XLARGE = 144;
  140. void CMapHeader::setupEvents()
  141. {
  142. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  143. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  144. defeatCondition.value = 7;
  145. //Victory condition - defeat all
  146. TriggeredEvent standardVictory;
  147. standardVictory.effect.type = EventEffect::VICTORY;
  148. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  149. standardVictory.identifier = "standardVictory";
  150. standardVictory.description = ""; // TODO: display in quest window
  151. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  152. standardVictory.trigger = EventExpression(victoryCondition);
  153. //Loss condition - 7 days without town
  154. TriggeredEvent standardDefeat;
  155. standardDefeat.effect.type = EventEffect::DEFEAT;
  156. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  157. standardDefeat.identifier = "standardDefeat";
  158. standardDefeat.description = ""; // TODO: display in quest window
  159. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  160. standardDefeat.trigger = EventExpression(defeatCondition);
  161. triggeredEvents.push_back(standardVictory);
  162. triggeredEvents.push_back(standardDefeat);
  163. victoryIconIndex = 11;
  164. victoryMessage = VLC->generaltexth->victoryConditions[0];
  165. defeatIconIndex = 3;
  166. defeatMessage = VLC->generaltexth->lossCondtions[0];
  167. }
  168. CMapHeader::CMapHeader() : version(EMapFormat::SOD), height(72), width(72),
  169. twoLevel(true), difficulty(1), levelLimit(0), howManyTeams(0), areAnyPlayers(false)
  170. {
  171. setupEvents();
  172. allowedHeroes = VLC->heroh->getDefaultAllowed();
  173. players.resize(PlayerColor::PLAYER_LIMIT_I);
  174. }
  175. CMapHeader::~CMapHeader()
  176. {
  177. }
  178. CMap::CMap() : checksum(0), grailPos(-1, -1, -1), grailRadius(0), terrain(nullptr)
  179. {
  180. allHeroes.resize(allowedHeroes.size());
  181. allowedAbilities = VLC->heroh->getDefaultAllowedAbilities();
  182. allowedArtifact = VLC->arth->getDefaultAllowed();
  183. allowedSpell = VLC->spellh->getDefaultAllowed();
  184. }
  185. CMap::~CMap()
  186. {
  187. if(terrain)
  188. {
  189. for (int i=0; i<width; i++)
  190. {
  191. for(int j=0; j<height; j++)
  192. {
  193. delete [] terrain[i][j];
  194. delete [] guardingCreaturePositions[i][j];
  195. }
  196. delete [] terrain[i];
  197. delete [] guardingCreaturePositions[i];
  198. }
  199. delete [] terrain;
  200. delete [] guardingCreaturePositions;
  201. }
  202. }
  203. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  204. {
  205. for(int fx=0; fx<obj->getWidth(); ++fx)
  206. {
  207. for(int fy=0; fy<obj->getHeight(); ++fy)
  208. {
  209. int xVal = obj->pos.x - fx;
  210. int yVal = obj->pos.y - fy;
  211. int zVal = obj->pos.z;
  212. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  213. {
  214. TerrainTile & curt = terrain[xVal][yVal][zVal];
  215. if(total || obj->visitableAt(xVal, yVal))
  216. {
  217. curt.visitableObjects -= obj;
  218. curt.visitable = curt.visitableObjects.size();
  219. }
  220. if(total || obj->blockingAt(xVal, yVal))
  221. {
  222. curt.blockingObjects -= obj;
  223. curt.blocked = curt.blockingObjects.size();
  224. }
  225. }
  226. }
  227. }
  228. }
  229. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  230. {
  231. for(int fx=0; fx<obj->getWidth(); ++fx)
  232. {
  233. for(int fy=0; fy<obj->getHeight(); ++fy)
  234. {
  235. int xVal = obj->pos.x - fx;
  236. int yVal = obj->pos.y - fy;
  237. int zVal = obj->pos.z;
  238. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  239. {
  240. TerrainTile & curt = terrain[xVal][yVal][zVal];
  241. if( obj->visitableAt(xVal, yVal))
  242. {
  243. curt.visitableObjects.push_back(obj);
  244. curt.visitable = true;
  245. }
  246. if( obj->blockingAt(xVal, yVal))
  247. {
  248. curt.blockingObjects.push_back(obj);
  249. curt.blocked = true;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. void CMap::calculateGuardingGreaturePositions()
  256. {
  257. int levels = twoLevel ? 2 : 1;
  258. for (int i=0; i<width; i++)
  259. {
  260. for(int j=0; j<height; j++)
  261. {
  262. for (int k = 0; k < levels; k++)
  263. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  264. }
  265. }
  266. }
  267. CGHeroInstance * CMap::getHero(int heroID)
  268. {
  269. for(auto & elem : heroesOnMap)
  270. if(elem->subID == heroID)
  271. return elem;
  272. return nullptr;
  273. }
  274. bool CMap::isInTheMap(const int3 & pos) const
  275. {
  276. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  277. || pos.z > (twoLevel ? 1 : 0))
  278. {
  279. return false;
  280. }
  281. else
  282. {
  283. return true;
  284. }
  285. }
  286. TerrainTile & CMap::getTile(const int3 & tile)
  287. {
  288. assert(isInTheMap(tile));
  289. return terrain[tile.x][tile.y][tile.z];
  290. }
  291. const TerrainTile & CMap::getTile(const int3 & tile) const
  292. {
  293. assert(isInTheMap(tile));
  294. return terrain[tile.x][tile.y][tile.z];
  295. }
  296. bool CMap::isWaterTile(const int3 &pos) const
  297. {
  298. return isInTheMap(pos) && getTile(pos).terType == ETerrainType::WATER;
  299. }
  300. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  301. {
  302. if (!pom->entrableTerrain()) //rock is never accessible
  303. return false;
  304. for (auto obj : pom->visitableObjects) //checking destination tile
  305. {
  306. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  307. continue;
  308. if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
  309. return false;
  310. }
  311. return true;
  312. }
  313. int3 CMap::guardingCreaturePosition (int3 pos) const
  314. {
  315. const int3 originalPos = pos;
  316. // Give monster at position priority.
  317. if (!isInTheMap(pos))
  318. return int3(-1, -1, -1);
  319. const TerrainTile &posTile = getTile(pos);
  320. if (posTile.visitable)
  321. {
  322. for (CGObjectInstance* obj : posTile.visitableObjects)
  323. {
  324. if(obj->blockVisit)
  325. {
  326. if (obj->ID == Obj::MONSTER) // Monster
  327. return pos;
  328. else
  329. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  330. }
  331. }
  332. }
  333. // See if there are any monsters adjacent.
  334. bool water = posTile.isWater();
  335. pos -= int3(1, 1, 0); // Start with top left.
  336. for (int dx = 0; dx < 3; dx++)
  337. {
  338. for (int dy = 0; dy < 3; dy++)
  339. {
  340. if (isInTheMap(pos))
  341. {
  342. const auto & tile = getTile(pos);
  343. if (tile.visitable && (tile.isWater() == water))
  344. {
  345. for (CGObjectInstance* obj : tile.visitableObjects)
  346. {
  347. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  348. {
  349. return pos;
  350. }
  351. }
  352. }
  353. }
  354. pos.y++;
  355. }
  356. pos.y -= 3;
  357. pos.x++;
  358. }
  359. return int3(-1, -1, -1);
  360. }
  361. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  362. {
  363. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  364. {
  365. if (object->ID == type)
  366. return object;
  367. }
  368. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  369. // Try to workaround that and find closest object that we can use
  370. logGlobal->errorStream() << "Failed to find object of type " << int(type) << " at " << pos;
  371. logGlobal->errorStream() << "Will try to find closest matching object";
  372. CGObjectInstance * bestMatch = nullptr;
  373. for (CGObjectInstance * object : objects)
  374. {
  375. if (object && object->ID == type)
  376. {
  377. if (bestMatch == nullptr)
  378. bestMatch = object;
  379. else
  380. {
  381. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  382. bestMatch = object;// closer than one we already found
  383. }
  384. }
  385. }
  386. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  387. logGlobal->errorStream() << "Will use " << bestMatch->getObjectName() << " from " << bestMatch->pos;
  388. return bestMatch;
  389. }
  390. void CMap::checkForObjectives()
  391. {
  392. // NOTE: probably should be moved to MapFormatH3M.cpp
  393. for (TriggeredEvent & event : triggeredEvents)
  394. {
  395. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  396. {
  397. switch (cond.condition)
  398. {
  399. break; case EventCondition::HAVE_ARTIFACT:
  400. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
  401. break; case EventCondition::HAVE_CREATURES:
  402. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
  403. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  404. break; case EventCondition::HAVE_RESOURCES:
  405. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  406. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  407. break; case EventCondition::HAVE_BUILDING:
  408. if (isInTheMap(cond.position))
  409. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  410. break; case EventCondition::CONTROL:
  411. if (isInTheMap(cond.position))
  412. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  413. if (cond.object)
  414. {
  415. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  416. if (town)
  417. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  418. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  419. if (hero)
  420. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  421. }
  422. break; case EventCondition::DESTROY:
  423. if (isInTheMap(cond.position))
  424. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  425. if (cond.object)
  426. {
  427. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  428. if (hero)
  429. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  430. }
  431. break; case EventCondition::TRANSPORT:
  432. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  433. //break; case EventCondition::DAYS_PASSED:
  434. //break; case EventCondition::IS_HUMAN:
  435. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  436. //break; case EventCondition::STANDARD_WIN:
  437. }
  438. return cond;
  439. };
  440. event.trigger = event.trigger.morph(patcher);
  441. }
  442. }
  443. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  444. {
  445. art->id = ArtifactInstanceID(artInstances.size());
  446. artInstances.push_back(art);
  447. }
  448. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  449. {
  450. assert(artInstances[art->id.getNum()] == art);
  451. artInstances[art->id.getNum()].dellNull();
  452. }
  453. void CMap::addQuest(CGObjectInstance * quest)
  454. {
  455. auto q = dynamic_cast<IQuestObject *>(quest);
  456. q->quest->qid = quests.size();
  457. quests.push_back(q->quest);
  458. }
  459. void CMap::initTerrain()
  460. {
  461. int level = twoLevel ? 2 : 1;
  462. terrain = new TerrainTile**[width];
  463. guardingCreaturePositions = new int3**[width];
  464. for (int i = 0; i < width; ++i)
  465. {
  466. terrain[i] = new TerrainTile*[height];
  467. guardingCreaturePositions[i] = new int3*[height];
  468. for (int j = 0; j < height; ++j)
  469. {
  470. terrain[i][j] = new TerrainTile[level];
  471. guardingCreaturePositions[i][j] = new int3[level];
  472. }
  473. }
  474. }
  475. CMapEditManager * CMap::getEditManager()
  476. {
  477. if(!editManager) editManager = make_unique<CMapEditManager>(this);
  478. return editManager.get();
  479. }