File: MapFormatH3M.cpp

package info (click to toggle)
vcmi 0.99%2Bdfsg%2Bgit20190113.f06c8a87-2
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 11,136 kB
  • sloc: cpp: 142,615; sh: 315; objc: 248; makefile: 32; ansic: 28; python: 13
file content (2257 lines) | stat: -rw-r--r-- 58,672 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
/*
 * MapFormatH3M.cpp, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */

#include "StdInc.h"
#include <boost/crc.hpp>

#include "MapFormatH3M.h"
#include "CMap.h"

#include "../CStopWatch.h"
#include "../filesystem/Filesystem.h"
#include "../spells/CSpellHandler.h"
#include "../CSkillHandler.h"
#include "../CCreatureHandler.h"
#include "../CGeneralTextHandler.h"
#include "../CHeroHandler.h"
#include "../mapObjects/CObjectClassesHandler.h"
#include "../mapObjects/MapObjects.h"
#include "../VCMI_Lib.h"
#include "../NetPacksBase.h"


const bool CMapLoaderH3M::IS_PROFILING_ENABLED = false;

CMapLoaderH3M::CMapLoaderH3M(CInputStream * stream) : map(nullptr), reader(stream),inputStream(stream)
{
}

CMapLoaderH3M::~CMapLoaderH3M()
{
}

std::unique_ptr<CMap> CMapLoaderH3M::loadMap()
{
	// Init map object by parsing the input buffer
	map = new CMap();
	mapHeader = std::unique_ptr<CMapHeader>(dynamic_cast<CMapHeader *>(map));
	init();

	return std::unique_ptr<CMap>(dynamic_cast<CMap *>(mapHeader.release()));
}

std::unique_ptr<CMapHeader> CMapLoaderH3M::loadMapHeader()
{
	// Read header
	mapHeader = make_unique<CMapHeader>();
	readHeader();

	return std::move(mapHeader);
}

void CMapLoaderH3M::init()
{
	//FIXME: get rid of double input process
	si64 temp_size = inputStream->getSize();
	inputStream->seek(0);

	auto  temp_buffer = new ui8[temp_size];
	inputStream->read(temp_buffer,temp_size);

	// Compute checksum
	boost::crc_32_type  result;
	result.process_bytes(temp_buffer, temp_size);
	map->checksum = result.checksum();

	delete [] temp_buffer;
	inputStream->seek(0);

	CStopWatch sw;

	struct MapLoadingTime
	{
		std::string name;
		si64 time;

		MapLoadingTime(std::string name, si64 time) : name(name),
			time(time)
		{

		}
	};
	std::vector<MapLoadingTime> times;

	readHeader();
	times.push_back(MapLoadingTime("header", sw.getDiff()));

	map->allHeroes.resize(map->allowedHeroes.size());

	readDisposedHeroes();
	times.push_back(MapLoadingTime("disposed heroes", sw.getDiff()));

	readAllowedArtifacts();
	times.push_back(MapLoadingTime("allowed artifacts", sw.getDiff()));

	readAllowedSpellsAbilities();
	times.push_back(MapLoadingTime("allowed spells and abilities", sw.getDiff()));

	readRumors();
	times.push_back(MapLoadingTime("rumors", sw.getDiff()));

	readPredefinedHeroes();
	times.push_back(MapLoadingTime("predefined heroes", sw.getDiff()));

	readTerrain();
	times.push_back(MapLoadingTime("terrain", sw.getDiff()));

	readDefInfo();
	times.push_back(MapLoadingTime("def info", sw.getDiff()));

	readObjects();
	times.push_back(MapLoadingTime("objects", sw.getDiff()));

	readEvents();
	times.push_back(MapLoadingTime("events", sw.getDiff()));

	times.push_back(MapLoadingTime("blocked/visitable tiles", sw.getDiff()));

	// Print profiling times
	if(IS_PROFILING_ENABLED)
	{
		for(MapLoadingTime & mlt : times)
		{
			logGlobal->debug("\tReading %s took %d ms", mlt.name, mlt.time);
		}
	}
	map->calculateGuardingGreaturePositions();
	afterRead();
}

void CMapLoaderH3M::readHeader()
{
	// Check map for validity
	// Note: disabled, causes decompression of the entire file ( = SLOW)
	//if(inputStream->getSize() < 50)
	//{
	//	throw std::runtime_error("Corrupted map file.");
	//}

	// Map version
	mapHeader->version = (EMapFormat::EMapFormat)(reader.readUInt32());
	if(mapHeader->version != EMapFormat::ROE && mapHeader->version != EMapFormat::AB && mapHeader->version != EMapFormat::SOD
			&& mapHeader->version != EMapFormat::WOG)
	{
		throw std::runtime_error("Invalid map format!");
	}

	// Read map name, description, dimensions,...
	mapHeader->areAnyPlayers = reader.readBool();
	mapHeader->height = mapHeader->width = reader.readUInt32();
	mapHeader->twoLevel = reader.readBool();
	mapHeader->name = reader.readString();
	mapHeader->description = reader.readString();
	mapHeader->difficulty = reader.readInt8();
	if(mapHeader->version != EMapFormat::ROE)
	{
		mapHeader->levelLimit = reader.readUInt8();
	}
	else
	{
		mapHeader->levelLimit = 0;
	}

	readPlayerInfo();
	readVictoryLossConditions();
	readTeamInfo();
	readAllowedHeroes();
}

void CMapLoaderH3M::readPlayerInfo()
{
	for(int i = 0; i < mapHeader->players.size(); ++i)
	{
		mapHeader->players[i].canHumanPlay = reader.readBool();
		mapHeader->players[i].canComputerPlay = reader.readBool();

		// If nobody can play with this player
		if((!(mapHeader->players[i].canHumanPlay || mapHeader->players[i].canComputerPlay)))
		{
			switch(mapHeader->version)
			{
			case EMapFormat::SOD:
			case EMapFormat::WOG:
				reader.skip(13);
				break;
			case EMapFormat::AB:
				reader.skip(12);
				break;
			case EMapFormat::ROE:
				reader.skip(6);
				break;
			}
			continue;
		}

		mapHeader->players[i].aiTactic = static_cast<EAiTactic::EAiTactic>(reader.readUInt8());

		if(mapHeader->version == EMapFormat::SOD || mapHeader->version == EMapFormat::WOG)
		{
			mapHeader->players[i].p7 = reader.readUInt8();
		}
		else
		{
			mapHeader->players[i].p7 = -1;
		}

		// Factions this player can choose
		ui16 allowedFactions = reader.readUInt8();
		// How many factions will be read from map
		ui16 totalFactions = GameConstants::F_NUMBER;

		if(mapHeader->version != EMapFormat::ROE)
			allowedFactions += reader.readUInt8() * 256;
		else
			totalFactions--; //exclude conflux for ROE

		for(int fact = 0; fact < totalFactions; ++fact)
		{
			if(!(allowedFactions & (1 << fact)))
			{
				mapHeader->players[i].allowedFactions.erase(fact);
			}
		}

		mapHeader->players[i].isFactionRandom = reader.readBool();
		mapHeader->players[i].hasMainTown = reader.readBool();
		if(mapHeader->players[i].hasMainTown)
		{
			if(mapHeader->version != EMapFormat::ROE)
			{
				mapHeader->players[i].generateHeroAtMainTown = reader.readBool();
				mapHeader->players[i].generateHero = reader.readBool();
			}
			else
			{
				mapHeader->players[i].generateHeroAtMainTown = true;
				mapHeader->players[i].generateHero = false;
			}

			mapHeader->players[i].posOfMainTown = readInt3();
		}

		mapHeader->players[i].hasRandomHero = reader.readBool();
		mapHeader->players[i].mainCustomHeroId = reader.readUInt8();

		if(mapHeader->players[i].mainCustomHeroId != 0xff)
		{
			mapHeader->players[i].mainCustomHeroPortrait = reader.readUInt8();
			if (mapHeader->players[i].mainCustomHeroPortrait == 0xff)
				mapHeader->players[i].mainCustomHeroPortrait = -1; //correct 1-byte -1 (0xff) into 4-byte -1

			mapHeader->players[i].mainCustomHeroName = reader.readString();
		}
		else
			mapHeader->players[i].mainCustomHeroId = -1; //correct 1-byte -1 (0xff) into 4-byte -1

		if(mapHeader->version != EMapFormat::ROE)
		{
			mapHeader->players[i].powerPlaceholders = reader.readUInt8(); //unknown byte
			int heroCount = reader.readUInt8();
			reader.skip(3);
			for(int pp = 0; pp < heroCount; ++pp)
			{
				SHeroName vv;
				vv.heroId = reader.readUInt8();
				vv.heroName = reader.readString();

				mapHeader->players[i].heroesNames.push_back(vv);
			}
		}
	}
}

