CMap.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  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() : checksum(0), grailPos(-1, -1, -1), grailRadius(0), terrain(nullptr)
  177. {
  178. allHeroes.resize(allowedHeroes.size());
  179. allowedAbilities = VLC->heroh->getDefaultAllowedAbilities();
  180. allowedArtifact = VLC->arth->getDefaultAllowed();
  181. allowedSpell = VLC->spellh->getDefaultAllowed();
  182. }
  183. CMap::~CMap()
  184. {
  185. if(terrain)
  186. {
  187. for (int i=0; i<width; i++)
  188. {
  189. for(int j=0; j<height; j++)
  190. {
  191. delete [] terrain[i][j];
  192. delete [] guardingCreaturePositions[i][j];
  193. }
  194. delete [] terrain[i];
  195. delete [] guardingCreaturePositions[i];
  196. }
  197. delete [] terrain;
  198. delete [] guardingCreaturePositions;
  199. }
  200. for(auto obj : objects)
  201. obj.dellNull();
  202. for(auto quest : quests)
  203. quest.dellNull();
  204. }
  205. void CMap::removeBlockVisTiles(CGObjectInstance * obj, bool total)
  206. {
  207. for(int fx=0; fx<obj->getWidth(); ++fx)
  208. {
  209. for(int fy=0; fy<obj->getHeight(); ++fy)
  210. {
  211. int xVal = obj->pos.x - fx;
  212. int yVal = obj->pos.y - fy;
  213. int zVal = obj->pos.z;
  214. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  215. {
  216. TerrainTile & curt = terrain[xVal][yVal][zVal];
  217. if(total || obj->visitableAt(xVal, yVal))
  218. {
  219. curt.visitableObjects -= obj;
  220. curt.visitable = curt.visitableObjects.size();
  221. }
  222. if(total || obj->blockingAt(xVal, yVal))
  223. {
  224. curt.blockingObjects -= obj;
  225. curt.blocked = curt.blockingObjects.size();
  226. }
  227. }
  228. }
  229. }
  230. }
  231. void CMap::addBlockVisTiles(CGObjectInstance * obj)
  232. {
  233. for(int fx=0; fx<obj->getWidth(); ++fx)
  234. {
  235. for(int fy=0; fy<obj->getHeight(); ++fy)
  236. {
  237. int xVal = obj->pos.x - fx;
  238. int yVal = obj->pos.y - fy;
  239. int zVal = obj->pos.z;
  240. if(xVal>=0 && xVal<width && yVal>=0 && yVal<height)
  241. {
  242. TerrainTile & curt = terrain[xVal][yVal][zVal];
  243. if( obj->visitableAt(xVal, yVal))
  244. {
  245. curt.visitableObjects.push_back(obj);
  246. curt.visitable = true;
  247. }
  248. if( obj->blockingAt(xVal, yVal))
  249. {
  250. curt.blockingObjects.push_back(obj);
  251. curt.blocked = true;
  252. }
  253. }
  254. }
  255. }
  256. }
  257. void CMap::calculateGuardingGreaturePositions()
  258. {
  259. int levels = twoLevel ? 2 : 1;
  260. for (int i=0; i<width; i++)
  261. {
  262. for(int j=0; j<height; j++)
  263. {
  264. for (int k = 0; k < levels; k++)
  265. guardingCreaturePositions[i][j][k] = guardingCreaturePosition(int3(i,j,k));
  266. }
  267. }
  268. }
  269. CGHeroInstance * CMap::getHero(int heroID)
  270. {
  271. for(auto & elem : heroesOnMap)
  272. if(elem->subID == heroID)
  273. return elem;
  274. return nullptr;
  275. }
  276. bool CMap::isCoastalTile(const int3 & pos) const
  277. {
  278. //todo: refactoring: extract neighbor tile iterator and use it in GameState
  279. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  280. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  281. if(!isInTheMap(pos))
  282. {
  283. logGlobal->errorStream() << "Coastal check outside of map :"<<pos;
  284. return false;
  285. }
  286. if(isWaterTile(pos))
  287. return false;
  288. for (auto & dir : dirs)
  289. {
  290. const int3 hlp = pos + dir;
  291. if(!isInTheMap(hlp))
  292. continue;
  293. const TerrainTile &hlpt = getTile(hlp);
  294. if(hlpt.isWater())
  295. return true;
  296. }
  297. return false;
  298. }
  299. bool CMap::isInTheMap(const int3 & pos) const
  300. {
  301. if(pos.x < 0 || pos.y < 0 || pos.z < 0 || pos.x >= width || pos.y >= height
  302. || pos.z > (twoLevel ? 1 : 0))
  303. {
  304. return false;
  305. }
  306. else
  307. {
  308. return true;
  309. }
  310. }
  311. TerrainTile & CMap::getTile(const int3 & tile)
  312. {
  313. assert(isInTheMap(tile));
  314. return terrain[tile.x][tile.y][tile.z];
  315. }
  316. const TerrainTile & CMap::getTile(const int3 & tile) const
  317. {
  318. assert(isInTheMap(tile));
  319. return terrain[tile.x][tile.y][tile.z];
  320. }
  321. bool CMap::isWaterTile(const int3 &pos) const
  322. {
  323. return isInTheMap(pos) && getTile(pos).isWater();
  324. }
  325. bool CMap::checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  326. {
  327. if (!pom->entrableTerrain()) //rock is never accessible
  328. return false;
  329. for (auto obj : pom->visitableObjects) //checking destination tile
  330. {
  331. if(!vstd::contains(pom->blockingObjects, obj)) //this visitable object is not blocking, ignore
  332. continue;
  333. if (!obj->appearance.isVisitableFrom(src.x - dst.x, src.y - dst.y))
  334. return false;
  335. }
  336. return true;
  337. }
  338. int3 CMap::guardingCreaturePosition (int3 pos) const
  339. {
  340. const int3 originalPos = pos;
  341. // Give monster at position priority.
  342. if (!isInTheMap(pos))
  343. return int3(-1, -1, -1);
  344. const TerrainTile &posTile = getTile(pos);
  345. if (posTile.visitable)
  346. {
  347. for (CGObjectInstance* obj : posTile.visitableObjects)
  348. {
  349. if(obj->blockVisit)
  350. {
  351. if (obj->ID == Obj::MONSTER) // Monster
  352. return pos;
  353. else
  354. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  355. }
  356. }
  357. }
  358. // See if there are any monsters adjacent.
  359. bool water = posTile.isWater();
  360. pos -= int3(1, 1, 0); // Start with top left.
  361. for (int dx = 0; dx < 3; dx++)
  362. {
  363. for (int dy = 0; dy < 3; dy++)
  364. {
  365. if (isInTheMap(pos))
  366. {
  367. const auto & tile = getTile(pos);
  368. if (tile.visitable && (tile.isWater() == water))
  369. {
  370. for (CGObjectInstance* obj : tile.visitableObjects)
  371. {
  372. if (obj->ID == Obj::MONSTER && checkForVisitableDir(pos, &posTile, originalPos)) // Monster being able to attack investigated tile
  373. {
  374. return pos;
  375. }
  376. }
  377. }
  378. }
  379. pos.y++;
  380. }
  381. pos.y -= 3;
  382. pos.x++;
  383. }
  384. return int3(-1, -1, -1);
  385. }
  386. const CGObjectInstance * CMap::getObjectiveObjectFrom(int3 pos, Obj::EObj type)
  387. {
  388. for (CGObjectInstance * object : getTile(pos).visitableObjects)
  389. {
  390. if (object->ID == type)
  391. return object;
  392. }
  393. // There is weird bug because of which sometimes heroes will not be found properly despite having correct position
  394. // Try to workaround that and find closest object that we can use
  395. logGlobal->errorStream() << "Failed to find object of type " << int(type) << " at " << pos;
  396. logGlobal->errorStream() << "Will try to find closest matching object";
  397. CGObjectInstance * bestMatch = nullptr;
  398. for (CGObjectInstance * object : objects)
  399. {
  400. if (object && object->ID == type)
  401. {
  402. if (bestMatch == nullptr)
  403. bestMatch = object;
  404. else
  405. {
  406. if (object->pos.dist2dSQ(pos) < bestMatch->pos.dist2dSQ(pos))
  407. bestMatch = object;// closer than one we already found
  408. }
  409. }
  410. }
  411. assert(bestMatch != nullptr); // if this happens - victory conditions or map itself is very, very broken
  412. logGlobal->errorStream() << "Will use " << bestMatch->getObjectName() << " from " << bestMatch->pos;
  413. return bestMatch;
  414. }
  415. void CMap::checkForObjectives()
  416. {
  417. // NOTE: probably should be moved to MapFormatH3M.cpp
  418. for (TriggeredEvent & event : triggeredEvents)
  419. {
  420. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  421. {
  422. switch (cond.condition)
  423. {
  424. break; case EventCondition::HAVE_ARTIFACT:
  425. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->arth->artifacts[cond.objectType]->Name());
  426. break; case EventCondition::HAVE_CREATURES:
  427. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->creh->creatures[cond.objectType]->nameSing);
  428. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  429. break; case EventCondition::HAVE_RESOURCES:
  430. boost::algorithm::replace_first(event.onFulfill, "%s", VLC->generaltexth->restypes[cond.objectType]);
  431. boost::algorithm::replace_first(event.onFulfill, "%d", boost::lexical_cast<std::string>(cond.value));
  432. break; case EventCondition::HAVE_BUILDING:
  433. if (isInTheMap(cond.position))
  434. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  435. break; case EventCondition::CONTROL:
  436. if (isInTheMap(cond.position))
  437. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  438. if (cond.object)
  439. {
  440. const CGTownInstance *town = dynamic_cast<const CGTownInstance*>(cond.object);
  441. if (town)
  442. boost::algorithm::replace_first(event.onFulfill, "%s", town->name);
  443. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  444. if (hero)
  445. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  446. }
  447. break; case EventCondition::DESTROY:
  448. if (isInTheMap(cond.position))
  449. cond.object = getObjectiveObjectFrom(cond.position, Obj::EObj(cond.objectType));
  450. if (cond.object)
  451. {
  452. const CGHeroInstance *hero = dynamic_cast<const CGHeroInstance*>(cond.object);
  453. if (hero)
  454. boost::algorithm::replace_first(event.onFulfill, "%s", hero->name);
  455. }
  456. break; case EventCondition::TRANSPORT:
  457. cond.object = getObjectiveObjectFrom(cond.position, Obj::TOWN);
  458. //break; case EventCondition::DAYS_PASSED:
  459. //break; case EventCondition::IS_HUMAN:
  460. //break; case EventCondition::DAYS_WITHOUT_TOWN:
  461. //break; case EventCondition::STANDARD_WIN:
  462. }
  463. return cond;
  464. };
  465. event.trigger = event.trigger.morph(patcher);
  466. }
  467. }
  468. void CMap::addNewArtifactInstance(CArtifactInstance * art)
  469. {
  470. art->id = ArtifactInstanceID(artInstances.size());
  471. artInstances.push_back(art);
  472. }
  473. void CMap::eraseArtifactInstance(CArtifactInstance * art)
  474. {
  475. assert(artInstances[art->id.getNum()] == art);
  476. artInstances[art->id.getNum()].dellNull();
  477. }
  478. void CMap::addNewObject(CGObjectInstance * obj)
  479. {
  480. if(obj->id != ObjectInstanceID(objects.size()))
  481. throw std::runtime_error("Invalid object instance id");
  482. if(obj->instanceName == "")
  483. throw std::runtime_error("Object instance name missing");
  484. auto it = instanceNames.find(obj->instanceName);
  485. if(it != instanceNames.end())
  486. throw std::runtime_error("Object instance name duplicated: "+obj->instanceName);
  487. objects.push_back(obj);
  488. instanceNames[obj->instanceName] = obj;
  489. addBlockVisTiles(obj);
  490. //todo: make this virtual method of CGObjectInstance
  491. switch (obj->ID)
  492. {
  493. case Obj::TOWN:
  494. towns.push_back(static_cast<CGTownInstance *>(obj));
  495. break;
  496. case Obj::HERO:
  497. heroesOnMap.push_back(static_cast<CGHeroInstance*>(obj));
  498. break;
  499. case Obj::SEER_HUT:
  500. case Obj::QUEST_GUARD:
  501. case Obj::BORDERGUARD:
  502. case Obj::BORDER_GATE:
  503. {
  504. auto q = dynamic_cast<IQuestObject *>(obj);
  505. q->quest->qid = quests.size();
  506. quests.push_back(q->quest);
  507. }
  508. break;
  509. case Obj::SPELL_SCROLL:
  510. {
  511. CGArtifact * art = dynamic_cast<CGArtifact *>(obj);
  512. if(art->storedArtifact && art->storedArtifact->id.getNum() < 0)
  513. addNewArtifactInstance(art->storedArtifact);
  514. }
  515. break;
  516. default:
  517. break;
  518. }
  519. }
  520. void CMap::initTerrain()
  521. {
  522. int level = twoLevel ? 2 : 1;
  523. terrain = new TerrainTile**[width];
  524. guardingCreaturePositions = new int3**[width];
  525. for (int i = 0; i < width; ++i)
  526. {
  527. terrain[i] = new TerrainTile*[height];
  528. guardingCreaturePositions[i] = new int3*[height];
  529. for (int j = 0; j < height; ++j)
  530. {
  531. terrain[i][j] = new TerrainTile[level];
  532. guardingCreaturePositions[i][j] = new int3[level];
  533. }
  534. }
  535. }
  536. CMapEditManager * CMap::getEditManager()
  537. {
  538. if(!editManager) editManager = make_unique<CMapEditManager>(this);
  539. return editManager.get();
  540. }