CampaignState.cpp 13 KB

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