namespace EVictoryConditionType
{
	enum EVictoryConditionType { ARTIFACT, GATHERTROOP, GATHERRESOURCE, BUILDCITY, BUILDGRAIL, BEATHERO,
		CAPTURECITY, BEATMONSTER, TAKEDWELLINGS, TAKEMINES, TRANSPORTITEM, WINSTANDARD = 255 };
}

namespace ELossConditionType
{
	enum ELossConditionType { LOSSCASTLE, LOSSHERO, TIMEEXPIRES, LOSSSTANDARD = 255 };
}

void CMapLoaderH3M::readVictoryLossConditions()
{
	mapHeader->triggeredEvents.clear();

	auto vicCondition = (EVictoryConditionType::EVictoryConditionType)reader.readUInt8();

	EventCondition victoryCondition(EventCondition::STANDARD_WIN);
	EventCondition defeatCondition(EventCondition::DAYS_WITHOUT_TOWN);
	defeatCondition.value = 7;

	TriggeredEvent standardVictory;
	standardVictory.effect.type = EventEffect::VICTORY;
	standardVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
	standardVictory.identifier = "standardVictory";
	standardVictory.description = ""; // TODO: display in quest window
	standardVictory.onFulfill = VLC->generaltexth->allTexts[659];
	standardVictory.trigger = EventExpression(victoryCondition);

	TriggeredEvent standardDefeat;
	standardDefeat.effect.type = EventEffect::DEFEAT;
	standardDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[8];
	standardDefeat.identifier = "standardDefeat";
	standardDefeat.description = ""; // TODO: display in quest window
	standardDefeat.onFulfill = VLC->generaltexth->allTexts[7];
	standardDefeat.trigger = EventExpression(defeatCondition);

	// Specific victory conditions
	if(vicCondition == EVictoryConditionType::WINSTANDARD)
	{
		// create normal condition
		mapHeader->triggeredEvents.push_back(standardVictory);
		mapHeader->victoryIconIndex = 11;
		mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[0];
	}
	else
	{
		TriggeredEvent specialVictory;
		specialVictory.effect.type = EventEffect::VICTORY;
		specialVictory.identifier = "specialVictory";
		specialVictory.description = ""; // TODO: display in quest window

		mapHeader->victoryIconIndex = ui16(vicCondition);
		mapHeader->victoryMessage = VLC->generaltexth->victoryConditions[size_t(vicCondition) + 1];

		bool allowNormalVictory = reader.readBool();
		bool appliesToAI = reader.readBool();

		if (allowNormalVictory)
		{
			size_t playersOnMap = boost::range::count_if(mapHeader->players,[](const PlayerInfo & info) { return info.canAnyonePlay();});

			if (playersOnMap == 1)
			{
				logGlobal->warn("Map %s has only one player but allows normal victory?", mapHeader->name);
				allowNormalVictory = false; // makes sense? Not much. Works as H3? Yes!
			}
		}

		switch(vicCondition)
		{
		case EVictoryConditionType::ARTIFACT:
			{
				EventCondition cond(EventCondition::HAVE_ARTIFACT);
				cond.objectType = reader.readUInt8();
				if (mapHeader->version != EMapFormat::ROE)
					reader.skip(1);

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[281];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[280];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::GATHERTROOP:
			{
				EventCondition cond(EventCondition::HAVE_CREATURES);
				cond.objectType = reader.readUInt8();
				if (mapHeader->version != EMapFormat::ROE)
					reader.skip(1);
				cond.value = reader.readUInt32();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[277];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[276];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::GATHERRESOURCE:
			{
				EventCondition cond(EventCondition::HAVE_RESOURCES);
				cond.objectType = reader.readUInt8();
				cond.value = reader.readUInt32();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[279];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[278];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::BUILDCITY:
			{
				EventExpression::OperatorAll oper;
				EventCondition cond(EventCondition::HAVE_BUILDING);
				cond.position = readInt3();
				cond.objectType = BuildingID::VILLAGE_HALL + reader.readUInt8();
				oper.expressions.push_back(cond);
				cond.objectType = BuildingID::FORT + reader.readUInt8();
				oper.expressions.push_back(cond);

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[283];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[282];
				specialVictory.trigger = EventExpression(oper);
				break;
			}
		case EVictoryConditionType::BUILDGRAIL:
			{
				EventCondition cond(EventCondition::HAVE_BUILDING);
				cond.objectType = BuildingID::GRAIL;
				cond.position = readInt3();
				if(cond.position.z > 2)
					cond.position = int3(-1,-1,-1);

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[285];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[284];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::BEATHERO:
			{
				EventCondition cond(EventCondition::DESTROY);
				cond.objectType = Obj::HERO;
				cond.position = readInt3();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[253];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[252];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::CAPTURECITY:
			{
				EventCondition cond(EventCondition::CONTROL);
				cond.objectType = Obj::TOWN;
				cond.position = readInt3();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[250];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[249];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::BEATMONSTER:
			{
				EventCondition cond(EventCondition::DESTROY);
				cond.objectType = Obj::MONSTER;
				cond.position = readInt3();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[287];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[286];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::TAKEDWELLINGS:
			{
				EventExpression::OperatorAll oper;
				oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR1));
				oper.expressions.push_back(EventCondition(EventCondition::CONTROL, 0, Obj::CREATURE_GENERATOR4));

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[289];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[288];
				specialVictory.trigger = EventExpression(oper);
				break;
			}
		case EVictoryConditionType::TAKEMINES:
			{
				EventCondition cond(EventCondition::CONTROL);
				cond.objectType = Obj::MINE;

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[291];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[290];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		case EVictoryConditionType::TRANSPORTITEM:
			{
				EventCondition cond(EventCondition::TRANSPORT);
				cond.objectType = reader.readUInt8();
				cond.position = readInt3();

				specialVictory.effect.toOtherMessage = VLC->generaltexth->allTexts[293];
				specialVictory.onFulfill = VLC->generaltexth->allTexts[292];
				specialVictory.trigger = EventExpression(cond);
				break;
			}
		default:
			assert(0);
		}

		// if condition is human-only turn it into following construction: AllOf(human, condition)
		if (!appliesToAI)
		{
			EventExpression::OperatorAll oper;
			EventCondition notAI(EventCondition::IS_HUMAN);
			notAI.value = 1;
			oper.expressions.push_back(notAI);
			oper.expressions.push_back(specialVictory.trigger.get());
			specialVictory.trigger = EventExpression(oper);
		}

		// if normal victory allowed - add one more quest
		if (allowNormalVictory)
		{
			mapHeader->victoryMessage += " / ";
			mapHeader->victoryMessage += VLC->generaltexth->victoryConditions[0];
			mapHeader->triggeredEvents.push_back(standardVictory);
		}
		mapHeader->triggeredEvents.push_back(specialVictory);
	}

	// Read loss conditions
	auto lossCond = (ELossConditionType::ELossConditionType)reader.readUInt8();
	if (lossCond == ELossConditionType::LOSSSTANDARD)
	{
		mapHeader->defeatIconIndex = 3;
		mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[0];
	}
	else
	{
		TriggeredEvent specialDefeat;
		specialDefeat.effect.type = EventEffect::DEFEAT;
		specialDefeat.effect.toOtherMessage = VLC->generaltexth->allTexts[5];
		specialDefeat.identifier = "specialDefeat";
		specialDefeat.description = ""; // TODO: display in quest window

		mapHeader->defeatIconIndex = ui16(lossCond);
		mapHeader->defeatMessage = VLC->generaltexth->lossCondtions[size_t(lossCond) + 1];

		switch(lossCond)
		{
		case ELossConditionType::LOSSCASTLE:
			{
				EventExpression::OperatorNone noneOf;
				EventCondition cond(EventCondition::CONTROL);
				cond.objectType = Obj::TOWN;
				cond.position = readInt3();

				noneOf.expressions.push_back(cond);
				specialDefeat.onFulfill = VLC->generaltexth->allTexts[251];
				specialDefeat.trigger = EventExpression(noneOf);
				break;
			}
		case ELossConditionType::LOSSHERO:
			{
				EventExpression::OperatorNone noneOf;
				EventCondition cond(EventCondition::CONTROL);
				cond.objectType = Obj::HERO;
				cond.position = readInt3();

				noneOf.expressions.push_back(cond);
				specialDefeat.onFulfill = VLC->generaltexth->allTexts[253];
				specialDefeat.trigger = EventExpression(noneOf);
				break;
			}
		case ELossConditionType::TIMEEXPIRES:
			{
				EventCondition cond(EventCondition::DAYS_PASSED);
				cond.value = reader.readUInt16();

				specialDefeat.onFulfill = VLC->generaltexth->allTexts[254];
				specialDefeat.trigger = EventExpression(cond);
				break;
			}
		}
		// turn simple loss condition into complete one that can be evaluated later:
		// - any of :
		//   - days without town: 7
		//   - all of:
		//     - is human
		//     - (expression)

		EventExpression::OperatorAll allOf;
		EventCondition isHuman(EventCondition::IS_HUMAN);
		isHuman.value = 1;

		allOf.expressions.push_back(isHuman);
		allOf.expressions.push_back(specialDefeat.trigger.get());
		specialDefeat.trigger = EventExpression(allOf);

		mapHeader->triggeredEvents.push_back(specialDefeat);
	}
	mapHeader->triggeredEvents.push_back(standardDefeat);
}

void CMapLoaderH3M::readTeamInfo()
{
	mapHeader->howManyTeams = reader.readUInt8();
	if(mapHeader->howManyTeams > 0)
	{
		// Teams
		for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
		{
			mapHeader->players[i].team = TeamID(reader.readUInt8());
		}
	}
	else
	{
		// No alliances
		for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
		{
			if(mapHeader->players[i].canComputerPlay || mapHeader->players[i].canHumanPlay)
			{
				mapHeader->players[i].team = TeamID(mapHeader->howManyTeams++);
			}
		}
	}
}

void CMapLoaderH3M::readAllowedHeroes()
{
	mapHeader->allowedHeroes.resize(VLC->heroh->heroes.size(), true);

	const int bytes = mapHeader->version == EMapFormat::ROE ? 16 : 20;

	readBitmask(mapHeader->allowedHeroes,bytes,GameConstants::HEROES_QUANTITY, false);

	// Probably reserved for further heroes
	if(mapHeader->version > EMapFormat::ROE)
	{
		int placeholdersQty = reader.readUInt32();

		reader.skip(placeholdersQty * 1);

//		std::vector<ui16> placeholdedHeroes;
//
//		for(int p = 0; p < placeholdersQty; ++p)
//		{
//			placeholdedHeroes.push_back(reader.readUInt8());
//		}
	}
}

void CMapLoaderH3M::readDisposedHeroes()
{
	// Reading disposed heroes (20 bytes)
	if(map->version >= EMapFormat::SOD)
	{
		ui8 disp = reader.readUInt8();
		map->disposedHeroes.resize(disp);
		for(int g = 0; g < disp; ++g)
		{
			map->disposedHeroes[g].heroId = reader.readUInt8();
			map->disposedHeroes[g].portrait = reader.readUInt8();
			map->disposedHeroes[g].name = reader.readString();
			map->disposedHeroes[g].players = reader.readUInt8();
		}
	}

	//omitting NULLS
	reader.skip(31);
}

void CMapLoaderH3M::readAllowedArtifacts()
{
	map->allowedArtifact.resize (VLC->arth->artifacts.size(),true); //handle new artifacts, make them allowed by default

	// Reading allowed artifacts:  17 or 18 bytes
	if(map->version != EMapFormat::ROE)
	{
		const int bytes = map->version == EMapFormat::AB ? 17 : 18;

		readBitmask(map->allowedArtifact,bytes,GameConstants::ARTIFACTS_QUANTITY);

	}

	// ban combo artifacts
	if (map->version == EMapFormat::ROE || map->version == EMapFormat::AB)
	{
		for(CArtifact * artifact : VLC->arth->artifacts)
		{
			// combo
			if (artifact->constituents)
			{
				map->allowedArtifact[artifact->id] = false;
			}
		}
		if (map->version == EMapFormat::ROE)
		{
			map->allowedArtifact[ArtifactID::ARMAGEDDONS_BLADE] = false;
		}
	}

	// Messy, but needed
	for (TriggeredEvent & event : map->triggeredEvents)
	{
		auto patcher = [&](EventCondition cond) -> EventExpression::Variant
		{
			if (cond.condition == EventCondition::HAVE_ARTIFACT ||
				cond.condition == EventCondition::TRANSPORT)
			{
				map->allowedArtifact[cond.objectType] = false;
			}
			return cond;
		};

		event.trigger = event.trigger.morph(patcher);
	}
}

void CMapLoaderH3M::readAllowedSpellsAbilities()
{
	// Read allowed spells, including new ones
	map->allowedSpell.resize(VLC->spellh->objects.size(), true);

	// Read allowed abilities
	map->allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);

	if(map->version >= EMapFormat::SOD)
	{
		// Reading allowed spells (9 bytes)
		const int spell_bytes = 9;
		readBitmask(map->allowedSpell, spell_bytes, GameConstants::SPELLS_QUANTITY);

		// Allowed hero's abilities (4 bytes)
		const int abil_bytes = 4;
		readBitmask(map->allowedAbilities, abil_bytes, GameConstants::SKILL_QUANTITY);
	}

	//do not generate special abilities and spells
	for (auto spell : VLC->spellh->objects)
		if (spell->isSpecialSpell() || spell->isCreatureAbility())
			map->allowedSpell[spell->id] = false;
}

void CMapLoaderH3M::readRumors()
{
	int rumNr = reader.readUInt32();

	for(int it = 0; it < rumNr; it++)
	{
		Rumor ourRumor;
		ourRumor.name = reader.readString();
		ourRumor.text = reader.readString();
		map->rumors.push_back(ourRumor);
	}
}

void CMapLoaderH3M::readPredefinedHeroes()
{
	switch(map->version)
	{
	case EMapFormat::WOG:
	case EMapFormat::SOD:
		{
			// Disposed heroes
			for(int z = 0; z < GameConstants::HEROES_QUANTITY; z++)
			{
				int custom =  reader.readUInt8();
				if(!custom) continue;

				auto  hero = new CGHeroInstance();
				hero->ID = Obj::HERO;
				hero->subID = z;

				bool hasExp = reader.readBool();
				if(hasExp)
				{
					hero->exp = reader.readUInt32();
				}
				else
				{
					hero->exp = 0;
				}

				bool hasSecSkills = reader.readBool();
				if(hasSecSkills)
				{
					int howMany = reader.readUInt32();
					hero->secSkills.resize(howMany);
					for(int yy = 0; yy < howMany; ++yy)
					{
						hero->secSkills[yy].first = SecondarySkill(reader.readUInt8());
						hero->secSkills[yy].second = reader.readUInt8();
					}
				}

				loadArtifactsOfHero(hero);

				bool hasCustomBio = reader.readBool();
				if(hasCustomBio)
				{
					hero->biography = reader.readString();
				}

				// 0xFF is default, 00 male, 01 female
				hero->sex = reader.readUInt8();

				bool hasCustomSpells = reader.readBool();
				if(hasCustomSpells)
				{
					readSpells(hero->spells);
				}

				bool hasCustomPrimSkills = reader.readBool();
				if(hasCustomPrimSkills)
				{
					for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; xx++)
					{
						hero->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
					}
				}
				map->predefinedHeroes.push_back(hero);
			}
			break;
		}
	case EMapFormat::ROE:
		break;
	}
}

void CMapLoaderH3M::loadArtifactsOfHero(CGHeroInstance * hero)
{
	bool artSet = reader.readBool();

	// True if artifact set is not default (hero has some artifacts)
	if(artSet)
	{
		if(hero->artifactsWorn.size() ||  hero->artifactsInBackpack.size())
		{
			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());
			hero->artifactsInBackpack.clear();
			while(hero->artifactsWorn.size())
				hero->eraseArtSlot(hero->artifactsWorn.begin()->first);
		}

		for(int pom = 0; pom < 16; pom++)
		{
			loadArtifactToSlot(hero, pom);
		}

		// misc5 art //17
		if(map->version >= EMapFormat::SOD)
		{
			assert(!hero->getArt(ArtifactPosition::MACH4));
			if(!loadArtifactToSlot(hero, ArtifactPosition::MACH4))
			{
				// catapult by default
				assert(!hero->getArt(ArtifactPosition::MACH4));
				hero->putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createArtifact(map, ArtifactID::CATAPULT));
			}
		}

		loadArtifactToSlot(hero, ArtifactPosition::SPELLBOOK);

		// 19 //???what is that? gap in file or what? - it's probably fifth slot..
		if(map->version > EMapFormat::ROE)
		{
			loadArtifactToSlot(hero, ArtifactPosition::MISC5);
		}
		else
		{
			reader.skip(1);
		}

		// bag artifacts //20
		// number of artifacts in hero's bag
		int amount = reader.readUInt16();
		for(int ss = 0; ss < amount; ++ss)
		{
			loadArtifactToSlot(hero, GameConstants::BACKPACK_START + hero->artifactsInBackpack.size());
		}
	}
}

bool CMapLoaderH3M::loadArtifactToSlot(CGHeroInstance * hero, int slot)
{
	const int artmask = map->version == EMapFormat::ROE ? 0xff : 0xffff;
	int aid;

	if(map->version == EMapFormat::ROE)
	{
		aid = reader.readUInt8();
	}
	else
	{
		aid = reader.readUInt16();
	}

	bool isArt  =  aid != artmask;
	if(isArt)
	{
		const CArtifact * art = ArtifactID(aid).toArtifact();

		if(nullptr == art)
		{
			logGlobal->warn("Invalid artifact in hero's backpack, ignoring...");
			return false;
		}

		if(art->isBig() && slot >= GameConstants::BACKPACK_START)
		{
			logGlobal->warn("A big artifact (war machine) in hero's backpack, ignoring...");
			return false;
		}
		if(aid == 0 && slot == ArtifactPosition::MISC5)
		{
			//TODO: check how H3 handles it -> art 0 in slot 18 in AB map
			logGlobal->warn("Spellbook to MISC5 slot? Putting it spellbook place. AB format peculiarity? (format %d)", static_cast<int>(map->version));
			slot = ArtifactPosition::SPELLBOOK;
		}

		// this is needed, because some H3M maps (last scenario of ROE map) contain invalid data like misplaced artifacts
		auto artifact =  CArtifactInstance::createArtifact(map, aid);
		auto artifactPos = ArtifactPosition(slot);
		if (artifact->canBePutAt(ArtifactLocation(hero, artifactPos)))
		{
			hero->putArtifact(artifactPos, artifact);
		}
		else
		{
			logGlobal->debug("Artifact can't be put at the specified location."); //TODO add more debugging information
		}
	}

	return isArt;
}

void CMapLoaderH3M::readTerrain()
{
	map->initTerrain();

	// Read terrain
	for(int a = 0; a < 2; ++a)
	{
		if(a == 1 && !map->twoLevel)
		{
			break;
		}

		for(int c = 0; c < map->width; c++)
		{
			for(int z = 0; z < map->height; z++)
			{
				auto & tile = map->getTile(int3(z, c, a));
				tile.terType = ETerrainType(reader.readUInt8());
				tile.terView = reader.readUInt8();
				tile.riverType = static_cast<ERiverType::ERiverType>(reader.readUInt8());
				tile.riverDir = reader.readUInt8();
				tile.roadType = static_cast<ERoadType::ERoadType>(reader.readUInt8());
				tile.roadDir = reader.readUInt8();
				tile.extTileFlags = reader.readUInt8();
				tile.blocked = ((tile.terType == ETerrainType::ROCK || tile.terType == ETerrainType::BORDER ) ? true : false); //underground tiles are always blocked
				tile.visitable = 0;
			}
		}
	}
}

void CMapLoaderH3M::readDefInfo()
{
	int defAmount = reader.readUInt32();

	templates.reserve(defAmount);

	// Read custom defs
	for(int idd = 0; idd < defAmount; ++idd)
	{
		ObjectTemplate tmpl;
		tmpl.readMap(reader);
		templates.push_back(tmpl);
	}
}

void CMapLoaderH3M::readObjects()
{
	int howManyObjs = reader.readUInt32();

	for(int ww = 0; ww < howManyObjs; ++ww)
	{
		CGObjectInstance * nobj = nullptr;

		int3 objPos = readInt3();

		int defnum = reader.readUInt32();
		ObjectInstanceID idToBeGiven = ObjectInstanceID(map->objects.size());

		ObjectTemplate & objTempl = templates.at(defnum);
		reader.skip(5);

		switch(objTempl.id)
		{
		case Obj::EVENT:
			{
				auto  evnt = new CGEvent();
				nobj = evnt;

				readMessageAndGuards(evnt->message, evnt);

				evnt->gainedExp = reader.readUInt32();
				evnt->manaDiff = reader.readUInt32();
				evnt->moraleDiff = reader.readInt8();
				evnt->luckDiff = reader.readInt8();

				readResourses(evnt->resources);

				evnt->primskills.resize(GameConstants::PRIMARY_SKILLS);
				for(int x = 0; x < 4; ++x)
				{
					evnt->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader.readUInt8());
				}

				int gabn = reader.readUInt8(); // Number of gained abilities
				for(int oo = 0; oo < gabn; ++oo)
				{
					evnt->abilities.push_back(SecondarySkill(reader.readUInt8()));
					evnt->abilityLevels.push_back(reader.readUInt8());
				}

				int gart = reader.readUInt8(); // Number of gained artifacts
				for(int oo = 0; oo < gart; ++oo)
				{
					if(map->version == EMapFormat::ROE)
					{
						evnt->artifacts.push_back(ArtifactID(reader.readUInt8()));
					}
					else
					{
						evnt->artifacts.push_back(ArtifactID(reader.readUInt16()));
					}
				}

				int gspel = reader.readUInt8(); // Number of gained spells
				for(int oo = 0; oo < gspel; ++oo)
				{
					evnt->spells.push_back(SpellID(reader.readUInt8()));
				}

				int gcre = reader.readUInt8(); //number of gained creatures
				readCreatureSet(&evnt->creatures, gcre);

				reader.skip(8);
				evnt->availableFor = reader.readUInt8();
				evnt->computerActivate = reader.readUInt8();
				evnt->removeAfterVisit = reader.readUInt8();
				evnt->humanActivate = true;

				reader.skip(4);
				break;
			}
		case Obj::HERO:
		case Obj::RANDOM_HERO:
		case Obj::PRISON:
			{
				nobj = readHero(idToBeGiven, objPos);
				break;
			}
		case Obj::MONSTER:  //Monster
		case Obj::RANDOM_MONSTER:
		case Obj::RANDOM_MONSTER_L1:
		case Obj::RANDOM_MONSTER_L2:
		case Obj::RANDOM_MONSTER_L3:
		case Obj::RANDOM_MONSTER_L4:
		case Obj::RANDOM_MONSTER_L5:
		case Obj::RANDOM_MONSTER_L6:
		case Obj::RANDOM_MONSTER_L7:
			{
				auto  cre = new CGCreature();
				nobj = cre;

				if(map->version > EMapFormat::ROE)
				{
					cre->identifier = reader.readUInt32();
					map->questIdentifierToId[cre->identifier] = idToBeGiven;
				}

				auto  hlp = new CStackInstance();
				hlp->count = reader.readUInt16();

				//type will be set during initialization
				cre->putStack(SlotID(0), hlp);

				cre->character = reader.readUInt8();

				bool hasMessage = reader.readBool();
				if(hasMessage)
				{
					cre->message = reader.readString();
					readResourses(cre->resources);

					int artID;
					if (map->version == EMapFormat::ROE)
					{
						artID = reader.readUInt8();
					}
					else
					{
						artID = reader.readUInt16();
					}

					if(map->version == EMapFormat::ROE)
					{
						if(artID != 0xff)
						{
							cre->gainedArtifact = ArtifactID(artID);
						}
						else
						{
							cre->gainedArtifact = ArtifactID::NONE;
						}
					}
					else
					{
						if(artID != 0xffff)
						{
							cre->gainedArtifact = ArtifactID(artID);
						}
						else
						{
							cre->gainedArtifact = ArtifactID::NONE;
						}
					}
				}
				cre->neverFlees = reader.readUInt8();
				cre->notGrowingTeam =reader.readUInt8();
				reader.skip(2);
				break;
			}
		case Obj::OCEAN_BOTTLE:
		case Obj::SIGN:
			{
				auto  sb = new CGSignBottle();
				nobj = sb;
				sb->message = reader.readString();
				reader.skip(4);
				break;
			}
		case Obj::SEER_HUT:
			{
				nobj = readSeerHut();
				break;
			}
		case Obj::WITCH_HUT:
			{
				auto  wh = new CGWitchHut();
				nobj = wh;

				// in RoE we cannot specify it - all are allowed (I hope)
				if(map->version > EMapFormat::ROE)
				{
					for(int i = 0 ; i < 4; ++i)
					{
						ui8 c = reader.readUInt8();
						for(int yy = 0; yy < 8; ++yy)
						{
							if(i * 8 + yy < GameConstants::SKILL_QUANTITY)
							{
								if(c == (c | static_cast<ui8>(std::pow(2., yy))))
								{
									wh->allowedAbilities.push_back(i * 8 + yy);
								}
							}
						}
					}
					// enable new (modded) skills
					if(wh->allowedAbilities.size() != 1)
					{
						for(int skillID = GameConstants::SKILL_QUANTITY; skillID < VLC->skillh->size(); ++skillID)
							wh->allowedAbilities.push_back(skillID);
					}
				}
				else
				{
					// RoE map
					for(int skillID = 0; skillID < VLC->skillh->size(); ++skillID)
						wh->allowedAbilities.push_back(skillID);
				}
				break;
			}
		case Obj::SCHOLAR:
			{
				auto  sch = new CGScholar();
				nobj = sch;
				sch->bonusType = static_cast<CGScholar::EBonusType>(reader.readUInt8());
				sch->bonusID = reader.readUInt8();
				reader.skip(6);
				break;
			}
		case Obj::GARRISON:
		case Obj::GARRISON2:
			{
				auto  gar = new CGGarrison();
				nobj = gar;
				nobj->setOwner(PlayerColor(reader.readUInt8()));
				reader.skip(3);
				readCreatureSet(gar, 7);
				if(map->version > EMapFormat::ROE)
				{
					gar->removableUnits = reader.readBool();
				}
				else
				{
					gar->removableUnits = true;
				}
				reader.skip(8);
				break;
			}
		case Obj::ARTIFACT:
		case Obj::RANDOM_ART:
		case Obj::RANDOM_TREASURE_ART:
		case Obj::RANDOM_MINOR_ART:
		case Obj::RANDOM_MAJOR_ART:
		case Obj::RANDOM_RELIC_ART:
		case Obj::SPELL_SCROLL:
			{
				int artID = ArtifactID::NONE; //random, set later
				int spellID = -1;
				auto  art = new CGArtifact();
				nobj = art;

				readMessageAndGuards(art->message, art);

				if(objTempl.id == Obj::SPELL_SCROLL)
				{
					spellID = reader.readUInt32();
					artID = ArtifactID::SPELL_SCROLL;
				}
				else if(objTempl.id == Obj::ARTIFACT)
				{
					//specific artifact
					artID = objTempl.subid;
				}

				art->storedArtifact = CArtifactInstance::createArtifact(map, artID, spellID);
				break;
			}
		case Obj::RANDOM_RESOURCE:
		case Obj::RESOURCE:
			{
				auto  res = new CGResource();
				nobj = res;

				readMessageAndGuards(res->message, res);

				res->amount = reader.readUInt32();
				if(objTempl.subid == Res::GOLD)
				{
					// Gold is multiplied by 100.
					res->amount *= 100;
				}
				reader.skip(4);
				break;
			}
		case Obj::RANDOM_TOWN:
		case Obj::TOWN:
			{
				nobj = readTown(objTempl.subid);
				break;
			}
		case Obj::MINE:
		case Obj::ABANDONED_MINE:
			{
				nobj = new CGMine();
				nobj->setOwner(PlayerColor(reader.readUInt8()));
				reader.skip(3);
				break;
			}
		case Obj::CREATURE_GENERATOR1:
		case Obj::CREATURE_GENERATOR2:
		case Obj::CREATURE_GENERATOR3:
		case Obj::CREATURE_GENERATOR4:
			{
				nobj = new CGDwelling();
				nobj->setOwner(PlayerColor(reader.readUInt8()));
				reader.skip(3);
				break;
			}
		case Obj::SHRINE_OF_MAGIC_INCANTATION:
		case Obj::SHRINE_OF_MAGIC_GESTURE:
		case Obj::SHRINE_OF_MAGIC_THOUGHT:
			{
				auto  shr = new CGShrine();
				nobj = shr;
				ui8 raw_id = reader.readUInt8();

				if (255 == raw_id)
				{
					shr->spell = SpellID(SpellID::NONE);
				}
				else
				{
					shr->spell = SpellID(raw_id);
				}

				reader.skip(3);
				break;
			}
		case Obj::PANDORAS_BOX:
			{
				auto  box = new CGPandoraBox();
				nobj = box;
				readMessageAndGuards(box->message, box);

				box->gainedExp = reader.readUInt32();
				box->manaDiff = reader.readUInt32();
				box->moraleDiff = reader.readInt8();
				box->luckDiff = reader.readInt8();

				readResourses(box->resources);

				box->primskills.resize(GameConstants::PRIMARY_SKILLS);
				for(int x = 0; x < 4; ++x)
				{
					box->primskills[x] = static_cast<PrimarySkill::PrimarySkill>(reader.readUInt8());
				}

				int gabn = reader.readUInt8();//number of gained abilities
				for(int oo = 0; oo < gabn; ++oo)
				{
					box->abilities.push_back(SecondarySkill(reader.readUInt8()));
					box->abilityLevels.push_back(reader.readUInt8());
				}
				int gart = reader.readUInt8(); //number of gained artifacts
				for(int oo = 0; oo < gart; ++oo)
				{
					if(map->version > EMapFormat::ROE)
					{
						box->artifacts.push_back(ArtifactID(reader.readUInt16()));
					}
					else
					{
						box->artifacts.push_back(ArtifactID(reader.readUInt8()));
					}
				}
				int gspel = reader.readUInt8(); //number of gained spells
				for(int oo = 0; oo < gspel; ++oo)
				{
					box->spells.push_back(SpellID(reader.readUInt8()));
				}
				int gcre = reader.readUInt8(); //number of gained creatures
				readCreatureSet(&box->creatures, gcre);
				reader.skip(8);
				break;
			}
		case Obj::GRAIL:
			{
				map->grailPos = objPos;
				map->grailRadius = reader.readUInt32();
				continue;
			}
		case Obj::RANDOM_DWELLING: //same as castle + level range
		case Obj::RANDOM_DWELLING_LVL: //same as castle, fixed level
		case Obj::RANDOM_DWELLING_FACTION: //level range, fixed faction
			{
				auto dwelling = new CGDwelling();
				nobj = dwelling;
				CSpecObjInfo * spec = nullptr;
				switch(objTempl.id)
				{
				case Obj::RANDOM_DWELLING:
					spec = new CCreGenLeveledCastleInfo();
					break;
				case Obj::RANDOM_DWELLING_LVL:
					spec = new CCreGenAsCastleInfo();
					break;
				case Obj::RANDOM_DWELLING_FACTION:
					spec = new CCreGenLeveledInfo();
					break;
				default:
					throw std::runtime_error("Invalid random dwelling format");
				}
				spec->owner = dwelling;

				nobj->setOwner(PlayerColor(reader.readUInt32()));

				//216 and 217
				if (auto castleSpec = dynamic_cast<CCreGenAsCastleInfo *>(spec))
				{
					castleSpec->instanceId = "";
					castleSpec->identifier = reader.readUInt32();
					if(!castleSpec->identifier)
					{
						castleSpec->asCastle = false;
						const int MASK_SIZE = 8;
						ui8 mask[2];
						mask[0] = reader.readUInt8();
						mask[1] = reader.readUInt8();

						castleSpec->allowedFactions.clear();
						castleSpec->allowedFactions.resize(VLC->townh->factions.size(), false);

						for(int i = 0; i < MASK_SIZE; i++)
							castleSpec->allowedFactions[i] = ((mask[0] & (1 << i))>0);

						for(int i = 0; i < (GameConstants::F_NUMBER-MASK_SIZE); i++)
							castleSpec->allowedFactions[i+MASK_SIZE] = ((mask[1] & (1 << i))>0);
					}
					else
					{
						castleSpec->asCastle = true;
					}
				}

				//216 and 218
				if (auto lvlSpec = dynamic_cast<CCreGenLeveledInfo *>(spec))
				{
					lvlSpec->minLevel = std::max(reader.readUInt8(), ui8(1));
					lvlSpec->maxLevel = std::min(reader.readUInt8(), ui8(7));
				}
				dwelling->info = spec;
				break;
			}
		case Obj::QUEST_GUARD:
			{
				auto  guard = new CGQuestGuard();
				readQuest(guard);
				nobj = guard;
				break;
			}
		case Obj::SHIPYARD:
			{
				nobj = new CGShipyard();
				nobj->setOwner(PlayerColor(reader.readUInt32()));
				break;
			}
		case Obj::HERO_PLACEHOLDER: //hero placeholder
			{
				auto  hp = new CGHeroPlaceholder();
				nobj = hp;

				hp->setOwner(PlayerColor(reader.readUInt8()));

				int htid = reader.readUInt8(); //hero type id
				nobj->subID = htid;

				if(htid == 0xff)
				{
					hp->power = reader.readUInt8();
					logGlobal->info("Hero placeholder: by power at %s", objPos.toString());
				}
				else
				{
					logGlobal->info("Hero placeholder: %s at %s", VLC->heroh->heroes[htid]->name, objPos.toString());
					hp->power = 0;
				}

				break;
			}
		case Obj::BORDERGUARD:
			{
				nobj = new CGBorderGuard();
				break;
			}
		case Obj::BORDER_GATE:
			{
				nobj = new CGBorderGate();
				break;
			}
		case Obj::PYRAMID: //Pyramid of WoG object
			{
				if(objTempl.subid == 0)
				{
					nobj = new CBank();
				}
				else
				{
					//WoG object
					//TODO: possible special handling
					nobj = new CGObjectInstance();
				}
				break;
			}
		case Obj::LIGHTHOUSE: //Lighthouse
			{
				nobj = new CGLighthouse();
				nobj->tempOwner = PlayerColor(reader.readUInt32());
				break;
			}
		default: //any other object
			{
				if (VLC->objtypeh->knownSubObjects(objTempl.id).count(objTempl.subid))
				{
					nobj = VLC->objtypeh->getHandlerFor(objTempl.id, objTempl.subid)->create(objTempl);
				}
				else
				{
					logGlobal->warn("Unrecognized object: %d:%d at %s on map %s", objTempl.id.toEnum(), objTempl.subid, objPos.toString(), map->name);
					nobj = new CGObjectInstance();
				}
				break;
			}
		}

		nobj->pos = objPos;
		nobj->ID = objTempl.id;
		nobj->id = idToBeGiven;
		if(nobj->ID != Obj::HERO && nobj->ID != Obj::HERO_PLACEHOLDER && nobj->ID != Obj::PRISON)
		{
			nobj->subID = objTempl.subid;
		}
		nobj->appearance = objTempl;
		assert(idToBeGiven == ObjectInstanceID(map->objects.size()));

		{
			//TODO: define valid typeName and subtypeName fro H3M maps
			//boost::format fmt("%s_%d");
			//fmt % nobj->typeName % nobj->id.getNum();
			boost::format fmt("obj_%d");
			fmt % nobj->id.getNum();
			nobj->instanceName = fmt.str();
		}
		map->addNewObject(nobj);
	}

	std::sort(map->heroesOnMap.begin(), map->heroesOnMap.end(), [](const ConstTransitivePtr<CGHeroInstance> & a, const ConstTransitivePtr<CGHeroInstance> & b)
	{
		return a->subID < b->subID;
	});
}

void CMapLoaderH3M::readCreatureSet(CCreatureSet * out, int number)
{
	const bool version = (map->version > EMapFormat::ROE);
	const int maxID = version ? 0xffff : 0xff;

	for(int ir = 0; ir < number; ++ir)
	{
		CreatureID creID;
		int count;

		if (version)
		{
			creID = CreatureID(reader.readUInt16());
		}
		else
		{
			creID = CreatureID(reader.readUInt8());
		}
		count = reader.readUInt16();

		// Empty slot
		if(creID == maxID)
			continue;

		auto  hlp = new CStackInstance();
		hlp->count = count;

		if(creID > maxID - 0xf)
		{
			//this will happen when random object has random army
			hlp->idRand = maxID - creID - 1;
		}
		else
		{
			hlp->setType(creID);
		}

		out->putStack(SlotID(ir), hlp);
	}

	out->validTypes(true);
}

CGObjectInstance * CMapLoaderH3M::readHero(ObjectInstanceID idToBeGiven, const int3 & initialPos)
{
	auto nhi = new CGHeroInstance();

	if(map->version > EMapFormat::ROE)
	{
		unsigned int identifier = reader.readUInt32();
		map->questIdentifierToId[identifier] = idToBeGiven;
	}

	PlayerColor owner = PlayerColor(reader.readUInt8());
	nhi->subID = reader.readUInt8();

	assert(!nhi->getArt(ArtifactPosition::MACH4));

	//If hero of this type has been predefined, use that as a base.
	//Instance data will overwrite the predefined values where appropriate.
	for(auto & elem : map->predefinedHeroes)
	{
		if(elem->subID == nhi->subID)
		{
			logGlobal->debug("Hero %d will be taken from the predefined heroes list.", nhi->subID);
			delete nhi;
			nhi = elem;
			break;
		}
	}
	nhi->setOwner(owner);

	nhi->portrait = nhi->subID;

	for(auto & elem : map->disposedHeroes)
	{
		if(elem.heroId == nhi->subID)
		{
			nhi->name = elem.name;
			nhi->portrait = elem.portrait;
			break;
		}
	}

	bool hasName = reader.readBool();
	if(hasName)
	{
		nhi->name = reader.readString();
	}
	if(map->version > EMapFormat::AB)
	{
		bool hasExp = reader.readBool();
		if(hasExp)
		{
			nhi->exp = reader.readUInt32();
		}
		else
		{
			nhi->exp = 0xffffffff;
		}
	}
	else
	{
		nhi->exp = reader.readUInt32();

		//0 means "not set" in <=AB maps
		if(!nhi->exp)
		{
			nhi->exp = 0xffffffff;
		}
	}

	bool hasPortrait = reader.readBool();
	if(hasPortrait)
	{
		nhi->portrait = reader.readUInt8();
	}

	bool hasSecSkills = reader.readBool();
	if(hasSecSkills)
	{
		if(nhi->secSkills.size())
		{
			nhi->secSkills.clear();
			//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);
		}

		int howMany = reader.readUInt32();
		nhi->secSkills.resize(howMany);
		for(int yy = 0; yy < howMany; ++yy)
		{
			nhi->secSkills[yy].first = SecondarySkill(reader.readUInt8());
			nhi->secSkills[yy].second = reader.readUInt8();
		}
	}

	bool hasGarison = reader.readBool();
	if(hasGarison)
	{
		readCreatureSet(nhi, 7);
	}

	nhi->formation = reader.readUInt8();
	loadArtifactsOfHero(nhi);
	nhi->patrol.patrolRadius = reader.readUInt8();
	if(nhi->patrol.patrolRadius == 0xff)
	{
		nhi->patrol.patrolling = false;
	}
	else
	{
		nhi->patrol.patrolling = true;
		nhi->patrol.initialPos = CGHeroInstance::convertPosition(initialPos, false);
	}

	if(map->version > EMapFormat::ROE)
	{
		bool hasCustomBiography = reader.readBool();
		if(hasCustomBiography)
		{
			nhi->biography = reader.readString();
		}
		nhi->sex = reader.readUInt8();

		// Remove trash
		if (nhi->sex != 0xFF)
		{
			nhi->sex &= 1;
		}
	}
	else
	{
		nhi->sex = 0xFF;
	}

	// Spells
	if(map->version > EMapFormat::AB)
	{
		bool hasCustomSpells = reader.readBool();
		if(nhi->spells.size())
		{
			nhi->clear();
			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);
		}

		if(hasCustomSpells)
		{
			nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"

			readSpells(nhi->spells);
		}
	}
	else if(map->version == EMapFormat::AB)
	{
		//we can read one spell
		ui8 buff = reader.readUInt8();
		if(buff != 254)
		{
			nhi->spells.insert(SpellID::PRESET); //placeholder "preset spells"
			if(buff < 254) //255 means no spells
			{
				nhi->spells.insert(SpellID(buff));
			}
		}
	}

	if(map->version > EMapFormat::AB)
	{
		bool hasCustomPrimSkills = reader.readBool();
		if(hasCustomPrimSkills)
		{
			auto ps = nhi->getAllBonuses(Selector::type(Bonus::PRIMARY_SKILL)
								.And(Selector::sourceType(Bonus::HERO_BASE_SKILL)), nullptr);
			if(ps->size())
			{
				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);
				for(auto b : *ps)
					nhi->removeBonus(b);
			}


			for(int xx = 0; xx < GameConstants::PRIMARY_SKILLS; ++xx)
			{
				nhi->pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(xx), reader.readUInt8());
			}
		}
	}
	reader.skip(16);
	return nhi;
}

