MapFormatH3M.cpp 57 KB

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