CampaignState.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /*
  2. * CCampaignHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CampaignState.h"
  12. #include "../Point.h"
  13. #include "../filesystem/ResourcePath.h"
  14. #include "../VCMI_Lib.h"
  15. #include "../texts/CGeneralTextHandler.h"
  16. #include "../mapping/CMapService.h"
  17. #include "../mapping/CMapInfo.h"
  18. #include "../mapping/CMap.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../serializer/JsonDeserializer.h"
  21. #include "../serializer/JsonSerializer.h"
  22. VCMI_LIB_NAMESPACE_BEGIN
  23. void CampaignScenario::loadPreconditionRegions(ui32 regions)
  24. {
  25. for (int i=0; i<32; i++) //for each bit in region. h3c however can only hold up to 16
  26. {
  27. if ( (1 << i) & regions)
  28. preconditionRegions.insert(static_cast<CampaignScenarioID>(i));
  29. }
  30. }
  31. CampaignRegions::RegionDescription CampaignRegions::RegionDescription::fromJson(const JsonNode & node)
  32. {
  33. CampaignRegions::RegionDescription rd;
  34. rd.infix = node["infix"].String();
  35. rd.xpos = static_cast<int>(node["x"].Float());
  36. rd.ypos = static_cast<int>(node["y"].Float());
  37. return rd;
  38. }
  39. CampaignRegions CampaignRegions::fromJson(const JsonNode & node)
  40. {
  41. CampaignRegions cr;
  42. cr.campPrefix = node["prefix"].String();
  43. cr.colorSuffixLength = static_cast<int>(node["colorSuffixLength"].Float());
  44. cr.campSuffix = node["suffix"].isNull() ? std::vector<std::string>() : std::vector<std::string>{node["suffix"].Vector()[0].String(), node["suffix"].Vector()[1].String(), node["suffix"].Vector()[2].String()};
  45. cr.campBackground = node["background"].isNull() ? "" : node["background"].String();
  46. for(const JsonNode & desc : node["desc"].Vector())
  47. cr.regions.push_back(CampaignRegions::RegionDescription::fromJson(desc));
  48. return cr;
  49. }
  50. CampaignRegions CampaignRegions::getLegacy(int campId)
  51. {
  52. static std::vector<CampaignRegions> campDescriptions;
  53. if(campDescriptions.empty()) //read once
  54. {
  55. const JsonNode config(JsonPath::builtin("config/campaign_regions.json"));
  56. for(const JsonNode & campaign : config["campaign_regions"].Vector())
  57. campDescriptions.push_back(CampaignRegions::fromJson(campaign));
  58. }
  59. return campDescriptions.at(campId);
  60. }
  61. ImagePath CampaignRegions::getBackgroundName() const
  62. {
  63. if(campBackground.empty())
  64. return ImagePath::builtin(campPrefix + "_BG.BMP");
  65. else
  66. return ImagePath::builtin(campBackground);
  67. }
  68. Point CampaignRegions::getPosition(CampaignScenarioID which) const
  69. {
  70. auto const & region = regions[which.getNum()];
  71. return Point(region.xpos, region.ypos);
  72. }
  73. ImagePath CampaignRegions::getNameFor(CampaignScenarioID which, int colorIndex, std::string type) const
  74. {
  75. auto const & region = regions[which.getNum()];
  76. static const std::array<std::array<std::string, 8>, 3> colors = {{
  77. { "", "", "", "", "", "", "", "" },
  78. { "R", "B", "N", "G", "O", "V", "T", "P" },
  79. { "Re", "Bl", "Br", "Gr", "Or", "Vi", "Te", "Pi" }
  80. }};
  81. std::string color = colors[colorSuffixLength][colorIndex];
  82. return ImagePath::builtin(campPrefix + region.infix + "_" + type + color + ".BMP");
  83. }
  84. ImagePath CampaignRegions::getAvailableName(CampaignScenarioID which, int color) const
  85. {
  86. if(campSuffix.empty())
  87. return getNameFor(which, color, "En");
  88. else
  89. return getNameFor(which, color, campSuffix[0]);
  90. }
  91. ImagePath CampaignRegions::getSelectedName(CampaignScenarioID which, int color) const
  92. {
  93. if(campSuffix.empty())
  94. return getNameFor(which, color, "Se");
  95. else
  96. return getNameFor(which, color, campSuffix[1]);
  97. }
  98. ImagePath CampaignRegions::getConqueredName(CampaignScenarioID which, int color) const
  99. {
  100. if(campSuffix.empty())
  101. return getNameFor(which, color, "Co");
  102. else
  103. return getNameFor(which, color, campSuffix[2]);
  104. }
  105. bool CampaignBonus::isBonusForHero() const
  106. {
  107. return type == CampaignBonusType::SPELL ||
  108. type == CampaignBonusType::MONSTER ||
  109. type == CampaignBonusType::ARTIFACT ||
  110. type == CampaignBonusType::SPELL_SCROLL ||
  111. type == CampaignBonusType::PRIMARY_SKILL ||
  112. type == CampaignBonusType::SECONDARY_SKILL;
  113. }
  114. void CampaignHeader::loadLegacyData(ui8 campId)
  115. {
  116. campaignRegions = CampaignRegions::getLegacy(campId);
  117. numberOfScenarios = VLC->generaltexth->getCampaignLength(campId);
  118. }
  119. bool CampaignHeader::playerSelectedDifficulty() const
  120. {
  121. return difficultyChosenByPlayer;
  122. }
  123. bool CampaignHeader::formatVCMI() const
  124. {
  125. return version == CampaignVersion::VCMI;
  126. }
  127. std::string CampaignHeader::getDescriptionTranslated() const
  128. {
  129. return description.toString();
  130. }
  131. std::string CampaignHeader::getNameTranslated() const
  132. {
  133. return name.toString();
  134. }
  135. std::string CampaignHeader::getAuthor() const
  136. {
  137. return authorContact.toString();
  138. }
  139. std::string CampaignHeader::getAuthorContact() const
  140. {
  141. return authorContact.toString();
  142. }
  143. std::string CampaignHeader::getCampaignVersion() const
  144. {
  145. return campaignVersion.toString();
  146. }
  147. time_t CampaignHeader::getCreationDateTime() const
  148. {
  149. return creationDateTime;
  150. }
  151. std::string CampaignHeader::getFilename() const
  152. {
  153. return filename;
  154. }
  155. std::string CampaignHeader::getModName() const
  156. {
  157. return modName;
  158. }
  159. std::string CampaignHeader::getEncoding() const
  160. {
  161. return encoding;
  162. }
  163. AudioPath CampaignHeader::getMusic() const
  164. {
  165. return music;
  166. }
  167. const CampaignRegions & CampaignHeader::getRegions() const
  168. {
  169. return campaignRegions;
  170. }
  171. TextContainerRegistrable & CampaignHeader::getTexts()
  172. {
  173. return textContainer;
  174. }
  175. bool CampaignState::isConquered(CampaignScenarioID whichScenario) const
  176. {
  177. return vstd::contains(mapsConquered, whichScenario);
  178. }
  179. bool CampaignState::isAvailable(CampaignScenarioID whichScenario) const
  180. {
  181. //check for void scenraio
  182. if (!scenario(whichScenario).isNotVoid())
  183. {
  184. return false;
  185. }
  186. if (vstd::contains(mapsConquered, whichScenario))
  187. {
  188. return false;
  189. }
  190. //check preconditioned regions
  191. for (auto const & it : scenario(whichScenario).preconditionRegions)
  192. {
  193. if (!vstd::contains(mapsConquered, it))
  194. return false;
  195. }
  196. return true;
  197. }
  198. bool CampaignScenario::isNotVoid() const
  199. {
  200. return !mapName.empty();
  201. }
  202. std::set<HeroTypeID> CampaignState::getReservedHeroes() const
  203. {
  204. std::set<HeroTypeID> result;
  205. for (auto const & scenarioID : allScenarios())
  206. {
  207. if (isConquered(scenarioID))
  208. continue;
  209. auto header = getMapHeader(scenarioID);
  210. result.insert(header->reservedCampaignHeroes.begin(), header->reservedCampaignHeroes.end());
  211. }
  212. return result;
  213. }
  214. const CGHeroInstance * CampaignState::strongestHero(CampaignScenarioID scenarioId, const PlayerColor & owner) const
  215. {
  216. std::function<bool(const JsonNode & node)> isOwned = [&](const JsonNode & node)
  217. {
  218. auto * h = CampaignState::crossoverDeserialize(node, nullptr);
  219. bool result = h->tempOwner == owner;
  220. vstd::clear_pointer(h);
  221. return result;
  222. };
  223. auto ownedHeroes = scenarioHeroPool.at(scenarioId) | boost::adaptors::filtered(isOwned);
  224. if (ownedHeroes.empty())
  225. return nullptr;
  226. return CampaignState::crossoverDeserialize(ownedHeroes.front(), nullptr);
  227. }
  228. /// Returns heroes that can be instantiated as hero placeholders by power
  229. const std::vector<JsonNode> & CampaignState::getHeroesByPower(CampaignScenarioID scenarioId) const
  230. {
  231. static const std::vector<JsonNode> emptyVector;
  232. if (scenarioHeroPool.count(scenarioId))
  233. return scenarioHeroPool.at(scenarioId);
  234. return emptyVector;
  235. }
  236. /// Returns hero for instantiation as placeholder by type
  237. /// May return empty JsonNode if such hero was not found
  238. const JsonNode & CampaignState::getHeroByType(HeroTypeID heroID) const
  239. {
  240. static const JsonNode emptyNode;
  241. if (!getReservedHeroes().count(heroID))
  242. return emptyNode;
  243. if (!globalHeroPool.count(heroID))
  244. return emptyNode;
  245. return globalHeroPool.at(heroID);
  246. }
  247. void CampaignState::setCurrentMapAsConquered(std::vector<CGHeroInstance *> heroes)
  248. {
  249. range::sort(heroes, [](const CGHeroInstance * a, const CGHeroInstance * b)
  250. {
  251. return a->getHeroStrength() > b->getHeroStrength();
  252. });
  253. logGlobal->info("Scenario %d of campaign %s (%s) has been completed", currentMap->getNum(), getFilename(), getNameTranslated());
  254. mapsConquered.push_back(*currentMap);
  255. auto reservedHeroes = getReservedHeroes();
  256. for (auto * hero : heroes)
  257. {
  258. JsonNode node = CampaignState::crossoverSerialize(hero);
  259. if (reservedHeroes.count(hero->getHeroType()))
  260. {
  261. logGlobal->info("Hero crossover: %d (%s) exported to global pool", hero->getHeroType(), hero->getNameTranslated());
  262. globalHeroPool[hero->getHeroType()] = node;
  263. }
  264. else
  265. {
  266. logGlobal->info("Hero crossover: %d (%s) exported to scenario pool", hero->getHeroType(), hero->getNameTranslated());
  267. scenarioHeroPool[*currentMap].push_back(node);
  268. }
  269. }
  270. }
  271. std::optional<CampaignBonus> CampaignState::getBonus(CampaignScenarioID which) const
  272. {
  273. auto bonuses = scenario(which).travelOptions.bonusesToChoose;
  274. assert(chosenCampaignBonuses.count(*currentMap) || bonuses.empty());
  275. if(bonuses.empty())
  276. return std::optional<CampaignBonus>();
  277. if (!getBonusID(which))
  278. return std::optional<CampaignBonus>();
  279. return bonuses[getBonusID(which).value()];
  280. }
  281. std::optional<ui8> CampaignState::getBonusID(CampaignScenarioID which) const
  282. {
  283. if (!chosenCampaignBonuses.count(which))
  284. return std::nullopt;
  285. return chosenCampaignBonuses.at(which);
  286. }
  287. std::unique_ptr<CMap> CampaignState::getMap(CampaignScenarioID scenarioId, IGameCallback * cb)
  288. {
  289. // FIXME: there is certainly better way to handle maps inside campaigns
  290. if(scenarioId == CampaignScenarioID::NONE)
  291. scenarioId = currentMap.value();
  292. CMapService mapService;
  293. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  294. boost::to_lower(scenarioName);
  295. scenarioName += ':' + std::to_string(scenarioId.getNum());
  296. const auto & mapContent = mapPieces.find(scenarioId)->second;
  297. auto result = mapService.loadMap(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding(), cb);
  298. mapTranslations[scenarioId] = result->texts;
  299. return result;
  300. }
  301. std::unique_ptr<CMapHeader> CampaignState::getMapHeader(CampaignScenarioID scenarioId) const
  302. {
  303. if(scenarioId == CampaignScenarioID::NONE)
  304. scenarioId = currentMap.value();
  305. CMapService mapService;
  306. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  307. boost::to_lower(scenarioName);
  308. scenarioName += ':' + std::to_string(scenarioId.getNum());
  309. const auto & mapContent = mapPieces.find(scenarioId)->second;
  310. return mapService.loadMapHeader(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding());
  311. }
  312. std::shared_ptr<CMapInfo> CampaignState::getMapInfo(CampaignScenarioID scenarioId) const
  313. {
  314. if(scenarioId == CampaignScenarioID::NONE)
  315. scenarioId = currentMap.value();
  316. auto mapInfo = std::make_shared<CMapInfo>();
  317. mapInfo->fileURI = getFilename();
  318. mapInfo->mapHeader = getMapHeader(scenarioId);
  319. mapInfo->countPlayers();
  320. return mapInfo;
  321. }
  322. JsonNode CampaignState::crossoverSerialize(CGHeroInstance * hero) const
  323. {
  324. JsonNode node;
  325. JsonSerializer handler(nullptr, node);
  326. hero->serializeJsonOptions(handler);
  327. return node;
  328. }
  329. CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap * map) const
  330. {
  331. JsonDeserializer handler(nullptr, const_cast<JsonNode&>(node));
  332. auto * hero = new CGHeroInstance(map ? map->cb : nullptr);
  333. hero->ID = Obj::HERO;
  334. hero->serializeJsonOptions(handler);
  335. if (map)
  336. hero->serializeJsonArtifacts(handler, "artifacts");
  337. map->addNewArtifactInstance(*hero);
  338. return hero;
  339. }
  340. void CampaignState::setCurrentMap(CampaignScenarioID which)
  341. {
  342. assert(scenario(which).isNotVoid());
  343. currentMap = which;
  344. }
  345. void CampaignState::setCurrentMapBonus(ui8 which)
  346. {
  347. chosenCampaignBonuses[*currentMap] = which;
  348. }
  349. std::optional<CampaignScenarioID> CampaignState::currentScenario() const
  350. {
  351. return currentMap;
  352. }
  353. std::optional<CampaignScenarioID> CampaignState::lastScenario() const
  354. {
  355. if (mapsConquered.empty())
  356. return std::nullopt;
  357. return mapsConquered.back();
  358. }
  359. std::set<CampaignScenarioID> CampaignState::conqueredScenarios() const
  360. {
  361. std::set<CampaignScenarioID> result;
  362. result.insert(mapsConquered.begin(), mapsConquered.end());
  363. return result;
  364. }
  365. std::set<CampaignScenarioID> Campaign::allScenarios() const
  366. {
  367. std::set<CampaignScenarioID> result;
  368. for (auto const & entry : scenarios)
  369. {
  370. if (entry.second.isNotVoid())
  371. result.insert(entry.first);
  372. }
  373. return result;
  374. }
  375. int Campaign::scenariosCount() const
  376. {
  377. return allScenarios().size();
  378. }
  379. const CampaignScenario & Campaign::scenario(CampaignScenarioID which) const
  380. {
  381. assert(scenarios.count(which));
  382. assert(scenarios.at(which).isNotVoid());
  383. return scenarios.at(which);
  384. }
  385. bool CampaignState::isCampaignFinished() const
  386. {
  387. return conqueredScenarios() == allScenarios();
  388. }
  389. VCMI_LIB_NAMESPACE_END