MapFormatH3M.cpp 86 KB

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