CampaignState.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. bool CampaignHeader::playerSelectedDifficulty() const
  126. {
  127. return difficultyChosenByPlayer;
  128. }
  129. bool CampaignHeader::formatVCMI() const
  130. {
  131. return version == CampaignVersion::VCMI;
  132. }
  133. std::string CampaignHeader::getDescriptionTranslated() const
  134. {
  135. return description.toString();
  136. }
  137. std::string CampaignHeader::getNameTranslated() const
  138. {
  139. return name.toString();
  140. }
  141. std::string CampaignHeader::getAuthor() const
  142. {
  143. return authorContact.toString();
  144. }
  145. std::string CampaignHeader::getAuthorContact() const
  146. {
  147. return authorContact.toString();
  148. }
  149. std::string CampaignHeader::getCampaignVersion() const
  150. {
  151. return campaignVersion.toString();
  152. }
  153. time_t CampaignHeader::getCreationDateTime() const
  154. {
  155. return creationDateTime;
  156. }
  157. std::string CampaignHeader::getFilename() const
  158. {
  159. return filename;
  160. }
  161. std::string CampaignHeader::getModName() const
  162. {
  163. return modName;
  164. }
  165. std::string CampaignHeader::getEncoding() const
  166. {
  167. return encoding;
  168. }
  169. AudioPath CampaignHeader::getMusic() const
  170. {
  171. return music;
  172. }
  173. ImagePath CampaignHeader::getLoadingBackground() const
  174. {
  175. return loadingBackground;
  176. }
  177. ImagePath CampaignHeader::getIntroVideoRim() const
  178. {
  179. return introVideoRim;
  180. }
  181. VideoPath CampaignHeader::getIntroVideo() const
  182. {
  183. return introVideo;
  184. }
  185. const CampaignRegions & CampaignHeader::getRegions() const
  186. {
  187. return campaignRegions;
  188. }
  189. TextContainerRegistrable & CampaignHeader::getTexts()
  190. {
  191. return textContainer;
  192. }
  193. bool CampaignState::isConquered(CampaignScenarioID whichScenario) const
  194. {
  195. return vstd::contains(mapsConquered, whichScenario);
  196. }
  197. bool CampaignState::isAvailable(CampaignScenarioID whichScenario) const
  198. {
  199. //check for void scenraio
  200. if (!scenario(whichScenario).isNotVoid())
  201. {
  202. return false;
  203. }
  204. if (vstd::contains(mapsConquered, whichScenario))
  205. {
  206. return false;
  207. }
  208. //check preconditioned regions
  209. for (auto const & it : scenario(whichScenario).preconditionRegions)
  210. {
  211. if (!vstd::contains(mapsConquered, it))
  212. return false;
  213. }
  214. return true;
  215. }
  216. bool CampaignScenario::isNotVoid() const
  217. {
  218. return !mapName.empty();
  219. }
  220. std::set<HeroTypeID> CampaignState::getReservedHeroes() const
  221. {
  222. std::set<HeroTypeID> result;
  223. for (auto const & scenarioID : allScenarios())
  224. {
  225. if (isConquered(scenarioID))
  226. continue;
  227. auto header = getMapHeader(scenarioID);
  228. result.insert(header->reservedCampaignHeroes.begin(), header->reservedCampaignHeroes.end());
  229. }
  230. return result;
  231. }
  232. const CGHeroInstance * CampaignState::strongestHero(CampaignScenarioID scenarioId, const PlayerColor & owner) const
  233. {
  234. std::function<bool(const JsonNode & node)> isOwned = [&](const JsonNode & node)
  235. {
  236. auto * h = CampaignState::crossoverDeserialize(node, nullptr);
  237. bool result = h->tempOwner == owner;
  238. vstd::clear_pointer(h);
  239. return result;
  240. };
  241. auto ownedHeroes = scenarioHeroPool.at(scenarioId) | boost::adaptors::filtered(isOwned);
  242. if (ownedHeroes.empty())
  243. return nullptr;
  244. return CampaignState::crossoverDeserialize(ownedHeroes.front(), nullptr);
  245. }
  246. /// Returns heroes that can be instantiated as hero placeholders by power
  247. const std::vector<JsonNode> & CampaignState::getHeroesByPower(CampaignScenarioID scenarioId) const
  248. {
  249. static const std::vector<JsonNode> emptyVector;
  250. if (scenarioHeroPool.count(scenarioId))
  251. return scenarioHeroPool.at(scenarioId);
  252. return emptyVector;
  253. }
  254. /// Returns hero for instantiation as placeholder by type
  255. /// May return empty JsonNode if such hero was not found
  256. const JsonNode & CampaignState::getHeroByType(HeroTypeID heroID) const
  257. {
  258. static const JsonNode emptyNode;
  259. if (!getReservedHeroes().count(heroID))
  260. return emptyNode;
  261. if (!globalHeroPool.count(heroID))
  262. return emptyNode;
  263. return globalHeroPool.at(heroID);
  264. }
  265. void CampaignState::setCurrentMapAsConquered(std::vector<CGHeroInstance *> heroes)
  266. {
  267. range::sort(heroes, [](const CGHeroInstance * a, const CGHeroInstance * b)
  268. {
  269. return a->getHeroStrengthForCampaign() > b->getHeroStrengthForCampaign();
  270. });
  271. logGlobal->info("Scenario %d of campaign %s (%s) has been completed", currentMap->getNum(), getFilename(), getNameTranslated());
  272. mapsConquered.push_back(*currentMap);
  273. auto reservedHeroes = getReservedHeroes();
  274. for (auto * hero : heroes)
  275. {
  276. JsonNode node = CampaignState::crossoverSerialize(hero);
  277. if (reservedHeroes.count(hero->getHeroType()))
  278. {
  279. logGlobal->info("Hero crossover: %d (%s) exported to global pool", hero->getHeroType(), hero->getNameTranslated());
  280. globalHeroPool[hero->getHeroType()] = node;
  281. }
  282. else
  283. {
  284. logGlobal->info("Hero crossover: %d (%s) exported to scenario pool", hero->getHeroType(), hero->getNameTranslated());
  285. scenarioHeroPool[*currentMap].push_back(node);
  286. }
  287. }
  288. }
  289. std::optional<CampaignBonus> CampaignState::getBonus(CampaignScenarioID which) const
  290. {
  291. auto bonuses = scenario(which).travelOptions.bonusesToChoose;
  292. assert(chosenCampaignBonuses.count(*currentMap) || bonuses.empty());
  293. if(bonuses.empty())
  294. return std::optional<CampaignBonus>();
  295. if (!getBonusID(which))
  296. return std::optional<CampaignBonus>();
  297. return bonuses[getBonusID(which).value()];
  298. }
  299. std::optional<ui8> CampaignState::getBonusID(CampaignScenarioID which) const
  300. {
  301. if (!chosenCampaignBonuses.count(which))
  302. return std::nullopt;
  303. return chosenCampaignBonuses.at(which);
  304. }
  305. std::unique_ptr<CMap> CampaignState::getMap(CampaignScenarioID scenarioId, IGameCallback * cb)
  306. {
  307. // FIXME: there is certainly better way to handle maps inside campaigns
  308. if(scenarioId == CampaignScenarioID::NONE)
  309. scenarioId = currentMap.value();
  310. CMapService mapService;
  311. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  312. boost::to_lower(scenarioName);
  313. scenarioName += ':' + std::to_string(scenarioId.getNum());
  314. const auto & mapContent = mapPieces.find(scenarioId)->second;
  315. auto result = mapService.loadMap(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding(), cb);
  316. mapTranslations[scenarioId] = result->texts;
  317. return result;
  318. }
  319. std::unique_ptr<CMapHeader> CampaignState::getMapHeader(CampaignScenarioID scenarioId) const
  320. {
  321. if(scenarioId == CampaignScenarioID::NONE)
  322. scenarioId = currentMap.value();
  323. CMapService mapService;
  324. std::string scenarioName = getFilename().substr(0, getFilename().find('.'));
  325. boost::to_lower(scenarioName);
  326. scenarioName += ':' + std::to_string(scenarioId.getNum());
  327. const auto & mapContent = mapPieces.find(scenarioId)->second;
  328. return mapService.loadMapHeader(mapContent.data(), mapContent.size(), scenarioName, getModName(), getEncoding());
  329. }
  330. std::shared_ptr<CMapInfo> CampaignState::getMapInfo(CampaignScenarioID scenarioId) const
  331. {
  332. if(scenarioId == CampaignScenarioID::NONE)
  333. scenarioId = currentMap.value();
  334. auto mapInfo = std::make_shared<CMapInfo>();
  335. mapInfo->fileURI = getFilename();
  336. mapInfo->mapHeader = getMapHeader(scenarioId);
  337. mapInfo->countPlayers();
  338. return mapInfo;
  339. }
  340. JsonNode CampaignState::crossoverSerialize(CGHeroInstance * hero) const
  341. {
  342. JsonNode node;
  343. JsonSerializer handler(nullptr, node);
  344. hero->serializeJsonOptions(handler);
  345. return node;
  346. }
  347. CGHeroInstance * CampaignState::crossoverDeserialize(const JsonNode & node, CMap * map) const
  348. {
  349. JsonDeserializer handler(nullptr, const_cast<JsonNode&>(node));
  350. auto * hero = new CGHeroInstance(map ? map->cb : nullptr);
  351. hero->ID = Obj::HERO;
  352. hero->serializeJsonOptions(handler);
  353. if (map)
  354. {
  355. hero->serializeJsonArtifacts(handler, "artifacts");
  356. map->addNewArtifactInstance(*hero);
  357. }
  358. return hero;
  359. }
  360. void CampaignState::setCurrentMap(CampaignScenarioID which)
  361. {
  362. assert(scenario(which).isNotVoid());
  363. currentMap = which;
  364. }
  365. void CampaignState::setCurrentMapBonus(ui8 which)
  366. {
  367. chosenCampaignBonuses[*currentMap] = which;
  368. }
  369. std::optional<CampaignScenarioID> CampaignState::currentScenario() const
  370. {
  371. return currentMap;
  372. }
  373. std::optional<CampaignScenarioID> CampaignState::lastScenario() const
  374. {
  375. if (mapsConquered.empty())
  376. return std::nullopt;
  377. return mapsConquered.back();
  378. }
  379. std::set<CampaignScenarioID> CampaignState::conqueredScenarios() const
  380. {
  381. std::set<CampaignScenarioID> result;
  382. result.insert(mapsConquered.begin(), mapsConquered.end());
  383. return result;
  384. }
  385. std::set<CampaignScenarioID> Campaign::allScenarios() const
  386. {
  387. std::set<CampaignScenarioID> result;
  388. for (auto const & entry : scenarios)
  389. {
  390. if (entry.second.isNotVoid())
  391. result.insert(entry.first);
  392. }
  393. return result;
  394. }
  395. void Campaign::overrideCampaign()
  396. {
  397. const JsonNode node = JsonUtils::assembleFromFiles("config/campaignOverrides.json");
  398. for (auto & entry : node.Struct())
  399. if(filename == entry.first)
  400. {
  401. if(!entry.second["regions"].isNull() && !entry.second["scenarioCount"].isNull())
  402. loadLegacyData(CampaignRegions::fromJson(entry.second["regions"]), entry.second["scenarioCount"].Integer());
  403. if(!entry.second["loadingBackground"].isNull())
  404. loadingBackground = ImagePath::builtin(entry.second["loadingBackground"].String());
  405. if(!entry.second["introVideoRim"].isNull())
  406. introVideoRim = ImagePath::builtin(entry.second["introVideoRim"].String());
  407. if(!entry.second["introVideo"].isNull())
  408. introVideo = VideoPath::builtin(entry.second["introVideo"].String());
  409. }
  410. }
  411. void Campaign::overrideCampaignScenarios()
  412. {
  413. const JsonNode node = JsonUtils::assembleFromFiles("config/campaignOverrides.json");
  414. for (auto & entry : node.Struct())
  415. if(filename == entry.first)
  416. {
  417. if(!entry.second["scenarios"].isNull())
  418. {
  419. auto sc = entry.second["scenarios"].Vector();
  420. for(int i = 0; i < sc.size(); i++)
  421. {
  422. auto it = scenarios.begin();
  423. std::advance(it, i);
  424. if(!sc.at(i)["voiceProlog"].isNull())
  425. it->second.prolog.prologVoice = AudioPath::builtin(sc.at(i)["voiceProlog"].String());
  426. if(!sc.at(i)["voiceEpilog"].isNull())
  427. it->second.epilog.prologVoice = AudioPath::builtin(sc.at(i)["voiceEpilog"].String());
  428. }
  429. }
  430. }
  431. }
  432. int Campaign::scenariosCount() const
  433. {
  434. return allScenarios().size();
  435. }
  436. const CampaignScenario & Campaign::scenario(CampaignScenarioID which) const
  437. {
  438. assert(scenarios.count(which));
  439. assert(scenarios.at(which).isNotVoid());
  440. return scenarios.at(which);
  441. }
  442. bool CampaignState::isCampaignFinished() const
  443. {
  444. return conqueredScenarios() == allScenarios();
  445. }
  446. VCMI_LIB_NAMESPACE_END