CMap.cpp 15 KB

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