2
0

MapFormatH3M.cpp 56 KB

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