MapFormatH3M.cpp 57 KB

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