MapFormatH3M.cpp 87 KB

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