MapFormatH3M.cpp 86 KB

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