CGSeerHut * CMapLoaderH3M::readSeerHut()
{
	auto  hut = new CGSeerHut();

	if(map->version > EMapFormat::ROE)
	{
		readQuest(hut);
	}
	else
	{
		//RoE
		int artID = reader.readUInt8();
		if (artID != 255)
		{
			//not none quest
			hut->quest->m5arts.push_back (artID);
			hut->quest->missionType = CQuest::MISSION_ART;
		}
		else
		{
			hut->quest->missionType = CQuest::MISSION_NONE;
		}
		hut->quest->lastDay = -1; //no timeout
		hut->quest->isCustomFirst = hut->quest->isCustomNext = hut->quest->isCustomComplete = false;
	}

	if (hut->quest->missionType)
	{
		auto rewardType = static_cast<CGSeerHut::ERewardType>(reader.readUInt8());
		hut->rewardType = rewardType;
		switch(rewardType)
		{
		case CGSeerHut::EXPERIENCE:
			{
				hut->rVal = reader.readUInt32();
				break;
			}
		case CGSeerHut::MANA_POINTS:
			{
				hut->rVal = reader.readUInt32();
				break;
			}
		case CGSeerHut::MORALE_BONUS:
			{
				hut->rVal = reader.readUInt8();
				break;
			}
		case CGSeerHut::LUCK_BONUS:
			{
				hut->rVal = reader.readUInt8();
				break;
			}
		case CGSeerHut::RESOURCES:
			{
				hut->rID = reader.readUInt8();
				// Only the first 3 bytes are used. Skip the 4th.
				hut->rVal = reader.readUInt32() & 0x00ffffff;
				break;
			}
		case CGSeerHut::PRIMARY_SKILL:
			{
				hut->rID = reader.readUInt8();
				hut->rVal = reader.readUInt8();
				break;
			}
		case CGSeerHut::SECONDARY_SKILL:
			{
				hut->rID = reader.readUInt8();
				hut->rVal = reader.readUInt8();
				break;
			}
		case CGSeerHut::ARTIFACT:
			{
				if (map->version == EMapFormat::ROE)
				{
					hut->rID = reader.readUInt8();
				}
				else
				{
					hut->rID = reader.readUInt16();
				}
				break;
			}
		case CGSeerHut::SPELL:
			{
				hut->rID = reader.readUInt8();
				break;
			}
		case CGSeerHut::CREATURE:
			{
				if(map->version > EMapFormat::ROE)
				{
					hut->rID = reader.readUInt16();
					hut->rVal = reader.readUInt16();
				}
				else
				{
					hut->rID = reader.readUInt8();
					hut->rVal = reader.readUInt16();
				}
				break;
			}
		}
		reader.skip(2);
	}
	else
	{
		// missionType==255
		reader.skip(3);
	}

	return hut;
}

