MapFormatH3M.cpp 57 KB

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