MapFormatH3M.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  1. /*
  2. * MapFormatH3M.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 "MapFormatH3M.h"
  12. #include "CMap.h"
  13. #include "MapReaderH3M.h"
  14. #include "../CCreatureHandler.h"
  15. #include "../CGeneralTextHandler.h"
  16. #include "../CHeroHandler.h"
  17. #include "../CSkillHandler.h"
  18. #include "../CStopWatch.h"
  19. #include "../RiverHandler.h"
  20. #include "../RoadHandler.h"
  21. #include "../TerrainHandler.h"
  22. #include "../TextOperations.h"
  23. #include "../VCMI_Lib.h"
  24. #include "../filesystem/CBinaryReader.h"
  25. #include "../filesystem/Filesystem.h"
  26. #include "../mapObjects/CObjectClassesHandler.h"
  27. #include "../mapObjects/MapObjects.h"
  28. #include "../spells/CSpellHandler.h"
  29. #include <boost/crc.hpp>
  30. VCMI_LIB_NAMESPACE_BEGIN
  31. static std::string convertMapName(std::string input)
  32. {
  33. boost::algorithm::to_lower(input);
  34. boost::algorithm::trim(input);
  35. size_t slashPos = input.find_last_of('/');
  36. if(slashPos != std::string::npos)
  37. return input.substr(slashPos + 1);
  38. return input;
  39. }
  40. CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
  41. : map(nullptr)
  42. , reader(new MapReaderH3M(stream))
  43. , inputStream(stream)
  44. , mapName(convertMapName(mapName))
  45. , modName(modName)
  46. , fileEncoding(encodingName)
  47. {
  48. }
  49. //must be instantiated in .cpp file for access to complete types of all member fields
  50. CMapLoaderH3M::~CMapLoaderH3M() = default;
  51. std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
  52. {
  53. // Init map object by parsing the input buffer
  54. map = new CMap();
  55. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  56. init();
  57. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  58. }
  59. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  60. {
  61. // Read header
  62. mapHeader = std::make_unique<CMapHeader>();
  63. readHeader();
  64. return std::move(mapHeader);
  65. }
  66. void CMapLoaderH3M::init()
  67. {
  68. //TODO: get rid of double input process
  69. si64 temp_size = inputStream->getSize();
  70. inputStream->seek(0);
  71. auto * temp_buffer = new ui8[temp_size];
  72. inputStream->read(temp_buffer, temp_size);
  73. // Compute checksum
  74. boost::crc_32_type result;
  75. result.process_bytes(temp_buffer, temp_size);
  76. map->checksum = result.checksum();
  77. delete[] temp_buffer;
  78. inputStream->seek(0);
  79. readHeader();
  80. map->allHeroes.resize(map->allowedHeroes.size());
  81. readDisposedHeroes();
  82. readMapOptions();
  83. readAllowedArtifacts();
  84. readAllowedSpellsAbilities();
  85. readRumors();
  86. readPredefinedHeroes();
  87. readTerrain();
  88. readDefInfo();
  89. readObjects();
  90. readEvents();
  91. map->calculateGuardingGreaturePositions();
  92. afterRead();
  93. }
  94. void CMapLoaderH3M::readHeader()
  95. {
  96. // Map version
  97. mapHeader->version = static_cast<EMapFormat>(reader->readUInt32());
  98. if(mapHeader->version == EMapFormat::HOTA)
  99. {
  100. uint32_t hotaVersion = reader->readUInt32();
  101. features = MapFormatFeaturesH3M::find(mapHeader->version, hotaVersion);
  102. reader->setFormatLevel(mapHeader->version, hotaVersion);
  103. if(hotaVersion > 0)
  104. {
  105. reader->skipZero(1);
  106. //TODO: HotA
  107. bool isDuelMap = reader->readBool();
  108. if (isDuelMap)
  109. {
  110. logGlobal->warn("Map '%s': Duel maps are not supported!", mapName);
  111. throw std::runtime_error("Invalid map format!");
  112. }
  113. }
  114. if(hotaVersion > 1)
  115. {
  116. uint8_t unknown = reader->readUInt32();
  117. assert(unknown == 12);
  118. MAYBE_UNUSED(unknown);
  119. }
  120. }
  121. else
  122. {
  123. features = MapFormatFeaturesH3M::find(mapHeader->version, 0);
  124. reader->setFormatLevel(mapHeader->version, 0);
  125. }
  126. // Read map name, description, dimensions,...
  127. mapHeader->areAnyPlayers = reader->readBool();
  128. mapHeader->height = mapHeader->width = reader->readInt32();
  129. mapHeader->twoLevel = reader->readBool();
  130. mapHeader->name = readLocalizedString("header.name");
  131. mapHeader->description = readLocalizedString("header.description");
  132. mapHeader->difficulty = reader->readInt8();
  133. if(features.levelAB)
  134. mapHeader->levelLimit = reader->readUInt8();
  135. else
  136. mapHeader->levelLimit = 0;
  137. readPlayerInfo();
  138. readVictoryLossConditions();
  139. readTeamInfo();
  140. readAllowedHeroes();
  141. }
  142. void CMapLoaderH3M::readPlayerInfo()
  143. {
  144. for(int i = 0; i < mapHeader->players.size(); ++i)
  145. {
  146. auto & playerInfo = mapHeader->players[i];
  147. playerInfo.canHumanPlay = reader->readBool();
  148. playerInfo.canComputerPlay = reader->readBool();
  149. // If nobody can play with this player - skip loading of these properties
  150. if((!(playerInfo.canHumanPlay || playerInfo.canComputerPlay)))
  151. {
  152. if(features.levelROE)
  153. reader->skipUnused(6);
  154. if(features.levelAB)
  155. reader->skipUnused(6);
  156. if(features.levelSOD)
  157. reader->skipUnused(1);
  158. continue;
  159. }
  160. playerInfo.aiTactic = static_cast<EAiTactic::EAiTactic>(reader->readUInt8());
  161. if(features.levelSOD)
  162. reader->skipUnused(1); //TODO: check meaning?
  163. std::set<FactionID> allowedFactions;
  164. reader->readBitmask(allowedFactions, features.factionsBytes, features.factionsCount, false);
  165. const bool isFactionRandom = playerInfo.isFactionRandom = reader->readBool();
  166. const bool allFactionsAllowed = isFactionRandom && allowedFactions.size() == features.factionsCount;
  167. if(!allFactionsAllowed)
  168. playerInfo.allowedFactions = allowedFactions;
  169. playerInfo.hasMainTown = reader->readBool();
  170. if(playerInfo.hasMainTown)
  171. {
  172. if(features.levelAB)
  173. {
  174. playerInfo.generateHeroAtMainTown = reader->readBool();
  175. reader->skipUnused(1); //TODO: check meaning?
  176. }
  177. else
  178. {
  179. playerInfo.generateHeroAtMainTown = true;
  180. }
  181. playerInfo.posOfMainTown = reader->readInt3();
  182. }
  183. playerInfo.hasRandomHero = reader->readBool();
  184. playerInfo.mainCustomHeroId = reader->readHero().getNum();
  185. if(playerInfo.mainCustomHeroId != -1)
  186. {
  187. playerInfo.mainCustomHeroPortrait = reader->readHero().getNum();
  188. playerInfo.mainCustomHeroName = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
  189. }
  190. if(features.levelAB)
  191. {
  192. reader->skipUnused(1); //TODO: check meaning?
  193. uint32_t heroCount = reader->readUInt32();
  194. for(int pp = 0; pp < heroCount; ++pp)
  195. {
  196. SHeroName vv;
  197. vv.heroId = reader->readUInt8();
  198. vv.heroName = readLocalizedString(TextIdentifier("header", "heroNames", vv.heroId));
  199. playerInfo.heroesNames.push_back(vv);
  200. }
  201. }
  202. }
  203. }
  204. enum class EVictoryConditionType : uint8_t
  205. {
  206. ARTIFACT = 0,
  207. GATHERTROOP = 1,
  208. GATHERRESOURCE = 2,
  209. BUILDCITY = 3,
  210. BUILDGRAIL = 4,
  211. BEATHERO = 5,
  212. CAPTURECITY = 6,
  213. BEATMONSTER = 7,
  214. TAKEDWELLINGS = 8,
  215. TAKEMINES = 9,
  216. TRANSPORTITEM = 10,
  217. HOTA_ELIMINATE_ALL_MONSTERS = 11,
  218. HOTA_SURVIVE_FOR_DAYS = 12,
  219. WINSTANDARD = 255
  220. };
  221. enum class ELossConditionType : uint8_t
  222. {
  223. LOSSCASTLE = 0,
  224. LOSSHERO = 1,
  225. TIMEEXPIRES = 2,
  226. LOSSSTANDARD = 255
  227. };
  228. void CMapLoaderH3M::readVictoryLossConditions()
  229. {
  230. mapHeader->triggeredEvents.clear();
  231. auto vicCondition = static_cast<EVictoryConditionType>(reader->readUInt8());
  232. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  233. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  234. defeatCondition.value = 7;
  235. TriggeredEvent standardVictory;
  236. standardVictory.effect.type = EventEffect::VICTORY;
  237. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  238. standardVictory.identifier = "standardVictory";
  239. standardVictory.description.clear(); // TODO: display in quest window
  240. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  241. standardVictory.trigger = EventExpression(victoryCondition);
  242. TriggeredEvent standardDefeat;
  243. standardDefeat.effect.type = EventEffect::DEFEAT;
  244. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  245. standardDefeat.identifier = "standardDefeat";
  246. standardDefeat.description.clear(); // TODO: display in quest window
  247. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  248. standardDefeat.trigger = EventExpression(defeatCondition);
  249. // Specific victory conditions
  250. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  251. {
  252. // create normal condition
  253. mapHeader->triggeredEvents.push_back(standardVictory);
  254. mapHeader->victoryIconIndex = 11;
  255. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
  256. }
  257. else
  258. {
  259. TriggeredEvent specialVictory;
  260. specialVictory.effect.type = EventEffect::VICTORY;
  261. specialVictory.identifier = "specialVictory";
  262. specialVictory.description.clear(); // TODO: display in quest window
  263. mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
  264. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[static_cast<size_t>(vicCondition) + 1];
  265. bool allowNormalVictory = reader->readBool();
  266. bool appliesToAI = reader->readBool();
  267. if(allowNormalVictory)
  268. {
  269. size_t playersOnMap = boost::range::count_if(
  270. mapHeader->players,
  271. [](const PlayerInfo & info)
  272. {
  273. return info.canAnyonePlay();
  274. }
  275. );
  276. if(playersOnMap == 1)
  277. {
  278. logGlobal->warn("Map %s: Only one player exists, but normal victory allowed!", mapName);
  279. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  280. }
  281. }
  282. switch(vicCondition)
  283. {
  284. case EVictoryConditionType::ARTIFACT:
  285. {
  286. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  287. cond.objectType = reader->readArtifact();
  288. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
  289. specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
  290. specialVictory.trigger = EventExpression(cond);
  291. break;
  292. }
  293. case EVictoryConditionType::GATHERTROOP:
  294. {
  295. EventCondition cond(EventCondition::HAVE_CREATURES);
  296. cond.objectType = reader->readCreature();
  297. cond.value = reader->readInt32();
  298. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
  299. specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
  300. specialVictory.trigger = EventExpression(cond);
  301. break;
  302. }
  303. case EVictoryConditionType::GATHERRESOURCE:
  304. {
  305. EventCondition cond(EventCondition::HAVE_RESOURCES);
  306. cond.objectType = reader->readUInt8();
  307. cond.value = reader->readInt32();
  308. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
  309. specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
  310. specialVictory.trigger = EventExpression(cond);
  311. break;
  312. }
  313. case EVictoryConditionType::BUILDCITY:
  314. {
  315. EventExpression::OperatorAll oper;
  316. EventCondition cond(EventCondition::HAVE_BUILDING);
  317. cond.position = reader->readInt3();
  318. cond.objectType = BuildingID::TOWN_HALL + reader->readUInt8();
  319. oper.expressions.emplace_back(cond);
  320. cond.objectType = BuildingID::FORT + reader->readUInt8();
  321. oper.expressions.emplace_back(cond);
  322. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
  323. specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
  324. specialVictory.trigger = EventExpression(oper);
  325. break;
  326. }
  327. case EVictoryConditionType::BUILDGRAIL:
  328. {
  329. EventCondition cond(EventCondition::HAVE_BUILDING);
  330. cond.objectType = BuildingID::GRAIL;
  331. cond.position = reader->readInt3();
  332. if(cond.position.z > 2)
  333. cond.position = int3(-1, -1, -1);
  334. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
  335. specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
  336. specialVictory.trigger = EventExpression(cond);
  337. break;
  338. }
  339. case EVictoryConditionType::BEATHERO:
  340. {
  341. EventCondition cond(EventCondition::DESTROY);
  342. cond.objectType = Obj::HERO;
  343. cond.position = reader->readInt3();
  344. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
  345. specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
  346. specialVictory.trigger = EventExpression(cond);
  347. break;
  348. }
  349. case EVictoryConditionType::CAPTURECITY:
  350. {
  351. EventCondition cond(EventCondition::CONTROL);
  352. cond.objectType = Obj::TOWN;
  353. cond.position = reader->readInt3();
  354. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
  355. specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
  356. specialVictory.trigger = EventExpression(cond);
  357. break;
  358. }
  359. case EVictoryConditionType::BEATMONSTER:
  360. {
  361. EventCondition cond(EventCondition::DESTROY);
  362. cond.objectType = Obj::MONSTER;
  363. cond.position = reader->readInt3();
  364. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
  365. specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
  366. specialVictory.trigger = EventExpression(cond);
  367. break;
  368. }
  369. case EVictoryConditionType::TAKEDWELLINGS:
  370. {
  371. EventExpression::OperatorAll oper;
  372. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
  373. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
  374. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
  375. specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
  376. specialVictory.trigger = EventExpression(oper);
  377. break;
  378. }
  379. case EVictoryConditionType::TAKEMINES:
  380. {
  381. EventCondition cond(EventCondition::CONTROL);
  382. cond.objectType = Obj::MINE;
  383. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
  384. specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
  385. specialVictory.trigger = EventExpression(cond);
  386. break;
  387. }
  388. case EVictoryConditionType::TRANSPORTITEM:
  389. {
  390. EventCondition cond(EventCondition::TRANSPORT);
  391. cond.objectType = reader->readUInt8();
  392. cond.position = reader->readInt3();
  393. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
  394. specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
  395. specialVictory.trigger = EventExpression(cond);
  396. break;
  397. }
  398. case EVictoryConditionType::HOTA_ELIMINATE_ALL_MONSTERS:
  399. //TODO: HOTA
  400. logGlobal->warn("Map '%s': Victory condition 'Eliminate all monsters' is not implemented!", mapName);
  401. break;
  402. case EVictoryConditionType::HOTA_SURVIVE_FOR_DAYS:
  403. {
  404. //TODO: HOTA
  405. uint32_t daysToSurvive = reader->readUInt32(); // Number of days
  406. logGlobal->warn("Map '%s': Victory condition 'Survive for %d days' is not implemented!", mapName, daysToSurvive);
  407. break;
  408. }
  409. default:
  410. assert(0);
  411. }
  412. // if condition is human-only turn it into following construction: AllOf(human, condition)
  413. if(!appliesToAI)
  414. {
  415. EventExpression::OperatorAll oper;
  416. EventCondition notAI(EventCondition::IS_HUMAN);
  417. notAI.value = 1;
  418. oper.expressions.emplace_back(notAI);
  419. oper.expressions.push_back(specialVictory.trigger.get());
  420. specialVictory.trigger = EventExpression(oper);
  421. }
  422. // if normal victory allowed - add one more quest
  423. if(allowNormalVictory)
  424. {
  425. mapHeader->victoryMessage += " / ";
  426. mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
  427. mapHeader->triggeredEvents.push_back(standardVictory);
  428. }
  429. mapHeader->triggeredEvents.push_back(specialVictory);
  430. }
  431. // Read loss conditions
  432. auto lossCond = static_cast<ELossConditionType>(reader->readUInt8());
  433. if(lossCond == ELossConditionType::LOSSSTANDARD)
  434. {
  435. mapHeader->defeatIconIndex = 3;
  436. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
  437. }
  438. else
  439. {
  440. TriggeredEvent specialDefeat;
  441. specialDefeat.effect.type = EventEffect::DEFEAT;
  442. specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  443. specialDefeat.identifier = "specialDefeat";
  444. specialDefeat.description.clear(); // TODO: display in quest window
  445. mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
  446. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[static_cast<size_t>(lossCond) + 1];
  447. switch(lossCond)
  448. {
  449. case ELossConditionType::LOSSCASTLE:
  450. {
  451. EventExpression::OperatorNone noneOf;
  452. EventCondition cond(EventCondition::CONTROL);
  453. cond.objectType = Obj::TOWN;
  454. cond.position = reader->readInt3();
  455. noneOf.expressions.emplace_back(cond);
  456. specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
  457. specialDefeat.trigger = EventExpression(noneOf);
  458. break;
  459. }
  460. case ELossConditionType::LOSSHERO:
  461. {
  462. EventExpression::OperatorNone noneOf;
  463. EventCondition cond(EventCondition::CONTROL);
  464. cond.objectType = Obj::HERO;
  465. cond.position = reader->readInt3();
  466. noneOf.expressions.emplace_back(cond);
  467. specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
  468. specialDefeat.trigger = EventExpression(noneOf);
  469. break;
  470. }
  471. case ELossConditionType::TIMEEXPIRES:
  472. {
  473. EventCondition cond(EventCondition::DAYS_PASSED);
  474. cond.value = reader->readUInt16();
  475. specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
  476. specialDefeat.trigger = EventExpression(cond);
  477. break;
  478. }
  479. }
  480. // turn simple loss condition into complete one that can be evaluated later:
  481. // - any of :
  482. // - days without town: 7
  483. // - all of:
  484. // - is human
  485. // - (expression)
  486. EventExpression::OperatorAll allOf;
  487. EventCondition isHuman(EventCondition::IS_HUMAN);
  488. isHuman.value = 1;
  489. allOf.expressions.emplace_back(isHuman);
  490. allOf.expressions.push_back(specialDefeat.trigger.get());
  491. specialDefeat.trigger = EventExpression(allOf);
  492. mapHeader->triggeredEvents.push_back(specialDefeat);
  493. }
  494. mapHeader->triggeredEvents.push_back(standardDefeat);
  495. }
  496. void CMapLoaderH3M::readTeamInfo()
  497. {
  498. mapHeader->howManyTeams = reader->readUInt8();
  499. if(mapHeader->howManyTeams > 0)
  500. {
  501. // Teams
  502. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  503. mapHeader->players[i].team = TeamID(reader->readUInt8());
  504. }
  505. else
  506. {
  507. // No alliances
  508. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  509. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  510. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  511. }
  512. }
  513. void CMapLoaderH3M::readAllowedHeroes()
  514. {
  515. mapHeader->allowedHeroes = VLC->heroh->getDefaultAllowed();
  516. uint32_t heroesCount = features.heroesCount;
  517. uint32_t heroesBytes = features.heroesBytes;
  518. if(features.levelHOTA0)
  519. {
  520. heroesCount = reader->readUInt32();
  521. heroesBytes = (heroesCount + 7) / 8;
  522. }
  523. assert(heroesCount <= features.heroesCount);
  524. reader->readBitmask(mapHeader->allowedHeroes, heroesBytes, heroesCount, false);
  525. //TODO: unknown value. Check meaning? Only present in campaign maps.
  526. if(features.levelAB)
  527. {
  528. uint32_t placeholdersQty = reader->readUInt32();
  529. reader->skipUnused(placeholdersQty * 1);
  530. }
  531. }
  532. void CMapLoaderH3M::readDisposedHeroes()
  533. {
  534. // Reading disposed heroes (20 bytes)
  535. if(features.levelSOD)
  536. {
  537. ui8 disp = reader->readUInt8();
  538. map->disposedHeroes.resize(disp);
  539. for(int g = 0; g < disp; ++g)
  540. {
  541. map->disposedHeroes[g].heroId = reader->readHero().getNum();
  542. map->disposedHeroes[g].portrait = reader->readHero().getNum();
  543. map->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", map->disposedHeroes[g].heroId));
  544. map->disposedHeroes[g].players = reader->readUInt8();
  545. }
  546. }
  547. }
  548. void CMapLoaderH3M::readMapOptions()
  549. {
  550. //omitting NULLS
  551. reader->skipZero(31);
  552. if(features.levelHOTA0)
  553. {
  554. //TODO: HotA
  555. bool allowSpecialMonths = reader->readBool();
  556. if(!allowSpecialMonths)
  557. logGlobal->warn("Map '%s': Option 'allow special months' is not implemented!", mapName);
  558. reader->skipZero(3);
  559. }
  560. if(features.levelHOTA1)
  561. {
  562. uint8_t unknownConstant = reader->readUInt8();
  563. assert(unknownConstant == 16);
  564. MAYBE_UNUSED(unknownConstant);
  565. reader->skipZero(5);
  566. }
  567. if(features.levelHOTA3)
  568. {
  569. //TODO: HotA
  570. int32_t roundLimit = reader->readInt32();
  571. if(roundLimit != -1)
  572. logGlobal->warn("Map '%s': roundLimit of %d is not implemented!", mapName, roundLimit);
  573. }
  574. }
  575. void CMapLoaderH3M::readAllowedArtifacts()
  576. {
  577. map->allowedArtifact = VLC->arth->getDefaultAllowed();
  578. uint32_t artifactsCount = features.artifactsCount;
  579. uint32_t artifactsBytes = features.artifactsBytes;
  580. if(features.levelHOTA0)
  581. {
  582. artifactsCount = reader->readUInt32();
  583. artifactsBytes = (artifactsCount + 7) / 8;
  584. }
  585. assert(artifactsCount <= features.artifactsCount);
  586. if(features.levelAB)
  587. reader->readBitmask(map->allowedArtifact, artifactsBytes, artifactsCount, true);
  588. // ban combo artifacts
  589. if(!features.levelSOD)
  590. {
  591. for(CArtifact * artifact : VLC->arth->objects)
  592. if(artifact->constituents)
  593. map->allowedArtifact[artifact->getId()] = false;
  594. }
  595. if(!features.levelAB)
  596. {
  597. map->allowedArtifact[ArtifactID::VIAL_OF_DRAGON_BLOOD] = false;
  598. map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
  599. }
  600. // Messy, but needed
  601. for(TriggeredEvent & event : map->triggeredEvents)
  602. {
  603. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  604. {
  605. if(cond.condition == EventCondition::HAVE_ARTIFACT || cond.condition == EventCondition::TRANSPORT)
  606. {
  607. map->allowedArtifact[cond.objectType] = false;
  608. }
  609. return cond;
  610. };
  611. event.trigger = event.trigger.morph(patcher);
  612. }
  613. }
  614. void CMapLoaderH3M::readAllowedSpellsAbilities()
  615. {
  616. map->allowedSpell = VLC->spellh->getDefaultAllowed();
  617. map->allowedAbilities = VLC->skillh->getDefaultAllowed();
  618. if(features.levelSOD)
  619. {
  620. reader->readBitmask(map->allowedSpell, features.spellsBytes, features.spellsCount, true);
  621. reader->readBitmask(map->allowedAbilities, features.skillsBytes, features.skillsCount, true);
  622. }
  623. }
  624. void CMapLoaderH3M::readRumors()
  625. {
  626. uint32_t rumorsCount = reader->readUInt32();
  627. assert(rumorsCount < 1000); // sanity check
  628. for(int it = 0; it < rumorsCount; it++)
  629. {
  630. Rumor ourRumor;
  631. ourRumor.name = readBasicString();
  632. ourRumor.text = readLocalizedString(TextIdentifier("header", "rumor", it, "text"));
  633. map->rumors.push_back(ourRumor);
  634. }
  635. }
  636. void CMapLoaderH3M::readPredefinedHeroes()
  637. {
  638. if(!features.levelSOD)
  639. return;
  640. uint32_t heroesCount = features.heroesCount;
  641. if(features.levelHOTA0)
  642. heroesCount = reader->readUInt32();
  643. assert(heroesCount <= features.heroesCount);
  644. for(int heroID = 0; heroID < heroesCount; heroID++)
  645. {
  646. bool custom = reader->readBool();
  647. if(!custom)
  648. continue;
  649. auto * hero = new CGHeroInstance();
  650. hero->ID = Obj::HERO;
  651. hero->subID = heroID;
  652. bool hasExp = reader->readBool();
  653. if(hasExp)
  654. {
  655. hero->exp = reader->readUInt32();
  656. }
  657. else
  658. {
  659. hero->exp = 0;
  660. }
  661. bool hasSecSkills = reader->readBool();
  662. if(hasSecSkills)
  663. {
  664. uint32_t howMany = reader->readUInt32();
  665. hero->secSkills.resize(howMany);
  666. for(int yy = 0; yy < howMany; ++yy)
  667. {
  668. hero->secSkills[yy].first = reader->readSkill();
  669. hero->secSkills[yy].second = reader->readUInt8();
  670. }
  671. }
  672. loadArtifactsOfHero(hero);
  673. bool hasCustomBio = reader->readBool();
  674. if(hasCustomBio)
  675. hero->biographyCustom = readLocalizedString(TextIdentifier("heroes", heroID, "biography"));
  676. // 0xFF is default, 00 male, 01 female
  677. hero->gender = static_cast<EHeroGender>(reader->readUInt8());
  678. assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
  679. bool hasCustomSpells = reader->readBool();
  680. if(hasCustomSpells)
  681. readSpells(hero->spells);
  682. bool hasCustomPrimSkills = reader->readBool();
  683. if(hasCustomPrimSkills)
  684. {
  685. for(int skillID = 0; skillID < GameConstants::PRIMARY_SKILLS; skillID++)
  686. {
  687. hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(skillID), reader->readUInt8());
  688. }
  689. }
  690. map->predefinedHeroes.emplace_back(hero);
  691. }
  692. }
  693. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  694. {
  695. bool hasArtSet = reader->readBool();
  696. // True if artifact set is not default (hero has some artifacts)
  697. if(!hasArtSet)
  698. return;
  699. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  700. {
  701. logGlobal->warn("Hero %s at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...", hero->getNameTranslated(), hero->pos.toString());
  702. hero->artifactsInBackpack.clear();
  703. while(!hero->artifactsWorn.empty())
  704. hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
  705. }
  706. for(int i = 0; i < features.artifactSlotsCount; i++)
  707. loadArtifactToSlot(hero, i);
  708. // bag artifacts
  709. // number of artifacts in hero's bag
  710. int amount = reader->readUInt16();
  711. for(int i = 0; i < amount; ++i)
  712. {
  713. loadArtifactToSlot(hero, GameConstants::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  714. }
  715. }
  716. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  717. {
  718. ArtifactID artifactID = reader->readArtifact();
  719. if(artifactID == ArtifactID::NONE)
  720. return false;
  721. const Artifact * art = artifactID.toArtifact(VLC->artifacts());
  722. if(!art)
  723. {
  724. logGlobal->warn("Map '%s': Invalid artifact in hero's backpack, ignoring...", mapName);
  725. return false;
  726. }
  727. if(art->isBig() && slot >= GameConstants::BACKPACK_START)
  728. {
  729. logGlobal->warn("Map '%s': A big artifact (war machine) in hero's backpack, ignoring...", mapName);
  730. return false;
  731. }
  732. // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
  733. // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
  734. // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
  735. auto * artifact = CArtifactInstance::createArtifact(map, artifactID);
  736. auto artifactPos = ArtifactPosition(slot);
  737. if(artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
  738. {
  739. hero->putArtifact(artifactPos, artifact);
  740. }
  741. else
  742. {
  743. logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, artifact->artType->getNameTranslated(), slot);
  744. return false;
  745. }
  746. return true;
  747. }
  748. void CMapLoaderH3M::readTerrain()
  749. {
  750. map->initTerrain();
  751. // Read terrain
  752. int3 pos;
  753. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  754. {
  755. //OH3 format is [z][y][x]
  756. for(pos.y = 0; pos.y < map->height; pos.y++)
  757. {
  758. for(pos.x = 0; pos.x < map->width; pos.x++)
  759. {
  760. auto & tile = map->getTile(pos);
  761. tile.terType = VLC->terrainTypeHandler->getById(reader->readTerrain());
  762. tile.terView = reader->readUInt8();
  763. tile.riverType = VLC->riverTypeHandler->getById(reader->readRiver());
  764. tile.riverDir = reader->readUInt8();
  765. tile.roadType = VLC->roadTypeHandler->getById(reader->readRoad());
  766. tile.roadDir = reader->readUInt8();
  767. tile.extTileFlags = reader->readUInt8();
  768. tile.blocked = !tile.terType->isPassable();
  769. tile.visitable = false;
  770. assert(tile.terType->getId() != ETerrainId::NONE);
  771. }
  772. }
  773. }
  774. }
  775. void CMapLoaderH3M::readDefInfo()
  776. {
  777. uint32_t defAmount = reader->readUInt32();
  778. templates.reserve(defAmount);
  779. // Read custom defs
  780. for(int defID = 0; defID < defAmount; ++defID)
  781. {
  782. auto * tmpl = new ObjectTemplate;
  783. tmpl->readMap(reader->getInternalReader());
  784. templates.push_back(std::shared_ptr<const ObjectTemplate>(tmpl));
  785. }
  786. }
  787. CGObjectInstance * CMapLoaderH3M::readEvent(const int3 & mapPosition)
  788. {
  789. auto * object = new CGEvent();
  790. readBoxContent(object, mapPosition);
  791. object->availableFor = reader->readUInt8();
  792. object->computerActivate = reader->readBool();
  793. object->removeAfterVisit = reader->readBool();
  794. reader->skipZero(4);
  795. if(features.levelHOTA3)
  796. object->humanActivate = reader->readBool();
  797. else
  798. object->humanActivate = true;
  799. return object;
  800. }
  801. CGObjectInstance * CMapLoaderH3M::readPandora(const int3 & mapPosition)
  802. {
  803. auto * object = new CGPandoraBox();
  804. readBoxContent(object, mapPosition);
  805. return object;
  806. }
  807. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition)
  808. {
  809. readMessageAndGuards(object->message, object, mapPosition);
  810. object->gainedExp = reader->readUInt32();
  811. object->manaDiff = reader->readInt32();
  812. object->moraleDiff = reader->readInt8();
  813. object->luckDiff = reader->readInt8();
  814. reader->readResourses(object->resources);
  815. object->primskills.resize(GameConstants::PRIMARY_SKILLS);
  816. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  817. object->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader->readUInt8());
  818. int gabn = reader->readUInt8(); //number of gained abilities
  819. for(int oo = 0; oo < gabn; ++oo)
  820. {
  821. object->abilities.emplace_back(reader->readSkill());
  822. object->abilityLevels.push_back(reader->readUInt8());
  823. }
  824. int gart = reader->readUInt8(); //number of gained artifacts
  825. for(int oo = 0; oo < gart; ++oo)
  826. object->artifacts.emplace_back(reader->readArtifact());
  827. int gspel = reader->readUInt8(); //number of gained spells
  828. for(int oo = 0; oo < gspel; ++oo)
  829. object->spells.emplace_back(reader->readSpell());
  830. int gcre = reader->readUInt8(); //number of gained creatures
  831. readCreatureSet(&object->creatures, gcre);
  832. reader->skipZero(8);
  833. }
  834. CGObjectInstance * CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  835. {
  836. auto * object = new CGCreature();
  837. if(features.levelAB)
  838. {
  839. object->identifier = reader->readUInt32();
  840. map->questIdentifierToId[object->identifier] = objectInstanceID;
  841. }
  842. auto * hlp = new CStackInstance();
  843. hlp->count = reader->readUInt16();
  844. //type will be set during initialization
  845. object->putStack(SlotID(0), hlp);
  846. object->character = reader->readInt8();
  847. bool hasMessage = reader->readBool();
  848. if(hasMessage)
  849. {
  850. object->message = readLocalizedString(TextIdentifier("monster", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  851. reader->readResourses(object->resources);
  852. object->gainedArtifact = reader->readArtifact();
  853. }
  854. object->neverFlees = reader->readBool();
  855. object->notGrowingTeam = reader->readBool();
  856. reader->skipZero(2);
  857. if(features.levelHOTA3)
  858. {
  859. //TODO: HotA
  860. int32_t agressionExact = reader->readInt32(); // -1 = default, 1-10 = possible values range
  861. bool joinOnlyForMoney = reader->readBool(); // if true, monsters will only join for money
  862. int32_t joinPercent = reader->readInt32(); // 100 = default, percent of monsters that will join on succesfull agression check
  863. int32_t upgradedStack = reader->readInt32(); // Presence of upgraded stack, -1 = random, 0 = never, 1 = always
  864. int32_t stacksCount = reader->readInt32(); // TODO: check possible values. How many creature stacks will be present on battlefield, -1 = default
  865. if(agressionExact != -1 || joinOnlyForMoney || joinPercent != 100 || upgradedStack != -1 || stacksCount != -1)
  866. logGlobal->warn(
  867. "Map '%s': Wandering monsters %s settings %d %d %d %d %d are not implemeted!",
  868. mapName,
  869. mapPosition.toString(),
  870. agressionExact,
  871. int(joinOnlyForMoney),
  872. joinPercent,
  873. upgradedStack,
  874. stacksCount
  875. );
  876. }
  877. return object;
  878. }
  879. CGObjectInstance * CMapLoaderH3M::readSign(const int3 & mapPosition)
  880. {
  881. auto * object = new CGSignBottle();
  882. object->message = readLocalizedString(TextIdentifier("sign", mapPosition.x, mapPosition.y, mapPosition.z, "message"));
  883. reader->skipZero(4);
  884. return object;
  885. }
  886. CGObjectInstance * CMapLoaderH3M::readWitchHut()
  887. {
  888. auto * object = new CGWitchHut();
  889. // AB and later maps have allowed abilities defined in H3M
  890. if(features.levelAB)
  891. {
  892. reader->readBitmask(object->allowedAbilities, features.skillsBytes, features.skillsCount, false);
  893. if(object->allowedAbilities.size() != 1)
  894. {
  895. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  896. for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
  897. if(defaultAllowed[skillID])
  898. object->allowedAbilities.insert(skillID);
  899. }
  900. }
  901. return object;
  902. }
  903. CGObjectInstance * CMapLoaderH3M::readScholar()
  904. {
  905. auto * object = new CGScholar();
  906. object->bonusType = static_cast<CGScholar::EBonusType>(reader->readUInt8());
  907. object->bonusID = reader->readUInt8();
  908. reader->skipZero(6);
  909. return object;
  910. }
  911. CGObjectInstance * CMapLoaderH3M::readGarrison(const int3 & mapPosition)
  912. {
  913. auto * object = new CGGarrison();
  914. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  915. readCreatureSet(object, 7);
  916. if(features.levelAB)
  917. object->removableUnits = reader->readBool();
  918. else
  919. object->removableUnits = true;
  920. reader->skipZero(8);
  921. return object;
  922. }
  923. CGObjectInstance * CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  924. {
  925. auto artID = ArtifactID::NONE; //random, set later
  926. int spellID = -1;
  927. auto * object = new CGArtifact();
  928. readMessageAndGuards(object->message, object, mapPosition);
  929. if(objectTemplate->id == Obj::SPELL_SCROLL)
  930. {
  931. spellID = reader->readSpell32();
  932. artID = ArtifactID::SPELL_SCROLL;
  933. }
  934. else if(objectTemplate->id == Obj::ARTIFACT)
  935. {
  936. //specific artifact
  937. artID = ArtifactID(objectTemplate->subid);
  938. }
  939. object->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
  940. return object;
  941. }
  942. CGObjectInstance * CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  943. {
  944. auto * object = new CGResource();
  945. readMessageAndGuards(object->message, object, mapPosition);
  946. object->amount = reader->readUInt32();
  947. if(objectTemplate->subid == GameResID(EGameResID::GOLD))
  948. {
  949. // Gold is multiplied by 100.
  950. object->amount *= 100;
  951. }
  952. reader->skipZero(4);
  953. return object;
  954. }
  955. CGObjectInstance * CMapLoaderH3M::readMine(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  956. {
  957. auto * object = new CGMine();
  958. if(objectTemplate->subid < 7)
  959. {
  960. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  961. }
  962. else
  963. {
  964. object->setOwner(PlayerColor::NEUTRAL);
  965. reader->readBitmask(object->abandonedMineResources, features.resourcesBytes, features.resourcesCount, false);
  966. }
  967. return object;
  968. }
  969. CGObjectInstance * CMapLoaderH3M::readDwelling(const int3 & position)
  970. {
  971. auto * object = new CGDwelling();
  972. setOwnerAndValidate(position, object, reader->readPlayer32());
  973. return object;
  974. }
  975. CGObjectInstance * CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  976. {
  977. auto * object = new CGDwelling();
  978. CSpecObjInfo * spec = nullptr;
  979. switch(objectTemplate->id)
  980. {
  981. case Obj::RANDOM_DWELLING:
  982. spec = new CCreGenLeveledCastleInfo();
  983. break;
  984. case Obj::RANDOM_DWELLING_LVL:
  985. spec = new CCreGenAsCastleInfo();
  986. break;
  987. case Obj::RANDOM_DWELLING_FACTION:
  988. spec = new CCreGenLeveledInfo();
  989. break;
  990. default:
  991. throw std::runtime_error("Invalid random dwelling format");
  992. }
  993. spec->owner = object;
  994. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  995. //216 and 217
  996. if(auto * castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
  997. {
  998. castleSpec->instanceId = "";
  999. castleSpec->identifier = reader->readUInt32();
  1000. if(!castleSpec->identifier)
  1001. {
  1002. castleSpec->asCastle = false;
  1003. const int MASK_SIZE = 8;
  1004. ui8 mask[2];
  1005. mask[0] = reader->readUInt8();
  1006. mask[1] = reader->readUInt8();
  1007. castleSpec->allowedFactions.clear();
  1008. castleSpec->allowedFactions.resize(VLC->townh->size(), false);
  1009. for(int i = 0; i < MASK_SIZE; i++)
  1010. castleSpec->allowedFactions[i] = ((mask[0] & (1 << i)) > 0);
  1011. for(int i = 0; i < (GameConstants::F_NUMBER - MASK_SIZE); i++)
  1012. castleSpec->allowedFactions[i + MASK_SIZE] = ((mask[1] & (1 << i)) > 0);
  1013. }
  1014. else
  1015. {
  1016. castleSpec->asCastle = true;
  1017. }
  1018. }
  1019. //216 and 218
  1020. if(auto * lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
  1021. {
  1022. lvlSpec->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(1));
  1023. lvlSpec->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(7));
  1024. }
  1025. object->info = spec;
  1026. return object;
  1027. }
  1028. CGObjectInstance * CMapLoaderH3M::readShrine()
  1029. {
  1030. auto * object = new CGShrine();
  1031. object->spell = reader->readSpell32();
  1032. return object;
  1033. }
  1034. CGObjectInstance * CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1035. {
  1036. auto * object = new CGHeroPlaceholder();
  1037. setOwnerAndValidate(mapPosition, object, reader->readPlayer());
  1038. HeroTypeID htid = reader->readHero(); //hero type id
  1039. object->subID = htid.getNum();
  1040. if(htid.getNum() == -1)
  1041. {
  1042. object->power = reader->readUInt8();
  1043. logGlobal->debug("Hero placeholder: by power at %s", mapPosition.toString());
  1044. }
  1045. else
  1046. {
  1047. object->power = 0;
  1048. logGlobal->debug("Hero placeholder: %s at %s", VLC->heroh->getById(htid)->getNameTranslated(), mapPosition.toString());
  1049. }
  1050. return object;
  1051. }
  1052. CGObjectInstance * CMapLoaderH3M::readGrail(const int3 & mapPosition)
  1053. {
  1054. map->grailPos = mapPosition;
  1055. map->grailRadius = reader->readInt32();
  1056. return nullptr;
  1057. }
  1058. CGObjectInstance * CMapLoaderH3M::readGeneric(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1059. {
  1060. if(VLC->objtypeh->knownSubObjects(objectTemplate->id).count(objectTemplate->subid))
  1061. return VLC->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid)->create(objectTemplate);
  1062. logGlobal->warn("Map '%s': Unrecognized object %d:%d ('%s') at %s found!", mapName, objectTemplate->id.toEnum(), objectTemplate->subid, objectTemplate->animationFile, mapPosition.toString());
  1063. return new CGObjectInstance();
  1064. }
  1065. CGObjectInstance * CMapLoaderH3M::readPyramid(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1066. {
  1067. if(objectTemplate->subid == 0)
  1068. return new CBank();
  1069. return new CGObjectInstance();
  1070. }
  1071. CGObjectInstance * CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1072. {
  1073. auto * guard = new CGQuestGuard();
  1074. readQuest(guard, mapPosition);
  1075. return guard;
  1076. }
  1077. CGObjectInstance * CMapLoaderH3M::readShipyard(const int3 & mapPosition)
  1078. {
  1079. auto * object = new CGShipyard();
  1080. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1081. return object;
  1082. }
  1083. CGObjectInstance * CMapLoaderH3M::readBorderGuard()
  1084. {
  1085. return new CGBorderGuard();
  1086. }
  1087. CGObjectInstance * CMapLoaderH3M::readBorderGate(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1088. {
  1089. if(objectTemplate->subid < 1000)
  1090. return new CGBorderGate();
  1091. //TODO: HotA - grave has same ID as border gate? WTF?
  1092. if(objectTemplate->subid == 1001)
  1093. return new CGObjectInstance();
  1094. logGlobal->warn("Map '%s: Quest gates at %s are not implemented!", mapName, mapPosition.toString());
  1095. return readQuestGuard(mapPosition);
  1096. }
  1097. CGObjectInstance * CMapLoaderH3M::readLighthouse(const int3 & mapPosition)
  1098. {
  1099. auto * object = new CGLighthouse();
  1100. setOwnerAndValidate(mapPosition, object, reader->readPlayer32());
  1101. return object;
  1102. }
  1103. CGObjectInstance * CMapLoaderH3M::readBank(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1104. {
  1105. if(features.levelHOTA3)
  1106. {
  1107. //TODO: HotA
  1108. // index of guards preset. -1 = random, 0-4 = index of possible guards settings
  1109. int32_t guardsPresetIndex = reader->readInt32();
  1110. // presence of upgraded stack: -1 = random, 0 = never, 1 = always
  1111. int8_t upgradedStackPresence = reader->readInt8();
  1112. assert(vstd::iswithin(guardsPresetIndex, -1, 4));
  1113. assert(vstd::iswithin(upgradedStackPresence, -1, 1));
  1114. // list of possible artifacts in reward
  1115. // - if list is empty, artifacts are either not present in reward or random
  1116. // - if non-empty, then list always have same number of elements as number of artifacts in bank
  1117. // - ArtifactID::NONE indictates random artifact, other values indicate artifact that should be used as reward
  1118. std::vector<ArtifactID> artifacts;
  1119. int artNumber = reader->readUInt32();
  1120. for(int yy = 0; yy < artNumber; ++yy)
  1121. {
  1122. artifacts.push_back(reader->readArtifact32());
  1123. }
  1124. if(guardsPresetIndex != -1 || upgradedStackPresence != -1 || !artifacts.empty())
  1125. logGlobal->warn(
  1126. "Map '%s: creature bank at %s settings %d %d %d are not implemented!",
  1127. mapName,
  1128. mapPosition.toString(),
  1129. guardsPresetIndex,
  1130. int(upgradedStackPresence),
  1131. artifacts.size()
  1132. );
  1133. }
  1134. return readGeneric(mapPosition, objectTemplate);
  1135. }
  1136. CGObjectInstance * CMapLoaderH3M::readObject(std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1137. {
  1138. switch(objectTemplate->id)
  1139. {
  1140. case Obj::EVENT:
  1141. return readEvent(mapPosition);
  1142. case Obj::HERO:
  1143. case Obj::RANDOM_HERO:
  1144. case Obj::PRISON:
  1145. return readHero(mapPosition, objectInstanceID);
  1146. case Obj::MONSTER:
  1147. case Obj::RANDOM_MONSTER:
  1148. case Obj::RANDOM_MONSTER_L1:
  1149. case Obj::RANDOM_MONSTER_L2:
  1150. case Obj::RANDOM_MONSTER_L3:
  1151. case Obj::RANDOM_MONSTER_L4:
  1152. case Obj::RANDOM_MONSTER_L5:
  1153. case Obj::RANDOM_MONSTER_L6:
  1154. case Obj::RANDOM_MONSTER_L7:
  1155. return readMonster(mapPosition, objectInstanceID);
  1156. case Obj::OCEAN_BOTTLE:
  1157. case Obj::SIGN:
  1158. return readSign(mapPosition);
  1159. case Obj::SEER_HUT:
  1160. return readSeerHut(mapPosition);
  1161. case Obj::WITCH_HUT:
  1162. return readWitchHut();
  1163. case Obj::SCHOLAR:
  1164. return readScholar();
  1165. case Obj::GARRISON:
  1166. case Obj::GARRISON2:
  1167. return readGarrison(mapPosition);
  1168. case Obj::ARTIFACT:
  1169. case Obj::RANDOM_ART:
  1170. case Obj::RANDOM_TREASURE_ART:
  1171. case Obj::RANDOM_MINOR_ART:
  1172. case Obj::RANDOM_MAJOR_ART:
  1173. case Obj::RANDOM_RELIC_ART:
  1174. case Obj::SPELL_SCROLL:
  1175. return readArtifact(mapPosition, objectTemplate);
  1176. case Obj::RANDOM_RESOURCE:
  1177. case Obj::RESOURCE:
  1178. return readResource(mapPosition, objectTemplate);
  1179. case Obj::RANDOM_TOWN:
  1180. case Obj::TOWN:
  1181. return readTown(mapPosition, objectTemplate);
  1182. case Obj::MINE:
  1183. case Obj::ABANDONED_MINE:
  1184. return readMine(mapPosition, objectTemplate);
  1185. case Obj::CREATURE_GENERATOR1:
  1186. case Obj::CREATURE_GENERATOR2:
  1187. case Obj::CREATURE_GENERATOR3:
  1188. case Obj::CREATURE_GENERATOR4:
  1189. return readDwelling(mapPosition);
  1190. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1191. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1192. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1193. return readShrine();
  1194. case Obj::PANDORAS_BOX:
  1195. return readPandora(mapPosition);
  1196. case Obj::GRAIL:
  1197. return readGrail(mapPosition);
  1198. case Obj::RANDOM_DWELLING:
  1199. case Obj::RANDOM_DWELLING_LVL:
  1200. case Obj::RANDOM_DWELLING_FACTION:
  1201. return readDwellingRandom(mapPosition, objectTemplate);
  1202. case Obj::QUEST_GUARD:
  1203. return readQuestGuard(mapPosition);
  1204. case Obj::SHIPYARD:
  1205. return readShipyard(mapPosition);
  1206. case Obj::HERO_PLACEHOLDER:
  1207. return readHeroPlaceholder(mapPosition);
  1208. case Obj::BORDERGUARD:
  1209. return readBorderGuard();
  1210. case Obj::BORDER_GATE:
  1211. return readBorderGate(mapPosition, objectTemplate);
  1212. case Obj::PYRAMID:
  1213. return readPyramid(mapPosition, objectTemplate);
  1214. case Obj::LIGHTHOUSE:
  1215. return readLighthouse(mapPosition);
  1216. case Obj::CREATURE_BANK:
  1217. case Obj::DERELICT_SHIP:
  1218. case Obj::DRAGON_UTOPIA:
  1219. case Obj::CRYPT:
  1220. case Obj::SHIPWRECK:
  1221. return readBank(mapPosition, objectTemplate);
  1222. default: //any other object
  1223. return readGeneric(mapPosition, objectTemplate);
  1224. }
  1225. }
  1226. void CMapLoaderH3M::readObjects()
  1227. {
  1228. uint32_t objectsCount = reader->readUInt32();
  1229. for(uint32_t i = 0; i < objectsCount; ++i)
  1230. {
  1231. int3 mapPosition = reader->readInt3();
  1232. uint32_t defIndex = reader->readUInt32();
  1233. ObjectInstanceID objectInstanceID = ObjectInstanceID(static_cast<si32>(map->objects.size()));
  1234. std::shared_ptr<const ObjectTemplate> objectTemplate = templates.at(defIndex);
  1235. reader->skipZero(5);
  1236. CGObjectInstance * newObject = readObject(objectTemplate, mapPosition, objectInstanceID);
  1237. if(!newObject)
  1238. continue;
  1239. newObject->pos = mapPosition;
  1240. newObject->ID = objectTemplate->id;
  1241. newObject->id = objectInstanceID;
  1242. if(newObject->ID != Obj::HERO && newObject->ID != Obj::HERO_PLACEHOLDER && newObject->ID != Obj::PRISON)
  1243. {
  1244. newObject->subID = objectTemplate->subid;
  1245. }
  1246. newObject->appearance = objectTemplate;
  1247. assert(objectInstanceID == ObjectInstanceID((si32)map->objects.size()));
  1248. {
  1249. //TODO: define valid typeName and subtypeName for H3M maps
  1250. //boost::format fmt("%s_%d");
  1251. //fmt % nobj->typeName % nobj->id.getNum();
  1252. boost::format fmt("obj_%d");
  1253. fmt % newObject->id.getNum();
  1254. newObject->instanceName = fmt.str();
  1255. }
  1256. map->addNewObject(newObject);
  1257. }
  1258. std::sort(
  1259. map->heroesOnMap.begin(),
  1260. map->heroesOnMap.end(),
  1261. [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
  1262. {
  1263. return a->subID < b->subID;
  1264. }
  1265. );
  1266. }
  1267. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1268. {
  1269. for(int index = 0; index < number; ++index)
  1270. {
  1271. CreatureID creatureID = reader->readCreature();
  1272. int count = reader->readUInt16();
  1273. // Empty slot
  1274. if(creatureID == CreatureID::NONE)
  1275. continue;
  1276. auto * result = new CStackInstance();
  1277. result->count = count;
  1278. if(creatureID < CreatureID::NONE)
  1279. {
  1280. int value = -creatureID.getNum() - 2;
  1281. assert(value >= 0 && value < 14);
  1282. uint8_t level = value / 2;
  1283. uint8_t upgrade = value % 2;
  1284. //this will happen when random object has random army
  1285. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1286. }
  1287. else
  1288. {
  1289. result->setType(creatureID);
  1290. }
  1291. out->putStack(SlotID(index), result);
  1292. }
  1293. out->validTypes(true);
  1294. }
  1295. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1296. {
  1297. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1298. if(owner == PlayerColor::NEUTRAL)
  1299. {
  1300. object->setOwner(PlayerColor::NEUTRAL);
  1301. return;
  1302. }
  1303. if(!owner.isValidPlayer())
  1304. {
  1305. object->setOwner(PlayerColor::NEUTRAL);
  1306. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1307. return;
  1308. }
  1309. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1310. {
  1311. object->setOwner(PlayerColor::NEUTRAL);
  1312. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1313. );
  1314. return;
  1315. }
  1316. object->setOwner(owner);
  1317. }
  1318. CGObjectInstance * CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1319. {
  1320. auto * object = new CGHeroInstance();
  1321. if(features.levelAB)
  1322. {
  1323. unsigned int identifier = reader->readUInt32();
  1324. map->questIdentifierToId[identifier] = objectInstanceID;
  1325. }
  1326. PlayerColor owner = reader->readPlayer();
  1327. object->subID = reader->readUInt8();
  1328. //If hero of this type has been predefined, use that as a base.
  1329. //Instance data will overwrite the predefined values where appropriate.
  1330. for(auto & elem : map->predefinedHeroes)
  1331. {
  1332. if(elem->subID == object->subID)
  1333. {
  1334. logGlobal->debug("Hero %d will be taken from the predefined heroes list.", object->subID);
  1335. delete object;
  1336. object = elem;
  1337. break;
  1338. }
  1339. }
  1340. setOwnerAndValidate(mapPosition, object, owner);
  1341. object->portrait = object->subID;
  1342. for(auto & elem : map->disposedHeroes)
  1343. {
  1344. if(elem.heroId == object->subID)
  1345. {
  1346. object->nameCustom = elem.name;
  1347. object->portrait = elem.portrait;
  1348. break;
  1349. }
  1350. }
  1351. bool hasName = reader->readBool();
  1352. if(hasName)
  1353. object->nameCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "name"));
  1354. if(features.levelSOD)
  1355. {
  1356. bool hasCustomExperience = reader->readBool();
  1357. if(hasCustomExperience)
  1358. object->exp = reader->readUInt32();
  1359. else
  1360. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1361. }
  1362. else
  1363. {
  1364. object->exp = reader->readUInt32();
  1365. //0 means "not set" in <=AB maps
  1366. if(!object->exp)
  1367. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1368. }
  1369. bool hasPortrait = reader->readBool();
  1370. if(hasPortrait)
  1371. object->portrait = reader->readHero().getNum();
  1372. bool hasSecSkills = reader->readBool();
  1373. if(hasSecSkills)
  1374. {
  1375. if(!object->secSkills.empty())
  1376. {
  1377. if(object->secSkills[0].first != SecondarySkill::DEFAULT)
  1378. logGlobal->warn("Hero %s subID=%d has set secondary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1379. object->secSkills.clear();
  1380. }
  1381. uint32_t skillsCount = reader->readUInt32();
  1382. object->secSkills.resize(skillsCount);
  1383. for(int i = 0; i < skillsCount; ++i)
  1384. {
  1385. object->secSkills[i].first = reader->readSkill();
  1386. object->secSkills[i].second = reader->readUInt8();
  1387. }
  1388. }
  1389. bool hasGarison = reader->readBool();
  1390. if(hasGarison)
  1391. readCreatureSet(object, 7);
  1392. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1393. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1394. loadArtifactsOfHero(object);
  1395. object->patrol.patrolRadius = reader->readUInt8();
  1396. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1397. if(features.levelAB)
  1398. {
  1399. bool hasCustomBiography = reader->readBool();
  1400. if(hasCustomBiography)
  1401. object->biographyCustom = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1402. object->gender = static_cast<EHeroGender>(reader->readUInt8());
  1403. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1404. }
  1405. else
  1406. {
  1407. object->gender = EHeroGender::DEFAULT;
  1408. }
  1409. // Spells
  1410. if(features.levelSOD)
  1411. {
  1412. bool hasCustomSpells = reader->readBool();
  1413. if(hasCustomSpells)
  1414. {
  1415. if(!object->spells.empty())
  1416. {
  1417. object->clear();
  1418. logGlobal->warn("Hero %s subID=%d has spells set twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1419. }
  1420. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1421. readSpells(object->spells);
  1422. }
  1423. }
  1424. else if(features.levelAB)
  1425. {
  1426. //we can read one spell
  1427. SpellID spell = reader->readSpell();
  1428. if(spell != SpellID::NONE)
  1429. object->spells.insert(spell);
  1430. }
  1431. if(features.levelSOD)
  1432. {
  1433. bool hasCustomPrimSkills = reader->readBool();
  1434. if(hasCustomPrimSkills)
  1435. {
  1436. auto ps = object->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL).And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
  1437. if(ps->size())
  1438. {
  1439. logGlobal->warn("Hero %s subID=%d has set primary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTranslated(), object->subID );
  1440. for(const auto & b : *ps)
  1441. object->removeBonus(b);
  1442. }
  1443. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1444. {
  1445. object->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader->readUInt8());
  1446. }
  1447. }
  1448. }
  1449. reader->skipZero(16);
  1450. return object;
  1451. }
  1452. CGObjectInstance * CMapLoaderH3M::readSeerHut(const int3 & position)
  1453. {
  1454. auto * hut = new CGSeerHut();
  1455. uint32_t questsCount = 1;
  1456. if(features.levelHOTA3)
  1457. questsCount = reader->readUInt32();
  1458. //TODO: HotA
  1459. if(questsCount > 1)
  1460. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1461. for(size_t i = 0; i < questsCount; ++i)
  1462. readSeerHutQuest(hut, position);
  1463. if(features.levelHOTA3)
  1464. {
  1465. uint32_t repeateableQuestsCount = reader->readUInt32();
  1466. if(repeateableQuestsCount != 0)
  1467. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1468. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1469. readSeerHutQuest(hut, position);
  1470. }
  1471. reader->skipZero(2);
  1472. return hut;
  1473. }
  1474. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position)
  1475. {
  1476. if(features.levelAB)
  1477. {
  1478. readQuest(hut, position);
  1479. }
  1480. else
  1481. {
  1482. //RoE
  1483. auto artID = reader->readArtifact();
  1484. if(artID != ArtifactID::NONE)
  1485. {
  1486. //not none quest
  1487. hut->quest->addArtifactID(artID);
  1488. hut->quest->missionType = CQuest::MISSION_ART;
  1489. }
  1490. else
  1491. {
  1492. hut->quest->missionType = CQuest::MISSION_NONE;
  1493. }
  1494. hut->quest->lastDay = -1; //no timeout
  1495. hut->quest->isCustomFirst = false;
  1496. hut->quest->isCustomNext = false;
  1497. hut->quest->isCustomComplete = false;
  1498. }
  1499. if(hut->quest->missionType)
  1500. {
  1501. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader->readUInt8());
  1502. hut->rewardType = rewardType;
  1503. switch(rewardType)
  1504. {
  1505. case CGSeerHut::EXPERIENCE:
  1506. {
  1507. hut->rVal = reader->readUInt32();
  1508. break;
  1509. }
  1510. case CGSeerHut::MANA_POINTS:
  1511. {
  1512. hut->rVal = reader->readUInt32();
  1513. break;
  1514. }
  1515. case CGSeerHut::MORALE_BONUS:
  1516. {
  1517. hut->rVal = reader->readUInt8();
  1518. break;
  1519. }
  1520. case CGSeerHut::LUCK_BONUS:
  1521. {
  1522. hut->rVal = reader->readUInt8();
  1523. break;
  1524. }
  1525. case CGSeerHut::RESOURCES:
  1526. {
  1527. hut->rID = reader->readUInt8();
  1528. hut->rVal = reader->readUInt32();
  1529. assert(hut->rID < features.resourcesCount);
  1530. assert((hut->rVal & 0x00ffffff) == hut->rVal);
  1531. break;
  1532. }
  1533. case CGSeerHut::PRIMARY_SKILL:
  1534. {
  1535. hut->rID = reader->readUInt8();
  1536. hut->rVal = reader->readUInt8();
  1537. break;
  1538. }
  1539. case CGSeerHut::SECONDARY_SKILL:
  1540. {
  1541. hut->rID = reader->readSkill();
  1542. hut->rVal = reader->readUInt8();
  1543. break;
  1544. }
  1545. case CGSeerHut::ARTIFACT:
  1546. {
  1547. hut->rID = reader->readArtifact();
  1548. break;
  1549. }
  1550. case CGSeerHut::SPELL:
  1551. {
  1552. hut->rID = reader->readSpell();
  1553. break;
  1554. }
  1555. case CGSeerHut::CREATURE:
  1556. {
  1557. hut->rID = reader->readCreature();
  1558. hut->rVal = reader->readUInt16();
  1559. break;
  1560. }
  1561. case CGSeerHut::NOTHING:
  1562. {
  1563. // no-op
  1564. break;
  1565. }
  1566. default:
  1567. {
  1568. assert(0);
  1569. }
  1570. }
  1571. }
  1572. else
  1573. {
  1574. // missionType==255
  1575. reader->skipZero(1);
  1576. }
  1577. }
  1578. void CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1579. {
  1580. guard->quest->missionType = static_cast<CQuest::Emission>(reader->readUInt8());
  1581. switch(guard->quest->missionType)
  1582. {
  1583. case CQuest::MISSION_NONE:
  1584. return;
  1585. case CQuest::MISSION_PRIMARY_STAT:
  1586. {
  1587. guard->quest->m2stats.resize(4);
  1588. for(int x = 0; x < 4; ++x)
  1589. {
  1590. guard->quest->m2stats[x] = reader->readUInt8();
  1591. }
  1592. }
  1593. break;
  1594. case CQuest::MISSION_LEVEL:
  1595. case CQuest::MISSION_KILL_HERO:
  1596. case CQuest::MISSION_KILL_CREATURE:
  1597. {
  1598. guard->quest->m13489val = reader->readUInt32();
  1599. break;
  1600. }
  1601. case CQuest::MISSION_ART:
  1602. {
  1603. int artNumber = reader->readUInt8();
  1604. for(int yy = 0; yy < artNumber; ++yy)
  1605. {
  1606. auto artid = reader->readArtifact();
  1607. guard->quest->addArtifactID(artid);
  1608. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1609. }
  1610. break;
  1611. }
  1612. case CQuest::MISSION_ARMY:
  1613. {
  1614. int typeNumber = reader->readUInt8();
  1615. guard->quest->m6creatures.resize(typeNumber);
  1616. for(int hh = 0; hh < typeNumber; ++hh)
  1617. {
  1618. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader->readCreature()];
  1619. guard->quest->m6creatures[hh].count = reader->readUInt16();
  1620. }
  1621. break;
  1622. }
  1623. case CQuest::MISSION_RESOURCES:
  1624. {
  1625. for(int x = 0; x < 7; ++x)
  1626. guard->quest->m7resources[x] = reader->readUInt32();
  1627. break;
  1628. }
  1629. case CQuest::MISSION_HERO:
  1630. {
  1631. guard->quest->m13489val = reader->readHero().getNum();
  1632. break;
  1633. }
  1634. case CQuest::MISSION_PLAYER:
  1635. {
  1636. guard->quest->m13489val = reader->readPlayer().getNum();
  1637. break;
  1638. }
  1639. case CQuest::MISSION_HOTA_MULTI:
  1640. {
  1641. uint32_t missionSubID = reader->readUInt32();
  1642. if(missionSubID == 0)
  1643. {
  1644. guard->quest->missionType = CQuest::MISSION_HOTA_HERO_CLASS;
  1645. std::set<HeroClassID> heroClasses;
  1646. uint32_t classesCount = reader->readUInt32();
  1647. uint32_t classesBytes = (classesCount + 7) / 8;
  1648. reader->readBitmask(heroClasses, classesBytes, classesCount, false);
  1649. logGlobal->warn("Map '%s': Quest at %s 'Belong to one of %d classes' is not implemented!", mapName, position.toString(), heroClasses.size());
  1650. break;
  1651. }
  1652. if(missionSubID == 1)
  1653. {
  1654. guard->quest->missionType = CQuest::MISSION_HOTA_REACH_DATE;
  1655. uint32_t daysPassed = reader->readUInt32();
  1656. logGlobal->warn("Map '%s': Quest at %s 'Wait till %d days passed' is not implemented!", mapName, position.toString(), daysPassed);
  1657. break;
  1658. }
  1659. assert(0);
  1660. break;
  1661. }
  1662. default:
  1663. {
  1664. assert(0);
  1665. }
  1666. }
  1667. guard->quest->lastDay = reader->readInt32();
  1668. guard->quest->firstVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit"));
  1669. guard->quest->nextVisitText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit"));
  1670. guard->quest->completedText = readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed"));
  1671. guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
  1672. guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
  1673. guard->quest->isCustomComplete = !guard->quest->completedText.empty();
  1674. }
  1675. CGObjectInstance * CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1676. {
  1677. auto * object = new CGTownInstance();
  1678. if(features.levelAB)
  1679. object->identifier = reader->readUInt32();
  1680. setOwnerAndValidate(position, object, reader->readPlayer());
  1681. bool hasName = reader->readBool();
  1682. if(hasName)
  1683. object->setNameTranslated(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  1684. bool hasGarrison = reader->readBool();
  1685. if(hasGarrison)
  1686. readCreatureSet(object, 7);
  1687. object->formation = static_cast<EArmyFormation>(reader->readUInt8());
  1688. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1689. bool hasCustomBuildings = reader->readBool();
  1690. if(hasCustomBuildings)
  1691. {
  1692. reader->readBitmask(object->builtBuildings, features.buildingsBytes, features.buildingsCount, false);
  1693. reader->readBitmask(object->forbiddenBuildings, features.buildingsBytes, features.buildingsCount, false);
  1694. object->builtBuildings = convertBuildings(object->builtBuildings, objectTemplate->subid);
  1695. object->forbiddenBuildings = convertBuildings(object->forbiddenBuildings, objectTemplate->subid);
  1696. }
  1697. // Standard buildings
  1698. else
  1699. {
  1700. bool hasFort = reader->readBool();
  1701. if(hasFort)
  1702. object->builtBuildings.insert(BuildingID::FORT);
  1703. //means that set of standard building should be included
  1704. object->builtBuildings.insert(BuildingID::DEFAULT);
  1705. }
  1706. if(features.levelAB)
  1707. {
  1708. std::set<SpellID> spellsMask;
  1709. reader->readBitmask(spellsMask, features.spellsBytes, features.spellsCount, false);
  1710. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  1711. }
  1712. {
  1713. std::set<SpellID> spellsMask;
  1714. reader->readBitmask(spellsMask, features.spellsBytes, features.spellsCount, true);
  1715. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  1716. auto defaultAllowed = VLC->spellh->getDefaultAllowed();
  1717. //add all spells from mods
  1718. for(int i = features.spellsCount; i < defaultAllowed.size(); ++i)
  1719. if(defaultAllowed[i])
  1720. object->possibleSpells.emplace_back(i);
  1721. }
  1722. if(features.levelHOTA1)
  1723. {
  1724. // TODO: HOTA support
  1725. bool spellResearchAvailable = reader->readBool();
  1726. MAYBE_UNUSED(spellResearchAvailable);
  1727. }
  1728. // Read castle events
  1729. uint32_t eventsCount = reader->readUInt32();
  1730. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1731. {
  1732. CCastleEvent event;
  1733. event.town = object;
  1734. event.name = readBasicString();
  1735. event.message = readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  1736. reader->readResourses(event.resources);
  1737. event.players = reader->readUInt8();
  1738. if(features.levelSOD)
  1739. event.humanAffected = reader->readBool();
  1740. else
  1741. event.humanAffected = true;
  1742. event.computerAffected = reader->readUInt8();
  1743. event.firstOccurence = reader->readUInt16();
  1744. event.nextOccurence = reader->readUInt8();
  1745. reader->skipZero(17);
  1746. // New buildings
  1747. reader->readBitmask(event.buildings, features.buildingsBytes, features.buildingsCount, false);
  1748. event.buildings = convertBuildings(event.buildings, objectTemplate->subid, false);
  1749. event.creatures.resize(7);
  1750. for(int i = 0; i < 7; ++i)
  1751. event.creatures[i] = reader->readUInt16();
  1752. reader->skipZero(4);
  1753. object->events.push_back(event);
  1754. }
  1755. if(features.levelHOTA0)
  1756. {
  1757. // TODO: HOTA support
  1758. uint8_t alignment = reader->readUInt8();
  1759. if(alignment < PlayerColor::PLAYER_LIMIT.getNum() || alignment == PlayerColor::NEUTRAL.getNum())
  1760. object->alignmentToPlayer = PlayerColor(alignment);
  1761. else
  1762. logGlobal->warn("%s - Aligment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  1763. }
  1764. else if(features.levelSOD)
  1765. {
  1766. object->alignmentToPlayer = reader->readPlayer();
  1767. }
  1768. reader->skipZero(3);
  1769. return object;
  1770. }
  1771. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> & h3m, int castleID, bool addAuxiliary) const
  1772. {
  1773. std::map<int, BuildingID> helperMap;
  1774. std::set<BuildingID> ret;
  1775. // Note: this file is parsed many times.
  1776. static const JsonNode config(ResourceID("config/buildings5.json"));
  1777. for(const JsonNode & entry : config["table"].Vector())
  1778. {
  1779. int town = static_cast<int>(entry["town"].Float());
  1780. if(town == castleID || town == -1)
  1781. {
  1782. helperMap[static_cast<int>(entry["h3"].Float())] = BuildingID(static_cast<si32>(entry["vcmi"].Float()));
  1783. }
  1784. }
  1785. for(const auto & elem : h3m)
  1786. {
  1787. if(helperMap[elem] >= BuildingID::FIRST_REGULAR_ID)
  1788. {
  1789. ret.insert(helperMap[elem]);
  1790. }
  1791. // horde buildings use indexes from -1 to -5, where creature level is 1 to 5
  1792. else if(helperMap[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1793. {
  1794. int level = (helperMap[elem]);
  1795. //(-30)..(-36) - horde buildings (for game loading only)
  1796. //They will be replaced in CGameState::initTowns()
  1797. ret.insert(BuildingID(level + BuildingID::HORDE_BUILDING_CONVERTER)); //-1 => -30
  1798. }
  1799. else
  1800. {
  1801. logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
  1802. }
  1803. }
  1804. if(addAuxiliary)
  1805. {
  1806. //village hall is always present
  1807. ret.insert(BuildingID::VILLAGE_HALL);
  1808. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1809. {
  1810. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1811. }
  1812. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1813. {
  1814. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1815. }
  1816. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1817. {
  1818. ret.insert(BuildingID::EXTRA_CAPITOL);
  1819. }
  1820. }
  1821. return ret;
  1822. }
  1823. void CMapLoaderH3M::readEvents()
  1824. {
  1825. uint32_t eventsCount = reader->readUInt32();
  1826. for(int eventID = 0; eventID < eventsCount; ++eventID)
  1827. {
  1828. CMapEvent event;
  1829. event.name = readBasicString();
  1830. event.message = readLocalizedString(TextIdentifier("event", eventID, "description"));
  1831. reader->readResourses(event.resources);
  1832. event.players = reader->readUInt8();
  1833. if(features.levelSOD)
  1834. {
  1835. event.humanAffected = reader->readBool();
  1836. }
  1837. else
  1838. {
  1839. event.humanAffected = true;
  1840. }
  1841. event.computerAffected = reader->readBool();
  1842. event.firstOccurence = reader->readUInt16();
  1843. event.nextOccurence = reader->readUInt8();
  1844. reader->skipZero(17);
  1845. map->events.push_back(event);
  1846. }
  1847. }
  1848. void CMapLoaderH3M::readMessageAndGuards(std::string & message, CCreatureSet * guards, const int3 & position)
  1849. {
  1850. bool hasMessage = reader->readBool();
  1851. if(hasMessage)
  1852. {
  1853. message = readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message"));
  1854. bool hasGuards = reader->readBool();
  1855. if(hasGuards)
  1856. readCreatureSet(guards, 7);
  1857. reader->skipZero(4);
  1858. }
  1859. }
  1860. void CMapLoaderH3M::readSpells(std::set<SpellID> & dest)
  1861. {
  1862. reader->readBitmask(dest, features.spellsBytes, features.spellsCount, false);
  1863. }
  1864. std::string CMapLoaderH3M::readBasicString()
  1865. {
  1866. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1867. }
  1868. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  1869. {
  1870. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  1871. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  1872. if(mapString.empty())
  1873. return "";
  1874. VLC->generaltexth->registerString(modName, fullIdentifier, mapString);
  1875. return VLC->generaltexth->translate(fullIdentifier.get());
  1876. }
  1877. void CMapLoaderH3M::afterRead()
  1878. {
  1879. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1880. for(auto & p : map->players)
  1881. {
  1882. int3 posOfMainTown = p.posOfMainTown;
  1883. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1884. {
  1885. const TerrainTile & t = map->getTile(posOfMainTown);
  1886. const CGObjectInstance * mainTown = nullptr;
  1887. for(auto * obj : t.visitableObjects)
  1888. {
  1889. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1890. {
  1891. mainTown = obj;
  1892. break;
  1893. }
  1894. }
  1895. if(mainTown == nullptr)
  1896. continue;
  1897. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1898. }
  1899. }
  1900. }
  1901. VCMI_LIB_NAMESPACE_END