MapFormatH3M.cpp 62 KB

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