CMap.cpp 15 KB

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