MapFormatH3M.cpp 87 KB

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