void CMapLoaderH3M::readQuest(IQuestObject * guard)
{
	guard->quest->missionType = static_cast<CQuest::Emission>(reader.readUInt8());

	switch(guard->quest->missionType)
	{
	case CQuest::MISSION_NONE:
		return;
	case CQuest::MISSION_PRIMARY_STAT:
		{
			guard->quest->m2stats.resize(4);
			for(int x = 0; x < 4; ++x)
			{
				guard->quest->m2stats[x] = reader.readUInt8();
			}
		}
		break;
	case CQuest::MISSION_LEVEL:
	case CQuest::MISSION_KILL_HERO:
	case CQuest::MISSION_KILL_CREATURE:
		{
			guard->quest->m13489val = reader.readUInt32();
			break;
		}
	case CQuest::MISSION_ART:
		{
			int artNumber = reader.readUInt8();
			for(int yy = 0; yy < artNumber; ++yy)
			{
				int artid = reader.readUInt16();
				guard->quest->m5arts.push_back(artid);
				map->allowedArtifact[artid] = false; //these are unavailable for random generation
			}
			break;
		}
	case CQuest::MISSION_ARMY:
		{
			int typeNumber = reader.readUInt8();
			guard->quest->m6creatures.resize(typeNumber);
			for(int hh = 0; hh < typeNumber; ++hh)
			{
				guard->quest->m6creatures[hh].type = VLC->creh->creatures[reader.readUInt16()];
				guard->quest->m6creatures[hh].count = reader.readUInt16();
			}
			break;
		}
	case CQuest::MISSION_RESOURCES:
		{
			guard->quest->m7resources.resize(7);
			for(int x = 0; x < 7; ++x)
			{
				guard->quest->m7resources[x] = reader.readUInt32();
			}
			break;
		}
	case CQuest::MISSION_HERO:
	case CQuest::MISSION_PLAYER:
		{
			guard->quest->m13489val = reader.readUInt8();
			break;
		}
	}

	int limit = reader.readUInt32();
	if(limit == (static_cast<int>(0xffffffff)))
	{
		guard->quest->lastDay = -1;
	}
	else
	{
		guard->quest->lastDay = limit;
	}
	guard->quest->firstVisitText = reader.readString();
	guard->quest->nextVisitText = reader.readString();
	guard->quest->completedText = reader.readString();
	guard->quest->isCustomFirst = guard->quest->firstVisitText.size() > 0;
	guard->quest->isCustomNext = guard->quest->nextVisitText.size() > 0;
	guard->quest->isCustomComplete = guard->quest->completedText.size() > 0;
}

