MapFormatH3M.cpp 58 KB

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