MapFormatH3M.cpp 86 KB

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