2
0

MapFormatH3M.cpp 58 KB

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