MapFormatH3M.cpp 56 KB

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