MapFormatH3M.cpp 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266
  1. /*
  2. * MapFormatH3M.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <boost/crc.hpp>
  12. #include "MapFormatH3M.h"
  13. #include "CMap.h"
  14. #include "../CStopWatch.h"
  15. #include "../filesystem/Filesystem.h"
  16. #include "../spells/CSpellHandler.h"
  17. #include "../CSkillHandler.h"
  18. #include "../CCreatureHandler.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../CHeroHandler.h"
  21. #include "../mapObjects/CObjectClassesHandler.h"
  22. #include "../mapObjects/MapObjects.h"
  23. #include "../VCMI_Lib.h"
  24. #include "../NetPacksBase.h"
  25. const bool CMapLoaderH3M::IS_PROFILING_ENABLED = false;
  26. CMapLoaderH3M::CMapLoaderH3M(CInputStream * stream) : map(nullptr), reader(stream),inputStream(stream)
  27. {
  28. }
  29. CMapLoaderH3M::~CMapLoaderH3M()
  30. {
  31. }
  32. std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
  33. {
  34. // Init map object by parsing the input buffer
  35. map = new CMap();
  36. mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
  37. init();
  38. return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
  39. }
  40. std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
  41. {
  42. // Read header
  43. mapHeader = make_unique<CMapHeader>();
  44. readHeader();
  45. return std::move(mapHeader);
  46. }
  47. void CMapLoaderH3M::init()
  48. {
  49. //FIXME: get rid of double input process
  50. si64 temp_size = inputStream->getSize();
  51. inputStream->seek(0);
  52. auto temp_buffer = new ui8[temp_size];
  53. inputStream->read(temp_buffer,temp_size);
  54. // Compute checksum
  55. boost::crc_32_type result;
  56. result.process_bytes(temp_buffer, temp_size);
  57. map->checksum = result.checksum();
  58. delete [] temp_buffer;
  59. inputStream->seek(0);
  60. CStopWatch sw;
  61. struct MapLoadingTime
  62. {
  63. std::string name;
  64. si64 time;
  65. MapLoadingTime(std::string name, si64 time) : name(name),
  66. time(time)
  67. {
  68. }
  69. };
  70. std::vector<MapLoadingTime> times;
  71. readHeader();
  72. times.push_back(MapLoadingTime("header", sw.getDiff()));
  73. map->allHeroes.resize(map->allowedHeroes.size());
  74. readDisposedHeroes();
  75. times.push_back(MapLoadingTime("disposed heroes", sw.getDiff()));
  76. readAllowedArtifacts();
  77. times.push_back(MapLoadingTime("allowed artifacts", sw.getDiff()));
  78. readAllowedSpellsAbilities();
  79. times.push_back(MapLoadingTime("allowed spells and abilities", sw.getDiff()));
  80. readRumors();
  81. times.push_back(MapLoadingTime("rumors", sw.getDiff()));
  82. readPredefinedHeroes();
  83. times.push_back(MapLoadingTime("predefined heroes", sw.getDiff()));
  84. readTerrain();
  85. times.push_back(MapLoadingTime("terrain", sw.getDiff()));
  86. readDefInfo();
  87. times.push_back(MapLoadingTime("def info", sw.getDiff()));
  88. readObjects();
  89. times.push_back(MapLoadingTime("objects", sw.getDiff()));
  90. readEvents();
  91. times.push_back(MapLoadingTime("events", sw.getDiff()));
  92. times.push_back(MapLoadingTime("blocked/visitable tiles", sw.getDiff()));
  93. // Print profiling times
  94. if(IS_PROFILING_ENABLED)
  95. {
  96. for(MapLoadingTime & mlt : times)
  97. {
  98. logGlobal->debug("\tReading %s took %d ms", mlt.name, mlt.time);
  99. }
  100. }
  101. map->calculateGuardingGreaturePositions();
  102. afterRead();
  103. }
  104. void CMapLoaderH3M::readHeader()
  105. {
  106. // Check map for validity
  107. // Note: disabled, causes decompression of the entire file ( = SLOW)
  108. //if(inputStream->getSize() < 50)
  109. //{
  110. // throw std::runtime_error("Corrupted map file.");
  111. //}
  112. // Map version
  113. mapHeader->version = (EMapFormat::EMapFormat)(reader.readUInt32());
  114. if(mapHeader->version != EMapFormat::ROE && mapHeader->version != EMapFormat::AB && mapHeader->version != EMapFormat::SOD
  115. && mapHeader->version != EMapFormat::WOG)
  116. {
  117. throw std::runtime_error("Invalid map format!");
  118. }
  119. // Read map name, description, dimensions,...
  120. mapHeader->areAnyPlayers = reader.readBool();
  121. mapHeader->height = mapHeader->width = reader.readUInt32();
  122. mapHeader->twoLevel = reader.readBool();
  123. mapHeader->name = reader.readString();
  124. mapHeader->description = reader.readString();
  125. mapHeader->difficulty = reader.readInt8();
  126. if(mapHeader->version != EMapFormat::ROE)
  127. {
  128. mapHeader->levelLimit = reader.readUInt8();
  129. }
  130. else
  131. {
  132. mapHeader->levelLimit = 0;
  133. }
  134. readPlayerInfo();
  135. readVictoryLossConditions();
  136. readTeamInfo();
  137. readAllowedHeroes();
  138. }
  139. void CMapLoaderH3M::readPlayerInfo()
  140. {
  141. for(int i = 0; i < mapHeader->players.size(); ++i)
  142. {
  143. mapHeader->players[i].canHumanPlay = reader.readBool();
  144. mapHeader->players[i].canComputerPlay = reader.readBool();
  145. // If nobody can play with this player
  146. if((!(mapHeader->players[i].canHumanPlay || mapHeader->players[i].canComputerPlay)))
  147. {
  148. switch(mapHeader->version)
  149. {
  150. case EMapFormat::SOD:
  151. case EMapFormat::WOG:
  152. reader.skip(13);
  153. break;
  154. case EMapFormat::AB:
  155. reader.skip(12);
  156. break;
  157. case EMapFormat::ROE:
  158. reader.skip(6);
  159. break;
  160. }
  161. continue;
  162. }
  163. mapHeader->players[i].aiTactic = static_cast<EAiTactic::EAiTactic>(reader.readUInt8());
  164. if(mapHeader->version == EMapFormat::SOD || mapHeader->version == EMapFormat::WOG)
  165. {
  166. mapHeader->players[i].p7 = reader.readUInt8();
  167. }
  168. else
  169. {
  170. mapHeader->players[i].p7 = -1;
  171. }
  172. // Factions this player can choose
  173. ui16 allowedFactions = reader.readUInt8();
  174. // How many factions will be read from map
  175. ui16 totalFactions = GameConstants::F_NUMBER;
  176. if(mapHeader->version != EMapFormat::ROE)
  177. allowedFactions += reader.readUInt8() * 256; // 256 = 2^8 = 0b100000000
  178. else
  179. totalFactions--; //exclude conflux for ROE
  180. const bool isFactionRandom = mapHeader->players[i].isFactionRandom = reader.readBool();
  181. const ui16 allFactionsMask = (mapHeader->version == EMapFormat::ROE)
  182. ? 0b11111111 // 8 towns for ROE
  183. : 0b111111111; // 8 towns + Conflux
  184. const bool allFactionsAllowed = mapHeader->version == EMapFormat::VCMI
  185. || (isFactionRandom && ((allowedFactions & allFactionsMask) == allFactionsMask));
  186. if(!allFactionsAllowed)
  187. {
  188. mapHeader->players[i].allowedFactions.clear();
  189. for(int fact = 0; fact < totalFactions; ++fact)
  190. {
  191. if(allowedFactions & (1 << fact))
  192. mapHeader->players[i].allowedFactions.insert(fact);
  193. }
  194. }
  195. mapHeader->players[i].hasMainTown = reader.readBool();
  196. if(mapHeader->players[i].hasMainTown)
  197. {
  198. if(mapHeader->version != EMapFormat::ROE)
  199. {
  200. mapHeader->players[i].generateHeroAtMainTown = reader.readBool();
  201. mapHeader->players[i].generateHero = reader.readBool();
  202. }
  203. else
  204. {
  205. mapHeader->players[i].generateHeroAtMainTown = true;
  206. mapHeader->players[i].generateHero = false;
  207. }
  208. mapHeader->players[i].posOfMainTown = readInt3();
  209. }
  210. mapHeader->players[i].hasRandomHero = reader.readBool();
  211. mapHeader->players[i].mainCustomHeroId = reader.readUInt8();
  212. if(mapHeader->players[i].mainCustomHeroId != 0xff)
  213. {
  214. mapHeader->players[i].mainCustomHeroPortrait = reader.readUInt8();
  215. if (mapHeader->players[i].mainCustomHeroPortrait == 0xff)
  216. mapHeader->players[i].mainCustomHeroPortrait = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  217. mapHeader->players[i].mainCustomHeroName = reader.readString();
  218. }
  219. else
  220. mapHeader->players[i].mainCustomHeroId = -1; //correct 1-byte -1 (0xff) into 4-byte -1
  221. if(mapHeader->version != EMapFormat::ROE)
  222. {
  223. mapHeader->players[i].powerPlaceholders = reader.readUInt8(); //unknown byte
  224. int heroCount = reader.readUInt8();
  225. reader.skip(3);
  226. for(int pp = 0; pp < heroCount; ++pp)
  227. {
  228. SHeroName vv;
  229. vv.heroId = reader.readUInt8();
  230. vv.heroName = reader.readString();
  231. mapHeader->players[i].heroesNames.push_back(vv);
  232. }
  233. }
  234. }
  235. }
  236. namespace EVictoryConditionType
  237. {
  238. enum EVictoryConditionType { ARTIFACT, GATHERTROOP, GATHERRESOURCE, BUILDCITY, BUILDGRAIL, BEATHERO,
  239. CAPTURECITY, BEATMONSTER, TAKEDWELLINGS, TAKEMINES, TRANSPORTITEM, WINSTANDARD = 255 };
  240. }
  241. namespace ELossConditionType
  242. {
  243. enum ELossConditionType { LOSSCASTLE, LOSSHERO, TIMEEXPIRES, LOSSSTANDARD = 255 };
  244. }
  245. void CMapLoaderH3M::readVictoryLossConditions()
  246. {
  247. mapHeader->triggeredEvents.clear();
  248. auto vicCondition = (EVictoryConditionType::EVictoryConditionType)reader.readUInt8();
  249. EventCondition victoryCondition(EventCondition::STANDARD_WIN);
  250. EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
  251. defeatCondition.value = 7;
  252. TriggeredEvent standardVictory;
  253. standardVictory.effect.type = EventEffect::VICTORY;
  254. standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  255. standardVictory.identifier = "standardVictory";
  256. standardVictory.description = ""; // TODO: display in quest window
  257. standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
  258. standardVictory.trigger = EventExpression(victoryCondition);
  259. TriggeredEvent standardDefeat;
  260. standardDefeat.effect.type = EventEffect::DEFEAT;
  261. standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
  262. standardDefeat.identifier = "standardDefeat";
  263. standardDefeat.description = ""; // TODO: display in quest window
  264. standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
  265. standardDefeat.trigger = EventExpression(defeatCondition);
  266. // Specific victory conditions
  267. if(vicCondition == EVictoryConditionType::WINSTANDARD)
  268. {
  269. // create normal condition
  270. mapHeader->triggeredEvents.push_back(standardVictory);
  271. mapHeader->victoryIconIndex = 11;
  272. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
  273. }
  274. else
  275. {
  276. TriggeredEvent specialVictory;
  277. specialVictory.effect.type = EventEffect::VICTORY;
  278. specialVictory.identifier = "specialVictory";
  279. specialVictory.description = ""; // TODO: display in quest window
  280. mapHeader->victoryIconIndex = ui16(vicCondition);
  281. mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[size_t(vicCondition) + 1];
  282. bool allowNormalVictory = reader.readBool();
  283. bool appliesToAI = reader.readBool();
  284. if (allowNormalVictory)
  285. {
  286. size_t playersOnMap = boost::range::count_if(mapHeader->players,[](const PlayerInfo & info) { return info.canAnyonePlay();});
  287. if (playersOnMap == 1)
  288. {
  289. logGlobal->warn("Map %s has only one player but allows normal victory?", mapHeader->name);
  290. allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
  291. }
  292. }
  293. switch(vicCondition)
  294. {
  295. case EVictoryConditionType::ARTIFACT:
  296. {
  297. EventCondition cond(EventCondition::HAVE_ARTIFACT);
  298. cond.objectType = reader.readUInt8();
  299. if (mapHeader->version != EMapFormat::ROE)
  300. reader.skip(1);
  301. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
  302. specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
  303. specialVictory.trigger = EventExpression(cond);
  304. break;
  305. }
  306. case EVictoryConditionType::GATHERTROOP:
  307. {
  308. EventCondition cond(EventCondition::HAVE_CREATURES);
  309. cond.objectType = reader.readUInt8();
  310. if (mapHeader->version != EMapFormat::ROE)
  311. reader.skip(1);
  312. cond.value = reader.readUInt32();
  313. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
  314. specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
  315. specialVictory.trigger = EventExpression(cond);
  316. break;
  317. }
  318. case EVictoryConditionType::GATHERRESOURCE:
  319. {
  320. EventCondition cond(EventCondition::HAVE_RESOURCES);
  321. cond.objectType = reader.readUInt8();
  322. cond.value = reader.readUInt32();
  323. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
  324. specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
  325. specialVictory.trigger = EventExpression(cond);
  326. break;
  327. }
  328. case EVictoryConditionType::BUILDCITY:
  329. {
  330. EventExpression::OperatorAll oper;
  331. EventCondition cond(EventCondition::HAVE_BUILDING);
  332. cond.position = readInt3();
  333. cond.objectType = BuildingID::VILLAGE_HALL + reader.readUInt8();
  334. oper.expressions.push_back(cond);
  335. cond.objectType = BuildingID::FORT + reader.readUInt8();
  336. oper.expressions.push_back(cond);
  337. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
  338. specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
  339. specialVictory.trigger = EventExpression(oper);
  340. break;
  341. }
  342. case EVictoryConditionType::BUILDGRAIL:
  343. {
  344. EventCondition cond(EventCondition::HAVE_BUILDING);
  345. cond.objectType = BuildingID::GRAIL;
  346. cond.position = readInt3();
  347. if(cond.position.z > 2)
  348. cond.position = int3(-1,-1,-1);
  349. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
  350. specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
  351. specialVictory.trigger = EventExpression(cond);
  352. break;
  353. }
  354. case EVictoryConditionType::BEATHERO:
  355. {
  356. EventCondition cond(EventCondition::DESTROY);
  357. cond.objectType = Obj::HERO;
  358. cond.position = readInt3();
  359. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
  360. specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
  361. specialVictory.trigger = EventExpression(cond);
  362. break;
  363. }
  364. case EVictoryConditionType::CAPTURECITY:
  365. {
  366. EventCondition cond(EventCondition::CONTROL);
  367. cond.objectType = Obj::TOWN;
  368. cond.position = readInt3();
  369. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
  370. specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
  371. specialVictory.trigger = EventExpression(cond);
  372. break;
  373. }
  374. case EVictoryConditionType::BEATMONSTER:
  375. {
  376. EventCondition cond(EventCondition::DESTROY);
  377. cond.objectType = Obj::MONSTER;
  378. cond.position = readInt3();
  379. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
  380. specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
  381. specialVictory.trigger = EventExpression(cond);
  382. break;
  383. }
  384. case EVictoryConditionType::TAKEDWELLINGS:
  385. {
  386. EventExpression::OperatorAll oper;
  387. oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
  388. oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));
  389. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
  390. specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
  391. specialVictory.trigger = EventExpression(oper);
  392. break;
  393. }
  394. case EVictoryConditionType::TAKEMINES:
  395. {
  396. EventCondition cond(EventCondition::CONTROL);
  397. cond.objectType = Obj::MINE;
  398. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
  399. specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
  400. specialVictory.trigger = EventExpression(cond);
  401. break;
  402. }
  403. case EVictoryConditionType::TRANSPORTITEM:
  404. {
  405. EventCondition cond(EventCondition::TRANSPORT);
  406. cond.objectType = reader.readUInt8();
  407. cond.position = readInt3();
  408. specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
  409. specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
  410. specialVictory.trigger = EventExpression(cond);
  411. break;
  412. }
  413. default:
  414. assert(0);
  415. }
  416. // if condition is human-only turn it into following construction: AllOf(human, condition)
  417. if (!appliesToAI)
  418. {
  419. EventExpression::OperatorAll oper;
  420. EventCondition notAI(EventCondition::IS_HUMAN);
  421. notAI.value = 1;
  422. oper.expressions.push_back(notAI);
  423. oper.expressions.push_back(specialVictory.trigger.get());
  424. specialVictory.trigger = EventExpression(oper);
  425. }
  426. // if normal victory allowed - add one more quest
  427. if (allowNormalVictory)
  428. {
  429. mapHeader->victoryMessage += " / ";
  430. mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
  431. mapHeader->triggeredEvents.push_back(standardVictory);
  432. }
  433. mapHeader->triggeredEvents.push_back(specialVictory);
  434. }
  435. // Read loss conditions
  436. auto lossCond = (ELossConditionType::ELossConditionType)reader.readUInt8();
  437. if (lossCond == ELossConditionType::LOSSSTANDARD)
  438. {
  439. mapHeader->defeatIconIndex = 3;
  440. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
  441. }
  442. else
  443. {
  444. TriggeredEvent specialDefeat;
  445. specialDefeat.effect.type = EventEffect::DEFEAT;
  446. specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
  447. specialDefeat.identifier = "specialDefeat";
  448. specialDefeat.description = ""; // TODO: display in quest window
  449. mapHeader->defeatIconIndex = ui16(lossCond);
  450. mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[size_t(lossCond) + 1];
  451. switch(lossCond)
  452. {
  453. case ELossConditionType::LOSSCASTLE:
  454. {
  455. EventExpression::OperatorNone noneOf;
  456. EventCondition cond(EventCondition::CONTROL);
  457. cond.objectType = Obj::TOWN;
  458. cond.position = readInt3();
  459. noneOf.expressions.push_back(cond);
  460. specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
  461. specialDefeat.trigger = EventExpression(noneOf);
  462. break;
  463. }
  464. case ELossConditionType::LOSSHERO:
  465. {
  466. EventExpression::OperatorNone noneOf;
  467. EventCondition cond(EventCondition::CONTROL);
  468. cond.objectType = Obj::HERO;
  469. cond.position = readInt3();
  470. noneOf.expressions.push_back(cond);
  471. specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
  472. specialDefeat.trigger = EventExpression(noneOf);
  473. break;
  474. }
  475. case ELossConditionType::TIMEEXPIRES:
  476. {
  477. EventCondition cond(EventCondition::DAYS_PASSED);
  478. cond.value = reader.readUInt16();
  479. specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
  480. specialDefeat.trigger = EventExpression(cond);
  481. break;
  482. }
  483. }
  484. // turn simple loss condition into complete one that can be evaluated later:
  485. // - any of :
  486. // - days without town: 7
  487. // - all of:
  488. // - is human
  489. // - (expression)
  490. EventExpression::OperatorAll allOf;
  491. EventCondition isHuman(EventCondition::IS_HUMAN);
  492. isHuman.value = 1;
  493. allOf.expressions.push_back(isHuman);
  494. allOf.expressions.push_back(specialDefeat.trigger.get());
  495. specialDefeat.trigger = EventExpression(allOf);
  496. mapHeader->triggeredEvents.push_back(specialDefeat);
  497. }
  498. mapHeader->triggeredEvents.push_back(standardDefeat);
  499. }
  500. void CMapLoaderH3M::readTeamInfo()
  501. {
  502. mapHeader->howManyTeams = reader.readUInt8();
  503. if(mapHeader->howManyTeams > 0)
  504. {
  505. // Teams
  506. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  507. {
  508. mapHeader->players[i].team = TeamID(reader.readUInt8());
  509. }
  510. }
  511. else
  512. {
  513. // No alliances
  514. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  515. {
  516. if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
  517. {
  518. mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
  519. }
  520. }
  521. }
  522. }
  523. void CMapLoaderH3M::readAllowedHeroes()
  524. {
  525. mapHeader->allowedHeroes.resize(VLC->heroh->size(), true);
  526. const int bytes = mapHeader->version == EMapFormat::ROE ? 16 : 20;
  527. readBitmask(mapHeader->allowedHeroes,bytes,GameConstants::HEROES_QUANTITY, false);
  528. // Probably reserved for further heroes
  529. if(mapHeader->version > EMapFormat::ROE)
  530. {
  531. int placeholdersQty = reader.readUInt32();
  532. reader.skip(placeholdersQty * 1);
  533. // std::vector<ui16> placeholdedHeroes;
  534. //
  535. // for(int p = 0; p < placeholdersQty; ++p)
  536. // {
  537. // placeholdedHeroes.push_back(reader.readUInt8());
  538. // }
  539. }
  540. }
  541. void CMapLoaderH3M::readDisposedHeroes()
  542. {
  543. // Reading disposed heroes (20 bytes)
  544. if(map->version >= EMapFormat::SOD)
  545. {
  546. ui8 disp = reader.readUInt8();
  547. map->disposedHeroes.resize(disp);
  548. for(int g = 0; g < disp; ++g)
  549. {
  550. map->disposedHeroes[g].heroId = reader.readUInt8();
  551. map->disposedHeroes[g].portrait = reader.readUInt8();
  552. map->disposedHeroes[g].name = reader.readString();
  553. map->disposedHeroes[g].players = reader.readUInt8();
  554. }
  555. }
  556. //omitting NULLS
  557. reader.skip(31);
  558. }
  559. void CMapLoaderH3M::readAllowedArtifacts()
  560. {
  561. map->allowedArtifact.resize (VLC->arth->objects.size(),true); //handle new artifacts, make them allowed by default
  562. // Reading allowed artifacts: 17 or 18 bytes
  563. if(map->version != EMapFormat::ROE)
  564. {
  565. const int bytes = map->version == EMapFormat::AB ? 17 : 18;
  566. readBitmask(map->allowedArtifact,bytes,GameConstants::ARTIFACTS_QUANTITY);
  567. }
  568. // ban combo artifacts
  569. if (map->version == EMapFormat::ROE || map->version == EMapFormat::AB)
  570. {
  571. for(CArtifact * artifact : VLC->arth->objects)
  572. {
  573. // combo
  574. if (artifact->constituents)
  575. {
  576. map->allowedArtifact[artifact->id] = false;
  577. }
  578. }
  579. if (map->version == EMapFormat::ROE)
  580. {
  581. map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
  582. }
  583. }
  584. // Messy, but needed
  585. for (TriggeredEvent & event : map->triggeredEvents)
  586. {
  587. auto patcher = [&](EventCondition cond) -> EventExpression::Variant
  588. {
  589. if (cond.condition == EventCondition::HAVE_ARTIFACT ||
  590. cond.condition == EventCondition::TRANSPORT)
  591. {
  592. map->allowedArtifact[cond.objectType] = false;
  593. }
  594. return cond;
  595. };
  596. event.trigger = event.trigger.morph(patcher);
  597. }
  598. }
  599. void CMapLoaderH3M::readAllowedSpellsAbilities()
  600. {
  601. // Read allowed spells, including new ones
  602. map->allowedSpell.resize(VLC->spellh->objects.size(), true);
  603. // Read allowed abilities
  604. map->allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);
  605. if(map->version >= EMapFormat::SOD)
  606. {
  607. // Reading allowed spells (9 bytes)
  608. const int spell_bytes = 9;
  609. readBitmask(map->allowedSpell, spell_bytes, GameConstants::SPELLS_QUANTITY);
  610. // Allowed hero's abilities (4 bytes)
  611. const int abil_bytes = 4;
  612. readBitmask(map->allowedAbilities, abil_bytes, GameConstants::SKILL_QUANTITY);
  613. }
  614. //do not generate special abilities and spells
  615. for (auto spell : VLC->spellh->objects)
  616. if (spell->isSpecial() || spell->isCreatureAbility())
  617. map->allowedSpell[spell->id] = false;
  618. }
  619. void CMapLoaderH3M::readRumors()
  620. {
  621. int rumNr = reader.readUInt32();
  622. for(int it = 0; it < rumNr; it++)
  623. {
  624. Rumor ourRumor;
  625. ourRumor.name = reader.readString();
  626. ourRumor.text = reader.readString();
  627. map->rumors.push_back(ourRumor);
  628. }
  629. }
  630. void CMapLoaderH3M::readPredefinedHeroes()
  631. {
  632. switch(map->version)
  633. {
  634. case EMapFormat::WOG:
  635. case EMapFormat::SOD:
  636. {
  637. // Disposed heroes
  638. for(int z = 0; z < GameConstants::HEROES_QUANTITY; z++)
  639. {
  640. int custom = reader.readUInt8();
  641. if(!custom) continue;
  642. auto hero = new CGHeroInstance();
  643. hero->ID = Obj::HERO;
  644. hero->subID = z;
  645. bool hasExp = reader.readBool();
  646. if(hasExp)
  647. {
  648. hero->exp = reader.readUInt32();
  649. }
  650. else
  651. {
  652. hero->exp = 0;
  653. }
  654. bool hasSecSkills = reader.readBool();
  655. if(hasSecSkills)
  656. {
  657. int howMany = reader.readUInt32();
  658. hero->secSkills.resize(howMany);
  659. for(int yy = 0; yy < howMany; ++yy)
  660. {
  661. hero->secSkills[yy].first = SecondarySkill(reader.readUInt8());
  662. hero->secSkills[yy].second = reader.readUInt8();
  663. }
  664. }
  665. loadArtifactsOfHero(hero);
  666. bool hasCustomBio = reader.readBool();
  667. if(hasCustomBio)
  668. {
  669. hero->biography = reader.readString();
  670. }
  671. // 0xFF is default, 00 male, 01 female
  672. hero->sex = reader.readUInt8();
  673. bool hasCustomSpells = reader.readBool();
  674. if(hasCustomSpells)
  675. {
  676. readSpells(hero->spells);
  677. }
  678. bool hasCustomPrimSkills = reader.readBool();
  679. if(hasCustomPrimSkills)
  680. {
  681. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; xx++)
  682. {
  683. hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  684. }
  685. }
  686. map->predefinedHeroes.push_back(hero);
  687. }
  688. break;
  689. }
  690. case EMapFormat::ROE:
  691. break;
  692. }
  693. }
  694. void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
  695. {
  696. bool artSet = reader.readBool();
  697. // True if artifact set is not default (hero has some artifacts)
  698. if(artSet)
  699. {
  700. if(hero->artifactsWorn.size() || hero->artifactsInBackpack.size())
  701. {
  702. 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());
  703. hero->artifactsInBackpack.clear();
  704. while(hero->artifactsWorn.size())
  705. hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
  706. }
  707. for(int pom = 0; pom < 16; pom++)
  708. {
  709. loadArtifactToSlot(hero, pom);
  710. }
  711. // misc5 art //17
  712. if(map->version >= EMapFormat::SOD)
  713. {
  714. assert(!hero->getArt(ArtifactPosition::MACH4));
  715. if(!loadArtifactToSlot(hero, ArtifactPosition::MACH4))
  716. {
  717. // catapult by default
  718. assert(!hero->getArt(ArtifactPosition::MACH4));
  719. hero->putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createArtifact(map, ArtifactID::CATAPULT));
  720. }
  721. }
  722. loadArtifactToSlot(hero, ArtifactPosition::SPELLBOOK);
  723. // 19 //???what is that? gap in file or what? - it's probably fifth slot..
  724. if(map->version > EMapFormat::ROE)
  725. {
  726. loadArtifactToSlot(hero, ArtifactPosition::MISC5);
  727. }
  728. else
  729. {
  730. reader.skip(1);
  731. }
  732. // bag artifacts //20
  733. // number of artifacts in hero's bag
  734. int amount = reader.readUInt16();
  735. for(int ss = 0; ss < amount; ++ss)
  736. {
  737. loadArtifactToSlot(hero, GameConstants::BACKPACK_START + (int)hero->artifactsInBackpack.size());
  738. }
  739. }
  740. }
  741. bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
  742. {
  743. const int artmask = map->version == EMapFormat::ROE ? 0xff : 0xffff;
  744. int aid;
  745. if(map->version == EMapFormat::ROE)
  746. {
  747. aid = reader.readUInt8();
  748. }
  749. else
  750. {
  751. aid = reader.readUInt16();
  752. }
  753. bool isArt = aid != artmask;
  754. if(isArt)
  755. {
  756. const Artifact * art = ArtifactID(aid).toArtifact(VLC->artifacts());
  757. if(nullptr == art)
  758. {
  759. logGlobal->warn("Invalid artifact in hero's backpack, ignoring...");
  760. return false;
  761. }
  762. if(art->isBig() && slot >= GameConstants::BACKPACK_START)
  763. {
  764. logGlobal->warn("A big artifact (war machine) in hero's backpack, ignoring...");
  765. return false;
  766. }
  767. if(aid == 0 && slot == ArtifactPosition::MISC5)
  768. {
  769. //TODO: check how H3 handles it -> art 0 in slot 18 in AB map
  770. logGlobal->warn("Spellbook to MISC5 slot? Putting it spellbook place. AB format peculiarity? (format %d)", static_cast<int>(map->version));
  771. slot = ArtifactPosition::SPELLBOOK;
  772. }
  773. // this is needed, because some H3M maps (last scenario of ROE map) contain invalid data like misplaced artifacts
  774. auto artifact = CArtifactInstance::createArtifact(map, aid);
  775. auto artifactPos = ArtifactPosition(slot);
  776. if (artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
  777. {
  778. hero->putArtifact(artifactPos, artifact);
  779. }
  780. else
  781. {
  782. logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
  783. }
  784. }
  785. return isArt;
  786. }
  787. void CMapLoaderH3M::readTerrain()
  788. {
  789. map->initTerrain();
  790. // Read terrain
  791. for(int a = 0; a < 2; ++a)
  792. {
  793. if(a == 1 && !map->twoLevel)
  794. {
  795. break;
  796. }
  797. for(int c = 0; c < map->width; c++)
  798. {
  799. for(int z = 0; z < map->height; z++)
  800. {
  801. auto & tile = map->getTile(int3(z, c, a));
  802. tile.terType = Terrain::createTerrainTypeH3M(reader.readUInt8());
  803. tile.terView = reader.readUInt8();
  804. tile.riverType = RIVER_NAMES[reader.readUInt8()];
  805. tile.riverDir = reader.readUInt8();
  806. tile.roadType = ROAD_NAMES[reader.readUInt8()];
  807. tile.roadDir = reader.readUInt8();
  808. tile.extTileFlags = reader.readUInt8();
  809. tile.blocked = ((!tile.terType.isPassable() || tile.terType == Terrain("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. int 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 = 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. if(nhi->patrol.patrolRadius == 0xff)
  1450. {
  1451. nhi->patrol.patrolling = false;
  1452. }
  1453. else
  1454. {
  1455. nhi->patrol.patrolling = true;
  1456. nhi->patrol.initialPos = CGHeroInstance::convertPosition(initialPos, false);
  1457. }
  1458. if(map->version > EMapFormat::ROE)
  1459. {
  1460. bool hasCustomBiography = reader.readBool();
  1461. if(hasCustomBiography)
  1462. {
  1463. nhi->biography = reader.readString();
  1464. }
  1465. nhi->sex = reader.readUInt8();
  1466. // Remove trash
  1467. if (nhi->sex != 0xFF)
  1468. {
  1469. nhi->sex &= 1;
  1470. }
  1471. }
  1472. else
  1473. {
  1474. nhi->sex = 0xFF;
  1475. }
  1476. // Spells
  1477. if(map->version > EMapFormat::AB)
  1478. {
  1479. bool hasCustomSpells = reader.readBool();
  1480. if(nhi->spells.size())
  1481. {
  1482. nhi->clear();
  1483. 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);
  1484. }
  1485. if(hasCustomSpells)
  1486. {
  1487. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1488. readSpells(nhi->spells);
  1489. }
  1490. }
  1491. else if(map->version == EMapFormat::AB)
  1492. {
  1493. //we can read one spell
  1494. ui8 buff = reader.readUInt8();
  1495. if(buff != 254)
  1496. {
  1497. nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
  1498. if(buff < 254) //255 means no spells
  1499. {
  1500. nhi->spells.insert(SpellID(buff));
  1501. }
  1502. }
  1503. }
  1504. if(map->version > EMapFormat::AB)
  1505. {
  1506. bool hasCustomPrimSkills = reader.readBool();
  1507. if(hasCustomPrimSkills)
  1508. {
  1509. auto ps = nhi->getAllBonuses(Selector::type()(Bonus::PRIMARY_SKILL)
  1510. .And(Selector::sourceType()(Bonus::HERO_BASE_SKILL)), nullptr);
  1511. if(ps->size())
  1512. {
  1513. 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);
  1514. for(auto b : *ps)
  1515. nhi->removeBonus(b);
  1516. }
  1517. for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
  1518. {
  1519. nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
  1520. }
  1521. }
  1522. }
  1523. reader.skip(16);
  1524. return nhi;
  1525. }
  1526. CGSeerHut * CMapLoaderH3M::readSeerHut()
  1527. {
  1528. auto hut = new CGSeerHut();
  1529. if(map->version > EMapFormat::ROE)
  1530. {
  1531. readQuest(hut);
  1532. }
  1533. else
  1534. {
  1535. //RoE
  1536. int artID = reader.readUInt8();
  1537. if (artID != 255)
  1538. {
  1539. //not none quest
  1540. hut->quest->m5arts.push_back (artID);
  1541. hut->quest->missionType = CQuest::MISSION_ART;
  1542. }
  1543. else
  1544. {
  1545. hut->quest->missionType = CQuest::MISSION_NONE;
  1546. }
  1547. hut->quest->lastDay = -1; //no timeout
  1548. hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
  1549. }
  1550. if (hut->quest->missionType)
  1551. {
  1552. auto rewardType = static_cast<CGSeerHut::ERewardType>(reader.readUInt8());
  1553. hut->rewardType = rewardType;
  1554. switch(rewardType)
  1555. {
  1556. case CGSeerHut::EXPERIENCE:
  1557. {
  1558. hut->rVal = reader.readUInt32();
  1559. break;
  1560. }
  1561. case CGSeerHut::MANA_POINTS:
  1562. {
  1563. hut->rVal = reader.readUInt32();
  1564. break;
  1565. }
  1566. case CGSeerHut::MORALE_BONUS:
  1567. {
  1568. hut->rVal = reader.readUInt8();
  1569. break;
  1570. }
  1571. case CGSeerHut::LUCK_BONUS:
  1572. {
  1573. hut->rVal = reader.readUInt8();
  1574. break;
  1575. }
  1576. case CGSeerHut::RESOURCES:
  1577. {
  1578. hut->rID = reader.readUInt8();
  1579. // Only the first 3 bytes are used. Skip the 4th.
  1580. hut->rVal = reader.readUInt32() & 0x00ffffff;
  1581. break;
  1582. }
  1583. case CGSeerHut::PRIMARY_SKILL:
  1584. {
  1585. hut->rID = reader.readUInt8();
  1586. hut->rVal = reader.readUInt8();
  1587. break;
  1588. }
  1589. case CGSeerHut::SECONDARY_SKILL:
  1590. {
  1591. hut->rID = reader.readUInt8();
  1592. hut->rVal = reader.readUInt8();
  1593. break;
  1594. }
  1595. case CGSeerHut::ARTIFACT:
  1596. {
  1597. if (map->version == EMapFormat::ROE)
  1598. {
  1599. hut->rID = reader.readUInt8();
  1600. }
  1601. else
  1602. {
  1603. hut->rID = reader.readUInt16();
  1604. }
  1605. break;
  1606. }
  1607. case CGSeerHut::SPELL:
  1608. {
  1609. hut->rID = reader.readUInt8();
  1610. break;
  1611. }
  1612. case CGSeerHut::CREATURE:
  1613. {
  1614. if(map->version > EMapFormat::ROE)
  1615. {
  1616. hut->rID = reader.readUInt16();
  1617. hut->rVal = reader.readUInt16();
  1618. }
  1619. else
  1620. {
  1621. hut->rID = reader.readUInt8();
  1622. hut->rVal = reader.readUInt16();
  1623. }
  1624. break;
  1625. }
  1626. }
  1627. reader.skip(2);
  1628. }
  1629. else
  1630. {
  1631. // missionType==255
  1632. reader.skip(3);
  1633. }
  1634. return hut;
  1635. }
  1636. void CMapLoaderH3M::readQuest(IQuestObject * guard)
  1637. {
  1638. guard->quest->missionType = static_cast<CQuest::Emission>(reader.readUInt8());
  1639. switch(guard->quest->missionType)
  1640. {
  1641. case CQuest::MISSION_NONE:
  1642. return;
  1643. case CQuest::MISSION_PRIMARY_STAT:
  1644. {
  1645. guard->quest->m2stats.resize(4);
  1646. for(int x = 0; x < 4; ++x)
  1647. {
  1648. guard->quest->m2stats[x] = reader.readUInt8();
  1649. }
  1650. }
  1651. break;
  1652. case CQuest::MISSION_LEVEL:
  1653. case CQuest::MISSION_KILL_HERO:
  1654. case CQuest::MISSION_KILL_CREATURE:
  1655. {
  1656. guard->quest->m13489val = reader.readUInt32();
  1657. break;
  1658. }
  1659. case CQuest::MISSION_ART:
  1660. {
  1661. int artNumber = reader.readUInt8();
  1662. for(int yy = 0; yy < artNumber; ++yy)
  1663. {
  1664. int artid = reader.readUInt16();
  1665. guard->quest->m5arts.push_back(artid);
  1666. map->allowedArtifact[artid] = false; //these are unavailable for random generation
  1667. }
  1668. break;
  1669. }
  1670. case CQuest::MISSION_ARMY:
  1671. {
  1672. int typeNumber = reader.readUInt8();
  1673. guard->quest->m6creatures.resize(typeNumber);
  1674. for(int hh = 0; hh < typeNumber; ++hh)
  1675. {
  1676. guard->quest->m6creatures[hh].type = VLC->creh->objects[reader.readUInt16()];
  1677. guard->quest->m6creatures[hh].count = reader.readUInt16();
  1678. }
  1679. break;
  1680. }
  1681. case CQuest::MISSION_RESOURCES:
  1682. {
  1683. guard->quest->m7resources.resize(7);
  1684. for(int x = 0; x < 7; ++x)
  1685. {
  1686. guard->quest->m7resources[x] = reader.readUInt32();
  1687. }
  1688. break;
  1689. }
  1690. case CQuest::MISSION_HERO:
  1691. case CQuest::MISSION_PLAYER:
  1692. {
  1693. guard->quest->m13489val = reader.readUInt8();
  1694. break;
  1695. }
  1696. }
  1697. int limit = reader.readUInt32();
  1698. if(limit == (static_cast<int>(0xffffffff)))
  1699. {
  1700. guard->quest->lastDay = -1;
  1701. }
  1702. else
  1703. {
  1704. guard->quest->lastDay = limit;
  1705. }
  1706. guard->quest->firstVisitText = reader.readString();
  1707. guard->quest->nextVisitText = reader.readString();
  1708. guard->quest->completedText = reader.readString();
  1709. guard->quest->isCustomFirst = guard->quest->firstVisitText.size() > 0;
  1710. guard->quest->isCustomNext = guard->quest->nextVisitText.size() > 0;
  1711. guard->quest->isCustomComplete = guard->quest->completedText.size() > 0;
  1712. }
  1713. CGTownInstance * CMapLoaderH3M::readTown(int castleID)
  1714. {
  1715. auto nt = new CGTownInstance();
  1716. if(map->version > EMapFormat::ROE)
  1717. {
  1718. nt->identifier = reader.readUInt32();
  1719. }
  1720. nt->tempOwner = PlayerColor(reader.readUInt8());
  1721. bool hasName = reader.readBool();
  1722. if(hasName)
  1723. {
  1724. nt->name = reader.readString();
  1725. }
  1726. bool hasGarrison = reader.readBool();
  1727. if(hasGarrison)
  1728. {
  1729. readCreatureSet(nt, 7);
  1730. }
  1731. nt->formation = reader.readUInt8();
  1732. bool hasCustomBuildings = reader.readBool();
  1733. if(hasCustomBuildings)
  1734. {
  1735. readBitmask(nt->builtBuildings,6,48,false);
  1736. readBitmask(nt->forbiddenBuildings,6,48,false);
  1737. nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
  1738. nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
  1739. }
  1740. // Standard buildings
  1741. else
  1742. {
  1743. bool hasFort = reader.readBool();
  1744. if(hasFort)
  1745. {
  1746. nt->builtBuildings.insert(BuildingID::FORT);
  1747. }
  1748. //means that set of standard building should be included
  1749. nt->builtBuildings.insert(BuildingID::DEFAULT);
  1750. }
  1751. if(map->version > EMapFormat::ROE)
  1752. {
  1753. for(int i = 0; i < 9; ++i)
  1754. {
  1755. ui8 c = reader.readUInt8();
  1756. for(int yy = 0; yy < 8; ++yy)
  1757. {
  1758. if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
  1759. {
  1760. if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
  1761. {
  1762. nt->obligatorySpells.push_back(SpellID(i * 8 + yy));
  1763. }
  1764. }
  1765. }
  1766. }
  1767. }
  1768. for(int i = 0; i < 9; ++i)
  1769. {
  1770. ui8 c = reader.readUInt8();
  1771. for(int yy = 0; yy < 8; ++yy)
  1772. {
  1773. int spellid = i * 8 + yy;
  1774. if(spellid < GameConstants::SPELLS_QUANTITY)
  1775. {
  1776. if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
  1777. {
  1778. nt->possibleSpells.push_back(SpellID(spellid));
  1779. }
  1780. }
  1781. }
  1782. }
  1783. //add all spells from mods
  1784. //TODO: allow customize new spells in towns
  1785. for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
  1786. {
  1787. nt->possibleSpells.push_back(SpellID(i));
  1788. }
  1789. // Read castle events
  1790. int numberOfEvent = reader.readUInt32();
  1791. for(int gh = 0; gh < numberOfEvent; ++gh)
  1792. {
  1793. CCastleEvent nce;
  1794. nce.town = nt;
  1795. nce.name = reader.readString();
  1796. nce.message = reader.readString();
  1797. readResourses(nce.resources);
  1798. nce.players = reader.readUInt8();
  1799. if(map->version > EMapFormat::AB)
  1800. {
  1801. nce.humanAffected = reader.readUInt8();
  1802. }
  1803. else
  1804. {
  1805. nce.humanAffected = true;
  1806. }
  1807. nce.computerAffected = reader.readUInt8();
  1808. nce.firstOccurence = reader.readUInt16();
  1809. nce.nextOccurence = reader.readUInt8();
  1810. reader.skip(17);
  1811. // New buildings
  1812. readBitmask(nce.buildings,6,48,false);
  1813. nce.buildings = convertBuildings(nce.buildings, castleID, false);
  1814. nce.creatures.resize(7);
  1815. for(int vv = 0; vv < 7; ++vv)
  1816. {
  1817. nce.creatures[vv] = reader.readUInt16();
  1818. }
  1819. reader.skip(4);
  1820. nt->events.push_back(nce);
  1821. }
  1822. if(map->version > EMapFormat::AB)
  1823. {
  1824. nt->alignment = reader.readUInt8();
  1825. }
  1826. reader.skip(3);
  1827. return nt;
  1828. }
  1829. std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> h3m, int castleID, bool addAuxiliary)
  1830. {
  1831. std::map<int, BuildingID> mapa;
  1832. std::set<BuildingID> ret;
  1833. // Note: this file is parsed many times.
  1834. const JsonNode config(ResourceID("config/buildings5.json"));
  1835. for(const JsonNode & entry : config["table"].Vector())
  1836. {
  1837. int town = static_cast<int>(entry["town"].Float());
  1838. if (town == castleID || town == -1)
  1839. {
  1840. mapa[(int)entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float());
  1841. }
  1842. }
  1843. for(auto & elem : h3m)
  1844. {
  1845. if(mapa[elem] >= 0)
  1846. {
  1847. ret.insert(mapa[elem]);
  1848. }
  1849. // horde buildings
  1850. else if(mapa[elem] >= (-GameConstants::CREATURES_PER_TOWN))
  1851. {
  1852. int level = (mapa[elem]);
  1853. //(-30)..(-36) - horde buildings (for game loading only), don't see other way to handle hordes in random towns
  1854. ret.insert(BuildingID(level - 30));
  1855. }
  1856. else
  1857. {
  1858. logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
  1859. }
  1860. }
  1861. if(addAuxiliary)
  1862. {
  1863. //village hall is always present
  1864. ret.insert(BuildingID::VILLAGE_HALL);
  1865. if(ret.find(BuildingID::CITY_HALL) != ret.end())
  1866. {
  1867. ret.insert(BuildingID::EXTRA_CITY_HALL);
  1868. }
  1869. if(ret.find(BuildingID::TOWN_HALL) != ret.end())
  1870. {
  1871. ret.insert(BuildingID::EXTRA_TOWN_HALL);
  1872. }
  1873. if(ret.find(BuildingID::CAPITOL) != ret.end())
  1874. {
  1875. ret.insert(BuildingID::EXTRA_CAPITOL);
  1876. }
  1877. }
  1878. return ret;
  1879. }
  1880. void CMapLoaderH3M::readEvents()
  1881. {
  1882. int numberOfEvents = reader.readUInt32();
  1883. for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
  1884. {
  1885. CMapEvent ne;
  1886. ne.name = reader.readString();
  1887. ne.message = reader.readString();
  1888. readResourses(ne.resources);
  1889. ne.players = reader.readUInt8();
  1890. if(map->version > EMapFormat::AB)
  1891. {
  1892. ne.humanAffected = reader.readUInt8();
  1893. }
  1894. else
  1895. {
  1896. ne.humanAffected = true;
  1897. }
  1898. ne.computerAffected = reader.readUInt8();
  1899. ne.firstOccurence = reader.readUInt16();
  1900. ne.nextOccurence = reader.readUInt8();
  1901. reader.skip(17);
  1902. map->events.push_back(ne);
  1903. }
  1904. }
  1905. void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards)
  1906. {
  1907. bool hasMessage = reader.readBool();
  1908. if(hasMessage)
  1909. {
  1910. message = reader.readString();
  1911. bool hasGuards = reader.readBool();
  1912. if(hasGuards)
  1913. {
  1914. readCreatureSet(guards, 7);
  1915. }
  1916. reader.skip(4);
  1917. }
  1918. }
  1919. void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
  1920. {
  1921. readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
  1922. }
  1923. void CMapLoaderH3M::readResourses(TResources& resources)
  1924. {
  1925. resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
  1926. for(int x = 0; x < 7; ++x)
  1927. {
  1928. resources[x] = reader.readUInt32();
  1929. }
  1930. }
  1931. template <class Indentifier>
  1932. void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
  1933. {
  1934. std::vector<bool> temp;
  1935. temp.resize(limit,true);
  1936. readBitmask(temp, byteCount, limit, negate);
  1937. for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
  1938. {
  1939. if(temp[i])
  1940. {
  1941. dest.insert(static_cast<Indentifier>(i));
  1942. }
  1943. }
  1944. }
  1945. void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
  1946. {
  1947. for(int byte = 0; byte < byteCount; ++byte)
  1948. {
  1949. const ui8 mask = reader.readUInt8();
  1950. for(int bit = 0; bit < 8; ++bit)
  1951. {
  1952. if(byte * 8 + bit < limit)
  1953. {
  1954. const bool flag = mask & (1 << bit);
  1955. if((negate && flag) || (!negate && !flag)) // FIXME: check PR388
  1956. dest[byte * 8 + bit] = false;
  1957. }
  1958. }
  1959. }
  1960. }
  1961. ui8 CMapLoaderH3M::reverse(ui8 arg)
  1962. {
  1963. ui8 ret = 0;
  1964. for(int i = 0; i < 8; ++i)
  1965. {
  1966. if((arg & (1 << i)) >> i)
  1967. {
  1968. ret |= (128 >> i);
  1969. }
  1970. }
  1971. return ret;
  1972. }
  1973. void CMapLoaderH3M::afterRead()
  1974. {
  1975. //convert main town positions for all players to actual object position, in H3M it is position of active tile
  1976. for(auto & p : map->players)
  1977. {
  1978. int3 posOfMainTown = p.posOfMainTown;
  1979. if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
  1980. {
  1981. const TerrainTile & t = map->getTile(posOfMainTown);
  1982. const CGObjectInstance * mainTown = nullptr;
  1983. for(auto obj : t.visitableObjects)
  1984. {
  1985. if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
  1986. {
  1987. mainTown = obj;
  1988. break;
  1989. }
  1990. }
  1991. if(mainTown == nullptr)
  1992. continue;
  1993. p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
  1994. }
  1995. }
  1996. }