CGTownInstance * CMapLoaderH3M::readTown(int castleID)
{
	auto  nt = new CGTownInstance();
	if(map->version > EMapFormat::ROE)
	{
		nt->identifier = reader.readUInt32();
	}
	nt->tempOwner = PlayerColor(reader.readUInt8());
	bool hasName = reader.readBool();
	if(hasName)
	{
		nt->name = reader.readString();
	}

	bool hasGarrison = reader.readBool();
	if(hasGarrison)
	{
		readCreatureSet(nt, 7);
	}
	nt->formation = reader.readUInt8();

	bool hasCustomBuildings = reader.readBool();
	if(hasCustomBuildings)
	{
		readBitmask(nt->builtBuildings,6,48,false);

		readBitmask(nt->forbiddenBuildings,6,48,false);

		nt->builtBuildings = convertBuildings(nt->builtBuildings, castleID);
		nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings, castleID);
	}
	// Standard buildings
	else
	{
		bool hasFort = reader.readBool();
		if(hasFort)
		{
			nt->builtBuildings.insert(BuildingID::FORT);
		}

		//means that set of standard building should be included
		nt->builtBuildings.insert(BuildingID::DEFAULT);
	}

	if(map->version > EMapFormat::ROE)
	{
		for(int i = 0; i < 9; ++i)
		{
			ui8 c = reader.readUInt8();
			for(int yy = 0; yy < 8; ++yy)
			{
				if(i * 8 + yy < GameConstants::SPELLS_QUANTITY)
				{
					if(c == (c | static_cast<ui8>(std::pow(2., yy)))) //add obligatory spell even if it's banned on a map (?)
					{
						nt->obligatorySpells.push_back(SpellID(i * 8 + yy));
					}
				}
			}
		}
	}

	for(int i = 0; i < 9; ++i)
	{
		ui8 c = reader.readUInt8();
		for(int yy = 0; yy < 8; ++yy)
		{
			int spellid = i * 8 + yy;
			if(spellid < GameConstants::SPELLS_QUANTITY)
			{
				if(c != (c | static_cast<ui8>(std::pow(2., yy))) && map->allowedSpell[spellid]) //add random spell only if it's allowed on entire map
				{
					nt->possibleSpells.push_back(SpellID(spellid));
				}
			}
		}
	}
	//add all spells from mods
	//TODO: allow customize new spells in towns
	for (int i = SpellID::AFTER_LAST; i < VLC->spellh->objects.size(); ++i)
	{
		nt->possibleSpells.push_back(SpellID(i));
	}

	// Read castle events
	int numberOfEvent = reader.readUInt32();

	for(int gh = 0; gh < numberOfEvent; ++gh)
	{
		CCastleEvent nce;
		nce.town = nt;
		nce.name = reader.readString();
		nce.message = reader.readString();

		readResourses(nce.resources);

		nce.players = reader.readUInt8();
		if(map->version > EMapFormat::AB)
		{
			nce.humanAffected = reader.readUInt8();
		}
		else
		{
			nce.humanAffected = true;
		}

		nce.computerAffected = reader.readUInt8();
		nce.firstOccurence = reader.readUInt16();
		nce.nextOccurence =  reader.readUInt8();

		reader.skip(17);

		// New buildings

		readBitmask(nce.buildings,6,48,false);

		nce.buildings = convertBuildings(nce.buildings, castleID, false);

		nce.creatures.resize(7);
		for(int vv = 0; vv < 7; ++vv)
		{
			nce.creatures[vv] = reader.readUInt16();
		}
		reader.skip(4);
		nt->events.push_back(nce);
	}

	if(map->version > EMapFormat::AB)
	{
		nt->alignment = reader.readUInt8();
	}
	reader.skip(3);

	return nt;
}

