MapFormatH3M.cpp 70 KB

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