CMap.cpp 17 KB

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