std::set<BuildingID> CMapLoaderH3M::convertBuildings(const std::set<BuildingID> h3m, int castleID, bool addAuxiliary)
{
	std::map<int, BuildingID> mapa;
	std::set<BuildingID> ret;

	// Note: this file is parsed many times.
	const JsonNode config(ResourceID("config/buildings5.json"));

	for(const JsonNode & entry : config["table"].Vector())
	{
		int town = entry["town"].Float();

		if (town == castleID || town == -1)
		{
			mapa[entry["h3"].Float()] = BuildingID((si32)entry["vcmi"].Float());
		}
	}

	for(auto & elem : h3m)
	{
		if(mapa[elem] >= 0)
		{
			ret.insert(mapa[elem]);
		}
		// horde buildings
		else if(mapa[elem] >= (-GameConstants::CREATURES_PER_TOWN))
		{
			int level = (mapa[elem]);

			//(-30)..(-36) - horde buildings (for game loading only), don't see other way to handle hordes in random towns
			ret.insert(BuildingID(level - 30));
		}
		else
		{
			logGlobal->warn("Conversion warning: unknown building %d in castle %d", elem.num, castleID);
		}
	}

	if(addAuxiliary)
	{
		//village hall is always present
		ret.insert(BuildingID::VILLAGE_HALL);
	}

	if(ret.find(BuildingID::CITY_HALL) != ret.end())
	{
		ret.insert(BuildingID::EXTRA_CITY_HALL);
	}
	if(ret.find(BuildingID::TOWN_HALL) != ret.end())
	{
		ret.insert(BuildingID::EXTRA_TOWN_HALL);
	}
	if(ret.find(BuildingID::CAPITOL) != ret.end())
	{
		ret.insert(BuildingID::EXTRA_CAPITOL);
	}

	return ret;
}

