MapFormatH3M.cpp 61 KB

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