MapFormatH3M.cpp 61 KB

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