void CMapLoaderH3M::readEvents()
{
	int numberOfEvents = reader.readUInt32();
	for(int yyoo = 0; yyoo < numberOfEvents; ++yyoo)
	{
		CMapEvent ne;
		ne.name = reader.readString();
		ne.message = reader.readString();

		readResourses(ne.resources);
		ne.players = reader.readUInt8();
		if(map->version > EMapFormat::AB)
		{
			ne.humanAffected = reader.readUInt8();
		}
		else
		{
			ne.humanAffected = true;
		}
		ne.computerAffected = reader.readUInt8();
		ne.firstOccurence = reader.readUInt16();
		ne.nextOccurence = reader.readUInt8();

		reader.skip(17);

		map->events.push_back(ne);
	}
}

void CMapLoaderH3M::readMessageAndGuards(std::string& message, CCreatureSet* guards)
{
	bool hasMessage = reader.readBool();
	if(hasMessage)
	{
		message = reader.readString();
		bool hasGuards = reader.readBool();
		if(hasGuards)
		{
			readCreatureSet(guards, 7);
		}
		reader.skip(4);
	}
}

void CMapLoaderH3M::readSpells(std::set<SpellID>& dest)
{
	readBitmask(dest,9,GameConstants::SPELLS_QUANTITY,false);
}

