CampaignState.cpp 16 KB

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