CampaignState.cpp 16 KB

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