void CMapLoaderH3M::readResourses(TResources& resources)
{
	resources.resize(GameConstants::RESOURCE_QUANTITY); //needed?
	for(int x = 0; x < 7; ++x)
	{
		resources[x] = reader.readUInt32();
	}
}

template <class Indentifier>
void CMapLoaderH3M::readBitmask(std::set<Indentifier>& dest, const int byteCount, const int limit, bool negate)
{
	std::vector<bool> temp;
	temp.resize(limit,true);
	readBitmask(temp, byteCount, limit, negate);

	for(int i = 0; i< std::min(temp.size(), static_cast<size_t>(limit)); i++)
	{
		if(temp[i])
		{
			dest.insert(static_cast<Indentifier>(i));
		}
	}
}

void CMapLoaderH3M::readBitmask(std::vector<bool>& dest, const int byteCount, const int limit, bool negate)
{
	for(int byte = 0; byte < byteCount; ++byte)
	{
		const ui8 mask = reader.readUInt8();
		for(int bit = 0; bit < 8; ++bit)
		{
			if(byte * 8 + bit < limit)
			{
				const bool flag = mask & (1 << bit);
				if((negate && flag) || (!negate && !flag)) // FIXME: check PR388
					dest[byte * 8 + bit] = false;
			}
		}
	}
}

ui8 CMapLoaderH3M::reverse(ui8 arg)
{
	ui8 ret = 0;
	for(int i = 0; i < 8; ++i)
	{
		if((arg & (1 << i)) >> i)
		{
			ret |= (128 >> i);
		}
	}
	return ret;
}

void CMapLoaderH3M::afterRead()
{
    //convert main town positions for all players to actual object position, in H3M it is position of active tile

    for(auto & p : map->players)
	{
		int3 posOfMainTown = p.posOfMainTown;
		if(posOfMainTown.valid() && map->isInTheMap(posOfMainTown))
		{
			const TerrainTile & t = map->getTile(posOfMainTown);

			const CGObjectInstance * mainTown = nullptr;

			for(auto obj : t.visitableObjects)
			{
				if(obj->ID == Obj::TOWN || obj->ID == Obj::RANDOM_TOWN)
				{
					mainTown = obj;
					break;
				}
			}

			if(mainTown == nullptr)
				continue;

			p.posOfMainTown = posOfMainTown + mainTown->getVisitableOffset();
		}
	}
}