MapFormatH3M.cpp 58 KB

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