MapFormatH3M.cpp 58 KB

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