CMap.cpp 17 KB

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