MapFormatH3M.cpp 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762
  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 = std::make_shared<CGHeroInstance>(map->cb);
  739. hero->ID = Obj::HERO;
  740. hero->subID = heroID;
  741. bool hasExp = reader->readBool();
  742. if(hasExp)
  743. {
  744. hero->exp = reader->readUInt32();
  745. }
  746. else
  747. {
  748. hero->exp = 0;
  749. }
  750. bool hasSecSkills = reader->readBool();
  751. if(hasSecSkills)
  752. {
  753. uint32_t howMany = reader->readUInt32();
  754. hero->secSkills.resize(howMany);
  755. for(int yy = 0; yy < howMany; ++yy)
  756. {
  757. hero->secSkills[yy].first = reader->readSkill();
  758. hero->secSkills[yy].second = reader->readInt8Checked(1,3);
  759. }
  760. }
  761. loadArtifactsOfHero(hero.get());
  762. bool hasCustomBio = reader->readBool();
  763. if(hasCustomBio)
  764. hero->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", heroID, "biography"));
  765. // 0xFF is default, 00 male, 01 female
  766. hero->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  767. assert(hero->gender == EHeroGender::MALE || hero->gender == EHeroGender::FEMALE || hero->gender == EHeroGender::DEFAULT);
  768. bool hasCustomSpells = reader->readBool();
  769. if(hasCustomSpells)
  770. reader->readBitmaskSpells(hero->spells, false);
  771. bool hasCustomPrimSkills = reader->readBool();
  772. if(hasCustomPrimSkills)
  773. {
  774. for(int skillID = 0; skillID < GameConstants::PRIMARY_SKILLS; skillID++)
  775. {
  776. hero->pushPrimSkill(static_cast<PrimarySkill>(skillID), reader->readUInt8());
  777. }
  778. }
  779. map->addToHeroPool(hero);
  780. logGlobal->debug("Map '%s': Hero predefined in map: %s", mapName, hero->getHeroType()->getJsonKey());
  781. }
  782. if(features.levelHOTA5)
  783. {
  784. for(int heroID = 0; heroID < heroesCount; heroID++)
  785. {
  786. bool alwaysAddSkills = reader->readBool(); // prevent heroes from receiving additional random secondary skills at the start of the map if they are not of the first level
  787. bool cannotGainXP = reader->readBool();
  788. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  789. assert(level > 0);
  790. if (!alwaysAddSkills)
  791. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, heroID);
  792. if (cannotGainXP)
  793. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, heroID);
  794. if (level > 1)
  795. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, heroID, level);
  796. }
  797. }
  798. }
  799. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  800. {
  801. bool hasArtSet = reader->readBool();
  802. // True if artifact set is not default (hero has some artifacts)
  803. if(!hasArtSet)
  804. return;
  805. // Workaround - if hero has customized artifacts game should not attempt to add spellbook based on hero type
  806. hero->spells.insert(SpellID::SPELLBOOK_PRESET);
  807. if(!hero->artifactsWorn.empty() || !hero->artifactsInBackpack.empty())
  808. {
  809. logGlobal->debug("Hero %d at %s has set artifacts twice (in map properties and on adventure map instance). Using the latter set...", hero->getHeroTypeID().getNum(), hero->anchorPos().toString());
  810. hero->artifactsInBackpack.clear();
  811. while(!hero->artifactsWorn.empty())
  812. hero->removeArtifact(hero->artifactsWorn.begin()->first);
  813. }
  814. for(int i = 0; i < features.artifactSlotsCount; i++)
  815. loadArtifactToSlot(hero, i);
  816. // bag artifacts
  817. // number of artifacts in hero's bag
  818. size_t amount = reader->readUInt16();
  819. for(size_t i = 0; i < amount; ++i)
  820. {
  821. loadArtifactToSlot(hero, ArtifactPosition::BACKPACK_START + static_cast<int>(hero->artifactsInBackpack.size()));
  822. }
  823. }
  824. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  825. {
  826. ArtifactID artifactID = reader->readArtifact();
  827. SpellID scrollSpell = SpellID::NONE;
  828. if (features.levelHOTA5)
  829. scrollSpell = reader->readSpell16();
  830. if(artifactID == ArtifactID::NONE)
  831. return false;
  832. const Artifact * art = artifactID.toEntity(LIBRARY);
  833. if(!art)
  834. {
  835. logGlobal->warn("Map '%s': Invalid artifact in hero's backpack, ignoring...", mapName);
  836. return false;
  837. }
  838. if(art->isBig() && slot >= ArtifactPosition::BACKPACK_START)
  839. {
  840. logGlobal->warn("Map '%s': A big artifact (war machine) in hero's backpack, ignoring...", mapName);
  841. return false;
  842. }
  843. // H3 bug workaround - Enemy hero on 3rd scenario of Good1.h3c campaign ("Long Live The Queen")
  844. // He has Shackles of War (normally - MISC slot artifact) in LEFT_HAND slot set in editor
  845. // Artifact seems to be missing in game, so skip artifacts that don't fit target slot
  846. if(ArtifactID(artifactID).toArtifact()->canBePutAt(hero, ArtifactPosition(slot)))
  847. {
  848. auto * artifact = map->createArtifact(artifactID, scrollSpell);
  849. map->putArtifactInstance(*hero, artifact->getId(), slot);
  850. }
  851. else
  852. {
  853. logGlobal->warn("Map '%s': Artifact '%s' can't be put at the slot %d", mapName, ArtifactID(artifactID).toArtifact()->getNameTranslated(), slot);
  854. return false;
  855. }
  856. return true;
  857. }
  858. void CMapLoaderH3M::readTerrain()
  859. {
  860. map->initTerrain();
  861. // Read terrain
  862. int3 pos;
  863. for(pos.z = 0; pos.z < map->levels(); ++pos.z)
  864. {
  865. //OH3 format is [z][y][x]
  866. for(pos.y = 0; pos.y < map->height; pos.y++)
  867. {
  868. for(pos.x = 0; pos.x < map->width; pos.x++)
  869. {
  870. auto & tile = map->getTile(pos);
  871. tile.terrainType = reader->readTerrain();
  872. tile.terView = reader->readUInt8();
  873. tile.riverType = reader->readRiver();
  874. tile.riverDir = reader->readUInt8();
  875. tile.roadType = reader->readRoad();
  876. tile.roadDir = reader->readUInt8();
  877. tile.extTileFlags = reader->readUInt8();
  878. }
  879. }
  880. }
  881. map->calculateWaterContent();
  882. }
  883. void CMapLoaderH3M::readObjectTemplates()
  884. {
  885. uint32_t defAmount = reader->readUInt32();
  886. originalTemplates.reserve(defAmount);
  887. remappedTemplates.reserve(defAmount);
  888. // Read custom defs
  889. for(int defID = 0; defID < defAmount; ++defID)
  890. {
  891. auto tmpl = reader->readObjectTemplate();
  892. originalTemplates.push_back(tmpl);
  893. auto remapped = std::make_shared<ObjectTemplate>(*tmpl);
  894. reader->remapTemplate(*remapped);
  895. remappedTemplates.push_back(remapped);
  896. if (!CResourceHandler::get()->existsResource(remapped->animationFile.addPrefix("SPRITES/")))
  897. logMod->warn("Template animation %s of type (%d %d) is missing!", remapped->animationFile.getOriginalName(), remapped->id, remapped->subid );
  898. }
  899. }
  900. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readEvent(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  901. {
  902. auto object = std::make_shared<CGEvent>(map->cb);
  903. readBoxContent(object.get(), mapPosition, idToBeGiven);
  904. reader->readBitmaskPlayers(object->availableFor, false);
  905. object->computerActivate = reader->readBool();
  906. object->removeAfterVisit = reader->readBool();
  907. reader->skipZero(4);
  908. if(features.levelHOTA3)
  909. object->humanActivate = reader->readBool();
  910. else
  911. object->humanActivate = true;
  912. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  913. return object;
  914. }
  915. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readPandora(const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  916. {
  917. auto object = std::make_shared<CGPandoraBox>(map->cb);
  918. readBoxContent(object.get(), mapPosition, idToBeGiven);
  919. if(features.levelHOTA5)
  920. reader->skipZero(1); // Unknown value, always 0 so far
  921. readBoxHotaContent(object.get(), mapPosition, idToBeGiven);
  922. return object;
  923. }
  924. void CMapLoaderH3M::readBoxContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  925. {
  926. readMessageAndGuards(object->message, object, mapPosition);
  927. Rewardable::VisitInfo vinfo;
  928. auto & reward = vinfo.reward;
  929. reward.heroExperience = reader->readUInt32();
  930. reward.manaDiff = reader->readInt32();
  931. if(auto val = reader->readInt8Checked(-3, 3))
  932. reward.bonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven));
  933. if(auto val = reader->readInt8Checked(-3, 3))
  934. reward.bonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, val, BonusSourceID(idToBeGiven));
  935. reader->readResources(reward.resources);
  936. for(int x = 0; x < GameConstants::PRIMARY_SKILLS; ++x)
  937. reward.primary.at(x) = reader->readUInt8();
  938. size_t gabn = reader->readUInt8(); //number of gained abilities
  939. for(size_t oo = 0; oo < gabn; ++oo)
  940. {
  941. auto rId = reader->readSkill();
  942. auto rVal = reader->readInt8Checked(1,3);
  943. reward.secondary[rId] = rVal;
  944. }
  945. size_t gart = reader->readUInt8(); //number of gained artifacts
  946. for(size_t oo = 0; oo < gart; ++oo)
  947. {
  948. reward.artifacts.push_back(reader->readArtifact());
  949. if (features.levelHOTA5)
  950. {
  951. SpellID scrollSpell = reader->readSpell16();
  952. if (reward.artifacts.back() == ArtifactID::SPELL_SCROLL)
  953. logGlobal->warn("Map '%s': Pandora/Event at %s Option to give spell scroll (%s) via event or pandora is not implemented!", mapName, mapPosition.toString(), scrollSpell.toEntity(LIBRARY)->getJsonKey());
  954. }
  955. }
  956. size_t gspel = reader->readUInt8(); //number of gained spells
  957. for(size_t oo = 0; oo < gspel; ++oo)
  958. reward.spells.push_back(reader->readSpell());
  959. size_t gcre = reader->readUInt8(); //number of gained creatures
  960. for(size_t oo = 0; oo < gcre; ++oo)
  961. {
  962. auto rId = reader->readCreature();
  963. auto rVal = reader->readUInt16();
  964. reward.creatures.emplace_back(rId, rVal);
  965. }
  966. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  967. object->configuration.info.push_back(vinfo);
  968. reader->skipZero(8);
  969. }
  970. void CMapLoaderH3M::readBoxHotaContent(CGPandoraBox * object, const int3 & mapPosition, const ObjectInstanceID & idToBeGiven)
  971. {
  972. if(features.levelHOTA5)
  973. {
  974. int32_t movementMode = reader->readInt32(); // Give, Take, Nullify, Set, Replenish
  975. int32_t movementAmount = reader->readInt32();
  976. assert(movementMode >= 0 && movementMode <= 4);
  977. if (movementMode != 0 || movementAmount != 0)
  978. logGlobal->warn("Map '%s': Event/Pandora %s option to modify (mode %d) movement points by %d is not implemented!", mapName, mapPosition.toString(), movementMode, movementAmount);
  979. }
  980. if(features.levelHOTA6)
  981. {
  982. int32_t allowedDifficultiesMask = reader->readInt32();
  983. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  984. if (allowedDifficultiesMask != 31)
  985. logGlobal->warn("Map '%s': Event/Pandora %s availability by difficulty (mode %d) is not implemented!", mapName, mapPosition.toString(), allowedDifficultiesMask);
  986. }
  987. }
  988. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMonster(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  989. {
  990. auto object = std::make_shared<CGCreature>(map->cb);
  991. if(features.levelAB)
  992. {
  993. object->identifier = reader->readUInt32();
  994. map->questIdentifierToId[object->identifier] = objectInstanceID;
  995. }
  996. auto hlp = std::make_unique<CStackInstance>();
  997. hlp->count = reader->readUInt16();
  998. //type will be set during initialization
  999. object->putStack(SlotID(0), std::move(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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSign(const int3 & mapPosition)
  1042. {
  1043. auto object = std::make_shared<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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readWitchHut(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1049. {
  1050. auto object = readGeneric(position, objectTemplate);
  1051. auto rewardable = std::dynamic_pointer_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. std::shared_ptr<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 = std::dynamic_pointer_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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGarrison(const int3 & mapPosition)
  1156. {
  1157. auto object = std::make_shared<CGGarrison>(map->cb);
  1158. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1159. readCreatureSet(object.get(), 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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readArtifact(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1168. {
  1169. ArtifactID artID = ArtifactID::NONE; //random, set later
  1170. auto object = std::make_shared<CGArtifact>(map->cb);
  1171. readMessageAndGuards(object->message, object.get(), 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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readScroll(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1187. {
  1188. auto object = std::make_shared<CGArtifact>(map->cb);
  1189. readMessageAndGuards(object->message, object.get(), mapPosition);
  1190. SpellID spellID = reader->readSpell32();
  1191. object->storedArtifact = map->createArtifact(ArtifactID::SPELL_SCROLL, spellID.getNum());
  1192. return object;
  1193. }
  1194. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readResource(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1195. {
  1196. auto object = std::make_shared<CGResource>(map->cb);
  1197. readMessageAndGuards(object->message, object.get(), 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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readMine(const int3 & mapPosition)
  1209. {
  1210. auto object = std::make_shared<CGMine>(map->cb);
  1211. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1212. return object;
  1213. }
  1214. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readAbandonedMine(const int3 & mapPosition)
  1215. {
  1216. auto object = std::make_shared<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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwelling(const int3 & position)
  1235. {
  1236. auto object = std::make_shared<CGDwelling>(map->cb);
  1237. setOwnerAndValidate(position, object.get(), reader->readPlayer32());
  1238. return object;
  1239. }
  1240. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readDwellingRandom(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1241. {
  1242. auto object = std::make_shared<CGDwelling>(map->cb);
  1243. setOwnerAndValidate(mapPosition, object.get(), 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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShrine(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1268. {
  1269. auto object = readGeneric(position, objectTemplate);
  1270. auto rewardable = std::dynamic_pointer_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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHeroPlaceholder(const int3 & mapPosition)
  1289. {
  1290. auto object = std::make_shared<CGHeroPlaceholder>(map->cb);
  1291. setOwnerAndValidate(mapPosition, object.get(), 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. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readGrail(const int3 & mapPosition)
  1328. {
  1329. map->grailPos = mapPosition;
  1330. map->grailRadius = reader->readInt32();
  1331. return nullptr;
  1332. }
  1333. std::shared_ptr<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. std::shared_ptr<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 std::make_shared<CGObjectInstance>(map->cb);
  1345. }
  1346. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readQuestGuard(const int3 & mapPosition)
  1347. {
  1348. auto guard = std::make_shared<CGQuestGuard>(map->cb);
  1349. readQuest(guard.get(), mapPosition);
  1350. return guard;
  1351. }
  1352. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readShipyard(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1353. {
  1354. auto object = readGeneric(mapPosition, objectTemplate);
  1355. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1356. return object;
  1357. }
  1358. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readLighthouse(const int3 & mapPosition, std::shared_ptr<const ObjectTemplate> objectTemplate)
  1359. {
  1360. auto object = readGeneric(mapPosition, objectTemplate);
  1361. setOwnerAndValidate(mapPosition, object.get(), reader->readPlayer32());
  1362. return object;
  1363. }
  1364. std::shared_ptr<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. std::shared_ptr<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. std::shared_ptr<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. std::shared_ptr<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. std::shared_ptr<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. std::shared_ptr<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. ObjectInstanceID nextObjectID(0);
  1611. for(uint32_t i = 0; i < objectsCount; ++i)
  1612. {
  1613. int3 mapPosition = reader->readInt3();
  1614. 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)));
  1615. uint32_t defIndex = reader->readUInt32();
  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. auto newObject = readObject(originalID, originalSubID, remappedTemplate, mapPosition, nextObjectID);
  1622. if(!newObject)
  1623. continue;
  1624. newObject->setAnchorPos(mapPosition);
  1625. newObject->ID = remappedTemplate->id;
  1626. newObject->id = nextObjectID;
  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. if (newObject->isVisitable() && !map->isInTheMap(newObject->visitablePos()))
  1633. logGlobal->error("Map '%s': Object at %s - outside of map borders!", mapName, mapPosition.toString());
  1634. {
  1635. //TODO: define valid typeName and subtypeName for H3M maps
  1636. //boost::format fmt("%s_%d");
  1637. //fmt % nobj->typeName % nobj->id.getNum();
  1638. boost::format fmt("obj_%d");
  1639. fmt % newObject->id.getNum();
  1640. newObject->instanceName = fmt.str();
  1641. }
  1642. map->addNewObject(newObject);
  1643. nextObjectID.num += 1;
  1644. }
  1645. map->postInitialize();
  1646. }
  1647. void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
  1648. {
  1649. for(int index = 0; index < number; ++index)
  1650. {
  1651. CreatureID creatureID = reader->readCreature();
  1652. int count = reader->readUInt16();
  1653. // Empty slot
  1654. if(creatureID == CreatureID::NONE)
  1655. continue;
  1656. auto result = std::make_unique<CStackInstance>();
  1657. result->count = count;
  1658. if(creatureID < CreatureID::NONE)
  1659. {
  1660. int value = -creatureID.getNum() - 2;
  1661. assert(value >= 0 && value < 14);
  1662. uint8_t level = value / 2;
  1663. uint8_t upgrade = value % 2;
  1664. //this will happen when random object has random army
  1665. result->randomStack = CStackInstance::RandomStackInfo{level, upgrade};
  1666. }
  1667. else
  1668. {
  1669. result->setType(creatureID);
  1670. }
  1671. out->putStack(SlotID(index), std::move(result));
  1672. }
  1673. out->validTypes(true);
  1674. }
  1675. void CMapLoaderH3M::setOwnerAndValidate(const int3 & mapPosition, CGObjectInstance * object, const PlayerColor & owner)
  1676. {
  1677. assert(owner.isValidPlayer() || owner == PlayerColor::NEUTRAL);
  1678. if(owner == PlayerColor::NEUTRAL)
  1679. {
  1680. object->setOwner(PlayerColor::NEUTRAL);
  1681. return;
  1682. }
  1683. if(!owner.isValidPlayer())
  1684. {
  1685. object->setOwner(PlayerColor::NEUTRAL);
  1686. logGlobal->warn("Map '%s': Object at %s - owned by invalid player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum()));
  1687. return;
  1688. }
  1689. if(!mapHeader->players[owner.getNum()].canAnyonePlay())
  1690. {
  1691. object->setOwner(PlayerColor::NEUTRAL);
  1692. logGlobal->warn("Map '%s': Object at %s - owned by non-existing player %d! Will be set to neutral!", mapName, mapPosition.toString(), int(owner.getNum())
  1693. );
  1694. return;
  1695. }
  1696. object->setOwner(owner);
  1697. }
  1698. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readHero(const int3 & mapPosition, const ObjectInstanceID & objectInstanceID)
  1699. {
  1700. if(features.levelAB)
  1701. {
  1702. unsigned int identifier = reader->readUInt32();
  1703. map->questIdentifierToId[identifier] = objectInstanceID;
  1704. }
  1705. PlayerColor owner = reader->readPlayer();
  1706. HeroTypeID heroType = reader->readHero();
  1707. //If hero of this type has been predefined, use that as a base.
  1708. //Instance data will overwrite the predefined values where appropriate.
  1709. auto object = map->tryTakeFromHeroPool(heroType);
  1710. if (!object)
  1711. {
  1712. object = std::make_shared<CGHeroInstance>(map->cb);
  1713. object->subID = heroType.getNum();
  1714. }
  1715. setOwnerAndValidate(mapPosition, object.get(), owner);
  1716. for(auto & elem : map->disposedHeroes)
  1717. {
  1718. if(elem.heroId == object->getHeroTypeID())
  1719. {
  1720. object->nameCustomTextId = elem.name;
  1721. object->customPortraitSource = elem.portrait;
  1722. break;
  1723. }
  1724. }
  1725. bool hasName = reader->readBool();
  1726. if(hasName)
  1727. object->nameCustomTextId = readLocalizedString(TextIdentifier("heroes", object->getHeroTypeID().getNum(), "name"));
  1728. if(features.levelSOD)
  1729. {
  1730. bool hasCustomExperience = reader->readBool();
  1731. if(hasCustomExperience)
  1732. object->exp = reader->readUInt32();
  1733. }
  1734. else
  1735. {
  1736. object->exp = reader->readUInt32();
  1737. //0 means "not set" in <=AB maps
  1738. if(!object->exp)
  1739. object->exp = CGHeroInstance::UNINITIALIZED_EXPERIENCE;
  1740. }
  1741. bool hasPortrait = reader->readBool();
  1742. if(hasPortrait)
  1743. object->customPortraitSource = reader->readHeroPortrait();
  1744. bool hasSecSkills = reader->readBool();
  1745. if(hasSecSkills)
  1746. {
  1747. if(!object->secSkills.empty())
  1748. {
  1749. if(object->secSkills[0].first != SecondarySkill::NONE)
  1750. 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);
  1751. object->secSkills.clear();
  1752. }
  1753. uint32_t skillsCount = reader->readUInt32();
  1754. object->secSkills.resize(skillsCount);
  1755. for(int i = 0; i < skillsCount; ++i)
  1756. {
  1757. object->secSkills[i].first = reader->readSkill();
  1758. object->secSkills[i].second = reader->readInt8Checked(1,3);
  1759. }
  1760. }
  1761. bool hasGarison = reader->readBool();
  1762. if(hasGarison)
  1763. readCreatureSet(object.get(), 7);
  1764. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  1765. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  1766. loadArtifactsOfHero(object.get());
  1767. object->patrol.patrolRadius = reader->readUInt8();
  1768. object->patrol.patrolling = (object->patrol.patrolRadius != 0xff);
  1769. if(features.levelAB)
  1770. {
  1771. bool hasCustomBiography = reader->readBool();
  1772. if(hasCustomBiography)
  1773. object->biographyCustomTextId = readLocalizedString(TextIdentifier("heroes", object->subID, "biography"));
  1774. object->gender = static_cast<EHeroGender>(reader->readInt8Checked(-1, 1));
  1775. assert(object->gender == EHeroGender::MALE || object->gender == EHeroGender::FEMALE || object->gender == EHeroGender::DEFAULT);
  1776. }
  1777. else
  1778. {
  1779. object->gender = EHeroGender::DEFAULT;
  1780. }
  1781. // Spells
  1782. if(features.levelSOD)
  1783. {
  1784. bool hasCustomSpells = reader->readBool();
  1785. if(hasCustomSpells)
  1786. {
  1787. if(!object->spells.empty())
  1788. {
  1789. object->spells.clear();
  1790. 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);
  1791. }
  1792. reader->readBitmaskSpells(object->spells, false);
  1793. object->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1794. }
  1795. }
  1796. else if(features.levelAB)
  1797. {
  1798. //we can read one spell
  1799. SpellID spell = reader->readSpell();
  1800. // workaround: VCMI uses 'PRESET' spell to indicate that spellbook has been preconfigured on map
  1801. // but H3 uses 'PRESET' spell (-2) to indicate that game should give standard spell to hero
  1802. if(spell == SpellID::NONE)
  1803. object->spells.insert(SpellID::PRESET); //spellbook is preconfigured to be empty
  1804. if (spell.hasValue())
  1805. object->spells.insert(spell);
  1806. }
  1807. if(features.levelSOD)
  1808. {
  1809. bool hasCustomPrimSkills = reader->readBool();
  1810. if(hasCustomPrimSkills)
  1811. {
  1812. auto ps = object->getAllBonuses(Selector::type()(BonusType::PRIMARY_SKILL).And(Selector::sourceType()(BonusSource::HERO_BASE_SKILL)), nullptr);
  1813. if(ps->size())
  1814. {
  1815. logGlobal->debug("Hero %s has set primary skills twice (in map properties and on adventure map instance). Using the latter set...", object->getHeroTypeID().getNum() );
  1816. for(const auto & b : *ps)
  1817. object->removeBonus(b);
  1818. }
  1819. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1820. {
  1821. object->pushPrimSkill(static_cast<PrimarySkill>(xx), reader->readUInt8());
  1822. }
  1823. }
  1824. }
  1825. if (object->subID != MapObjectSubID())
  1826. logGlobal->debug("Map '%s': Hero on map: %s at %s, owned by %s", mapName, object->getHeroType()->getJsonKey(), mapPosition.toString(), object->getOwner().toString());
  1827. else
  1828. logGlobal->debug("Map '%s': Hero on map: (random) at %s, owned by %s", mapName, mapPosition.toString(), object->getOwner().toString());
  1829. reader->skipZero(16);
  1830. if(features.levelHOTA5)
  1831. {
  1832. 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
  1833. bool cannotGainXP = reader->readBool();
  1834. int32_t level = reader->readInt32(); // Needs investigation how this interacts with usual setting of level via experience
  1835. assert(level > 0);
  1836. if (!alwaysAddSkills)
  1837. logGlobal->warn("Map '%s': Option to prevent hero %d from gaining skills on map start is not implemented!", mapName, object->subID.num);
  1838. if (cannotGainXP)
  1839. logGlobal->warn("Map '%s': Option to prevent hero %d from receiveing experience is not implemented!", mapName, object->subID.num);
  1840. if (level > 1)
  1841. logGlobal->warn("Map '%s': Option to set level of hero %d to %d is not implemented!", mapName, object->subID.num, level);
  1842. }
  1843. return object;
  1844. }
  1845. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readSeerHut(const int3 & position, const ObjectInstanceID & idToBeGiven)
  1846. {
  1847. auto hut = std::make_shared<CGSeerHut>(map->cb);
  1848. uint32_t questsCount = 1;
  1849. if(features.levelHOTA3)
  1850. questsCount = reader->readUInt32();
  1851. //TODO: HotA
  1852. if(questsCount > 1)
  1853. logGlobal->warn("Map '%s': Seer Hut at %s - %d quests are not implemented!", mapName, position.toString(), questsCount);
  1854. for(size_t i = 0; i < questsCount; ++i)
  1855. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1856. if(features.levelHOTA3)
  1857. {
  1858. uint32_t repeateableQuestsCount = reader->readUInt32();
  1859. hut->quest->repeatedQuest = repeateableQuestsCount != 0;
  1860. if(repeateableQuestsCount != 0)
  1861. logGlobal->warn("Map '%s': Seer Hut at %s - %d repeatable quests are not implemented!", mapName, position.toString(), repeateableQuestsCount);
  1862. for(size_t i = 0; i < repeateableQuestsCount; ++i)
  1863. readSeerHutQuest(hut.get(), position, idToBeGiven);
  1864. }
  1865. reader->skipZero(2);
  1866. return hut;
  1867. }
  1868. enum class ESeerHutRewardType : uint8_t
  1869. {
  1870. NOTHING = 0,
  1871. EXPERIENCE = 1,
  1872. MANA_POINTS = 2,
  1873. MORALE = 3,
  1874. LUCK = 4,
  1875. RESOURCES = 5,
  1876. PRIMARY_SKILL = 6,
  1877. SECONDARY_SKILL = 7,
  1878. ARTIFACT = 8,
  1879. SPELL = 9,
  1880. CREATURE = 10,
  1881. };
  1882. void CMapLoaderH3M::readSeerHutQuest(CGSeerHut * hut, const int3 & position, const ObjectInstanceID & idToBeGiven)
  1883. {
  1884. EQuestMission missionType = EQuestMission::NONE;
  1885. if(features.levelAB)
  1886. {
  1887. missionType = readQuest(hut, position);
  1888. }
  1889. else
  1890. {
  1891. //RoE
  1892. auto artID = reader->readArtifact();
  1893. if(artID != ArtifactID::NONE)
  1894. {
  1895. //not none quest
  1896. hut->quest->mission.artifacts.push_back(artID);
  1897. missionType = EQuestMission::ARTIFACT;
  1898. }
  1899. hut->quest->lastDay = -1; //no timeout
  1900. hut->quest->isCustomFirst = false;
  1901. hut->quest->isCustomNext = false;
  1902. hut->quest->isCustomComplete = false;
  1903. }
  1904. if(missionType != EQuestMission::NONE)
  1905. {
  1906. auto rewardType = static_cast<ESeerHutRewardType>(reader->readInt8Checked(0, 10));
  1907. Rewardable::VisitInfo vinfo;
  1908. auto & reward = vinfo.reward;
  1909. switch(rewardType)
  1910. {
  1911. case ESeerHutRewardType::NOTHING:
  1912. {
  1913. // no-op
  1914. break;
  1915. }
  1916. case ESeerHutRewardType::EXPERIENCE:
  1917. {
  1918. reward.heroExperience = reader->readUInt32();
  1919. break;
  1920. }
  1921. case ESeerHutRewardType::MANA_POINTS:
  1922. {
  1923. reward.manaDiff = reader->readUInt32();
  1924. break;
  1925. }
  1926. case ESeerHutRewardType::MORALE:
  1927. {
  1928. reward.bonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::MORALE, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven));
  1929. break;
  1930. }
  1931. case ESeerHutRewardType::LUCK:
  1932. {
  1933. reward.bonuses.emplace_back(BonusDuration::ONE_BATTLE, BonusType::LUCK, BonusSource::OBJECT_INSTANCE, reader->readInt8Checked(-3, 3), BonusSourceID(idToBeGiven));
  1934. break;
  1935. }
  1936. case ESeerHutRewardType::RESOURCES:
  1937. {
  1938. auto rId = reader->readGameResID();
  1939. auto rVal = reader->readUInt32();
  1940. reward.resources[rId] = rVal;
  1941. break;
  1942. }
  1943. case ESeerHutRewardType::PRIMARY_SKILL:
  1944. {
  1945. auto rId = reader->readPrimary();
  1946. auto rVal = reader->readUInt8();
  1947. reward.primary.at(rId.getNum()) = rVal;
  1948. break;
  1949. }
  1950. case ESeerHutRewardType::SECONDARY_SKILL:
  1951. {
  1952. auto rId = reader->readSkill();
  1953. auto rVal = reader->readInt8Checked(1,3);
  1954. reward.secondary[rId] = rVal;
  1955. break;
  1956. }
  1957. case ESeerHutRewardType::ARTIFACT:
  1958. {
  1959. reward.artifacts.push_back(reader->readArtifact());
  1960. if (features.levelHOTA5)
  1961. {
  1962. SpellID scrollSpell = reader->readSpell16();
  1963. if (reward.artifacts.back() == ArtifactID::SPELL_SCROLL)
  1964. 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());
  1965. }
  1966. break;
  1967. }
  1968. case ESeerHutRewardType::SPELL:
  1969. {
  1970. reward.spells.push_back(reader->readSpell());
  1971. break;
  1972. }
  1973. case ESeerHutRewardType::CREATURE:
  1974. {
  1975. auto rId = reader->readCreature();
  1976. auto rVal = reader->readUInt16();
  1977. reward.creatures.emplace_back(rId, rVal);
  1978. break;
  1979. }
  1980. default:
  1981. {
  1982. assert(0);
  1983. }
  1984. }
  1985. vinfo.visitType = Rewardable::EEventType::EVENT_FIRST_VISIT;
  1986. hut->configuration.info.push_back(vinfo);
  1987. }
  1988. else
  1989. {
  1990. // missionType==255
  1991. reader->skipZero(1);
  1992. }
  1993. }
  1994. EQuestMission CMapLoaderH3M::readQuest(IQuestObject * guard, const int3 & position)
  1995. {
  1996. auto missionId = static_cast<EQuestMission>(reader->readInt8Checked(0, 10));
  1997. switch(missionId)
  1998. {
  1999. case EQuestMission::NONE:
  2000. return missionId;
  2001. case EQuestMission::PRIMARY_SKILL:
  2002. {
  2003. for(int x = 0; x < 4; ++x)
  2004. {
  2005. guard->quest->mission.primary[x] = reader->readUInt8();
  2006. }
  2007. break;
  2008. }
  2009. case EQuestMission::LEVEL:
  2010. {
  2011. guard->quest->mission.heroLevel = reader->readUInt32();
  2012. break;
  2013. }
  2014. case EQuestMission::KILL_HERO:
  2015. case EQuestMission::KILL_CREATURE:
  2016. {
  2017. guard->quest->killTarget = ObjectInstanceID(reader->readUInt32());
  2018. break;
  2019. }
  2020. case EQuestMission::ARTIFACT:
  2021. {
  2022. size_t artNumber = reader->readUInt8();
  2023. for(size_t yy = 0; yy < artNumber; ++yy)
  2024. {
  2025. auto artid = reader->readArtifact();
  2026. if (features.levelHOTA5)
  2027. {
  2028. SpellID scrollSpell = reader->readSpell16();
  2029. if (artid == ArtifactID::SPELL_SCROLL)
  2030. logGlobal->warn("Map '%s': Seer Hut at %s: Quest to find scroll '%s' is not implemented!", mapName, position.toString(), scrollSpell.toEntity(LIBRARY)->getJsonKey());
  2031. }
  2032. guard->quest->mission.artifacts.push_back(artid);
  2033. map->allowedArtifact.erase(artid); //these are unavailable for random generation
  2034. }
  2035. break;
  2036. }
  2037. case EQuestMission::ARMY:
  2038. {
  2039. size_t typeNumber = reader->readUInt8();
  2040. guard->quest->mission.creatures.resize(typeNumber);
  2041. for(size_t hh = 0; hh < typeNumber; ++hh)
  2042. {
  2043. guard->quest->mission.creatures[hh].setType(reader->readCreature().toCreature());
  2044. guard->quest->mission.creatures[hh].count = reader->readUInt16();
  2045. }
  2046. break;
  2047. }
  2048. case EQuestMission::RESOURCES:
  2049. {
  2050. for(int x = 0; x < 7; ++x)
  2051. guard->quest->mission.resources[x] = reader->readUInt32();
  2052. break;
  2053. }
  2054. case EQuestMission::HERO:
  2055. {
  2056. guard->quest->mission.heroes.push_back(reader->readHero());
  2057. break;
  2058. }
  2059. case EQuestMission::PLAYER:
  2060. {
  2061. guard->quest->mission.players.push_back(reader->readPlayer());
  2062. break;
  2063. }
  2064. case EQuestMission::HOTA_MULTI:
  2065. {
  2066. uint32_t missionSubID = reader->readUInt32();
  2067. assert(missionSubID < 3);
  2068. if(missionSubID == 0)
  2069. {
  2070. missionId = EQuestMission::HOTA_HERO_CLASS;
  2071. std::set<HeroClassID> heroClasses;
  2072. reader->readBitmaskHeroClassesSized(heroClasses, false);
  2073. for(auto & hc : heroClasses)
  2074. guard->quest->mission.heroClasses.push_back(hc);
  2075. break;
  2076. }
  2077. if(missionSubID == 1)
  2078. {
  2079. missionId = EQuestMission::HOTA_REACH_DATE;
  2080. guard->quest->mission.daysPassed = reader->readUInt32() + 1;
  2081. break;
  2082. }
  2083. if(missionSubID == 2)
  2084. {
  2085. missionId = EQuestMission::HOTA_GAME_DIFFICULTY;
  2086. int32_t difficultyMask = reader->readUInt32();
  2087. assert(difficultyMask > 0 && difficultyMask < 32);
  2088. logGlobal->warn("Map '%s': Seer Hut at %s: Difficulty-specific quest (%d) is not implemented!", mapName, position.toString(), difficultyMask);
  2089. break;
  2090. }
  2091. break;
  2092. }
  2093. default:
  2094. {
  2095. assert(0);
  2096. }
  2097. }
  2098. guard->quest->lastDay = reader->readInt32();
  2099. guard->quest->firstVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "firstVisit")));
  2100. guard->quest->nextVisitText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "nextVisit")));
  2101. guard->quest->completedText.appendTextID(readLocalizedString(TextIdentifier("quest", position.x, position.y, position.z, "completed")));
  2102. guard->quest->isCustomFirst = !guard->quest->firstVisitText.empty();
  2103. guard->quest->isCustomNext = !guard->quest->nextVisitText.empty();
  2104. guard->quest->isCustomComplete = !guard->quest->completedText.empty();
  2105. return missionId;
  2106. }
  2107. std::shared_ptr<CGObjectInstance> CMapLoaderH3M::readTown(const int3 & position, std::shared_ptr<const ObjectTemplate> objectTemplate)
  2108. {
  2109. auto object = std::make_shared<CGTownInstance>(map->cb);
  2110. if(features.levelAB)
  2111. object->identifier = reader->readUInt32();
  2112. setOwnerAndValidate(position, object.get(), reader->readPlayer());
  2113. std::optional<FactionID> faction;
  2114. if (objectTemplate->id == Obj::TOWN)
  2115. faction = FactionID(objectTemplate->subid);
  2116. bool hasName = reader->readBool();
  2117. if(hasName)
  2118. object->setNameTextId(readLocalizedString(TextIdentifier("town", position.x, position.y, position.z, "name")));
  2119. bool hasGarrison = reader->readBool();
  2120. if(hasGarrison)
  2121. readCreatureSet(object.get(), 7);
  2122. object->formation = static_cast<EArmyFormation>(reader->readInt8Checked(0, 1));
  2123. assert(object->formation == EArmyFormation::LOOSE || object->formation == EArmyFormation::TIGHT);
  2124. bool hasCustomBuildings = reader->readBool();
  2125. if(hasCustomBuildings)
  2126. {
  2127. std::set<BuildingID> builtBuildings;
  2128. reader->readBitmaskBuildings(builtBuildings, faction);
  2129. for(const auto & building : builtBuildings)
  2130. object->addBuilding(building);
  2131. reader->readBitmaskBuildings(object->forbiddenBuildings, faction);
  2132. }
  2133. // Standard buildings
  2134. else
  2135. {
  2136. bool hasFort = reader->readBool();
  2137. if(hasFort)
  2138. object->addBuilding(BuildingID::FORT);
  2139. //means that set of standard building should be included
  2140. object->addBuilding(BuildingID::DEFAULT);
  2141. }
  2142. if(features.levelAB)
  2143. {
  2144. std::set<SpellID> spellsMask;
  2145. reader->readBitmaskSpells(spellsMask, false);
  2146. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->obligatorySpells));
  2147. }
  2148. {
  2149. std::set<SpellID> spellsMask = LIBRARY->spellh->getDefaultAllowed(); // by default - include spells from mods
  2150. reader->readBitmaskSpells(spellsMask, true);
  2151. std::copy(spellsMask.begin(), spellsMask.end(), std::back_inserter(object->possibleSpells));
  2152. }
  2153. if(features.levelHOTA1)
  2154. object->spellResearchAllowed = reader->readBool();
  2155. if(features.levelHOTA5)
  2156. {
  2157. // Most likely customization of special buildings per faction -> 4x11 table
  2158. // presumably:
  2159. // 0 -> default / allowed
  2160. // 1 -> built?
  2161. // 2 -> banned?
  2162. uint32_t specialBuildingsSize = reader->readUInt32();
  2163. for (int i = 0; i < specialBuildingsSize; ++i)
  2164. {
  2165. int factionID = i / 4;
  2166. int buildingID = i % 4;
  2167. int8_t specialBuildingBuilt = reader->readInt8Checked(0, 2);
  2168. if (specialBuildingBuilt != 0)
  2169. 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);
  2170. }
  2171. }
  2172. // Read castle events
  2173. uint32_t eventsCount = reader->readUInt32();
  2174. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2175. {
  2176. CCastleEvent event;
  2177. event.creatures.resize(7);
  2178. readEventCommon(event, TextIdentifier("town", position.x, position.y, position.z, "event", eventID, "description"));
  2179. if(features.levelHOTA5)
  2180. {
  2181. int32_t creatureGrowth8 = reader->readInt32();
  2182. // always 44
  2183. int32_t hotaAmount = reader->readInt32();
  2184. // contains bitmask on which town-specific buildings to build
  2185. // 4 bits / town, for each of special building in town (special 1 - special 4)
  2186. int32_t hotaSpecialA = reader->readInt32();
  2187. int16_t hotaSpecialB = reader->readInt16();
  2188. if (hotaSpecialA != 0 || hotaSpecialB != 0 || hotaAmount != 44)
  2189. logGlobal->warn("Map '%s': Town at %s: Constructing town-specific special buildings in event is not implemented!", mapName, position.toString());
  2190. event.creatures.push_back(creatureGrowth8);
  2191. }
  2192. if(features.levelHOTA7)
  2193. {
  2194. [[maybe_unused]] bool neutralAffected = reader->readBool();
  2195. }
  2196. // New buildings
  2197. reader->readBitmaskBuildings(event.buildings, faction);
  2198. for(int i = 0; i < 7; ++i)
  2199. event.creatures[i] = reader->readUInt16();
  2200. reader->skipZero(4);
  2201. object->events.push_back(event);
  2202. }
  2203. if(features.levelSOD)
  2204. {
  2205. object->alignmentToPlayer = PlayerColor::NEUTRAL; // "same as owner or random"
  2206. uint8_t alignment = reader->readUInt8();
  2207. if(alignment != 255)
  2208. {
  2209. if(alignment < PlayerColor::PLAYER_LIMIT.getNum())
  2210. {
  2211. if (mapHeader->players[alignment].canAnyonePlay())
  2212. object->alignmentToPlayer = PlayerColor(alignment);
  2213. else
  2214. 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));
  2215. }
  2216. else
  2217. {
  2218. // TODO: HOTA support
  2219. uint8_t invertedAlignment = alignment - PlayerColor::PLAYER_LIMIT.getNum();
  2220. if(invertedAlignment < PlayerColor::PLAYER_LIMIT.getNum())
  2221. {
  2222. logGlobal->warn("Map '%s': Alignment of town at %s 'not as player %d' is not implemented!", mapName, position.toString(), alignment - PlayerColor::PLAYER_LIMIT.getNum());
  2223. }
  2224. else
  2225. {
  2226. logGlobal->warn("Map '%s': Alignment of town at %s is corrupted!!", mapName, position.toString());
  2227. }
  2228. }
  2229. }
  2230. }
  2231. reader->skipZero(3);
  2232. return object;
  2233. }
  2234. void CMapLoaderH3M::readEventCommon(CMapEvent & event, const TextIdentifier & messageID)
  2235. {
  2236. event.name = readBasicString();
  2237. event.message.appendTextID(readLocalizedString(messageID));
  2238. reader->readResources(event.resources);
  2239. reader->readBitmaskPlayers(event.players, false);
  2240. if(features.levelSOD)
  2241. event.humanAffected = reader->readBool();
  2242. else
  2243. event.humanAffected = true;
  2244. event.computerAffected = reader->readBool();
  2245. event.firstOccurrence = reader->readUInt16();
  2246. event.nextOccurrence = reader->readUInt16();
  2247. reader->skipZero(16);
  2248. if (features.levelHOTA7)
  2249. {
  2250. int32_t allowedDifficultiesMask = reader->readInt32();
  2251. assert(allowedDifficultiesMask > 0 && allowedDifficultiesMask < 32);
  2252. if (allowedDifficultiesMask != 31)
  2253. logGlobal->warn("Map '%s': Map event: availability by difficulty (mode %d) is not implemented!", mapName, allowedDifficultiesMask);
  2254. }
  2255. }
  2256. void CMapLoaderH3M::readEvents()
  2257. {
  2258. uint32_t eventsCount = reader->readUInt32();
  2259. for(int eventID = 0; eventID < eventsCount; ++eventID)
  2260. {
  2261. CMapEvent event;
  2262. readEventCommon(event, TextIdentifier("event", eventID, "description"));
  2263. // garbage bytes that were present in HOTA5 & HOTA6
  2264. if (features.levelHOTA5 && !features.levelHOTA7)
  2265. reader->skipUnused(14);
  2266. map->events.push_back(event);
  2267. }
  2268. }
  2269. void CMapLoaderH3M::readMessageAndGuards(MetaString & message, CCreatureSet * guards, const int3 & position)
  2270. {
  2271. bool hasMessage = reader->readBool();
  2272. if(hasMessage)
  2273. {
  2274. message.appendTextID(readLocalizedString(TextIdentifier("guards", position.x, position.y, position.z, "message")));
  2275. bool hasGuards = reader->readBool();
  2276. if(hasGuards)
  2277. readCreatureSet(guards, 7);
  2278. reader->skipZero(4);
  2279. }
  2280. }
  2281. std::string CMapLoaderH3M::readBasicString()
  2282. {
  2283. return TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2284. }
  2285. std::string CMapLoaderH3M::readLocalizedString(const TextIdentifier & stringIdentifier)
  2286. {
  2287. std::string mapString = TextOperations::toUnicode(reader->readBaseString(), fileEncoding);
  2288. TextIdentifier fullIdentifier("map", mapName, stringIdentifier.get());
  2289. if(mapString.empty())
  2290. return "";
  2291. return mapRegisterLocalizedString(modName, *mapHeader, fullIdentifier, mapString);
  2292. }
  2293. void CMapLoaderH3M::afterRead()
  2294. {
  2295. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  2296. for(auto & p : map->players)
  2297. {
  2298. int3 posOfMainTown = p.posOfMainTown;
  2299. if(posOfMainTown.isValid() && map->isInTheMap(posOfMainTown))
  2300. {
  2301. const TerrainTile & t = map->getTile(posOfMainTown);
  2302. const CGObjectInstance * mainTown = nullptr;
  2303. for(auto * obj : t.visitableObjects)
  2304. {
  2305. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  2306. {
  2307. mainTown = obj;
  2308. break;
  2309. }
  2310. }
  2311. if(mainTown == nullptr)
  2312. continue;
  2313. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  2314. }
  2315. }
  2316. map->resolveQuestIdentifiers();
  2317. }
  2318. VCMI_LIB_NAMESPACE_END