File: CHeroHandler.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 (980 lines) | stat: -rw-r--r-- 30,937 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
/*
 * CHeroHandler.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 "CHeroHandler.h"

#include "CGeneralTextHandler.h"
#include "filesystem/Filesystem.h"
#include "VCMI_Lib.h"
#include "JsonNode.h"
#include "StringConstants.h"
#include "battle/BattleHex.h"
#include "CCreatureHandler.h"
#include "CModHandler.h"
#include "CTownHandler.h"
#include "mapObjects/CObjectHandler.h" //for hero specialty
#include "CSkillHandler.h"
#include <math.h>

#include "mapObjects/CObjectClassesHandler.h"

SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
{
	int totalProb = 0;
	for(auto & possible : possibles)
	{
		totalProb += secSkillProbability[possible];
	}
	if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
	{
		auto ran = rand.nextInt(totalProb - 1);
		for(auto & possible : possibles)
		{
			ran -= secSkillProbability[possible];
			if(ran < 0)
			{
				return possible;
			}
		}
	}
	// FIXME: select randomly? How H3 handles such rare situation?
	return *possibles.begin();
}

bool CHeroClass::isMagicHero() const
{
	return affinity == MAGIC;
}

EAlignment::EAlignment CHeroClass::getAlignment() const
{
	return EAlignment::EAlignment(VLC->townh->factions[faction]->alignment);
}

CHeroClass::CHeroClass()
 : faction(0), id(0), affinity(0), defaultTavernChance(0), commander(nullptr)
{
}

std::vector<BattleHex> CObstacleInfo::getBlocked(BattleHex hex) const
{
	std::vector<BattleHex> ret;
	if(isAbsoluteObstacle)
	{
		assert(!hex.isValid());
		range::copy(blockedTiles, std::back_inserter(ret));
		return ret;
	}

	for(int offset : blockedTiles)
	{
		BattleHex toBlock = hex + offset;
		if((hex.getY() & 1) && !(toBlock.getY() & 1))
			toBlock += BattleHex::LEFT;

		if(!toBlock.isValid())
			logGlobal->error("Misplaced obstacle!");
		else
			ret.push_back(toBlock);
	}

	return ret;
}

bool CObstacleInfo::isAppropriate(ETerrainType terrainType, int specialBattlefield) const
{
	if(specialBattlefield != -1)
		return vstd::contains(allowedSpecialBfields, specialBattlefield);

	return vstd::contains(allowedTerrains, terrainType);
}

CHeroClass * CHeroClassHandler::loadFromJson(const JsonNode & node, const std::string & identifier)
{
	std::string affinityStr[2] = { "might", "magic" };

	auto  heroClass = new CHeroClass();
	heroClass->identifier = identifier;
	heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
	heroClass->imageBattleMale   = node["animation"]["battle"]["male"].String();
	//MODS COMPATIBILITY FOR 0.96
	heroClass->imageMapFemale    = node["animation"]["map"]["female"].String();
	heroClass->imageMapMale      = node["animation"]["map"]["male"].String();

	heroClass->name = node["name"].String();
	heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());

	for(const std::string & pSkill : PrimarySkill::names)
	{
		heroClass->primarySkillInitial.push_back(node["primarySkills"][pSkill].Float());
		heroClass->primarySkillLowLevel.push_back(node["lowLevelChance"][pSkill].Float());
		heroClass->primarySkillHighLevel.push_back(node["highLevelChance"][pSkill].Float());
	}

	for(auto skillPair : node["secondarySkills"].Struct())
	{
		int probability = skillPair.second.Integer();
		VLC->modh->identifiers.requestIdentifier(skillPair.second.meta, "skill", skillPair.first, [heroClass, probability](si32 skillID)
		{
			if(heroClass->secSkillProbability.size() <= skillID)
				heroClass->secSkillProbability.resize(skillID + 1, -1); // -1 = override with default later
			heroClass->secSkillProbability[skillID] = probability;
		});
	}

	VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
	[=](si32 commanderID)
	{
		heroClass->commander = VLC->creh->creatures[commanderID];
	});

	heroClass->defaultTavernChance = node["defaultTavern"].Float();
	for(auto & tavern : node["tavern"].Struct())
	{
		int value = tavern.second.Float();

		VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
		[=](si32 factionID)
		{
			heroClass->selectionProbability[factionID] = value;
		});
	}

	VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
	[=](si32 factionID)
	{
		heroClass->faction = factionID;
	});

	return heroClass;
}

std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
{
	heroClasses.resize(dataSize);
	std::vector<JsonNode> h3Data;
	h3Data.reserve(dataSize);

	CLegacyConfigParser parser("DATA/HCTRAITS.TXT");

	parser.endLine(); // header
	parser.endLine();

	for (size_t i=0; i<dataSize; i++)
	{
		JsonNode entry;

		entry["name"].String() = parser.readString();

		parser.readNumber(); // unused aggression

		for (auto & name : PrimarySkill::names)
			entry["primarySkills"][name].Float() = parser.readNumber();

		for (auto & name : PrimarySkill::names)
			entry["lowLevelChance"][name].Float() = parser.readNumber();

		for (auto & name : PrimarySkill::names)
			entry["highLevelChance"][name].Float() = parser.readNumber();

		for (auto & name : NSecondarySkill::names)
			entry["secondarySkills"][name].Float() = parser.readNumber();

		for(auto & name : ETownType::names)
			entry["tavern"][name].Float() = parser.readNumber();

		parser.endLine();
		h3Data.push_back(entry);
	}
	return h3Data;
}

void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
	auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
	object->id = heroClasses.size();

	heroClasses.push_back(object);

	VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
	{
		JsonNode classConf = data["mapObject"];
		classConf["heroClass"].String() = name;
		classConf.setMeta(scope);
		VLC->objtypeh->loadSubObject(name, classConf, index, object->id);
	});

	VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
}

void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
	auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
	object->id = index;

	assert(heroClasses[index] == nullptr); // ensure that this id was not loaded before
	heroClasses[index] = object;

	VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
	{
		JsonNode classConf = data["mapObject"];
		classConf["heroClass"].String() = name;
		classConf.setMeta(scope);
		VLC->objtypeh->loadSubObject(name, classConf, index, object->id);
	});

	VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
}

void CHeroClassHandler::afterLoadFinalization()
{
	// for each pair <class, town> set selection probability if it was not set before in tavern entries
	for (CHeroClass * heroClass : heroClasses)
	{
		for (CFaction * faction : VLC->townh->factions)
		{
			if (!faction->town)
				continue;
			if (heroClass->selectionProbability.count(faction->index))
				continue;

			float chance = heroClass->defaultTavernChance * faction->town->defaultTavernChance;
			heroClass->selectionProbability[faction->index] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
		}
		// set default probabilities for gaining secondary skills where not loaded previously
		heroClass->secSkillProbability.resize(VLC->skillh->size(), -1);
		for(int skillID = 0; skillID < VLC->skillh->size(); skillID++)
		{
			if(heroClass->secSkillProbability[skillID] < 0)
			{
				const CSkill * skill = (*VLC->skillh)[SecondarySkill(skillID)];
				logMod->trace("%s: no probability for %s, using default", heroClass->identifier, skill->identifier);
				heroClass->secSkillProbability[skillID] = skill->gainChance[heroClass->affinity];
			}
		}
	}

	for (CHeroClass * hc : heroClasses)
	{
		if (!hc->imageMapMale.empty())
		{
			JsonNode templ;
			templ["animation"].String() = hc->imageMapMale;
			VLC->objtypeh->getHandlerFor(Obj::HERO, hc->id)->addTemplate(templ);
		}
	}
}

std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
{
	return std::vector<bool>(heroClasses.size(), true);
}

CHeroClassHandler::~CHeroClassHandler()
{
	for(auto heroClass : heroClasses)
	{
		delete heroClass.get();
	}
}

CHeroHandler::~CHeroHandler()
{
	for(auto hero : heroes)
		delete hero.get();
}

CHeroHandler::CHeroHandler()
{
	VLC->heroh = this;

	loadObstacles();
	loadTerrains();
	for (int i = 0; i < GameConstants::TERRAIN_TYPES; ++i)
	{
		VLC->modh->identifiers.registerObject("core", "terrain", GameConstants::TERRAIN_NAMES[i], i);
	}
	loadBallistics();
	loadExperience();
}

CHero * CHeroHandler::loadFromJson(const JsonNode & node, const std::string & identifier)
{
	auto hero = new CHero();
	hero->identifier = identifier;
	hero->sex = node["female"].Bool();
	hero->special = node["special"].Bool();

	hero->name        = node["texts"]["name"].String();
	hero->biography   = node["texts"]["biography"].String();
	hero->specName    = node["texts"]["specialty"]["name"].String();
	hero->specTooltip = node["texts"]["specialty"]["tooltip"].String();
	hero->specDescr   = node["texts"]["specialty"]["description"].String();

	hero->iconSpecSmall = node["images"]["specialtySmall"].String();
	hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
	hero->portraitSmall = node["images"]["small"].String();
	hero->portraitLarge = node["images"]["large"].String();
	hero->battleImage = node["battleImage"].String();

	loadHeroArmy(hero, node);
	loadHeroSkills(hero, node);
	loadHeroSpecialty(hero, node);

	VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
	[=](si32 classID)
	{
		hero->heroClass = classes.heroClasses[classID];
	});

	return hero;
}

void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
{
	assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots

	hero->initialArmy.resize(node["army"].Vector().size());

	for (size_t i=0; i< hero->initialArmy.size(); i++)
	{
		const JsonNode & source = node["army"].Vector()[i];

		hero->initialArmy[i].minAmount = source["min"].Float();
		hero->initialArmy[i].maxAmount = source["max"].Float();

		assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);

		VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
		{
			hero->initialArmy[i].creature = CreatureID(creature);
		});
	}
}

void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
{
	for(const JsonNode &set : node["skills"].Vector())
	{
		int skillLevel = boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels);
		if (skillLevel < SecSkillLevel::LEVELS_SIZE)
		{
			size_t currentIndex = hero->secSkillsInit.size();
			hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));

			VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
			{
				hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
			});
		}
		else
		{
			logMod->error("Unknown skill level: %s", set["level"].String());
		}
	}

	// spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
	hero->haveSpellBook = !node["spellbook"].isNull();

	for(const JsonNode & spell : node["spellbook"].Vector())
	{
		VLC->modh->identifiers.requestIdentifier("spell", spell,
		[=](si32 spellID)
		{
			hero->spells.insert(SpellID(spellID));
		});
	}
}

// add standard creature specialty to result
void AddSpecialtyForCreature(int creatureID, std::shared_ptr<Bonus> bonus, std::vector<std::shared_ptr<Bonus>> &result)
{
	const CCreature &specBaseCreature = *VLC->creh->creatures[creatureID]; //base creature in which we have specialty

	bonus->limiter.reset(new CCreatureTypeLimiter(specBaseCreature, true));
	bonus->type = Bonus::STACKS_SPEED;
	bonus->valType = Bonus::ADDITIVE_VALUE;
	bonus->val = 1;
	result.push_back(bonus);

	// attack and defense may differ for upgraded creatures => separate bonuses
	std::vector<int> specTargets;
	specTargets.push_back(creatureID);
	specTargets.insert(specTargets.end(), specBaseCreature.upgrades.begin(), specBaseCreature.upgrades.end());

	for(int cid : specTargets)
	{
		const CCreature &specCreature = *VLC->creh->creatures[cid];
		bonus = std::make_shared<Bonus>(*bonus);
		bonus->limiter.reset(new CCreatureTypeLimiter(specCreature, false));
		bonus->type = Bonus::PRIMARY_SKILL;
		bonus->val = 0;

		int stepSize = specCreature.level ? specCreature.level : 5;

		bonus->subtype = PrimarySkill::ATTACK;
		bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getAttack(false), stepSize));
		result.push_back(bonus);

		bonus = std::make_shared<Bonus>(*bonus);
		bonus->subtype = PrimarySkill::DEFENSE;
		bonus->updater.reset(new GrowsWithLevelUpdater(specCreature.getDefence(false), stepSize));
		result.push_back(bonus);
	}
}

// convert deprecated format
std::vector<std::shared_ptr<Bonus>> SpecialtyInfoToBonuses(const SSpecialtyInfo & spec, int sid)
{
	std::vector<std::shared_ptr<Bonus>> result;

	std::shared_ptr<Bonus> bonus = std::make_shared<Bonus>();
	bonus->duration = Bonus::PERMANENT;
	bonus->source = Bonus::HERO_SPECIAL;
	bonus->sid = sid;
	bonus->val = spec.val;

	switch (spec.type)
	{
	case 1: //creature specialty
		AddSpecialtyForCreature(spec.additionalinfo, bonus, result);
		break;
	case 2: //secondary skill
		bonus->type = Bonus::SECONDARY_SKILL_PREMY;
		bonus->valType = Bonus::PERCENT_TO_BASE;
		bonus->subtype = spec.subtype;
		bonus->updater.reset(new TimesHeroLevelUpdater());
		result.push_back(bonus);
		break;
	case 3: //spell damage bonus, level dependent but calculated elsewhere
		bonus->type = Bonus::SPECIAL_SPELL_LEV;
		bonus->subtype = spec.subtype;
		bonus->updater.reset(new TimesHeroLevelUpdater());
		result.push_back(bonus);
		break;
	case 4: //creature stat boost
		switch (spec.subtype)
		{
		case 1:
			bonus->type = Bonus::PRIMARY_SKILL;
			bonus->subtype = PrimarySkill::ATTACK;
			break;
		case 2:
			bonus->type = Bonus::PRIMARY_SKILL;
			bonus->subtype = PrimarySkill::DEFENSE;
			break;
		case 3:
			bonus->type = Bonus::CREATURE_DAMAGE;
			bonus->subtype = 0; //both min and max
			break;
		case 4:
			bonus->type = Bonus::STACK_HEALTH;
			break;
		case 5:
			bonus->type = Bonus::STACKS_SPEED;
			break;
		default:
			logMod->warn("Unknown subtype for specialty 4");
			return result;
		}
		bonus->valType = Bonus::ADDITIVE_VALUE;
		bonus->limiter.reset(new CCreatureTypeLimiter(*VLC->creh->creatures[spec.additionalinfo], true));
		result.push_back(bonus);
		break;
	case 5: //spell damage bonus in percent
		bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
		bonus->valType = Bonus::BASE_NUMBER; //current spell system is screwed
		bonus->subtype = spec.subtype; //spell id
		result.push_back(bonus);
		break;
	case 6: //damage bonus for bless (Adela)
		bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
		bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
		bonus->additionalInfo = spec.additionalinfo; //damage factor
		bonus->updater.reset(new TimesHeroLevelUpdater());
		result.push_back(bonus);
		break;
	case 7: //maxed mastery for spell
		bonus->type = Bonus::MAXED_SPELL;
		bonus->subtype = spec.subtype; //spell id
		result.push_back(bonus);
		break;
	case 8: //peculiar spells - enchantments
		bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
		bonus->subtype = spec.subtype; //spell id
		bonus->additionalInfo = spec.additionalinfo; //0, 1 for Coronius
		result.push_back(bonus);
		break;
	case 9: //upgrade creatures
		{
			const auto &creatures = VLC->creh->creatures;
			bonus->type = Bonus::SPECIAL_UPGRADE;
			bonus->subtype = spec.subtype; //base id
			bonus->additionalInfo = spec.additionalinfo; //target id
			result.push_back(bonus);
			//propagate for regular upgrades of base creature
			for(auto cre_id : creatures[spec.subtype]->upgrades)
			{
				std::shared_ptr<Bonus> upgradeUpgradedVersion = std::make_shared<Bonus>(*bonus);
				upgradeUpgradedVersion->subtype = cre_id;
				result.push_back(upgradeUpgradedVersion);
			}
		}
		break;
	case 10: //resource generation
		bonus->type = Bonus::GENERATE_RESOURCE;
		bonus->subtype = spec.subtype;
		result.push_back(bonus);
		break;
	case 11: //starting skill with mastery (Adrienne)
		logMod->warn("Secondary skill mastery is no longer supported as specialty.");
		break;
	case 12: //army speed
		bonus->type = Bonus::STACKS_SPEED;
		result.push_back(bonus);
		break;
	case 13: //Dragon bonuses (Mutare)
		bonus->type = Bonus::PRIMARY_SKILL;
		bonus->valType = Bonus::ADDITIVE_VALUE;
		switch(spec.subtype)
		{
		case 1:
			bonus->subtype = PrimarySkill::ATTACK;
			break;
		case 2:
			bonus->subtype = PrimarySkill::DEFENSE;
			break;
		}
		bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
		result.push_back(bonus);
		break;
	default:
		logMod->warn("Unknown hero specialty %d", spec.type);
		break;
	}

	return result;
}

// convert deprecated format
std::vector<std::shared_ptr<Bonus>> SpecialtyBonusToBonuses(const SSpecialtyBonus & spec, int sid)
{
	std::vector<std::shared_ptr<Bonus>> result;
	for(std::shared_ptr<Bonus> oldBonus : spec.bonuses)
	{
		oldBonus->sid = sid;
		if(oldBonus->type == Bonus::SPECIAL_SPELL_LEV || oldBonus->type == Bonus::SPECIAL_BLESS_DAMAGE)
		{
			// these bonuses used to auto-scale with hero level
			std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
			newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
			result.push_back(newBonus);
		}
		else if(spec.growsWithLevel)
		{
			std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*oldBonus);
			switch(newBonus->type)
			{
			case Bonus::SECONDARY_SKILL_PREMY:
				break; // ignore - used to be overwritten based on SPECIAL_SECONDARY_SKILL
			case Bonus::SPECIAL_SECONDARY_SKILL:
				newBonus->type = Bonus::SECONDARY_SKILL_PREMY;
				newBonus->updater = std::make_shared<TimesHeroLevelUpdater>();
				result.push_back(newBonus);
				break;
			case Bonus::PRIMARY_SKILL:
				if((newBonus->subtype == PrimarySkill::ATTACK || newBonus->subtype == PrimarySkill::DEFENSE) && newBonus->limiter)
				{
					const std::shared_ptr<CCreatureTypeLimiter> creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(newBonus->limiter);
					if(creatureLimiter)
					{
						const CCreature * cre = creatureLimiter->creature;
						int creStat = newBonus->subtype == PrimarySkill::ATTACK ? cre->getAttack(false) : cre->getDefence(false);
						int creLevel = cre->level ? cre->level : 5;
						newBonus->updater = std::make_shared<GrowsWithLevelUpdater>(creStat, creLevel);
					}
					result.push_back(newBonus);
				}
				break;
			default:
				result.push_back(newBonus);
			}
		}
		else
		{
			result.push_back(oldBonus);
		}
	}
	return result;
}

void CHeroHandler::beforeValidate(JsonNode & object)
{
	//handle "base" specialty info
	JsonNode & specialtyNode = object["specialty"];
	if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
	{
		const JsonNode & base = specialtyNode["base"];
		if(!base.isNull())
		{
			if(specialtyNode["bonuses"].isNull())
			{
				logMod->warn("specialty has base without bonuses");
			}
			else
			{
				JsonMap & bonuses = specialtyNode["bonuses"].Struct();
				for(std::pair<std::string, JsonNode> keyValue : bonuses)
					JsonUtils::inherit(bonuses[keyValue.first], base);
			}
		}
	}
}

void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
{
	int sid = hero->ID.getNum();
	auto prepSpec = [=](std::shared_ptr<Bonus> bonus)
	{
		bonus->duration = Bonus::PERMANENT;
		bonus->source = Bonus::HERO_SPECIAL;
		bonus->sid = sid;
		return bonus;
	};

	//deprecated, used only for original specialties
	const JsonNode & specialtiesNode = node["specialties"];
	if (!specialtiesNode.isNull())
	{
		logMod->warn("Hero %s has deprecated specialties format.", hero->identifier);
		for(const JsonNode &specialty : specialtiesNode.Vector())
		{
			SSpecialtyInfo spec;
			spec.type = specialty["type"].Integer();
			spec.val = specialty["val"].Integer();
			spec.subtype = specialty["subtype"].Integer();
			spec.additionalinfo = specialty["info"].Integer();
			//we convert after loading completes, to have all identifiers for json logging
			hero->specDeprecated.push_back(spec);
		}
	}
	//new(er) format, using bonus system
	const JsonNode & specialtyNode = node["specialty"];
	if(specialtyNode.getType() == JsonNode::JsonType::DATA_VECTOR)
	{
		//deprecated middle-aged format
		for(const JsonNode & specialty : node["specialty"].Vector())
		{
			SSpecialtyBonus hs;
			hs.growsWithLevel = specialty["growsWithLevel"].Bool();
			for (const JsonNode & bonus : specialty["bonuses"].Vector())
				hs.bonuses.push_back(prepSpec(JsonUtils::parseBonus(bonus)));
			hero->specialtyDeprecated.push_back(hs);
		}
	}
	else if(specialtyNode.getType() == JsonNode::JsonType::DATA_STRUCT)
	{
		//creature specialty - alias for simplicity
		if(!specialtyNode["creature"].isNull())
		{
			VLC->modh->identifiers.requestIdentifier("creature", specialtyNode["creature"], [hero](si32 creature) {
				// use legacy format for delayed conversion (must have all creature data loaded, also for upgrades)
				SSpecialtyInfo spec;
				spec.type = 1;
				spec.additionalinfo = creature;
				hero->specDeprecated.push_back(spec);
			});
		}
		if(!specialtyNode["bonuses"].isNull())
		{
			//proper new format
			for(auto keyValue : specialtyNode["bonuses"].Struct())
				hero->specialty.push_back(prepSpec(JsonUtils::parseBonus(keyValue.second)));
		}
	}
}

void CHeroHandler::loadExperience()
{
	expPerLevel.push_back(0);
	expPerLevel.push_back(1000);
	expPerLevel.push_back(2000);
	expPerLevel.push_back(3200);
	expPerLevel.push_back(4600);
	expPerLevel.push_back(6200);
	expPerLevel.push_back(8000);
	expPerLevel.push_back(10000);
	expPerLevel.push_back(12200);
	expPerLevel.push_back(14700);
	expPerLevel.push_back(17500);
	expPerLevel.push_back(20600);
	expPerLevel.push_back(24320);
	expPerLevel.push_back(28784);
	expPerLevel.push_back(34140);
	while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
	{
		auto i = expPerLevel.size() - 1;
		auto diff = expPerLevel[i] - expPerLevel[i-1];
		diff += diff / 5;
		expPerLevel.push_back (expPerLevel[i] + diff);
	}
	expPerLevel.pop_back();//last value is broken
}

void CHeroHandler::loadObstacles()
{
	auto loadObstacles = [](const JsonNode &node, bool absolute, std::map<int, CObstacleInfo> &out)
	{
		for(const JsonNode &obs : node.Vector())
		{
			int ID = obs["id"].Float();
			CObstacleInfo & obi = out[ID];
			obi.ID = ID;
			obi.defName = obs["defname"].String();
			obi.width = obs["width"].Float();
			obi.height = obs["height"].Float();
			obi.allowedTerrains = obs["allowedTerrain"].convertTo<std::vector<ETerrainType> >();
			obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo<std::vector<BFieldType> >();
			obi.blockedTiles = obs["blockedTiles"].convertTo<std::vector<si16> >();
			obi.isAbsoluteObstacle = absolute;
		}
	};

	const JsonNode config(ResourceID("config/obstacles.json"));
	loadObstacles(config["obstacles"], false, obstacles);
	loadObstacles(config["absoluteObstacles"], true, absoluteObstacles);
	//loadObstacles(config["moats"], true, moats);
}

/// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
static std::string genRefName(std::string input)
{
	boost::algorithm::replace_all(input, " ", ""); //remove spaces
	input[0] = std::tolower(input[0]); // to camelCase
	return input;
}

void CHeroHandler::loadBallistics()
{
	CLegacyConfigParser ballParser("DATA/BALLIST.TXT");

	ballParser.endLine(); //header
	ballParser.endLine();

	do
	{
		ballParser.readString();
		ballParser.readString();

		CHeroHandler::SBallisticsLevelInfo bli;
		bli.keep   = ballParser.readNumber();
		bli.tower  = ballParser.readNumber();
		bli.gate   = ballParser.readNumber();
		bli.wall   = ballParser.readNumber();
		bli.shots  = ballParser.readNumber();
		bli.noDmg  = ballParser.readNumber();
		bli.oneDmg = ballParser.readNumber();
		bli.twoDmg = ballParser.readNumber();
		bli.sum    = ballParser.readNumber();
		ballistics.push_back(bli);

		assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
	}
	while (ballParser.endLine());
}

std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
{
	heroes.resize(dataSize);
	std::vector<JsonNode> h3Data;
	h3Data.reserve(dataSize);

	CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
	CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
	CLegacyConfigParser parser("DATA/HOTRAITS.TXT");

	parser.endLine(); //ignore header
	parser.endLine();

	specParser.endLine(); //ignore header
	specParser.endLine();

	for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
	{
		JsonNode heroData;

		heroData["texts"]["name"].String() = parser.readString();
		heroData["texts"]["biography"].String() = bioParser.readString();
		heroData["texts"]["specialty"]["name"].String() = specParser.readString();
		heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
		heroData["texts"]["specialty"]["description"].String() = specParser.readString();

		for(int x=0;x<3;x++)
		{
			JsonNode armySlot;
			armySlot["min"].Float() = parser.readNumber();
			armySlot["max"].Float() = parser.readNumber();
			armySlot["creature"].String() = genRefName(parser.readString());

			heroData["army"].Vector().push_back(armySlot);
		}
		parser.endLine();
		specParser.endLine();
		bioParser.endLine();

		h3Data.push_back(heroData);
	}
	return h3Data;
}

void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
{
	auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
	object->ID = HeroTypeID(heroes.size());
	object->imageIndex = heroes.size() + GameConstants::HERO_PORTRAIT_SHIFT; // 2 special frames + some extra portraits

	heroes.push_back(object);

	VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
}

void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
{
	auto object = loadFromJson(data, normalizeIdentifier(scope, "core", name));
	object->ID = HeroTypeID(index);
	object->imageIndex = index;

	assert(heroes[index] == nullptr); // ensure that this id was not loaded before
	heroes[index] = object;

	VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
}

void CHeroHandler::afterLoadFinalization()
{
	for(ConstTransitivePtr<CHero> hero : heroes)
	{
		for(auto bonus : hero->specialty)
		{
			bonus->sid = hero->ID.getNum();
		}

		if(hero->specDeprecated.size() > 0 || hero->specialtyDeprecated.size() > 0)
		{
			logMod->debug("Converting specialty format for hero %s(%s)", hero->identifier, VLC->townh->encodeFaction(hero->heroClass->faction));
			std::vector<std::shared_ptr<Bonus>> convertedBonuses;
			for(const SSpecialtyInfo & spec : hero->specDeprecated)
			{
				for(std::shared_ptr<Bonus> b : SpecialtyInfoToBonuses(spec, hero->ID.getNum()))
					convertedBonuses.push_back(b);
			}
			for(const SSpecialtyBonus & spec : hero->specialtyDeprecated)
			{
				for(std::shared_ptr<Bonus> b : SpecialtyBonusToBonuses(spec, hero->ID.getNum()))
					convertedBonuses.push_back(b);
			}
			hero->specDeprecated.clear();
			hero->specialtyDeprecated.clear();
			// store and create json for logging
			std::vector<JsonNode> specVec;
			std::vector<std::string> specNames;
			for(std::shared_ptr<Bonus> bonus : convertedBonuses)
			{
				hero->specialty.push_back(bonus);
				specVec.push_back(bonus->toJsonNode());
				// find fitting & unique bonus name
				std::string bonusName = bonus->nameForBonus();
				if(vstd::contains(specNames, bonusName))
				{
					int suffix = 2;
					while(vstd::contains(specNames, bonusName + std::to_string(suffix)))
						suffix++;
					bonusName += std::to_string(suffix);
				}
				specNames.push_back(bonusName);
			}
			// log new format for easy copy-and-paste
			JsonNode specNode(JsonNode::JsonType::DATA_STRUCT);
			if(specVec.size() > 1)
			{
				JsonNode base = JsonUtils::intersect(specVec);
				if(base.containsBaseData())
				{
					specNode["base"] = base;
					for(JsonNode & node : specVec)
						node = JsonUtils::difference(node, base);
				}
			}
			// add json for bonuses
			specNode["bonuses"].Struct();
			for(int i = 0; i < specVec.size(); i++)
				specNode["bonuses"][specNames[i]] = specVec[i];
			logMod->trace("\"specialty\" : %s", specNode.toJson(true));
		}
	}
}

ui32 CHeroHandler::level (ui64 experience) const
{
	return boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel);
}

ui64 CHeroHandler::reqExp (ui32 level) const
{
	if(!level)
		return 0;

	if (level <= expPerLevel.size())
	{
		return expPerLevel[level-1];
	}
	else
	{
		logGlobal->warn("A hero has reached unsupported amount of experience");
		return expPerLevel[expPerLevel.size()-1];
	}
}

void CHeroHandler::loadTerrains()
{
	const JsonNode config(ResourceID("config/terrains.json"));

	terrCosts.reserve(GameConstants::TERRAIN_TYPES);
	for(const std::string & name : GameConstants::TERRAIN_NAMES)
		terrCosts.push_back(config[name]["moveCost"].Float());
}

std::vector<bool> CHeroHandler::getDefaultAllowed() const
{
	// Look Data/HOTRAITS.txt for reference
	std::vector<bool> allowedHeroes;
	allowedHeroes.reserve(heroes.size());

	for(const CHero * hero : heroes)
	{
		allowedHeroes.push_back(!hero->special);
	}

	return allowedHeroes;
}

si32 CHeroHandler::decodeHero(const std::string & identifier)
{
	auto rawId = VLC->modh->identifiers.getIdentifier("core", "hero", identifier);
	if(rawId)
		return rawId.get();
	else
		return -1;
}

std::string CHeroHandler::encodeHero(const si32 index)
{
	return VLC->heroh->heroes.at(index)->identifier;
}