MapFormatH3M.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787
  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 "MapFormat.h"
  15. #include "../CCreatureHandler.h"
  16. #include "../texts/CGeneralTextHandler.h"
  17. #include "../CSkillHandler.h"
  18. #include "../CStopWatch.h"
  19. #include "../IGameSettings.h"
  20. #include "../RiverHandler.h"
  21. #include "../RoadHandler.h"
  22. #include "../TerrainHandler.h"
  23. #include "../GameLibrary.h"
  24. #include "../constants/StringConstants.h"
  25. #include "../entities/artifact/CArtHandler.h"
  26. #include "../entities/hero/CHeroHandler.h"
  27. #include "../filesystem/CBinaryReader.h"
  28. #include "../filesystem/Filesystem.h"
  29. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  30. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  31. #include "../mapObjectConstructors/CommonConstructors.h"
  32. #include "../mapObjects/CGCreature.h"
  33. #include "../mapObjects/CGResource.h"
  34. #include "../mapObjects/CQuest.h"
  35. #include "../mapObjects/MapObjects.h"
  36. #include "../mapObjects/ObjectTemplate.h"
  37. #include "../modding/ModScope.h"
  38. #include "../networkPacks/Component.h"
  39. #include "../networkPacks/ArtifactLocation.h"
  40. #include "../spells/CSpellHandler.h"
  41. #include "../texts/TextOperations.h"
  42. VCMI_LIB_NAMESPACE_BEGIN
  43. static std::string convertMapName(std::string input)
  44. {
  45. boost::algorithm::to_lower(input);
  46. boost::algorithm::trim(input);
  47. boost::algorithm::erase_all(input, ".");
  48. size_t slashPos = input.find_last_of('/');
  49. if(slashPos != std::string::npos)
  50. return input.substr(slashPos + 1);
  51. return input;
  52. }
  53. CMapLoaderH3M::CMapLoaderH3M(const std::string & mapName, const std::string & modName, const std::string & encodingName, CInputStream * stream)
  54. : map(nullptr)
  55. , reader(new MapReaderH3M(stream))
  56. , inputStream(stream)
  57. , mapName(convertMapName(mapName))
  58. , modName(modName)
  59. , fileEncoding(encodingName)
  60. {
  61. }
  62. //must be instantiated in .cpp file for access to complete types of all member fields
  63. CMapLoaderH3M::~CMapLoaderH3M() = default;
  64. std::unique_ptr<CMap> CMapLoaderH3M::loadMap(IGameInfoCallback * cb)
  65. {
  66. // Init map object by parsing the input buffer
  67. map = new CMap(cb);
  68. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  69. init();
  70. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  71. }
  72. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  73. {
  74. // Read header
  75. mapHeader = std::make_unique<CMapHeader>();
  76. readHeader();
  77. return std::move(mapHeader);
  78. }
  79. void CMapLoaderH3M::init()
  80. {
  81. inputStream->seek(0);
  82. readHeader();
  83. readMapOptions();
  84. readAllowedArtifacts();
  85. readAllowedSpellsAbilities();
  86. readRumors();
  87. readPredefinedHeroes();
  88. readTerrain();
  89. readObjectTemplates();
  90. readObjects();
  91. readEvents();
  92. map->calculateGuardingGreaturePositions();
  93. afterRead();
  94. //map->banWaterContent(); //Not sure if force this for custom scenarios
  95. }
  96. static MapIdentifiersH3M generateMapping(EMapFormat format)
  97. {
  98. auto features = MapFormatFeaturesH3M::find(format, 0);
  99. MapIdentifiersH3M identifierMapper;
  100. if(features.levelROE)
  101. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_RESTORATION_OF_ERATHIA));
  102. if(features.levelAB)
  103. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_ARMAGEDDONS_BLADE));
  104. if(features.levelSOD)
  105. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_SHADOW_OF_DEATH));
  106. if(features.levelCHR)
  107. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_CHRONICLES));
  108. if(features.levelWOG)
  109. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_IN_THE_WAKE_OF_GODS));
  110. if(features.levelHOTA0)
  111. identifierMapper.loadMapping(LIBRARY->engineSettings()->getValue(EGameSettings::MAP_FORMAT_HORN_OF_THE_ABYSS));
  112. return identifierMapper;
  113. }
  114. static std::map<EMapFormat, MapIdentifiersH3M> generateMappings()
  115. {
  116. std::map<EMapFormat, MapIdentifiersH3M> result;
  117. auto addMapping = [&result](EMapFormat format)
  118. {
  119. try
  120. {
  121. result[format] = generateMapping(format);
  122. }
  123. catch(const std::runtime_error &)
  124. {
  125. // unsupported map format - skip
  126. }
  127. };
  128. addMapping(EMapFormat::ROE);
  129. addMapping(EMapFormat::AB);
  130. addMapping(EMapFormat::SOD);
  131. addMapping(EMapFormat::CHR);
  132. addMapping(EMapFormat::HOTA);
  133. addMapping(EMapFormat::WOG);
  134. return result;
  135. }
  136. void CMapLoaderH3M::readHeader()
  137. {
  138. // Map version
  139. mapHeader->version = static_cast<EMapFormat>(reader->readUInt32());
  140. if(mapHeader->version == EMapFormat::HOTA)
  141. {
  142. uint32_t hotaVersion = reader->readUInt32();
  143. features = MapFormatFeaturesH3M::find(mapHeader->version, hotaVersion);
  144. reader->setFormatLevel(features);
  145. if(features.levelHOTA8)
  146. {
  147. int hotaVersionMajor = reader->readUInt32();
  148. int hotaVersionMinor = reader->readUInt32();
  149. int hotaVersionPatch = reader->readUInt32();
  150. logGlobal->trace("Loading HotA map, version %d.%d.%d", hotaVersionMajor, hotaVersionMinor, hotaVersionPatch);
  151. }
  152. if(features.levelHOTA1)
  153. {
  154. bool isMirrorMap = reader->readBool();
  155. bool isArenaMap = reader->readBool();
  156. //TODO: HotA
  157. if (isMirrorMap)
  158. logGlobal->warn("Map '%s': Mirror maps are not yet supported!", mapName);
  159. if (isArenaMap)
  160. logGlobal->warn("Map '%s': Arena maps are not supported!", mapName);
  161. }
  162. if(features.levelHOTA2)
  163. {
  164. int32_t terrainTypesCount = reader->readUInt32();
  165. assert(features.terrainsCount == terrainTypesCount);
  166. if (features.terrainsCount != terrainTypesCount)
  167. logGlobal->warn("Map '%s': Expected %d terrains, but %d found!", mapName, features.terrainsCount, terrainTypesCount);
  168. }
  169. if(features.levelHOTA5)
  170. {
  171. int32_t townTypesCount = reader->readUInt32();
  172. int8_t allowedDifficultiesMask = reader->readInt8Checked(0, 31);
  173. assert(features.factionsCount == townTypesCount);
  174. if (features.factionsCount != townTypesCount)
  175. logGlobal->warn("Map '%s': Expected %d factions, but %d found!", mapName, features.factionsCount, townTypesCount);
  176. if (allowedDifficultiesMask != 0)
  177. logGlobal->warn("Map '%s': List of allowed difficulties (%d) is not implemented!", mapName, static_cast<int>(allowedDifficultiesMask));
  178. }
  179. if(features.levelHOTA7)
  180. {
  181. bool canHireDefeatedHeroes = reader->readBool();
  182. if (!canHireDefeatedHeroes)
  183. logGlobal->warn("Map '%s': Option to block hiring of defeated heroes is not implemented!", mapName);
  184. }
  185. if(features.levelHOTA8)
  186. {
  187. bool forceMatchingVersion = reader->readBool();
  188. if (forceMatchingVersion)
  189. logGlobal->warn("Map '%s': This map is forced to use specific hota version!", mapName);
  190. }
  191. }
  192. else
  193. {
  194. features = MapFormatFeaturesH3M::find(mapHeader->version, 0);
  195. reader->setFormatLevel(features);
  196. }
  197. // optimization - load mappings only once to avoid slow parsing of map headers for map list
  198. static const std::map<EMapFormat, MapIdentifiersH3M> identifierMappers = generateMappings();
  199. if (!identifierMappers.count(mapHeader->version))
  200. throw std::runtime_error("Unsupported map format! Format ID " + std::to_string(static_cast<int>(mapHeader->version)));
  201. const MapIdentifiersH3M & identifierMapper = identifierMappers.at(mapHeader->version);
  202. reader->setIdentifierRemapper(identifierMapper);
  203. // Read map name, description, dimensions,...
  204. mapHeader->areAnyPlayers = reader->readBool();
  205. mapHeader->height = mapHeader->width = reader->readInt32();
  206. mapHeader->twoLevel = reader->readBool();
  207. mapHeader->name.appendTextID(readLocalizedString("header.name"));
  208. mapHeader->description.appendTextID(readLocalizedString("header.description"));
  209. mapHeader->author.appendRawString("");
  210. mapHeader->authorContact.appendRawString("");
  211. mapHeader->mapVersion.appendRawString("");
  212. mapHeader->creationDateTime = 0;
  213. mapHeader->difficulty = static_cast<EMapDifficulty>(reader->readInt8Checked(0, 4));
  214. if(features.levelAB)
  215. mapHeader->levelLimit = reader->readInt8Checked(0, std::min(100u, LIBRARY->heroh->maxSupportedLevel()));
  216. else
  217. mapHeader->levelLimit = 0;
  218. readPlayerInfo();
  219. readVictoryLossConditions();
  220. readTeamInfo();
  221. readAllowedHeroes();
  222. readDisposedHeroes();
  223. }
  224. void CMapLoaderH3M::readPlayerInfo()
  225. {
  226. for(int i = 0; i < mapHeader->players.size(); ++i)
  227. {
  228. auto & playerInfo = mapHeader->players[i];
  229. playerInfo.canHumanPlay = reader->readBool();
  230. playerInfo.canComputerPlay = reader->readBool();
  231. // If nobody can play with this player - skip loading of these properties
  232. if((!(playerInfo.canHumanPlay || playerInfo.canComputerPlay)))
  233. {
  234. if(features.levelROE)
  235. reader->skipUnused(6);
  236. if(features.levelAB)
  237. reader->skipUnused(6);
  238. if(features.levelSOD)
  239. reader->skipUnused(1);
  240. continue;
  241. }
  242. playerInfo.aiTactic = static_cast<EAiTactic>(reader->readInt8Checked(-1, 3));
  243. if(features.levelSOD)
  244. reader->skipUnused(1); //faction is selectable
  245. std::set<FactionID> allowedFactions;
  246. reader->readBitmaskFactions(allowedFactions, false);
  247. playerInfo.isFactionRandom = reader->readBool();
  248. const bool allFactionsAllowed = playerInfo.isFactionRandom && allowedFactions.size() == features.factionsCount;
  249. if(!allFactionsAllowed)
  250. playerInfo.allowedFactions = allowedFactions;
  251. playerInfo.hasMainTown = reader->readBool();
  252. if(playerInfo.hasMainTown)
  253. {
  254. if(features.levelAB)
  255. {
  256. playerInfo.generateHeroAtMainTown = reader->readBool();
  257. reader->skipUnused(1); // starting town type, unused
  258. }
  259. else
  260. {
  261. playerInfo.generateHeroAtMainTown = true;
  262. }
  263. playerInfo.posOfMainTown = reader->readInt3();
  264. }
  265. playerInfo.hasRandomHero = reader->readBool();
  266. playerInfo.mainCustomHeroId = reader->readHero();
  267. if(playerInfo.mainCustomHeroId != HeroTypeID::NONE)
  268. {
  269. playerInfo.mainCustomHeroPortrait = reader->readHeroPortrait();
  270. playerInfo.mainCustomHeroNameTextId = readLocalizedString(TextIdentifier("header", "player", i, "mainHeroName"));
  271. }
  272. if(features.levelAB)
  273. {
  274. reader->skipUnused(1); //TODO: check meaning?
  275. size_t heroCount = reader->readUInt32();
  276. for(size_t pp = 0; pp < heroCount; ++pp)
  277. {
  278. SHeroName vv;
  279. vv.heroId = reader->readHero();
  280. vv.heroName = readLocalizedString(TextIdentifier("header", "heroNames", vv.heroId.getNum()));
  281. playerInfo.heroesNames.push_back(vv);
  282. }
  283. }
  284. }
  285. }
  286. void CMapLoaderH3M::readVictoryLossConditions()
  287. {
  288. mapHeader->triggeredEvents.clear();
  289. mapHeader->victoryMessage.clear();
  290. mapHeader->defeatMessage.clear();
  291. auto vicCondition = static_cast<EVictoryConditionType>(reader->readInt8Checked(-1, 12));
  292. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  293. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  294. defeatCondition.value = 7;
  295. TriggeredEvent standardVictory;
  296. standardVictory.effect.type = EventEffect::VICTORY;
  297. standardVictory.effect.toOtherMessage.appendTextID("core.genrltxt.5");
  298. standardVictory.identifier = "standardVictory";
  299. standardVictory.description.clear(); // TODO: display in quest window
  300. standardVictory.onFulfill.appendTextID("core.genrltxt.659");
  301. standardVictory.trigger = EventExpression(victoryCondition);
  302. TriggeredEvent standardDefeat;
  303. standardDefeat.effect.type = EventEffect::DEFEAT;
  304. standardDefeat.effect.toOtherMessage.appendTextID("core.genrltxt.8");
  305. standardDefeat.identifier = "standardDefeat";
  306. standardDefeat.description.clear(); // TODO: display in quest window
  307. standardDefeat.onFulfill.appendTextID("core.genrltxt.7");
  308. standardDefeat.trigger = EventExpression(defeatCondition);
  309. // Specific victory conditions
  310. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  311. {
  312. // create normal condition
  313. mapHeader->triggeredEvents.push_back(standardVictory);
  314. mapHeader->victoryIconIndex = 11;
  315. mapHeader->victoryMessage.appendTextID("core.vcdesc.0");
  316. }
  317. else
  318. {
  319. TriggeredEvent specialVictory;
  320. specialVictory.effect.type = EventEffect::VICTORY;
  321. specialVictory.identifier = "specialVictory";
  322. specialVictory.description.clear(); // TODO: display in quest window
  323. mapHeader->victoryIconIndex = static_cast<ui16>(vicCondition);
  324. bool allowNormalVictory = reader->readBool();
  325. bool appliesToAI = reader->readBool();
  326. switch(vicCondition)
  327. {
  328. case EVictoryConditionType::ARTIFACT:
  329. {
  330. assert(allowNormalVictory == true); // not selectable in editor
  331. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  332. cond.objectType = reader->readArtifact();
  333. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.281");
  334. specialVictory.onFulfill.appendTextID("core.genrltxt.280");
  335. specialVictory.trigger = EventExpression(cond);
  336. mapHeader->victoryMessage.appendTextID("core.vcdesc.1");
  337. break;
  338. }
  339. case EVictoryConditionType::GATHERTROOP:
  340. {
  341. EventCondition cond(EventCondition::HAVE_CREATURES);
  342. cond.objectType = reader->readCreature();
  343. cond.value = reader->readInt32();
  344. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.277");
  345. specialVictory.onFulfill.appendTextID("core.genrltxt.276");
  346. specialVictory.trigger = EventExpression(cond);
  347. mapHeader->victoryMessage.appendTextID("core.vcdesc.2");
  348. break;
  349. }
  350. case EVictoryConditionType::GATHERRESOURCE:
  351. {
  352. EventCondition cond(EventCondition::HAVE_RESOURCES);
  353. cond.objectType = reader->readGameResID();
  354. cond.value = reader->readInt32();
  355. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.279");
  356. specialVictory.onFulfill.appendTextID("core.genrltxt.278");
  357. specialVictory.trigger = EventExpression(cond);
  358. mapHeader->victoryMessage.appendTextID("core.vcdesc.3");
  359. break;
  360. }
  361. case EVictoryConditionType::BUILDCITY:
  362. {
  363. assert(appliesToAI == true); // not selectable in editor
  364. EventExpression::OperatorAll oper;
  365. EventCondition cond(EventCondition::HAVE_BUILDING);
  366. cond.position = reader->readInt3();
  367. cond.objectType = BuildingID::HALL_LEVEL(reader->readInt8Checked(0,3) + 1);
  368. oper.expressions.emplace_back(cond);
  369. cond.objectType = BuildingID::FORT_LEVEL(reader->readInt8Checked(0, 2));
  370. oper.expressions.emplace_back(cond);
  371. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.283");
  372. specialVictory.onFulfill.appendTextID("core.genrltxt.282");
  373. specialVictory.trigger = EventExpression(oper);
  374. mapHeader->victoryMessage.appendTextID("core.vcdesc.4");
  375. break;
  376. }
  377. case EVictoryConditionType::BUILDGRAIL:
  378. {
  379. assert(allowNormalVictory == true); // not selectable in editor
  380. assert(appliesToAI == true); // not selectable in editor
  381. EventCondition cond(EventCondition::HAVE_BUILDING);
  382. cond.objectType = BuildingID(BuildingID::GRAIL);
  383. cond.position = reader->readInt3();
  384. if(cond.position.z > 2)
  385. cond.position = int3(-1, -1, -1);
  386. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.285");
  387. specialVictory.onFulfill.appendTextID("core.genrltxt.284");
  388. specialVictory.trigger = EventExpression(cond);
  389. mapHeader->victoryMessage.appendTextID("core.vcdesc.5");
  390. break;
  391. }
  392. case EVictoryConditionType::BEATHERO:
  393. {
  394. if (!allowNormalVictory)
  395. logGlobal->debug("Map %s: Has 'beat hero' as victory condition, but 'allow normal victory' not set. Ignoring", mapName);
  396. allowNormalVictory = true; // H3 behavior
  397. assert(appliesToAI == false); // not selectable in editor
  398. EventCondition cond(EventCondition::DESTROY);
  399. cond.objectType = MapObjectID(MapObjectID::HERO);
  400. cond.position = reader->readInt3();
  401. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.253");
  402. specialVictory.onFulfill.appendTextID("core.genrltxt.252");
  403. specialVictory.trigger = EventExpression(cond);
  404. mapHeader->victoryMessage.appendTextID("core.vcdesc.6");
  405. break;
  406. }
  407. case EVictoryConditionType::CAPTURECITY:
  408. {
  409. EventCondition cond(EventCondition::CONTROL);
  410. cond.objectType = MapObjectID(MapObjectID::TOWN);
  411. cond.position = reader->readInt3();
  412. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.250");
  413. specialVictory.onFulfill.appendTextID("core.genrltxt.249");
  414. specialVictory.trigger = EventExpression(cond);
  415. mapHeader->victoryMessage.appendTextID("core.vcdesc.7");
  416. break;
  417. }
  418. case EVictoryConditionType::BEATMONSTER:
  419. {
  420. assert(appliesToAI == true); // not selectable in editor
  421. EventCondition cond(EventCondition::DESTROY);
  422. cond.objectType = MapObjectID(MapObjectID::MONSTER);
  423. cond.position = reader->readInt3();
  424. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.287");
  425. specialVictory.onFulfill.appendTextID("core.genrltxt.286");
  426. specialVictory.trigger = EventExpression(cond);
  427. mapHeader->victoryMessage.appendTextID("core.vcdesc.8");
  428. break;
  429. }
  430. case EVictoryConditionType::TAKEDWELLINGS:
  431. {
  432. EventExpression::OperatorAll oper;
  433. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj(Obj::CREATURE_GENERATOR1)));
  434. oper.expressions.emplace_back(EventCondition(EventCondition::CONTROL, 0, Obj(Obj::CREATURE_GENERATOR4)));
  435. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.289");
  436. specialVictory.onFulfill.appendTextID("core.genrltxt.288");
  437. specialVictory.trigger = EventExpression(oper);
  438. mapHeader->victoryMessage.appendTextID("core.vcdesc.9");
  439. break;
  440. }
  441. case EVictoryConditionType::TAKEMINES:
  442. {
  443. EventCondition cond(EventCondition::CONTROL);
  444. cond.objectType = MapObjectID(MapObjectID::MINE);
  445. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.291");
  446. specialVictory.onFulfill.appendTextID("core.genrltxt.290");
  447. specialVictory.trigger = EventExpression(cond);
  448. mapHeader->victoryMessage.appendTextID("core.vcdesc.10");
  449. break;
  450. }
  451. case EVictoryConditionType::TRANSPORTITEM:
  452. {
  453. assert(allowNormalVictory == true); // not selectable in editor
  454. EventCondition cond(EventCondition::TRANSPORT);
  455. cond.objectType = reader->readArtifact8();
  456. cond.position = reader->readInt3();
  457. specialVictory.effect.toOtherMessage.appendTextID("core.genrltxt.293");
  458. specialVictory.onFulfill.appendTextID("core.genrltxt.292");
  459. specialVictory.trigger = EventExpression(cond);
  460. mapHeader->victoryMessage.appendTextID("core.vcdesc.11");
  461. break;
  462. }
  463. case EVictoryConditionType::HOTA_ELIMINATE_ALL_MONSTERS:
  464. {
  465. assert(appliesToAI == false); // not selectable in editor
  466. EventCondition cond(EventCondition::DESTROY);
  467. cond.objectType = MapObjectID(MapObjectID::MONSTER);
  468. specialVictory.effect.toOtherMessage.appendTextID("vcmi.map.victoryCondition.eliminateMonsters.toOthers");
  469. specialVictory.onFulfill.appendTextID("vcmi.map.victoryCondition.eliminateMonsters.toSelf");
  470. specialVictory.trigger = EventExpression(cond);
  471. mapHeader->victoryMessage.appendTextID("core.vcdesc.12");
  472. mapHeader->victoryIconIndex = 12;
  473. break;
  474. }
  475. case EVictoryConditionType::HOTA_SURVIVE_FOR_DAYS:
  476. {
  477. assert(appliesToAI == false); // not selectable in editor
  478. EventCondition cond(EventCondition::DAYS_PASSED);
  479. cond.value = reader->readUInt32();
  480. specialVictory.effect.toOtherMessage.appendTextID("vcmi.map.victoryCondition.daysPassed.toOthers");
  481. specialVictory.onFulfill.appendTextID("vcmi.map.victoryCondition.daysPassed.toSelf");
  482. specialVictory.trigger = EventExpression(cond);
  483. mapHeader->victoryMessage.appendTextID("core.vcdesc.13");
  484. mapHeader->victoryIconIndex = 13;
  485. break;
  486. }
  487. default:
  488. assert(0);
  489. }
  490. if(allowNormalVictory)
  491. {
  492. size_t playersOnMap = boost::range::count_if(
  493. mapHeader->players,
  494. [](const PlayerInfo & info)
  495. {
  496. return info.canAnyonePlay();
  497. }
  498. );
  499. if(playersOnMap == 1)
  500. {
  501. logGlobal->warn("Map %s: Only one player exists, but normal victory allowed!", mapName);
  502. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  503. }
  504. }
  505. // if condition is human-only turn it into following construction: AllOf(human, condition)
  506. if(!appliesToAI)
  507. {
  508. EventExpression::OperatorAll oper;
  509. EventCondition notAI(EventCondition::IS_HUMAN);
  510. notAI.value = 1;
  511. oper.expressions.emplace_back(notAI);
  512. oper.expressions.push_back(specialVictory.trigger.get());
  513. specialVictory.trigger = EventExpression(oper);
  514. }
  515. // if normal victory allowed - add one more quest
  516. if(allowNormalVictory)
  517. {
  518. mapHeader->victoryMessage.appendRawString(" / ");
  519. mapHeader->victoryMessage.appendTextID("core.vcdesc.0");
  520. mapHeader->triggeredEvents.push_back(standardVictory);
  521. }
  522. mapHeader->triggeredEvents.push_back(specialVictory);
  523. }
  524. // Read loss conditions
  525. auto lossCond = static_cast<ELossConditionType>(reader->readInt8Checked(-1, 2));
  526. if(lossCond == ELossConditionType::LOSSSTANDARD)
  527. {
  528. mapHeader->defeatIconIndex = 3;
  529. mapHeader->defeatMessage.appendTextID("core.lcdesc.0");
  530. }
  531. else
  532. {
  533. TriggeredEvent specialDefeat;
  534. specialDefeat.effect.type = EventEffect::DEFEAT;
  535. specialDefeat.effect.toOtherMessage.appendTextID("core.genrltxt.5");
  536. specialDefeat.identifier = "specialDefeat";
  537. specialDefeat.description.clear(); // TODO: display in quest window
  538. mapHeader->defeatIconIndex = static_cast<ui16>(lossCond);
  539. switch(lossCond)
  540. {
  541. case ELossConditionType::LOSSCASTLE:
  542. {
  543. EventExpression::OperatorNone noneOf;
  544. EventCondition cond(EventCondition::CONTROL);
  545. cond.objectType = Obj(Obj::TOWN);
  546. cond.position = reader->readInt3();
  547. noneOf.expressions.emplace_back(cond);
  548. specialDefeat.onFulfill.appendTextID("core.genrltxt.251");
  549. specialDefeat.trigger = EventExpression(noneOf);
  550. mapHeader->defeatMessage.appendTextID("core.lcdesc.1");
  551. break;
  552. }
  553. case ELossConditionType::LOSSHERO:
  554. {
  555. EventExpression::OperatorNone noneOf;
  556. EventCondition cond(EventCondition::CONTROL);
  557. cond.objectType = Obj(Obj::HERO);
  558. cond.position = reader->readInt3();
  559. noneOf.expressions.emplace_back(cond);
  560. specialDefeat.onFulfill.appendTextID("core.genrltxt.253");
  561. specialDefeat.trigger = EventExpression(noneOf);
  562. mapHeader->defeatMessage.appendTextID("core.lcdesc.2");
  563. break;
  564. }
  565. case ELossConditionType::TIMEEXPIRES:
  566. {
  567. EventCondition cond(EventCondition::DAYS_PASSED);
  568. cond.value = reader->readUInt16();
  569. specialDefeat.onFulfill.appendTextID("core.genrltxt.254");
  570. specialDefeat.trigger = EventExpression(cond);
  571. mapHeader->defeatMessage.appendTextID("core.lcdesc.3");
  572. break;
  573. }
  574. }
  575. // turn simple loss condition into complete one that can be evaluated later:
  576. // - any of :
  577. // - days without town: 7
  578. // - all of:
  579. // - is human
  580. // - (expression)
  581. EventExpression::OperatorAll allOf;
  582. EventCondition isHuman(EventCondition::IS_HUMAN);
  583. isHuman.value = 1;
  584. allOf.expressions.emplace_back(isHuman);
  585. allOf.expressions.push_back(specialDefeat.trigger.get());
  586. specialDefeat.trigger = EventExpression(allOf);
  587. mapHeader->triggeredEvents.push_back(specialDefeat);
  588. }
  589. mapHeader->triggeredEvents.push_back(standardDefeat);
  590. }
  591. void CMapLoaderH3M::readTeamInfo()
  592. {
  593. mapHeader->howManyTeams = reader->readUInt8();
  594. if(mapHeader->howManyTeams > 0)
  595. {
  596. // Teams
  597. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  598. mapHeader->players[i].team = TeamID(reader->readUInt8());
  599. }
  600. else
  601. {
  602. // No alliances
  603. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  604. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  605. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  606. }
  607. }
  608. void CMapLoaderH3M::readAllowedHeroes()
  609. {
  610. mapHeader->allowedHeroes = LIBRARY->heroh->getDefaultAllowed();
  611. if(features.levelHOTA0)
  612. reader->readBitmaskHeroesSized(mapHeader->allowedHeroes, false);
  613. else
  614. reader->readBitmaskHeroes(mapHeader->allowedHeroes, false);
  615. if(features.levelAB)
  616. {
  617. size_t placeholdersQty = reader->readUInt32();
  618. for (size_t i = 0; i < placeholdersQty; ++i)
  619. {
  620. auto heroID = reader->readHero();
  621. mapHeader->reservedCampaignHeroes.insert(heroID);
  622. }
  623. }
  624. }
  625. void CMapLoaderH3M::readDisposedHeroes()
  626. {
  627. // Reading disposed heroes (20 bytes)
  628. if(features.levelSOD)
  629. {
  630. size_t disp = reader->readUInt8();
  631. mapHeader->disposedHeroes.resize(disp);
  632. for(size_t g = 0; g < disp; ++g)
  633. {
  634. mapHeader->disposedHeroes[g].heroId = reader->readHero();
  635. mapHeader->disposedHeroes[g].portrait = reader->readHeroPortrait();
  636. mapHeader->disposedHeroes[g].name = readLocalizedString(TextIdentifier("header", "heroes", mapHeader->disposedHeroes[g].heroId.getNum()));
  637. reader->readBitmaskPlayers(mapHeader->disposedHeroes[g].players, false);
  638. }
  639. }
  640. }
  641. void CMapLoaderH3M::readMapOptions()
  642. {
  643. //omitting NULLS
  644. reader->skipZero(31);
  645. if(features.levelHOTA0)
  646. {
  647. bool allowSpecialMonths = reader->readBool();
  648. map->overrideGameSetting(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS, JsonNode(allowSpecialMonths));
  649. reader->skipZero(3);
  650. }
  651. if(features.levelHOTA1)
  652. {
  653. int32_t combinedArtifactsCount = reader->readInt32();
  654. int32_t combinedArtifactsBytes = (combinedArtifactsCount + 7) / 8;
  655. for (int i = 0; i < combinedArtifactsBytes; ++i)
  656. {
  657. uint8_t mask = reader->readUInt8();
  658. if (mask != 0)
  659. logGlobal->warn("Map '%s': Option to ban specific combined artifacts is not implemented!", mapName);
  660. }
  661. }
  662. if(features.levelHOTA3)
  663. {
  664. //TODO: HotA
  665. int32_t roundLimit = reader->readInt32();
  666. if(roundLimit != -1)
  667. logGlobal->warn("Map '%s': roundLimit of %d is not implemented!", mapName, roundLimit);
  668. }
  669. if(features.levelHOTA5)
  670. {
  671. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  672. {
  673. // unconfirmed, but only remainig option according to changelog
  674. bool heroRecruitmentBlocked = reader->readBool();
  675. if (heroRecruitmentBlocked)
  676. logGlobal->warn("Map '%s': option to ban hero recruitment for %s is not implemented!!", mapName, PlayerColor(i).toString());
  677. }
  678. }
  679. }
  680. void CMapLoaderH3M::readAllowedArtifacts()
  681. {
  682. map->allowedArtifact = LIBRARY->arth->getDefaultAllowed();
  683. if(features.levelAB)
  684. {
  685. if(features.levelHOTA0)
  686. reader->readBitmaskArtifactsSized(map->allowedArtifact, true);
  687. else
  688. reader->readBitmaskArtifacts(map->allowedArtifact, true);
  689. }
  690. // ban combo artifacts
  691. if(!features.levelSOD)
  692. {
  693. for(auto const & artifact : LIBRARY->arth->objects)
  694. if(artifact->isCombined())
  695. map->allowedArtifact.erase(artifact->getId());
  696. }
  697. if(!features.levelAB)
  698. {
  699. map->allowedArtifact.erase(ArtifactID::VIAL_OF_DRAGON_BLOOD);
  700. map->allowedArtifact.erase(ArtifactID::ARMAGEDDONS_BLADE);
  701. }
  702. // Messy, but needed
  703. for(TriggeredEvent & event : map->triggeredEvents)
  704. {
  705. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  706. {
  707. if(cond.condition == EventCondition::HAVE_ARTIFACT || cond.condition == EventCondition::TRANSPORT)
  708. {
  709. map->allowedArtifact.erase(cond.objectType.as<ArtifactID>());
  710. }
  711. return cond;
  712. };
  713. event.trigger = event.trigger.morph(patcher);
  714. }
  715. }
  716. void CMapLoaderH3M::readAllowedSpellsAbilities()
  717. {
  718. map->allowedSpells = LIBRARY->spellh->getDefaultAllowed();
  719. map->allowedAbilities = LIBRARY->skillh->getDefaultAllowed();
  720. if(features.levelSOD)
  721. {
  722. reader->readBitmaskSpells(map->allowedSpells, true);
  723. reader->readBitmaskSkills(map->allowedAbilities, true);
  724. }
  725. }
  726. void CMapLoaderH3M::readRumors()
  727. {
  728. size_t rumorsCount = reader->readUInt32();
  729. assert(rumorsCount < 1000); // sanity check
  730. for(size_t it = 0; it < rumorsCount; it++)
  731. {
  732. Rumor ourRumor;
  733. ourRumor.name = readBasicString();
  734. ourRumor.text.appendTextID(readLocalizedString(TextIdentifier("header", "rumor", it, "text")));
  735. map->rumors.push_back(ourRumor);
  736. }
  737. }
  738. void CMapLoaderH3M::readPredefinedHeroes()
  739. {
  740. if(!features.levelSOD)
  741. return;
  742. uint32_t heroesCount = features.heroesCount;
  743. if(features.levelHOTA0)
  744. heroesCount = reader->readUInt32();
  745. assert(heroesCount <= features.heroesCount);
  746. for(int heroID = 0; heroID < heroesCount; heroID++)
  747. {
  748. bool custom = reader->readBool();
  749. if(!custom)
  750. continue;
  751. auto hero = std::make_shared<CGHeroInstance>(map->cb);
  752. hero->ID = Obj::HERO;
  753. hero->subID = heroID;
  754. bool hasExp = reader->readBool();
  755. if(hasExp)
  756. {
  757. hero->exp = reader->readUInt32();
  758. }
  759. else
  760. {
  761. hero->exp = 0;
  762. }
  763. bool hasSecSkills = reader->readBool();
  764. if(hasSecSkills)
  765. {
  766. uint32_t howMany = reader->readUInt32();
  767. hero->secSkills.resize(howMany);
  768. for(int yy = 0; yy < howMany; ++yy)
  769. {
  770. hero->secSkills[yy].first = reader->readSkill();
  771. hero->secSkills[yy].second = reader->readInt8Checked(1,3);
  772. }
  773. }
  774. loadArtifactsOfHero(hero.get());
  775. bool hasCustomBio = reader->readBool();
  776. if(hasCustomBio)
  777. hero->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", heroID, "biography"));
  778. // 0xFF is default, 00 male, 01 female
  779. hero->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  780. assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
  781. bool hasCustomSpells = reader->readBool();
  782. if(hasCustomSpells)
  783. reader->readBitmaskSpells(hero->spells, false);
  784. bool hasCustomPrimSkills = reader->readBool();
  785. if(hasCustomPrimSkills)
  786. {
  787. for(int skillID = 0; skillID < GameConstants::PRIMARY_SKILLS; skillID++)
  788. {
  789. hero->pushPrimSkill(static_cast<PrimarySkill>(skillID), reader->readUInt8());
  790. }
  791. }
  792. map->addToHeroPool(hero);
  793. logGlobal->debug("Map '%s': Hero predefined in map: %s", mapName, hero->getHeroType()->getJsonKey());
  794. }
  795. if(features.levelHOTA5)
  796. {
  797. for(int heroID = 0; heroID < heroesCount; heroID++)
  798. {
  799. bool alwaysAddSkills = reader->readBool(); // prevent heroes from receiving additional random secondary skills at the start of the map if they are not of the first level
  800. bool cannotGainXP = reader->readBool();
  801. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  802. assert(level > 0);
  803. if (!alwaysAddSkills)
  804. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, heroID);
  805. if (cannotGainXP)
  806. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, heroID);
  807. if (level > 1)
  808. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, heroID, level);
  809. }
  810. }
  811. }
  812. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  813. {
  814. bool hasArtSet = reader->readBool();
  815. // True if artifact set is not default (hero has some artifacts)
  816. if(!hasArtSet)
  817. return;
  818. // Workaround - if hero has customized artifacts game should not attempt to add spellbook based on hero type
  819. hero->spells.insert(SpellID::SPELLBOOK_PRESET);
  820. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  821. {
  822. logGlobal->debug("Hero %d at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...", hero->getHeroTypeID().getNum(), hero->anchorPos().toString());
  823. hero->artifactsInBackpack.clear();
  824. while(!hero->artifactsWorn.empty())
  825. hero->removeArtifact(hero->artifactsWorn.begin()->first);
  826. }
  827. for(int i = 0; i < features.artifactSlotsCount; i++)
  828. loadArtifactToSlot(hero, i);
  829. // bag artifacts
  830. // number of artifacts in hero's bag
  831. size_t amount = reader->readUInt16();
  832. for(size_t i = 0; i < amount; ++i)
  833. {
  834. loadArtifactToSlot(hero, ArtifactPosition::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  835. }
  836. }
  837. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  838. {
  839. ArtifactID artifactID = reader->readArtifact();
  840. SpellID scrollSpell = SpellID::NONE;
  841. if (features.levelHOTA5)
  842. scrollSpell = reader->readSpell16();
  843. if(artifactID == ArtifactID::NONE)
  844. return false;
  845. const Artifact * art = artifactID.toEntity(LIBRARY);
  846. if(!art)
  847. {
  848. logGlobal->warn("Map '%s': Invalid artifact in hero's backpack, ignoring...", mapName);
  849. return false;
  850. }
  851. if(art->isBig() && slot >= ArtifactPosition::BACKPACK_START)
  852. {
  853. logGlobal->warn("Map '%s': A big artifact (war machine) in hero's backpack, ignoring...", mapName);
  854. return false;
  855. }
  856. // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
  857. // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
  858. // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
  859. if(ArtifactID(artifactID).toArtifact()->canBePutAt(hero, ArtifactPosition(slot)))
  860. {
  861. auto * artifact = map->createArtifact(artifactID, scrollSpell);
  862. map->putArtifactInstance(*hero, artifact->getId(), slot);
  863. }
  864. else
  865. {
  866. logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, ArtifactID(artifactID).toArtifact()->getNameTranslated(), slot);
  867. return false;
  868. }
  869. return true;
  870. }
  871. void CMapLoaderH3M::readTerrain()
  872. {
  873. map->initTerrain();
  874. // Read terrain
  875. int3 pos;
  876. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  877. {
  878. //OH3 format is [z][y][x]
  879. for(pos.y = 0; pos.y < map->height; pos.y++)
  880. {
  881. for(pos.x = 0; pos.x < map->width; pos.x++)
  882. {
  883. auto & tile = map->getTile(pos);
  884. tile.terrainType = reader->readTerrain();
  885. tile.terView = reader->readUInt8();
  886. tile.riverType = reader->readRiver();
  887. tile.riverDir = reader->readUInt8();
  888. tile.roadType = reader->readRoad();
  889. tile.roadDir = reader->readUInt8();
  890. tile.extTileFlags = reader->readUInt8();
  891. }
  892. }
  893. }
  894. map->calculateWaterContent();
  895. }
  896. void CMapLoaderH3M::readObjectTemplates()
  897. {
  898. uint32_t defAmount = reader->readUInt32();
  899. originalTemplates.reserve(defAmount);
  900. remappedTemplates.reserve(defAmount);
  901. // Read custom defs
  902. for(int defID = 0; defID < defAmount; ++defID)
  903. {
  904. auto tmpl = reader->readObjectTemplate();
  905. originalTemplates.push_back(tmpl);
  906. auto remapped = std::make_shared<ObjectTemplate>(*tmpl);
  907. reader->remapTemplate(*remapped);
  908. remappedTemplates.push_back(remapped);
  909. if (!CResourceHandler::get()->existsResource(remapped->animationFile.addPrefix("SPRITES/")))
  910. logMod->warn("Template animation %s of type (%d %d) is missing!", remapped->animationFile.getOriginalName(), remapped->id, remapped->subid );
  911. }
  912. }
  913. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readEvent(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  914. {
  915. auto object = std::make_shared<CGEvent>(map->cb);
  916. readBoxContent(object.get(), mapPosition, idToBeGiven);
  917. reader->readBitmaskPlayers(object->availableFor, false);
  918. object->computerActivate = reader->readBool();
  919. object->removeAfterVisit = reader->readBool();
  920. reader->skipZero(4);
  921. if(features.levelHOTA3)
  922. object->humanActivate = reader->readBool();
  923. else
  924. object->humanActivate = true;
  925. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  926. return object;
  927. }
  928. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readPandora(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  929. {
  930. auto object = std::make_shared<CGPandoraBox>(map->cb);
  931. readBoxContent(object.get(), mapPosition, idToBeGiven);
  932. if(features.levelHOTA5)
  933. reader->skipZero(1); // Unknown value, always 0 so far
  934. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  935. return object;
  936. }
  937. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  938. {
  939. readMessageAndGuards(object->message, object, mapPosition, idToBeGiven);
  940. Rewardable::VisitInfo vinfo;
  941. auto & reward = vinfo.reward;
  942. reward.heroExperience = reader->readUInt32();
  943. reward.manaDiff = reader->readInt32();
  944. if(auto val = reader->readInt8Checked(-3, 3))
  945. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven));
  946. if(auto val = reader->readInt8Checked(-3, 3))
  947. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven));
  948. reader->readResources(reward.resources);
  949. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  950. reward.primary.at(x) = reader->readUInt8();
  951. size_t gabn = reader->readUInt8(); //number of gained abilities
  952. for(size_t oo = 0; oo < gabn; ++oo)
  953. {
  954. auto rId = reader->readSkill();
  955. auto rVal = reader->readInt8Checked(1,3);
  956. reward.secondary[rId] = rVal;
  957. }
  958. size_t gart = reader->readUInt8(); //number of gained artifacts
  959. for(size_t oo = 0; oo < gart; ++oo)
  960. {
  961. ArtifactID grantedArtifact = reader->readArtifact();
  962. if (features.levelHOTA5)
  963. {
  964. SpellID scrollSpell = reader->readSpell16();
  965. if (grantedArtifact == ArtifactID::SPELL_SCROLL)
  966. reward.grantedScrolls.push_back(scrollSpell);
  967. }
  968. else
  969. reward.grantedArtifacts.push_back(grantedArtifact);
  970. }
  971. size_t gspel = reader->readUInt8(); //number of gained spells
  972. for(size_t oo = 0; oo < gspel; ++oo)
  973. reward.spells.push_back(reader->readSpell());
  974. size_t gcre = reader->readUInt8(); //number of gained creatures
  975. for(size_t oo = 0; oo < gcre; ++oo)
  976. {
  977. auto rId = reader->readCreature();
  978. auto rVal = reader->readUInt16();
  979. reward.creatures.emplace_back(rId, rVal);
  980. }
  981. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  982. object->configuration.info.push_back(vinfo);
  983. reader->skipZero(8);
  984. }
  985. void CMapLoaderH3M::readBoxHotaContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  986. {
  987. if(features.levelHOTA5)
  988. {
  989. int32_t movementMode = reader->readInt32(); // Give, Take, Nullify, Set, Replenish
  990. int32_t movementAmount = reader->readInt32();
  991. assert(movementMode >= 0 && movementMode <= 4);
  992. if (movementMode != 0 || movementAmount != 0)
  993. logGlobal->warn("Map '%s': Event/Pandora %s option to modify (mode %d) movement points by %d is not implemented!", mapName, mapPosition.toString(), movementMode, movementAmount);
  994. }
  995. if(features.levelHOTA6)
  996. {
  997. int32_t allowedDifficultiesMask = reader->readInt32();
  998. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  999. if (allowedDifficultiesMask != 31)
  1000. logGlobal->warn("Map '%s': Event/Pandora %s availability by difficulty (mode %d) is not implemented!", mapName, mapPosition.toString(), allowedDifficultiesMask);
  1001. }
  1002. }
  1003. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1004. {
  1005. auto object = std::make_shared<CGCreature>(map->cb);
  1006. object->id = objectInstanceID;
  1007. if(features.levelAB)
  1008. {
  1009. object->identifier = reader->readUInt32();
  1010. questIdentifierToId[object->identifier] = objectInstanceID;
  1011. }
  1012. auto hlp = std::make_unique<CStackInstance>(map->cb);
  1013. hlp->setCount(reader->readUInt16());
  1014. //type will be set during initialization
  1015. object->putStack(SlotID(0), std::move(hlp));
  1016. //TODO: 0-4 is h3 range. 5 is hota extension for exact aggression?
  1017. object->character = reader->readInt8Checked(0, 5);
  1018. bool hasMessage = reader->readBool();
  1019. if(hasMessage)
  1020. {
  1021. object->message.appendTextID(readLocalizedString(TextIdentifier("monster", mapPosition.x, mapPosition.y, mapPosition.z, "message")));
  1022. reader->readResources(object->resources);
  1023. object->gainedArtifact = reader->readArtifact();
  1024. }
  1025. object->neverFlees = reader->readBool();
  1026. object->notGrowingTeam = reader->readBool();
  1027. reader->skipZero(2);
  1028. if(features.levelHOTA3)
  1029. {
  1030. //TODO: HotA
  1031. int32_t aggressionExact = reader->readInt32(); // -1 = default, 1-10 = possible values range
  1032. bool joinOnlyForMoney = reader->readBool(); // if true, monsters will only join for money
  1033. int32_t joinPercent = reader->readInt32(); // 100 = default, percent of monsters that will join on successful aggression check
  1034. int32_t upgradedStack = reader->readInt32(); // Presence of upgraded stack, -1 = random, 0 = never, 1 = always
  1035. int32_t stacksCount = reader->readInt32(); // TODO: check possible values. How many creature stacks will be present on battlefield, -1 = default
  1036. if(aggressionExact != -1 || joinOnlyForMoney || joinPercent != 100 || upgradedStack != -1 || stacksCount != -1)
  1037. logGlobal->warn(
  1038. "Map '%s': Wandering monsters %s settings %d %d %d %d %d are not implemented!",
  1039. mapName,
  1040. mapPosition.toString(),
  1041. aggressionExact,
  1042. int(joinOnlyForMoney),
  1043. joinPercent,
  1044. upgradedStack,
  1045. stacksCount
  1046. );
  1047. }
  1048. if (features.levelHOTA5)
  1049. {
  1050. bool sizeByValue = reader->readBool();//FIXME: double-check this flag effect
  1051. int32_t targetValue = reader->readInt32();
  1052. if (sizeByValue || targetValue)
  1053. logGlobal->warn( "Map '%s': Wandering monsters %s option to set unit size to %d (%d) AI value is not implemented!", mapName, mapPosition.toString(), targetValue, sizeByValue);
  1054. }
  1055. return object;
  1056. }
  1057. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSign(const int3 & mapPosition)
  1058. {
  1059. auto object = std::make_shared<CGSignBottle>(map->cb);
  1060. object->message.appendTextID(readLocalizedString(TextIdentifier("sign", mapPosition.x, mapPosition.y, mapPosition.z, "message")));
  1061. reader->skipZero(4);
  1062. return object;
  1063. }
  1064. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readWitchHut(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1065. {
  1066. auto object = readGeneric(position, objectTemplate);
  1067. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1068. // AB and later maps have allowed abilities defined in H3M
  1069. if(features.levelAB)
  1070. {
  1071. std::set<SecondarySkill> allowedAbilities;
  1072. reader->readBitmaskSkills(allowedAbilities, false);
  1073. if (rewardable)
  1074. {
  1075. if(allowedAbilities.size() != 1)
  1076. {
  1077. auto defaultAllowed = LIBRARY->skillh->getDefaultAllowed();
  1078. for(int skillID = features.skillsCount; skillID < defaultAllowed.size(); ++skillID)
  1079. if(defaultAllowed.count(skillID))
  1080. allowedAbilities.insert(SecondarySkill(skillID));
  1081. }
  1082. JsonNode variable;
  1083. if (allowedAbilities.size() == 1)
  1084. {
  1085. variable.String() = LIBRARY->skills()->getById(*allowedAbilities.begin())->getJsonKey();
  1086. }
  1087. else
  1088. {
  1089. JsonVector anyOfList;
  1090. for (auto const & skill : allowedAbilities)
  1091. {
  1092. JsonNode entry;
  1093. entry.String() = LIBRARY->skills()->getById(skill)->getJsonKey();
  1094. anyOfList.push_back(entry);
  1095. }
  1096. variable["anyOf"].Vector() = anyOfList;
  1097. }
  1098. variable.setModScope(ModScope::scopeGame()); // list may include skills from all mods
  1099. rewardable->configuration.presetVariable("secondarySkill", "gainedSkill", variable);
  1100. }
  1101. else
  1102. {
  1103. logGlobal->warn("Failed to set allowed secondary skills to a Witch Hut! Object is not rewardable!");
  1104. }
  1105. }
  1106. return object;
  1107. }
  1108. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readScholar(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1109. {
  1110. enum class ScholarBonusType : int8_t {
  1111. RANDOM = -1,
  1112. PRIM_SKILL = 0,
  1113. SECONDARY_SKILL = 1,
  1114. SPELL = 2,
  1115. };
  1116. auto object = readGeneric(position, objectTemplate);
  1117. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1118. uint8_t bonusTypeRaw = reader->readInt8Checked(-1, 2);
  1119. auto bonusType = static_cast<ScholarBonusType>(bonusTypeRaw);
  1120. auto bonusID = reader->readUInt8();
  1121. if (rewardable)
  1122. {
  1123. switch (bonusType)
  1124. {
  1125. case ScholarBonusType::PRIM_SKILL:
  1126. {
  1127. JsonNode variable;
  1128. JsonNode dice;
  1129. variable.String() = NPrimarySkill::names[bonusID];
  1130. variable.setModScope(ModScope::scopeGame());
  1131. dice.Integer() = 80;
  1132. rewardable->configuration.presetVariable("primarySkill", "gainedStat", variable);
  1133. rewardable->configuration.presetVariable("dice", "0", dice);
  1134. break;
  1135. }
  1136. case ScholarBonusType::SECONDARY_SKILL:
  1137. {
  1138. JsonNode variable;
  1139. JsonNode dice;
  1140. variable.String() = LIBRARY->skills()->getByIndex(bonusID)->getJsonKey();
  1141. variable.setModScope(ModScope::scopeGame());
  1142. dice.Integer() = 50;
  1143. rewardable->configuration.presetVariable("secondarySkill", "gainedSkill", variable);
  1144. rewardable->configuration.presetVariable("dice", "0", dice);
  1145. break;
  1146. }
  1147. case ScholarBonusType::SPELL:
  1148. {
  1149. JsonNode variable;
  1150. JsonNode dice;
  1151. variable.String() = LIBRARY->spells()->getByIndex(bonusID)->getJsonKey();
  1152. variable.setModScope(ModScope::scopeGame());
  1153. dice.Integer() = 20;
  1154. rewardable->configuration.presetVariable("spell", "gainedSpell", variable);
  1155. rewardable->configuration.presetVariable("dice", "0", dice);
  1156. break;
  1157. }
  1158. case ScholarBonusType::RANDOM:
  1159. break;// No-op
  1160. default:
  1161. logGlobal->warn("Map '%s': Invalid Scholar settings! Ignoring...", mapName);
  1162. }
  1163. }
  1164. else
  1165. {
  1166. logGlobal->warn("Failed to set reward parameters for a Scholar! Object is not rewardable!");
  1167. }
  1168. reader->skipZero(6);
  1169. return object;
  1170. }
  1171. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGarrison(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  1172. {
  1173. auto object = std::make_shared<CGGarrison>(map->cb);
  1174. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1175. readCreatureSet(object.get(), idToBeGiven);
  1176. if(features.levelAB)
  1177. object->removableUnits = reader->readBool();
  1178. else
  1179. object->removableUnits = true;
  1180. reader->skipZero(8);
  1181. return object;
  1182. }
  1183. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1184. {
  1185. ArtifactID artID = ArtifactID::NONE; //random, set later
  1186. auto object = std::make_shared<CGArtifact>(map->cb);
  1187. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1188. //specific artifact
  1189. if(objectTemplate->id == Obj::ARTIFACT)
  1190. artID = ArtifactID(objectTemplate->subid);
  1191. if(features.levelHOTA5)
  1192. {
  1193. uint32_t pickupMode = reader->readUInt32();
  1194. uint8_t pickupFlags = reader->readUInt8();
  1195. assert(pickupMode == 0 || pickupMode == 1 || pickupMode == 2); // DISABLED, RANDOM, CUSTOM
  1196. if (pickupMode != 0)
  1197. logGlobal->warn("Map '%s': Artifact %s: not implemented pickup mode %d (flags: %d)", mapName, mapPosition.toString(), pickupMode, static_cast<int>(pickupFlags));
  1198. }
  1199. if (artID.hasValue())
  1200. object->setArtifactInstance(map->createArtifact(artID, SpellID::NONE));
  1201. // else - random, will be initialized later
  1202. return object;
  1203. }
  1204. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readScroll(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1205. {
  1206. auto object = std::make_shared<CGArtifact>(map->cb);
  1207. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1208. SpellID spellID = reader->readSpell32();
  1209. object->setArtifactInstance(map->createArtifact(ArtifactID::SPELL_SCROLL, spellID.getNum()));
  1210. return object;
  1211. }
  1212. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  1213. {
  1214. auto object = std::make_shared<CGResource>(map->cb);
  1215. readMessageAndGuards(object->message, object.get(), mapPosition, idToBeGiven);
  1216. object->amount = reader->readUInt32();
  1217. if (objectTemplate->id != Obj::RANDOM_RESOURCE)
  1218. {
  1219. const auto & baseHandler = LIBRARY->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid);
  1220. const auto & ourHandler = std::dynamic_pointer_cast<ResourceInstanceConstructor>(baseHandler);
  1221. object->amount *= ourHandler->getAmountMultiplier();
  1222. }
  1223. reader->skipZero(4);
  1224. return object;
  1225. }
  1226. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMine(const int3 & mapPosition)
  1227. {
  1228. auto object = std::make_shared<CGMine>(map->cb);
  1229. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1230. return object;
  1231. }
  1232. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readAbandonedMine(const int3 & mapPosition)
  1233. {
  1234. auto object = std::make_shared<CGMine>(map->cb);
  1235. object->setOwner(PlayerColor::NEUTRAL);
  1236. reader->readBitmaskResources(object->abandonedMineResources, false);
  1237. if(features.levelHOTA5)
  1238. {
  1239. bool customGuards = reader->readBool();
  1240. CreatureID guardsUnit = reader->readCreature32();
  1241. int32_t guardsMin = reader->readInt32();
  1242. int32_t guardsMax = reader->readInt32();
  1243. if (customGuards)
  1244. {
  1245. assert(guardsMin <= guardsMax);
  1246. assert(guardsUnit.hasValue());
  1247. logGlobal->warn("Map '%s': Abandoned Mine %s: not implemented guards of %d-%d %s", mapName, mapPosition.toString(), guardsMin, guardsMax, guardsUnit.toEntity(LIBRARY)->getJsonKey());
  1248. }
  1249. }
  1250. return object;
  1251. }
  1252. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwelling(const int3 & position)
  1253. {
  1254. auto object = std::make_shared<CGDwelling>(map->cb);
  1255. setOwnerAndValidate(position, object.get(), reader->readPlayer32());
  1256. return object;
  1257. }
  1258. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1259. {
  1260. auto object = std::make_shared<CGDwelling>(map->cb);
  1261. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1262. object->randomizationInfo = CGDwellingRandomizationInfo();
  1263. bool hasFactionInfo = objectTemplate->id == Obj::RANDOM_DWELLING || objectTemplate->id == Obj::RANDOM_DWELLING_LVL;
  1264. bool hasLevelInfo = objectTemplate->id == Obj::RANDOM_DWELLING || objectTemplate->id == Obj::RANDOM_DWELLING_FACTION;
  1265. if (hasFactionInfo)
  1266. {
  1267. object->randomizationInfo->identifier = reader->readUInt32();
  1268. if(object->randomizationInfo->identifier == 0)
  1269. reader->readBitmaskFactions(object->randomizationInfo->allowedFactions, false);
  1270. }
  1271. else
  1272. object->randomizationInfo->allowedFactions.insert(FactionID(objectTemplate->subid));
  1273. if(hasLevelInfo)
  1274. {
  1275. object->randomizationInfo->minLevel = std::max(reader->readUInt8(), static_cast<ui8>(0)) + 1;
  1276. object->randomizationInfo->maxLevel = std::min(reader->readUInt8(), static_cast<ui8>(6)) + 1;
  1277. }
  1278. else
  1279. {
  1280. object->randomizationInfo->minLevel = objectTemplate->subid;
  1281. object->randomizationInfo->maxLevel = objectTemplate->subid;
  1282. }
  1283. return object;
  1284. }
  1285. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShrine(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1286. {
  1287. auto object = readGeneric(position, objectTemplate);
  1288. auto rewardable = std::dynamic_pointer_cast<CRewardableObject>(object);
  1289. SpellID spell = reader->readSpell32();
  1290. if (rewardable)
  1291. {
  1292. if(spell != SpellID::NONE)
  1293. {
  1294. JsonNode variable;
  1295. variable.String() = LIBRARY->spells()->getById(spell)->getJsonKey();
  1296. variable.setModScope(ModScope::scopeGame()); // list may include spells from all mods
  1297. rewardable->configuration.presetVariable("spell", "gainedSpell", variable);
  1298. }
  1299. }
  1300. else
  1301. {
  1302. logGlobal->warn("Failed to set selected spell to a Shrine!. Object is not rewardable!");
  1303. }
  1304. return object;
  1305. }
  1306. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1307. {
  1308. auto object = std::make_shared<CGHeroPlaceholder>(map->cb);
  1309. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer());
  1310. HeroTypeID htid = reader->readHero(); //hero type id
  1311. if(htid.getNum() == -1)
  1312. {
  1313. object->powerRank = reader->readUInt8();
  1314. logGlobal->debug("Map '%s': Hero placeholder: by power at %s, owned by %s", mapName, mapPosition.toString(), object->getOwner().toString());
  1315. }
  1316. else
  1317. {
  1318. object->heroType = htid;
  1319. logGlobal->debug("Map '%s': Hero placeholder: %s at %s, owned by %s", mapName, LIBRARY->heroh->getById(htid)->getJsonKey(), mapPosition.toString(), object->getOwner().toString());
  1320. }
  1321. if(features.levelHOTA5)
  1322. {
  1323. bool customizedStatingUnits = reader->readBool();
  1324. if (customizedStatingUnits)
  1325. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to customize starting units", mapName);
  1326. for (int i = 0; i < 7; ++i)
  1327. {
  1328. int32_t unitAmount = reader->readInt32();
  1329. CreatureID unitToGive = reader->readCreature32();
  1330. if (unitToGive.hasValue())
  1331. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to give %d units of type %d on map start to slot %d is not implemented!", mapName, unitAmount, unitToGive.toEntity(LIBRARY)->getJsonKey(), i);
  1332. }
  1333. int32_t artifactsToGive = reader->readInt32();
  1334. assert(artifactsToGive >= 0);
  1335. assert(artifactsToGive < 100); // technically legal, but not possible in h3
  1336. for (int i = 0; i < artifactsToGive; ++i)
  1337. {
  1338. // NOTE: this might actually be 2 bytes for artifact ID + 2 bytes for spell scroll
  1339. ArtifactID startingArtifact = reader->readArtifact32();
  1340. logGlobal->warn("Map '%s': Hero placeholder: not implemented option to give hero artifact %d", mapName, startingArtifact.toEntity(LIBRARY)->getJsonKey());
  1341. }
  1342. }
  1343. return object;
  1344. }
  1345. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGrail(const int3 & mapPosition)
  1346. {
  1347. map->grailPos = mapPosition;
  1348. map->grailRadius = reader->readInt32();
  1349. return nullptr;
  1350. }
  1351. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHotaBattleLocation(const int3 & mapPosition)
  1352. {
  1353. // Battle location for arena mode in HotA
  1354. logGlobal->warn("Map '%s': Arena mode is not supported!", mapName);
  1355. return nullptr;
  1356. }
  1357. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGeneric(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1358. {
  1359. if(LIBRARY->objtypeh->knownSubObjects(objectTemplate->id).count(objectTemplate->subid))
  1360. return LIBRARY->objtypeh->getHandlerFor(objectTemplate->id, objectTemplate->subid)->create(map->cb, objectTemplate);
  1361. logGlobal->warn("Map '%s': Unrecognized object %d:%d ('%s') at %s found!", mapName, objectTemplate->id.toEnum(), objectTemplate->subid, objectTemplate->animationFile.getOriginalName(), mapPosition.toString());
  1362. return std::make_shared<CGObjectInstance>(map->cb);
  1363. }
  1364. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1365. {
  1366. auto guard = std::make_shared<CGQuestGuard>(map->cb);
  1367. readQuest(guard.get(), mapPosition);
  1368. return guard;
  1369. }
  1370. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShipyard(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1371. {
  1372. auto object = readGeneric(mapPosition, objectTemplate);
  1373. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1374. return object;
  1375. }
  1376. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readLighthouse(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1377. {
  1378. auto object = readGeneric(mapPosition, objectTemplate);
  1379. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1380. return object;
  1381. }
  1382. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readBank(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1383. {
  1384. if(features.levelHOTA3)
  1385. {
  1386. //TODO: HotA
  1387. // index of guards preset. -1 = random, 0-4 = index of possible guards settings
  1388. int32_t guardsPresetIndex = reader->readInt32();
  1389. // presence of upgraded stack: -1 = random, 0 = never, 1 = always
  1390. int8_t upgradedStackPresence = reader->readInt8Checked(-1, 1);
  1391. assert(vstd::iswithin(guardsPresetIndex, -1, 4));
  1392. assert(vstd::iswithin(upgradedStackPresence, -1, 1));
  1393. // list of possible artifacts in reward
  1394. // - if list is empty, artifacts are either not present in reward or random
  1395. // - if non-empty, then list always have same number of elements as number of artifacts in bank
  1396. // - ArtifactID::NONE indictates random artifact, other values indicate artifact that should be used as reward
  1397. std::vector<ArtifactID> artifacts;
  1398. int artNumber = reader->readUInt32();
  1399. for(int yy = 0; yy < artNumber; ++yy)
  1400. {
  1401. artifacts.push_back(reader->readArtifact32());
  1402. }
  1403. if(guardsPresetIndex != -1 || upgradedStackPresence != -1 || !artifacts.empty())
  1404. logGlobal->warn(
  1405. "Map '%s': creature bank at %s settings %d %d %d are not implemented!",
  1406. mapName,
  1407. mapPosition.toString(),
  1408. guardsPresetIndex,
  1409. int(upgradedStackPresence),
  1410. artifacts.size()
  1411. );
  1412. }
  1413. return readGeneric(mapPosition, objectTemplate);
  1414. }
  1415. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readRewardWithArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1416. {
  1417. if(features.levelHOTA5)
  1418. {
  1419. // TREASURE_CHEST - rewards index, if 3 - then 2nd value is artifact
  1420. // CORPSE - rewards index, if 1 - then 2nd value is artifact
  1421. // SHIPWRECK_SURVIVOR - if content = 0 then 2nd value is granted artifact
  1422. // SEA_CHEST - rewards index, if 2 - then 2nd value is artifact
  1423. // FLOTSAM - rewards index (0-3) + -1
  1424. // TREE_OF_KNOWLEDGE - rewards index (0-2) + -1
  1425. // PYRAMID - if content = 0 then 2nd value is granted spell
  1426. // WARRIORS_TOMB - if content = 0 then 2nd value is granted artifact
  1427. // HOTA_JETSAM - rewards index (0-3) + -1
  1428. // HOTA_VIAL_OF_MANA - rewards index (0-3) + -1
  1429. int32_t content = reader->readInt32();
  1430. ArtifactID artifact;
  1431. if (content != -1)
  1432. {
  1433. artifact = reader->readArtifact32(); // NOTE: might be 2 byte artifact + 2 bytes scroll spell
  1434. logGlobal->warn("Map '%s': Object (%d) %s settings %d %d are not implemented!", mapName, objectTemplate->id, mapPosition.toString(), content, artifact);
  1435. }
  1436. else
  1437. reader->skipUnused(4); // garbage data, usually -1, but sometimes uninitialized
  1438. }
  1439. return readGeneric(mapPosition, objectTemplate);
  1440. }
  1441. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readBlackMarket(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1442. {
  1443. if(features.levelHOTA5)
  1444. {
  1445. for (int i = 0; i < 7; ++i)
  1446. {
  1447. ArtifactID artifact = reader->readArtifact();
  1448. SpellID spellID = reader->readSpell16();
  1449. if (artifact.hasValue())
  1450. {
  1451. if (artifact != ArtifactID::SPELL_SCROLL)
  1452. logGlobal->warn("Map '%s': Black Market at %s: option to sell artifact %s is not implemented", mapName, mapPosition.toString(), artifact.toEntity(LIBRARY)->getJsonKey());
  1453. else
  1454. logGlobal->warn("Map '%s': Black Market at %s: option to sell scroll %s is not implemented", mapName, mapPosition.toString(), spellID.toEntity(LIBRARY)->getJsonKey());
  1455. }
  1456. }
  1457. }
  1458. return readGeneric(mapPosition, objectTemplate);
  1459. }
  1460. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readUniversity(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1461. {
  1462. if(features.levelHOTA5)
  1463. {
  1464. int32_t customized = reader->readInt32();
  1465. std::set<SecondarySkill> allowedSkills;
  1466. reader->readBitmaskSkills(allowedSkills, false);
  1467. // NOTE: check how this interacts with hota Seafaring Academy that is guaranteed to give Navigation
  1468. assert(customized == -1 || customized == 0);
  1469. if (customized != -1)
  1470. logGlobal->warn("Map '%s': University at %s: option to give specific skills out of %d is not implemented", mapName, mapPosition.toString(), allowedSkills.size());
  1471. }
  1472. return readGeneric(mapPosition, objectTemplate);
  1473. }
  1474. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readRewardWithArtifactAndResources(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1475. {
  1476. if(features.levelHOTA5)
  1477. {
  1478. // Sea Barrel / 0 -> aID = -1, aA = resource amount, rA = resource type, aB = garbage, rB = 0
  1479. // Sea Barrel / 1 -> aID = -1, aA = 1, rA = 1, aB = garbage, rB = 0
  1480. // Ancient Lamp / 0 -> aID = -1, aA = amount to recruit, rA = 0, aB = 1, rB = 0
  1481. // Grave / 0 -> aID = artifact to give, aA = resource amount, rA = resource type, aB = 1, rB = garbage
  1482. // CAMPFIRE 12 / 0 -> aID = -1, aA = gold amount, rA = gold type, aB = resource amount, rB = resource type
  1483. // WAGON 105 / 0 -> aID = -1 or artifact, aA = resource amount, rA = resource type, aB = 1, rB = garbage?
  1484. // WAGON 105 / 1 -> empty / garbage?
  1485. // LEAN_TO / 39 / 0 -> aID = -1, aA = resource amount, rA = resource type, aB = garbage, rB = 0
  1486. int32_t content = reader->readInt32();
  1487. int32_t artifact = reader->readInt32();
  1488. int32_t amountA = reader->readInt32();
  1489. int8_t resourceA = reader->readInt8();
  1490. int32_t amountB = reader->readInt32();
  1491. int8_t resourceB = reader->readInt8();
  1492. if (content != -1)
  1493. logGlobal->warn("Map '%s': Object (%d) %s settings %d %d %d %d %d %d are not implemented!", mapName, objectTemplate->id, mapPosition.toString(), content, artifact, amountA, static_cast<int>(resourceA), amountB, static_cast<int>(resourceB));
  1494. }
  1495. return readGeneric(mapPosition, objectTemplate);
  1496. }
  1497. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readObject(MapObjectID id, MapObjectSubID subid, std::shared_ptr<const ObjectTemplate> objectTemplate, const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1498. {
  1499. switch(id.toEnum())
  1500. {
  1501. case Obj::EVENT:
  1502. return readEvent(mapPosition, objectInstanceID);
  1503. case Obj::HERO:
  1504. case Obj::RANDOM_HERO:
  1505. case Obj::PRISON:
  1506. return readHero(mapPosition, objectInstanceID);
  1507. case Obj::MONSTER:
  1508. case Obj::RANDOM_MONSTER:
  1509. case Obj::RANDOM_MONSTER_L1:
  1510. case Obj::RANDOM_MONSTER_L2:
  1511. case Obj::RANDOM_MONSTER_L3:
  1512. case Obj::RANDOM_MONSTER_L4:
  1513. case Obj::RANDOM_MONSTER_L5:
  1514. case Obj::RANDOM_MONSTER_L6:
  1515. case Obj::RANDOM_MONSTER_L7:
  1516. return readMonster(mapPosition, objectInstanceID);
  1517. case Obj::OCEAN_BOTTLE:
  1518. case Obj::SIGN:
  1519. return readSign(mapPosition);
  1520. case Obj::SEER_HUT:
  1521. return readSeerHut(mapPosition, objectInstanceID);
  1522. case Obj::WITCH_HUT:
  1523. return readWitchHut(mapPosition, objectTemplate);
  1524. case Obj::SCHOLAR:
  1525. return readScholar(mapPosition, objectTemplate);
  1526. case Obj::GARRISON:
  1527. case Obj::GARRISON2:
  1528. return readGarrison(mapPosition, objectInstanceID);
  1529. case Obj::ARTIFACT:
  1530. case Obj::RANDOM_ART:
  1531. case Obj::RANDOM_TREASURE_ART:
  1532. case Obj::RANDOM_MINOR_ART:
  1533. case Obj::RANDOM_MAJOR_ART:
  1534. case Obj::RANDOM_RELIC_ART:
  1535. return readArtifact(mapPosition, objectTemplate, objectInstanceID);
  1536. case Obj::SPELL_SCROLL:
  1537. return readScroll(mapPosition, objectTemplate, objectInstanceID);
  1538. case Obj::RANDOM_RESOURCE:
  1539. case Obj::RESOURCE:
  1540. return readResource(mapPosition, objectTemplate, objectInstanceID);
  1541. case Obj::RANDOM_TOWN:
  1542. case Obj::TOWN:
  1543. return readTown(mapPosition, objectTemplate, objectInstanceID);
  1544. case Obj::MINE:
  1545. case Obj::ABANDONED_MINE:
  1546. if (subid < 7)
  1547. return readMine(mapPosition);
  1548. else
  1549. return readAbandonedMine(mapPosition);
  1550. case Obj::CREATURE_GENERATOR1:
  1551. case Obj::CREATURE_GENERATOR2:
  1552. case Obj::CREATURE_GENERATOR3:
  1553. case Obj::CREATURE_GENERATOR4:
  1554. return readDwelling(mapPosition);
  1555. case Obj::SHRINE_OF_MAGIC_INCANTATION:
  1556. case Obj::SHRINE_OF_MAGIC_GESTURE:
  1557. case Obj::SHRINE_OF_MAGIC_THOUGHT:
  1558. return readShrine(mapPosition, objectTemplate);
  1559. case Obj::PANDORAS_BOX:
  1560. return readPandora(mapPosition, objectInstanceID);
  1561. case Obj::GRAIL:
  1562. if (subid < 1000)
  1563. return readGrail(mapPosition);
  1564. else
  1565. return readHotaBattleLocation(mapPosition);
  1566. case Obj::RANDOM_DWELLING:
  1567. case Obj::RANDOM_DWELLING_LVL:
  1568. case Obj::RANDOM_DWELLING_FACTION:
  1569. return readDwellingRandom(mapPosition, objectTemplate);
  1570. case Obj::QUEST_GUARD:
  1571. return readQuestGuard(mapPosition);
  1572. case Obj::SHIPYARD:
  1573. return readShipyard(mapPosition, objectTemplate);
  1574. case Obj::HERO_PLACEHOLDER:
  1575. return readHeroPlaceholder(mapPosition);
  1576. case Obj::LIGHTHOUSE:
  1577. return readLighthouse(mapPosition, objectTemplate);
  1578. case Obj::CREATURE_BANK:
  1579. case Obj::DERELICT_SHIP:
  1580. case Obj::DRAGON_UTOPIA:
  1581. case Obj::CRYPT:
  1582. case Obj::SHIPWRECK:
  1583. return readBank(mapPosition, objectTemplate);
  1584. case Obj::TREASURE_CHEST:
  1585. case Obj::CORPSE:
  1586. case Obj::SHIPWRECK_SURVIVOR:
  1587. case Obj::SEA_CHEST:
  1588. case Obj::FLOTSAM:
  1589. case Obj::TREE_OF_KNOWLEDGE:
  1590. case Obj::PYRAMID:
  1591. case Obj::WARRIORS_TOMB:
  1592. return readRewardWithArtifact(mapPosition, objectTemplate);
  1593. case Obj::CAMPFIRE:
  1594. case Obj::WAGON:
  1595. case Obj::LEAN_TO:
  1596. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1597. case Obj::BORDER_GATE:
  1598. if (subid == 1000) // HotA hacks - Quest Gate
  1599. return readQuestGuard(mapPosition);
  1600. if (subid == 1001) // HotA hacks - Grave
  1601. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1602. return readGeneric(mapPosition, objectTemplate);
  1603. case Obj::HOTA_CUSTOM_OBJECT_1:
  1604. // 0 -> Ancient Lamp
  1605. // 1 -> Sea Barrel
  1606. // 2 -> Jetsam
  1607. // 3 -> Vial of Mana
  1608. if (subid == 0 || subid == 1)
  1609. return readRewardWithArtifactAndResources(mapPosition, objectTemplate);
  1610. else
  1611. return readRewardWithArtifact(mapPosition, objectTemplate);
  1612. case Obj::HOTA_CUSTOM_OBJECT_2:
  1613. if (subid == 0) // Seafaring Academy
  1614. return readUniversity(mapPosition, objectTemplate);
  1615. else
  1616. return readGeneric(mapPosition, objectTemplate);
  1617. case Obj::BLACK_MARKET:
  1618. return readBlackMarket(mapPosition, objectTemplate);
  1619. case Obj::UNIVERSITY:
  1620. return readUniversity(mapPosition, objectTemplate);
  1621. default: //any other object
  1622. return readGeneric(mapPosition, objectTemplate);
  1623. }
  1624. }
  1625. void CMapLoaderH3M::readObjects()
  1626. {
  1627. uint32_t objectsCount = reader->readUInt32();
  1628. for(uint32_t i = 0; i < objectsCount; ++i)
  1629. {
  1630. int3 mapPosition = reader->readInt3();
  1631. assert(map->isInTheMap(mapPosition) || map->isInTheMap(mapPosition - int3(0,8,0)) || map->isInTheMap(mapPosition - int3(8,0,0)) || map->isInTheMap(mapPosition - int3(8,8,0)));
  1632. uint32_t defIndex = reader->readUInt32();
  1633. std::shared_ptr<ObjectTemplate> originalTemplate = originalTemplates.at(defIndex);
  1634. std::shared_ptr<ObjectTemplate> remappedTemplate = remappedTemplates.at(defIndex);
  1635. auto originalID = originalTemplate->id;
  1636. auto originalSubID = originalTemplate->subid;
  1637. reader->skipZero(5);
  1638. ObjectInstanceID newObjectID = map->allocateUniqueInstanceID();
  1639. auto newObject = readObject(originalID, originalSubID, remappedTemplate, mapPosition, newObjectID);
  1640. if(!newObject)
  1641. continue;
  1642. newObject->setAnchorPos(mapPosition);
  1643. newObject->ID = remappedTemplate->id;
  1644. newObject->id = newObjectID;
  1645. if(newObject->ID != Obj::HERO && newObject->ID != Obj::HERO_PLACEHOLDER && newObject->ID != Obj::PRISON)
  1646. {
  1647. newObject->subID = remappedTemplate->subid;
  1648. }
  1649. newObject->appearance = remappedTemplate;
  1650. if (newObject->isVisitable() && !map->isInTheMap(newObject->visitablePos()))
  1651. logGlobal->error("Map '%s': Object at %s - outside of map borders!", mapName, mapPosition.toString());
  1652. map->generateUniqueInstanceName(newObject.get());
  1653. map->addNewObject(newObject);
  1654. }
  1655. }
  1656. void CMapLoaderH3M::readCreatureSet(CArmedInstance * out, const ObjectInstanceID & idToBeGiven)
  1657. {
  1658. constexpr int unitsToRead = 7;
  1659. out->id = idToBeGiven;
  1660. for(int index = 0; index < unitsToRead; ++index)
  1661. {
  1662. CreatureID creatureID = reader->readCreature();
  1663. int count = reader->readUInt16();
  1664. // Empty slot
  1665. if(creatureID == CreatureID::NONE)
  1666. continue;
  1667. auto result = std::make_unique<CStackInstance>(map->cb);
  1668. result->setCount(count);
  1669. if(creatureID < CreatureID::NONE)
  1670. {
  1671. int value = -creatureID.getNum() - 2;
  1672. assert(value >= 0 && value < 14);
  1673. uint8_t level = value / 2;
  1674. uint8_t upgrade = value % 2;
  1675. //this will happen when random object has random army
  1676. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1677. }
  1678. else
  1679. {
  1680. result->setType(creatureID);
  1681. }
  1682. out->putStack(SlotID(index), std::move(result));
  1683. }
  1684. out->validTypes(true);
  1685. }
  1686. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1687. {
  1688. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1689. if(owner == PlayerColor::NEUTRAL)
  1690. {
  1691. object->setOwner(PlayerColor::NEUTRAL);
  1692. return;
  1693. }
  1694. if(!owner.isValidPlayer())
  1695. {
  1696. object->setOwner(PlayerColor::NEUTRAL);
  1697. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1698. return;
  1699. }
  1700. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1701. {
  1702. object->setOwner(PlayerColor::NEUTRAL);
  1703. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1704. );
  1705. return;
  1706. }
  1707. object->setOwner(owner);
  1708. }
  1709. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1710. {
  1711. if(features.levelAB)
  1712. {
  1713. unsigned int identifier = reader->readUInt32();
  1714. questIdentifierToId[identifier] = objectInstanceID;
  1715. }
  1716. PlayerColor owner = reader->readPlayer();
  1717. HeroTypeID heroType = reader->readHero();
  1718. //If hero of this type has been predefined, use that as a base.
  1719. //Instance data will overwrite the predefined values where appropriate.
  1720. std::shared_ptr<CGHeroInstance> object;
  1721. if (heroType.hasValue())
  1722. object = map->tryTakeFromHeroPool(heroType);
  1723. if (!object)
  1724. {
  1725. object = std::make_shared<CGHeroInstance>(map->cb);
  1726. object->subID = heroType.getNum();
  1727. }
  1728. setOwnerAndValidate(mapPosition, object.get(), owner);
  1729. for(auto & elem : map->disposedHeroes)
  1730. {
  1731. if(elem.heroId == object->getHeroTypeID())
  1732. {
  1733. object->nameCustomTextId = elem.name;
  1734. object->customPortraitSource = elem.portrait;
  1735. break;
  1736. }
  1737. }
  1738. bool hasName = reader->readBool();
  1739. if(hasName)
  1740. object->nameCustomTextId = readLocalizedString(TextIdentifier("heroes", object->getHeroTypeID().getNum(), "name"));
  1741. if(features.levelSOD)
  1742. {
  1743. bool hasCustomExperience = reader->readBool();
  1744. if(hasCustomExperience)
  1745. object->exp = reader->readUInt32();
  1746. }
  1747. else
  1748. {
  1749. object->exp = reader->readUInt32();
  1750. //0 means "not set" in <=AB maps
  1751. if(!object->exp)
  1752. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1753. }
  1754. bool hasPortrait = reader->readBool();
  1755. if(hasPortrait)
  1756. object->customPortraitSource = reader->readHeroPortrait();
  1757. bool hasSecSkills = reader->readBool();
  1758. if(hasSecSkills)
  1759. {
  1760. if(!object->secSkills.empty())
  1761. {
  1762. if(object->secSkills[0].first != SecondarySkill::NONE)
  1763. logGlobal->debug("Map '%s': Hero %s subID=%d has set secondary skills twice (in map properties and on adventure map instance). Using the latter set...", mapName, object->getNameTextID(), object->subID);
  1764. object->secSkills.clear();
  1765. }
  1766. uint32_t skillsCount = reader->readUInt32();
  1767. object->secSkills.resize(skillsCount);
  1768. for(int i = 0; i < skillsCount; ++i)
  1769. {
  1770. object->secSkills[i].first = reader->readSkill();
  1771. object->secSkills[i].second = reader->readInt8Checked(1,3);
  1772. }
  1773. }
  1774. bool hasGarison = reader->readBool();
  1775. if(hasGarison)
  1776. readCreatureSet(object.get(), objectInstanceID);
  1777. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  1778. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1779. loadArtifactsOfHero(object.get());
  1780. object->patrol.patrolRadius = reader->readUInt8();
  1781. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1782. if(features.levelAB)
  1783. {
  1784. bool hasCustomBiography = reader->readBool();
  1785. if(hasCustomBiography)
  1786. object->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1787. object->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  1788. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1789. }
  1790. else
  1791. {
  1792. object->gender = EHeroGender::DEFAULT;
  1793. }
  1794. // Spells
  1795. if(features.levelSOD)
  1796. {
  1797. bool hasCustomSpells = reader->readBool();
  1798. if(hasCustomSpells)
  1799. {
  1800. if(!object->spells.empty())
  1801. {
  1802. object->spells.clear();
  1803. logGlobal->debug("Hero %s subID=%d has spells set twice (in map properties and on adventure map instance). Using the latter set...", object->getNameTextID(), object->subID);
  1804. }
  1805. reader->readBitmaskSpells(object->spells, false);
  1806. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1807. }
  1808. }
  1809. else if(features.levelAB)
  1810. {
  1811. //we can read one spell
  1812. SpellID spell = reader->readSpell();
  1813. // workaround: VCMI uses 'PRESET' spell to indicate that spellbook has been preconfigured on map
  1814. // but H3 uses 'PRESET' spell (-2) to indicate that game should give standard spell to hero
  1815. if(spell == SpellID::NONE)
  1816. object->spells.insert(SpellID::PRESET); //spellbook is preconfigured to be empty
  1817. if (spell.hasValue())
  1818. object->spells.insert(spell);
  1819. }
  1820. if(features.levelSOD)
  1821. {
  1822. bool hasCustomPrimSkills = reader->readBool();
  1823. if(hasCustomPrimSkills)
  1824. {
  1825. auto ps = object->getAllBonuses(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)), nullptr);
  1826. if(ps->size())
  1827. {
  1828. logGlobal->debug("Hero %s has set primary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getHeroTypeID().getNum() );
  1829. for(const auto & b : *ps)
  1830. object->removeBonus(b);
  1831. }
  1832. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1833. {
  1834. object->pushPrimSkill(static_cast<PrimarySkill>(xx), reader->readUInt8());
  1835. }
  1836. }
  1837. }
  1838. if (object->subID != MapObjectSubID())
  1839. logGlobal->debug("Map '%s': Hero on map: %s at %s, owned by %s", mapName, object->getHeroType()->getJsonKey(), mapPosition.toString(), object->getOwner().toString());
  1840. else
  1841. logGlobal->debug("Map '%s': Hero on map: (random) at %s, owned by %s", mapName, mapPosition.toString(), object->getOwner().toString());
  1842. reader->skipZero(16);
  1843. if(features.levelHOTA5)
  1844. {
  1845. bool alwaysAddSkills = reader->readBool(); // prevent heroes from receiving additional random secondary skills at the start of the map if they are not of the first level
  1846. bool cannotGainXP = reader->readBool();
  1847. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  1848. assert(level > 0);
  1849. if (!alwaysAddSkills)
  1850. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, object->subID.num);
  1851. if (cannotGainXP)
  1852. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, object->subID.num);
  1853. if (level > 1)
  1854. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, object->subID.num, level);
  1855. }
  1856. return object;
  1857. }
  1858. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSeerHut(const int3 & position, const ObjectInstanceID & idToBeGiven)
  1859. {
  1860. auto hut = std::make_shared<CGSeerHut>(map->cb);
  1861. uint32_t questsCount = 1;
  1862. if(features.levelHOTA3)
  1863. questsCount = reader->readUInt32();
  1864. //TODO: HotA
  1865. if(questsCount > 1)
  1866. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1867. for(size_t i = 0; i < questsCount; ++i)
  1868. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1869. if(features.levelHOTA3)
  1870. {
  1871. uint32_t repeateableQuestsCount = reader->readUInt32();
  1872. hut->getQuest().repeatedQuest = repeateableQuestsCount != 0;
  1873. if(repeateableQuestsCount != 0)
  1874. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1875. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1876. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1877. }
  1878. reader->skipZero(2);
  1879. return hut;
  1880. }
  1881. enum class ESeerHutRewardType : uint8_t
  1882. {
  1883. NOTHING = 0,
  1884. EXPERIENCE = 1,
  1885. MANA_POINTS = 2,
  1886. MORALE = 3,
  1887. LUCK = 4,
  1888. RESOURCES = 5,
  1889. PRIMARY_SKILL = 6,
  1890. SECONDARY_SKILL = 7,
  1891. ARTIFACT = 8,
  1892. SPELL = 9,
  1893. CREATURE = 10,
  1894. };
  1895. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position, const ObjectInstanceID & idToBeGiven)
  1896. {
  1897. EQuestMission missionType = EQuestMission::NONE;
  1898. if(features.levelAB)
  1899. {
  1900. missionType = readQuest(hut, position);
  1901. }
  1902. else
  1903. {
  1904. //RoE
  1905. auto artID = reader->readArtifact();
  1906. if(artID != ArtifactID::NONE)
  1907. {
  1908. //not none quest
  1909. hut->getQuest().mission.artifacts.push_back(artID);
  1910. missionType = EQuestMission::ARTIFACT;
  1911. }
  1912. hut->getQuest().lastDay = -1; //no timeout
  1913. hut->getQuest().isCustomFirst = false;
  1914. hut->getQuest().isCustomNext = false;
  1915. hut->getQuest().isCustomComplete = false;
  1916. }
  1917. if(missionType != EQuestMission::NONE)
  1918. {
  1919. auto rewardType = static_cast<ESeerHutRewardType>(reader->readInt8Checked(0, 10));
  1920. Rewardable::VisitInfo vinfo;
  1921. auto & reward = vinfo.reward;
  1922. switch(rewardType)
  1923. {
  1924. case ESeerHutRewardType::NOTHING:
  1925. {
  1926. // no-op
  1927. break;
  1928. }
  1929. case ESeerHutRewardType::EXPERIENCE:
  1930. {
  1931. reward.heroExperience = reader->readUInt32();
  1932. break;
  1933. }
  1934. case ESeerHutRewardType::MANA_POINTS:
  1935. {
  1936. reward.manaDiff = reader->readUInt32();
  1937. break;
  1938. }
  1939. case ESeerHutRewardType::MORALE:
  1940. {
  1941. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven));
  1942. break;
  1943. }
  1944. case ESeerHutRewardType::LUCK:
  1945. {
  1946. reward.heroBonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven));
  1947. break;
  1948. }
  1949. case ESeerHutRewardType::RESOURCES:
  1950. {
  1951. auto rId = reader->readGameResID();
  1952. auto rVal = reader->readUInt32();
  1953. reward.resources[rId] = rVal;
  1954. break;
  1955. }
  1956. case ESeerHutRewardType::PRIMARY_SKILL:
  1957. {
  1958. auto rId = reader->readPrimary();
  1959. auto rVal = reader->readUInt8();
  1960. reward.primary.at(rId.getNum()) = rVal;
  1961. break;
  1962. }
  1963. case ESeerHutRewardType::SECONDARY_SKILL:
  1964. {
  1965. auto rId = reader->readSkill();
  1966. auto rVal = reader->readInt8Checked(1,3);
  1967. reward.secondary[rId] = rVal;
  1968. break;
  1969. }
  1970. case ESeerHutRewardType::ARTIFACT:
  1971. {
  1972. ArtifactID grantedArtifact = reader->readArtifact();
  1973. if (features.levelHOTA5)
  1974. {
  1975. SpellID scrollSpell = reader->readSpell16();
  1976. if (grantedArtifact == ArtifactID::SPELL_SCROLL)
  1977. reward.grantedScrolls.push_back(scrollSpell);
  1978. }
  1979. else
  1980. reward.grantedArtifacts.push_back(grantedArtifact);
  1981. break;
  1982. }
  1983. case ESeerHutRewardType::SPELL:
  1984. {
  1985. reward.spells.push_back(reader->readSpell());
  1986. break;
  1987. }
  1988. case ESeerHutRewardType::CREATURE:
  1989. {
  1990. auto rId = reader->readCreature();
  1991. auto rVal = reader->readUInt16();
  1992. reward.creatures.emplace_back(rId, rVal);
  1993. break;
  1994. }
  1995. default:
  1996. {
  1997. assert(0);
  1998. }
  1999. }
  2000. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  2001. hut->configuration.info.push_back(vinfo);
  2002. }
  2003. else
  2004. {
  2005. // missionType==255
  2006. reader->skipZero(1);
  2007. }
  2008. }
  2009. EQuestMission CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  2010. {
  2011. auto missionId = static_cast<EQuestMission>(reader->readInt8Checked(0, 10));
  2012. switch(missionId)
  2013. {
  2014. case EQuestMission::NONE:
  2015. return missionId;
  2016. case EQuestMission::PRIMARY_SKILL:
  2017. {
  2018. for(int x = 0; x < 4; ++x)
  2019. {
  2020. guard->getQuest().mission.primary[x] = reader->readUInt8();
  2021. }
  2022. break;
  2023. }
  2024. case EQuestMission::LEVEL:
  2025. {
  2026. guard->getQuest().mission.heroLevel = reader->readUInt32();
  2027. break;
  2028. }
  2029. case EQuestMission::KILL_HERO:
  2030. case EQuestMission::KILL_CREATURE:
  2031. {
  2032. // NOTE: assert might fail on multi-quest seers
  2033. //assert(questsToResolve.count(guard) == 0);
  2034. questsToResolve[guard] = reader->readUInt32();
  2035. break;
  2036. }
  2037. case EQuestMission::ARTIFACT:
  2038. {
  2039. size_t artNumber = reader->readUInt8();
  2040. for(size_t yy = 0; yy < artNumber; ++yy)
  2041. {
  2042. ArtifactID requiredArtifact = reader->readArtifact();
  2043. if (features.levelHOTA5)
  2044. {
  2045. SpellID scrollSpell = reader->readSpell16();
  2046. if (requiredArtifact == ArtifactID::SPELL_SCROLL)
  2047. guard->getQuest().mission.scrolls.push_back(scrollSpell);
  2048. }
  2049. else
  2050. guard->getQuest().mission.artifacts.push_back(requiredArtifact);
  2051. map->allowedArtifact.erase(requiredArtifact); //these are unavailable for random generation
  2052. }
  2053. break;
  2054. }
  2055. case EQuestMission::ARMY:
  2056. {
  2057. size_t typeNumber = reader->readUInt8();
  2058. guard->getQuest().mission.creatures.resize(typeNumber);
  2059. for(size_t hh = 0; hh < typeNumber; ++hh)
  2060. {
  2061. guard->getQuest().mission.creatures[hh].setType(reader->readCreature().toCreature());
  2062. guard->getQuest().mission.creatures[hh].setCount(reader->readUInt16());
  2063. }
  2064. break;
  2065. }
  2066. case EQuestMission::RESOURCES:
  2067. {
  2068. for(int x = 0; x < 7; ++x)
  2069. guard->getQuest().mission.resources[x] = reader->readUInt32();
  2070. break;
  2071. }
  2072. case EQuestMission::HERO:
  2073. {
  2074. guard->getQuest().mission.heroes.push_back(reader->readHero());
  2075. break;
  2076. }
  2077. case EQuestMission::PLAYER:
  2078. {
  2079. guard->getQuest().mission.players.push_back(reader->readPlayer());
  2080. break;
  2081. }
  2082. case EQuestMission::HOTA_MULTI:
  2083. {
  2084. uint32_t missionSubID = reader->readUInt32();
  2085. assert(missionSubID < 3);
  2086. if(missionSubID == 0)
  2087. {
  2088. missionId = EQuestMission::HOTA_HERO_CLASS;
  2089. std::set<HeroClassID> heroClasses;
  2090. reader->readBitmaskHeroClassesSized(heroClasses, false);
  2091. for(auto & hc : heroClasses)
  2092. guard->getQuest().mission.heroClasses.push_back(hc);
  2093. break;
  2094. }
  2095. if(missionSubID == 1)
  2096. {
  2097. missionId = EQuestMission::HOTA_REACH_DATE;
  2098. guard->getQuest().mission.daysPassed = reader->readUInt32() + 1;
  2099. break;
  2100. }
  2101. if(missionSubID == 2)
  2102. {
  2103. missionId = EQuestMission::HOTA_GAME_DIFFICULTY;
  2104. int32_t difficultyMask = reader->readUInt32();
  2105. assert(difficultyMask > 0 && difficultyMask < 32);
  2106. logGlobal->warn("Map '%s': Seer Hut at %s: Difficulty-specific quest (%d) is not implemented!", mapName, position.toString(), difficultyMask);
  2107. break;
  2108. }
  2109. break;
  2110. }
  2111. default:
  2112. {
  2113. assert(0);
  2114. }
  2115. }
  2116. guard->getQuest().lastDay = reader->readInt32();
  2117. guard->getQuest().firstVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit")));
  2118. guard->getQuest().nextVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit")));
  2119. guard->getQuest().completedText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed")));
  2120. guard->getQuest().isCustomFirst = !guard->getQuest().firstVisitText.empty();
  2121. guard->getQuest().isCustomNext = !guard->getQuest().nextVisitText.empty();
  2122. guard->getQuest().isCustomComplete = !guard->getQuest().completedText.empty();
  2123. return missionId;
  2124. }
  2125. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate, const ObjectInstanceID & idToBeGiven)
  2126. {
  2127. auto object = std::make_shared<CGTownInstance>(map->cb);
  2128. if(features.levelAB)
  2129. object->identifier = reader->readUInt32();
  2130. setOwnerAndValidate(position, object.get(), reader->readPlayer());
  2131. std::optional<FactionID> faction;
  2132. if (objectTemplate->id == Obj::TOWN)
  2133. faction = FactionID(objectTemplate->subid);
  2134. bool hasName = reader->readBool();
  2135. if(hasName)
  2136. object->setNameTextId(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  2137. bool hasGarrison = reader->readBool();
  2138. if(hasGarrison)
  2139. readCreatureSet(object.get(), idToBeGiven);
  2140. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  2141. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  2142. bool hasCustomBuildings = reader->readBool();
  2143. if(hasCustomBuildings)
  2144. {
  2145. std::set<BuildingID> builtBuildings;
  2146. reader->readBitmaskBuildings(builtBuildings, faction);
  2147. for(const auto & building : builtBuildings)
  2148. object->addBuilding(building);
  2149. reader->readBitmaskBuildings(object->forbiddenBuildings, faction);
  2150. }
  2151. // Standard buildings
  2152. else
  2153. {
  2154. bool hasFort = reader->readBool();
  2155. if(hasFort)
  2156. object->addBuilding(BuildingID::FORT);
  2157. //means that set of standard building should be included
  2158. object->addBuilding(BuildingID::DEFAULT);
  2159. }
  2160. if(features.levelAB)
  2161. {
  2162. std::set<SpellID> spellsMask;
  2163. reader->readBitmaskSpells(spellsMask, false);
  2164. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  2165. }
  2166. {
  2167. std::set<SpellID> spellsMask = LIBRARY->spellh->getDefaultAllowed(); // by default - include spells from mods
  2168. reader->readBitmaskSpells(spellsMask, true);
  2169. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  2170. }
  2171. if(features.levelHOTA1)
  2172. object->spellResearchAllowed = reader->readBool();
  2173. if(features.levelHOTA5)
  2174. {
  2175. // Most likely customization of special buildings per faction -> 4x11 table
  2176. // presumably:
  2177. // 0 -> default / allowed
  2178. // 1 -> built?
  2179. // 2 -> banned?
  2180. uint32_t specialBuildingsSize = reader->readUInt32();
  2181. for (int i = 0; i < specialBuildingsSize; ++i)
  2182. {
  2183. int factionID = i / 4;
  2184. int buildingID = i % 4;
  2185. int8_t specialBuildingBuilt = reader->readInt8Checked(0, 2);
  2186. if (specialBuildingBuilt != 0)
  2187. logGlobal->warn("Map '%s': Town at %s: Constructing / banning town-specific special building %d in faction %d on start is not implemented!", mapName, position.toString(), buildingID, factionID);
  2188. }
  2189. }
  2190. // Read castle events
  2191. uint32_t eventsCount = reader->readUInt32();
  2192. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2193. {
  2194. CCastleEvent event;
  2195. event.creatures.resize(7);
  2196. readEventCommon(event, TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  2197. if(features.levelHOTA5)
  2198. {
  2199. int32_t creatureGrowth8 = reader->readInt32();
  2200. // always 44
  2201. int32_t hotaAmount = reader->readInt32();
  2202. // contains bitmask on which town-specific buildings to build
  2203. // 4 bits / town, for each of special building in town (special 1 - special 4)
  2204. int32_t hotaSpecialA = reader->readInt32();
  2205. int16_t hotaSpecialB = reader->readInt16();
  2206. if (hotaSpecialA != 0 || hotaSpecialB != 0 || hotaAmount != 44)
  2207. logGlobal->warn("Map '%s': Town at %s: Constructing town-specific special buildings in event is not implemented!", mapName, position.toString());
  2208. event.creatures.push_back(creatureGrowth8);
  2209. }
  2210. if(features.levelHOTA7)
  2211. {
  2212. [[maybe_unused]] bool neutralAffected = reader->readBool();
  2213. }
  2214. // New buildings
  2215. reader->readBitmaskBuildings(event.buildings, faction);
  2216. for(int i = 0; i < 7; ++i)
  2217. event.creatures[i] = reader->readUInt16();
  2218. reader->skipZero(4);
  2219. object->events.push_back(event);
  2220. }
  2221. if(features.levelSOD)
  2222. {
  2223. object->alignmentToPlayer = PlayerColor::NEUTRAL; // "same as owner or random"
  2224. uint8_t alignment = reader->readUInt8();
  2225. if(alignment != 255)
  2226. {
  2227. if(alignment < PlayerColor::PLAYER_LIMIT.getNum())
  2228. {
  2229. if (mapHeader->players[alignment].canAnyonePlay())
  2230. object->alignmentToPlayer = PlayerColor(alignment);
  2231. else
  2232. logGlobal->warn("Map '%s': Alignment of town at %s is invalid! Player %d is not present on map!", mapName, position.toString(), static_cast<int>(alignment));
  2233. }
  2234. else
  2235. {
  2236. // TODO: HOTA support
  2237. uint8_t invertedAlignment = alignment - PlayerColor::PLAYER_LIMIT.getNum();
  2238. if(invertedAlignment < PlayerColor::PLAYER_LIMIT.getNum())
  2239. {
  2240. logGlobal->warn("Map '%s': Alignment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  2241. }
  2242. else
  2243. {
  2244. logGlobal->warn("Map '%s': Alignment of town at %s is corrupted!!", mapName, position.toString());
  2245. }
  2246. }
  2247. }
  2248. }
  2249. reader->skipZero(3);
  2250. return object;
  2251. }
  2252. void CMapLoaderH3M::readEventCommon(CMapEvent & event, const TextIdentifier & messageID)
  2253. {
  2254. event.name = readBasicString();
  2255. event.message.appendTextID(readLocalizedString(messageID));
  2256. reader->readResources(event.resources);
  2257. reader->readBitmaskPlayers(event.players, false);
  2258. if(features.levelSOD)
  2259. event.humanAffected = reader->readBool();
  2260. else
  2261. event.humanAffected = true;
  2262. event.computerAffected = reader->readBool();
  2263. event.firstOccurrence = reader->readUInt16();
  2264. event.nextOccurrence = reader->readUInt16();
  2265. reader->skipZero(16);
  2266. if (features.levelHOTA7)
  2267. {
  2268. int32_t allowedDifficultiesMask = reader->readInt32();
  2269. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  2270. if (allowedDifficultiesMask != 31)
  2271. logGlobal->warn("Map '%s': Map event: availability by difficulty (mode %d) is not implemented!", mapName, allowedDifficultiesMask);
  2272. }
  2273. }
  2274. void CMapLoaderH3M::readEvents()
  2275. {
  2276. uint32_t eventsCount = reader->readUInt32();
  2277. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2278. {
  2279. CMapEvent event;
  2280. readEventCommon(event, TextIdentifier("event", eventID, "description"));
  2281. // garbage bytes that were present in HOTA5 & HOTA6
  2282. if (features.levelHOTA5 && !features.levelHOTA7)
  2283. reader->skipUnused(14);
  2284. map->events.push_back(event);
  2285. }
  2286. }
  2287. void CMapLoaderH3M::readMessageAndGuards(MetaString & message, CArmedInstance * guards, const int3 & position, const ObjectInstanceID & idToBeGiven)
  2288. {
  2289. bool hasMessage = reader->readBool();
  2290. if(hasMessage)
  2291. {
  2292. message.appendTextID(readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message")));
  2293. bool hasGuards = reader->readBool();
  2294. if(hasGuards)
  2295. readCreatureSet(guards, idToBeGiven);
  2296. reader->skipZero(4);
  2297. }
  2298. }
  2299. std::string CMapLoaderH3M::readBasicString()
  2300. {
  2301. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2302. }
  2303. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  2304. {
  2305. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2306. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  2307. if(mapString.empty())
  2308. return "";
  2309. return mapRegisterLocalizedString(modName, *mapHeader, fullIdentifier, mapString);
  2310. }
  2311. void CMapLoaderH3M::afterRead()
  2312. {
  2313. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  2314. for(auto & p : map->players)
  2315. {
  2316. int3 posOfMainTown = p.posOfMainTown;
  2317. if(posOfMainTown.isValid() && map->isInTheMap(posOfMainTown))
  2318. {
  2319. const TerrainTile & t = map->getTile(posOfMainTown);
  2320. const CGObjectInstance * mainTown = nullptr;
  2321. for(ObjectInstanceID objID : t.visitableObjects)
  2322. {
  2323. const CGObjectInstance * object = map->getObject(objID);
  2324. if(object->ID == Obj::TOWN || object->ID == Obj::RANDOM_TOWN)
  2325. {
  2326. mainTown = object;
  2327. break;
  2328. }
  2329. }
  2330. if(mainTown == nullptr)
  2331. continue;
  2332. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  2333. }
  2334. }
  2335. for (auto & quest : questsToResolve)
  2336. quest.first->getQuest().killTarget = questIdentifierToId.at(quest.second);
  2337. }
  2338. VCMI_LIB_NAMESPACE_END