CGameState.cpp 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "hch/CDefObjInfoHandler.h"
  8. #include "hch/CArtHandler.h"
  9. #include "hch/CTownHandler.h"
  10. #include "hch/CSpellHandler.h"
  11. #include "hch/CHeroHandler.h"
  12. #include "hch/CObjectHandler.h"
  13. #include "hch/CCreatureHandler.h"
  14. #include "lib/VCMI_Lib.h"
  15. #include "map.h"
  16. #include "StartInfo.h"
  17. #include "lib/NetPacks.h"
  18. #include <boost/foreach.hpp>
  19. #include <boost/thread.hpp>
  20. #include <boost/thread/shared_mutex.hpp>
  21. boost::rand48 ran;
  22. #ifdef min
  23. #undef min
  24. #endif
  25. #ifdef max
  26. #undef max
  27. #endif
  28. CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  29. {
  30. CGObjectInstance * nobj;
  31. switch(id)
  32. {
  33. case 34: //hero
  34. {
  35. CGHeroInstance * nobj = new CGHeroInstance();
  36. nobj->pos = pos;
  37. nobj->tempOwner = owner;
  38. nobj->subID = subid;
  39. //nobj->initHero(ran);
  40. return nobj;
  41. }
  42. case 98: //town
  43. nobj = new CGTownInstance;
  44. break;
  45. default: //rest of objects
  46. nobj = new CGObjectInstance;
  47. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  48. break;
  49. }
  50. nobj->ID = id;
  51. nobj->subID = subid;
  52. if(!nobj->defInfo)
  53. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  54. nobj->pos = pos;
  55. //nobj->state = NULL;//new CLuaObjectScript();
  56. nobj->tempOwner = owner;
  57. nobj->info = NULL;
  58. nobj->defInfo->id = id;
  59. nobj->defInfo->subid = subid;
  60. //assigning defhandler
  61. if(nobj->ID==34 || nobj->ID==98)
  62. return nobj;
  63. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  64. return nobj;
  65. }
  66. CStack * BattleInfo::getStack(int stackID)
  67. {
  68. for(int g=0; g<stacks.size(); ++g)
  69. {
  70. if(stacks[g]->ID == stackID)
  71. return stacks[g];
  72. }
  73. return NULL;
  74. }
  75. CStack * BattleInfo::getStackT(int tileID)
  76. {
  77. for(int g=0; g<stacks.size(); ++g)
  78. {
  79. if(stacks[g]->position == tileID
  80. || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  81. || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  82. {
  83. if(stacks[g]->alive())
  84. {
  85. return stacks[g];
  86. }
  87. }
  88. }
  89. return NULL;
  90. }
  91. void BattleInfo::getAccessibilityMap(bool *accessibility, int stackToOmmit)
  92. {
  93. memset(accessibility,1,187); //initialize array with trues
  94. for(int g=0; g<stacks.size(); ++g)
  95. {
  96. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit) //we don't want to lock position of this stack
  97. continue;
  98. accessibility[stacks[g]->position] = false;
  99. if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature
  100. {
  101. if(stacks[g]->attackerOwned)
  102. accessibility[stacks[g]->position-1] = false;
  103. else
  104. accessibility[stacks[g]->position+1] = false;
  105. }
  106. }
  107. //TODO: obstacles
  108. }
  109. void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide, int stackToOmmit) //send pointer to at least 187 allocated bytes
  110. {
  111. bool mac[187];
  112. getAccessibilityMap(mac,stackToOmmit);
  113. memcpy(accessibility,mac,187);
  114. for(int b=0; b<187; ++b)
  115. {
  116. if( mac[b] && !(atackerSide ? mac[b-1] : mac[b+1]))
  117. {
  118. accessibility[b] = false;
  119. }
  120. }
  121. //removing accessibility for side hexes
  122. for(int v=0; v<187; ++v)
  123. if(atackerSide ? (v%17)==1 : (v%17)==15)
  124. accessibility[v] = false;
  125. }
  126. void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays
  127. {
  128. //inits
  129. for(int b=0; b<187; ++b)
  130. predecessor[b] = -1;
  131. for(int g=0; g<187; ++g)
  132. dists[g] = 100000000;
  133. std::queue<int> hexq; //bfs queue
  134. hexq.push(start);
  135. dists[hexq.front()] = 0;
  136. int curNext = -1; //for bfs loop only (helper var)
  137. while(!hexq.empty()) //bfs loop
  138. {
  139. int curHex = hexq.front();
  140. std::vector<int> neighbours = neighbouringTiles(curHex);
  141. hexq.pop();
  142. for(int nr=0; nr<neighbours.size(); nr++)
  143. {
  144. curNext = neighbours[nr];
  145. if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  146. continue;
  147. hexq.push(curNext);
  148. dists[curNext] = dists[curHex] + 1;
  149. predecessor[curNext] = curHex;
  150. }
  151. }
  152. };
  153. std::vector<int> BattleInfo::getAccessibility(int stackID)
  154. {
  155. std::vector<int> ret;
  156. bool ac[187];
  157. CStack *s = getStack(stackID);
  158. if(s->creature->isDoubleWide())
  159. getAccessibilityMapForTwoHex(ac,s->attackerOwned,stackID);
  160. else
  161. getAccessibilityMap(ac,stackID);
  162. int pr[187], dist[187];
  163. makeBFS(s->position,ac,pr,dist);
  164. for(int i=0;i<187;i++)
  165. if(dist[i] <= s->creature->speed)
  166. ret.push_back(i);
  167. return ret;
  168. }
  169. bool BattleInfo::isStackBlocked(int ID)
  170. {
  171. CStack *our = getStack(ID);
  172. for(int i=0; i<stacks.size();i++)
  173. {
  174. if( !stacks[i]->alive()
  175. || stacks[i]->owner==our->owner
  176. )
  177. continue; //we ommit dead and allied stacks
  178. if( mutualPosition(stacks[i]->position,our->position) >= 0 )
  179. return true;
  180. }
  181. return false;
  182. }
  183. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  184. {
  185. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  186. return 0;
  187. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  188. return 1;
  189. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  190. return 5;
  191. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  192. return 2;
  193. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  194. return 4;
  195. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  196. return 3;
  197. return -1;
  198. }
  199. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  200. {
  201. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<187 && (hlp%17!=16) && hlp%17) ret.push_back(hlp);}
  202. std::vector<int> ret;
  203. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  204. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  205. CHECK_AND_PUSH(hex - 1);
  206. CHECK_AND_PUSH(hex + 1);
  207. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  208. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  209. #undef CHECK_AND_PUSH
  210. return ret;
  211. }
  212. std::vector<int> BattleInfo::getPath(int start, int dest, bool*accessibility)
  213. {
  214. int predecessor[187]; //for getting the Path
  215. int dist[187]; //calculated distances
  216. makeBFS(start,accessibility,predecessor,dist);
  217. //making the Path
  218. std::vector<int> path;
  219. int curElem = dest;
  220. while(curElem != start)
  221. {
  222. path.push_back(curElem);
  223. curElem = predecessor[curElem];
  224. }
  225. return path;
  226. }
  227. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  228. :creature(C),amount(A), baseAmount(A), owner(O), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints), slot(S), counterAttacks(1)
  229. {
  230. abilities = C->abilities;
  231. state.insert(ALIVE);
  232. }
  233. ui32 CStack::speed()
  234. {
  235. int premy=0;
  236. StackEffect *effect = 0;
  237. //haste effect check
  238. effect = getEffect(53);
  239. if(effect)
  240. premy += VLC->spellh->spells[effect->id].powers[effect->level];
  241. //slow effect check
  242. effect = getEffect(54);
  243. if(effect)
  244. premy -= VLC->spellh->spells[effect->id].powers[effect->level];
  245. //prayer effect check
  246. effect = getEffect(48);
  247. if(effect)
  248. premy -= VLC->spellh->spells[effect->id].powers[effect->level];
  249. //bind effect check
  250. effect = getEffect(72);
  251. if(effect)
  252. premy = -creature->speed;
  253. return creature->speed + premy;
  254. }
  255. CStack::StackEffect * CStack::getEffect(ui16 id)
  256. {
  257. for (int i=0; i< effects.size(); i++)
  258. if(effects[i].id == id)
  259. return &effects[i];
  260. return NULL;
  261. }
  262. CGHeroInstance* CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, int notThatOne)
  263. {
  264. if(player<0 || player>=PLAYER_LIMIT)
  265. {
  266. tlog1 << "Cannot pick hero for " << town->name << ". Wrong owner!\n";
  267. return NULL;
  268. }
  269. std::vector<CGHeroInstance *> pool;
  270. int sum=0, r;
  271. if(native)
  272. {
  273. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  274. {
  275. if(pavailable[i->first] & 1<<player
  276. && i->second->type->heroType/2 == town->typeID
  277. && i->second->subID != notThatOne
  278. )
  279. {
  280. pool.push_back(i->second);
  281. }
  282. }
  283. if(!pool.size())
  284. return pickHeroFor(false,player,town,notThatOne);
  285. else
  286. return pool[rand()%pool.size()];
  287. }
  288. else
  289. {
  290. for(std::map<ui32,CGHeroInstance *>::iterator i=heroesPool.begin(); i!=heroesPool.end(); i++)
  291. {
  292. if(pavailable[i->first] & 1<<player
  293. && i->second->subID != notThatOne
  294. )
  295. {
  296. pool.push_back(i->second);
  297. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  298. }
  299. }
  300. if(!pool.size())
  301. {
  302. tlog1 << "There are no heroes available for player " << player<<"!\n";
  303. return NULL;
  304. }
  305. r = rand()%sum;
  306. for(int i=0; i<pool.size(); i++)
  307. {
  308. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  309. if(r<0)
  310. return pool[i];
  311. }
  312. return pool[pool.size()-1];
  313. }
  314. }
  315. void CGameState::applyNL(IPack * pack)
  316. {
  317. switch(pack->getType())
  318. {
  319. case 101://NewTurn
  320. {
  321. NewTurn * n = static_cast<NewTurn*>(pack);
  322. day = n->day;
  323. BOOST_FOREACH(NewTurn::Hero h, n->heroes) //give mana/movement point
  324. {
  325. static_cast<CGHeroInstance*>(map->objects[h.id])->movement = h.move;
  326. static_cast<CGHeroInstance*>(map->objects[h.id])->mana = h.mana;
  327. }
  328. BOOST_FOREACH(SetResources h, n->res) //give resources
  329. applyNL(&h);
  330. BOOST_FOREACH(SetAvailableCreatures h, n->cres) //set available creatures in towns
  331. applyNL(&h);
  332. if(n->resetBuilded) //reset amount of structures set in this turn in towns
  333. BOOST_FOREACH(CGTownInstance* t, map->towns)
  334. t->builded = 0;
  335. break;
  336. }
  337. case 102: //set resource amount
  338. {
  339. SetResource *sr = static_cast<SetResource*>(pack);
  340. players[sr->player].resources[sr->resid] = sr->val;
  341. break;
  342. }
  343. case 104:
  344. {
  345. SetResources *sr = static_cast<SetResources*>(pack);
  346. for(int i=0;i<sr->res.size();i++)
  347. players[sr->player].resources[i] = sr->res[i];
  348. break;
  349. }
  350. case 105:
  351. {
  352. SetPrimSkill *sr = static_cast<SetPrimSkill*>(pack);
  353. CGHeroInstance *hero = getHero(sr->id);
  354. if(sr->which <4)
  355. {
  356. if(sr->abs)
  357. hero->primSkills[sr->which] = sr->val;
  358. else
  359. hero->primSkills[sr->which] += sr->val;
  360. }
  361. else if(sr->which == 4) //XP
  362. {
  363. if(sr->abs)
  364. hero->exp = sr->val;
  365. else
  366. hero->exp += sr->val;
  367. }
  368. break;
  369. }
  370. case 106:
  371. {
  372. SetSecSkill *sr = static_cast<SetSecSkill*>(pack);
  373. CGHeroInstance *hero = getHero(sr->id);
  374. if(hero->getSecSkillLevel(sr->which) == 0)
  375. {
  376. hero->secSkills.push_back(std::pair<int,int>(sr->which, sr->val));
  377. }
  378. else
  379. {
  380. for(unsigned i=0;i<hero->secSkills.size();i++)
  381. {
  382. if(hero->secSkills[i].first == sr->which)
  383. {
  384. if(sr->abs)
  385. hero->secSkills[i].second = sr->val;
  386. else
  387. hero->secSkills[i].second += sr->val;
  388. }
  389. }
  390. }
  391. break;
  392. }
  393. case 108:
  394. {
  395. HeroVisitCastle *vc = static_cast<HeroVisitCastle*>(pack);
  396. CGHeroInstance *h = getHero(vc->hid);
  397. CGTownInstance *t = getTown(vc->tid);
  398. if(vc->start())
  399. {
  400. if(vc->garrison())
  401. {
  402. t->garrisonHero = h;
  403. h->visitedTown = t;
  404. h->inTownGarrison = true;
  405. }
  406. else
  407. {
  408. t->visitingHero = h;
  409. h->visitedTown = t;
  410. h->inTownGarrison = false;
  411. }
  412. }
  413. else
  414. {
  415. if(vc->garrison())
  416. {
  417. t->garrisonHero = NULL;
  418. h->visitedTown = NULL;
  419. h->inTownGarrison = false;
  420. }
  421. else
  422. {
  423. t->visitingHero = NULL;
  424. h->visitedTown = NULL;
  425. h->inTownGarrison = false;
  426. }
  427. }
  428. break;
  429. }
  430. case 109:
  431. {
  432. ChangeSpells *rh = static_cast<ChangeSpells*>(pack);
  433. CGHeroInstance *hero = getHero(rh->hid);
  434. if(rh->learn)
  435. BOOST_FOREACH(ui32 sid, rh->spells)
  436. hero->spells.insert(sid);
  437. else
  438. BOOST_FOREACH(ui32 sid, rh->spells)
  439. hero->spells.erase(sid);
  440. break;
  441. }
  442. case 110:
  443. {
  444. SetMana *rh = static_cast<SetMana*>(pack);
  445. CGHeroInstance *hero = getHero(rh->hid);
  446. hero->mana = rh->val;
  447. break;
  448. }
  449. case 111:
  450. {
  451. SetMovePoints *rh = static_cast<SetMovePoints*>(pack);
  452. CGHeroInstance *hero = getHero(rh->hid);
  453. hero->movement = rh->val;
  454. break;
  455. }
  456. case 112:
  457. {
  458. FoWChange *rh = static_cast<FoWChange*>(pack);
  459. BOOST_FOREACH(int3 t, rh->tiles)
  460. players[rh->player].fogOfWarMap[t.x][t.y][t.z] = rh->mode;
  461. break;
  462. }
  463. case 113:
  464. {
  465. SetAvailableHeroes *rh = static_cast<SetAvailableHeroes*>(pack);
  466. players[rh->player].availableHeroes.clear();
  467. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid1]);
  468. players[rh->player].availableHeroes.push_back(hpool.heroesPool[rh->hid2]);
  469. if(rh->flags & 1)
  470. {
  471. hpool.heroesPool[rh->hid1]->army.slots.clear();
  472. hpool.heroesPool[rh->hid1]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid1]->type->refTypeStack[0]],1);
  473. }
  474. if(rh->flags & 2)
  475. {
  476. hpool.heroesPool[rh->hid2]->army.slots.clear();
  477. hpool.heroesPool[rh->hid2]->army.slots[0] = std::pair<ui32,si32>(VLC->creh->nameToID[hpool.heroesPool[rh->hid2]->type->refTypeStack[0]],1);
  478. }
  479. break;
  480. }
  481. case 500:
  482. {
  483. RemoveObject *rh = static_cast<RemoveObject*>(pack);
  484. CGObjectInstance *obj = map->objects[rh->id];
  485. if(obj->ID==34)
  486. {
  487. CGHeroInstance *h = static_cast<CGHeroInstance*>(obj);
  488. std::vector<CGHeroInstance*>::iterator nitr = std::find(map->heroes.begin(), map->heroes.end(),h);
  489. map->heroes.erase(nitr);
  490. int player = h->tempOwner;
  491. nitr = std::find(players[player].heroes.begin(), players[player].heroes.end(), h);
  492. players[player].heroes.erase(nitr);
  493. if(h->visitedTown)
  494. {
  495. if(h->inTownGarrison)
  496. h->visitedTown->garrisonHero = NULL;
  497. else
  498. h->visitedTown->visitingHero = NULL;
  499. h->visitedTown = NULL;
  500. }
  501. }
  502. map->objects[rh->id] = NULL;
  503. //unblock tiles
  504. if(obj->defInfo)
  505. {
  506. map->removeBlockVisTiles(obj);
  507. }
  508. break;
  509. }
  510. case 501://hero try-move
  511. {
  512. TryMoveHero * n = static_cast<TryMoveHero*>(pack);
  513. CGHeroInstance *h = static_cast<CGHeroInstance*>(map->objects[n->id]);
  514. h->movement = n->movePoints;
  515. if(n->start!=n->end && n->result)
  516. {
  517. map->removeBlockVisTiles(h);
  518. h->pos = n->end;
  519. map->addBlockVisTiles(h);
  520. }
  521. BOOST_FOREACH(int3 t, n->fowRevealed)
  522. players[h->getOwner()].fogOfWarMap[t.x][t.y][t.z] = 1;
  523. break;
  524. }
  525. case 502:
  526. {
  527. SetGarrisons * n = static_cast<SetGarrisons*>(pack);
  528. for(std::map<ui32,CCreatureSet>::iterator i = n->garrs.begin(); i!=n->garrs.end(); i++)
  529. {
  530. CArmedInstance *ai = static_cast<CArmedInstance*>(map->objects[i->first]);
  531. ai->army = i->second;
  532. if(ai->ID==98 && (static_cast<CGTownInstance*>(ai))->garrisonHero) //if there is a hero in garrison then we must update also his army
  533. const_cast<CGHeroInstance*>((static_cast<CGTownInstance*>(ai))->garrisonHero)->army = i->second;
  534. else if(ai->ID==34)
  535. {
  536. CGHeroInstance *h = static_cast<CGHeroInstance*>(ai);
  537. if(h->visitedTown && h->inTownGarrison)
  538. h->visitedTown->army = i->second;
  539. }
  540. }
  541. break;
  542. }
  543. case 503:
  544. {
  545. //SetStrInfo *ssi = static_cast<SetStrInfo*>(pack);
  546. //static_cast<CGTownInstance*>(map->objects[ssi->tid])->strInfo.creatures = ssi->cres;
  547. break;
  548. }
  549. case 504:
  550. {
  551. NewStructures *ns = static_cast<NewStructures*>(pack);
  552. CGTownInstance*t = static_cast<CGTownInstance*>(map->objects[ns->tid]);
  553. BOOST_FOREACH(si32 bid,ns->bid)
  554. t->builtBuildings.insert(bid);
  555. t->builded = ns->builded;
  556. break;
  557. }
  558. case 506:
  559. {
  560. SetAvailableCreatures *sac = static_cast<SetAvailableCreatures*>(pack);
  561. static_cast<CGTownInstance*>(map->objects[sac->tid])->strInfo.creatures = sac->creatures;
  562. break;
  563. }
  564. case 508:
  565. {
  566. SetHeroesInTown *sac = static_cast<SetHeroesInTown*>(pack);
  567. CGTownInstance *t = getTown(sac->tid);
  568. CGHeroInstance *v = getHero(sac->visiting), *g = getHero(sac->garrison);
  569. t->visitingHero = v;
  570. t->garrisonHero = g;
  571. if(v)
  572. {
  573. v->visitedTown = t;
  574. v->inTownGarrison = false;
  575. map->addBlockVisTiles(v);
  576. }
  577. if(g)
  578. {
  579. g->visitedTown = t;
  580. g->inTownGarrison = true;
  581. map->removeBlockVisTiles(g);
  582. }
  583. break;
  584. }
  585. case 509:
  586. {
  587. SetHeroArtifacts *sha = static_cast<SetHeroArtifacts*>(pack);
  588. CGHeroInstance *h = getHero(sha->hid);
  589. h->artifacts = sha->artifacts;
  590. h->artifWorn = sha->artifWorn;
  591. break;
  592. }
  593. case 515:
  594. {
  595. HeroRecruited *sha = static_cast<HeroRecruited*>(pack);
  596. CGHeroInstance *h = hpool.heroesPool[sha->hid];
  597. CGTownInstance *t = getTown(sha->tid);
  598. h->setOwner(sha->player);
  599. h->pos = sha->tile;
  600. h->movement = h->maxMovePoints(true);
  601. hpool.heroesPool.erase(sha->hid);
  602. if(h->id < 0)
  603. {
  604. h->id = map->objects.size();
  605. map->objects.push_back(h);
  606. }
  607. else
  608. map->objects[h->id] = h;
  609. map->heroes.push_back(h);
  610. players[h->tempOwner].heroes.push_back(h);
  611. map->addBlockVisTiles(h);
  612. t->visitingHero = h;
  613. h->visitedTown = t;
  614. h->inTownGarrison = false;
  615. break;
  616. }
  617. case 1001://set object property
  618. {
  619. SetObjectProperty *p = static_cast<SetObjectProperty*>(pack);
  620. if(p->what == 3) //set creatures amount
  621. {
  622. tlog5 << "Setting creatures amount in " << p->id << std::endl;
  623. static_cast<CCreatureObjInfo*>(map->objects[p->id]->info)->number = p->val;
  624. break;
  625. }
  626. ui8 CGObjectInstance::*point;
  627. switch(p->what)
  628. {
  629. case 1:
  630. point = &CGObjectInstance::tempOwner;
  631. break;
  632. case 2:
  633. point = &CGObjectInstance::blockVisit;
  634. break;
  635. }
  636. map->objects[p->id]->*point = p->val;
  637. break;
  638. }
  639. case 2000:
  640. {
  641. HeroLevelUp * bs = static_cast<HeroLevelUp*>(pack);
  642. getHero(bs->heroid)->level = bs->level;
  643. break;
  644. }
  645. case 3000:
  646. {
  647. BattleStart * bs = static_cast<BattleStart*>(pack);
  648. curB = bs->info;
  649. break;
  650. }
  651. case 3001:
  652. {
  653. BattleNextRound *ns = static_cast<BattleNextRound*>(pack);
  654. curB->round = ns->round;
  655. for(int i=0; i<curB->stacks.size();i++)
  656. curB->stacks[i]->counterAttacks = 1;
  657. break;
  658. }
  659. case 3002:
  660. {
  661. BattleSetActiveStack *ns = static_cast<BattleSetActiveStack*>(pack);
  662. curB->activeStack = ns->stack;
  663. break;
  664. }
  665. case 3003:
  666. {
  667. BattleResult *br = static_cast<BattleResult*>(pack);
  668. //TODO: give exp, artifacts to winner, decrease armies (casualties)
  669. for(unsigned i=0;i<curB->stacks.size();i++)
  670. delete curB->stacks[i];
  671. delete curB;
  672. curB = NULL;
  673. break;
  674. }
  675. case 3004:
  676. {
  677. BattleStackMoved *br = static_cast<BattleStackMoved*>(pack);
  678. curB->getStack(br->stack)->position = br->tile;
  679. break;
  680. }
  681. case 3005:
  682. {
  683. BattleStackAttacked *br = static_cast<BattleStackAttacked*>(pack);
  684. CStack * at = curB->getStack(br->stackAttacked);
  685. at->amount = br->newAmount;
  686. at->firstHPleft = br->newHP;
  687. if(br->killed())
  688. at->state -= ALIVE;
  689. break;
  690. }
  691. case 3006:
  692. {
  693. BattleAttack *br = static_cast<BattleAttack*>(pack);
  694. CStack *attacker = curB->getStack(br->stackAttacking);
  695. if(br->counter())
  696. attacker->counterAttacks--;
  697. if(br->shot())
  698. attacker->shots--;
  699. applyNL(&br->bsa);
  700. break;
  701. }
  702. case 3009:
  703. {
  704. SpellCasted *sc = static_cast<SpellCasted*>(pack);
  705. CGHeroInstance *h = (sc->side) ? getHero(curB->hero2) : getHero(curB->hero1);
  706. if(h)
  707. h->mana -= VLC->spellh->spells[sc->id].costs[sc->skill];
  708. //TODO: counter
  709. break;
  710. }
  711. case 3010:
  712. {
  713. SetStackEffect *sc = static_cast<SetStackEffect*>(pack);
  714. CStack *stack = curB->getStack(sc->stack);
  715. stack->effects.push_back(sc->effect);
  716. break;
  717. }
  718. }
  719. }
  720. void CGameState::apply(IPack * pack)
  721. {
  722. while(!mx->try_lock())
  723. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  724. applyNL(pack);
  725. mx->unlock();
  726. }
  727. int CGameState::pickHero(int owner)
  728. {
  729. int h=-1;
  730. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  731. return h;
  732. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  733. int i=0;
  734. do //try to find free hero of our faction
  735. {
  736. i++;
  737. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  738. } while( map->getHero(h) && i<175);
  739. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  740. {
  741. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  742. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  743. if(!map->getHero(j))
  744. h=j;
  745. }
  746. return h;
  747. }
  748. CGHeroInstance *CGameState::getHero(int objid)
  749. {
  750. if(objid<0 || objid>=map->objects.size())
  751. return NULL;
  752. return static_cast<CGHeroInstance *>(map->objects[objid]);
  753. }
  754. CGTownInstance *CGameState::getTown(int objid)
  755. {
  756. if(objid<0 || objid>=map->objects.size())
  757. return NULL;
  758. return static_cast<CGTownInstance *>(map->objects[objid]);
  759. }
  760. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  761. {
  762. switch(obj->ID)
  763. {
  764. case 65: //random artifact
  765. return std::pair<int,int>(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki
  766. case 66: //random treasure artifact
  767. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  768. case 67: //random minor artifact
  769. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  770. case 68: //random major artifact
  771. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  772. case 69: //random relic artifact
  773. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  774. case 70: //random hero
  775. {
  776. return std::pair<int,int>(34,pickHero(obj->tempOwner));
  777. }
  778. case 71: //random monster
  779. {
  780. int r;
  781. do
  782. {
  783. r = ran()%197;
  784. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  785. return std::pair<int,int>(54,r);
  786. }
  787. case 72: //random monster lvl1
  788. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  789. case 73: //random monster lvl2
  790. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  791. case 74: //random monster lvl3
  792. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  793. case 75: //random monster lvl4
  794. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  795. case 76: //random resource
  796. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  797. case 77: //random town
  798. {
  799. int align = ((CGTownInstance*)obj)->alignment,
  800. f;
  801. if(align>PLAYER_LIMIT-1)//same as owner / random
  802. {
  803. if(obj->tempOwner > PLAYER_LIMIT-1)
  804. f = -1; //random
  805. else
  806. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  807. }
  808. else
  809. {
  810. f = scenarioOps->getIthPlayersSettings(align).castle;
  811. }
  812. if(f<0) f = ran()%VLC->townh->towns.size();
  813. return std::pair<int,int>(98,f);
  814. }
  815. case 162: //random monster lvl5
  816. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  817. case 163: //random monster lvl6
  818. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  819. case 164: //random monster lvl7
  820. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  821. case 216: //random dwelling
  822. {
  823. int faction = ran()%F_NUMBER;
  824. CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info;
  825. if (info->asCastle)
  826. {
  827. for(int i=0;i<map->objects.size();i++)
  828. {
  829. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  830. {
  831. randomizeObject(map->objects[i]); //we have to randomize the castle first
  832. faction = map->objects[i]->subID;
  833. break;
  834. }
  835. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  836. {
  837. faction = map->objects[i]->subID;
  838. break;
  839. }
  840. }
  841. }
  842. else
  843. {
  844. while((!(info->castles[0]&(1<<faction))))
  845. {
  846. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  847. break;
  848. faction = ran()%F_NUMBER;
  849. }
  850. }
  851. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  852. int cid = VLC->townh->towns[faction].basicCreatures[level];
  853. for(int i=0;i<VLC->objh->cregens.size();i++)
  854. if(VLC->objh->cregens[i]==cid)
  855. return std::pair<int,int>(17,i);
  856. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  857. return std::pair<int,int>(17,0);
  858. }
  859. case 217:
  860. {
  861. int faction = ran()%F_NUMBER;
  862. CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info;
  863. if (info->asCastle)
  864. {
  865. for(int i=0;i<map->objects.size();i++)
  866. {
  867. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  868. {
  869. randomizeObject(map->objects[i]); //we have to randomize the castle first
  870. faction = map->objects[i]->subID;
  871. break;
  872. }
  873. else if(map->objects[i]->ID==98 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  874. {
  875. faction = map->objects[i]->subID;
  876. break;
  877. }
  878. }
  879. }
  880. else
  881. {
  882. while((!(info->castles[0]&(1<<faction))))
  883. {
  884. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  885. break;
  886. faction = ran()%F_NUMBER;
  887. }
  888. }
  889. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  890. for(int i=0;i<VLC->objh->cregens.size();i++)
  891. if(VLC->objh->cregens[i]==cid)
  892. return std::pair<int,int>(17,i);
  893. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  894. return std::pair<int,int>(17,0);
  895. }
  896. case 218:
  897. {
  898. CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info;
  899. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  900. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  901. for(int i=0;i<VLC->objh->cregens.size();i++)
  902. if(VLC->objh->cregens[i]==cid)
  903. return std::pair<int,int>(17,i);
  904. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  905. return std::pair<int,int>(17,0);
  906. }
  907. }
  908. return std::pair<int,int>(-1,-1);
  909. }
  910. void CGameState::randomizeObject(CGObjectInstance *cur)
  911. {
  912. std::pair<int,int> ran = pickObject(cur);
  913. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  914. {
  915. if(cur->ID==98) //town - set def
  916. {
  917. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  918. if(t->hasCapitol())
  919. t->defInfo = capitols[t->subID];
  920. else if(t->hasFort())
  921. t->defInfo = forts[t->subID];
  922. else
  923. t->defInfo = villages[t->subID];
  924. }
  925. return;
  926. }
  927. else if(ran.first==34)//special code for hero
  928. {
  929. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  930. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  931. cur->ID = ran.first;
  932. h->portrait = cur->subID = ran.second;
  933. h->type = VLC->heroh->heroes[ran.second];
  934. map->heroes.push_back(h);
  935. return; //TODO: maybe we should do something with definfo?
  936. }
  937. else if(ran.first==98)//special code for town
  938. {
  939. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  940. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  941. cur->ID = ran.first;
  942. cur->subID = ran.second;
  943. t->town = &VLC->townh->towns[ran.second];
  944. if(t->hasCapitol())
  945. t->defInfo = capitols[t->subID];
  946. else if(t->hasFort())
  947. t->defInfo = forts[t->subID];
  948. else
  949. t->defInfo = villages[t->subID];
  950. map->towns.push_back(t);
  951. return;
  952. }
  953. //we have to replace normal random object
  954. cur->ID = ran.first;
  955. cur->subID = ran.second;
  956. map->defs.insert(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  957. if(!cur->defInfo)
  958. {
  959. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  960. return;
  961. }
  962. }
  963. int CGameState::getDate(int mode) const
  964. {
  965. int temp;
  966. switch (mode)
  967. {
  968. case 0:
  969. return day;
  970. break;
  971. case 1:
  972. temp = (day)%7;
  973. if (temp)
  974. return temp;
  975. else return 7;
  976. break;
  977. case 2:
  978. temp = ((day-1)/7)+1;
  979. if (!(temp%4))
  980. return 4;
  981. else
  982. return (temp%4);
  983. break;
  984. case 3:
  985. return ((day-1)/28)+1;
  986. break;
  987. }
  988. return 0;
  989. }
  990. CGameState::CGameState()
  991. {
  992. mx = new boost::shared_mutex();
  993. }
  994. CGameState::~CGameState()
  995. {
  996. delete mx;
  997. }
  998. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  999. {
  1000. day = 0;
  1001. seed = Seed;
  1002. ran.seed((boost::int32_t)seed);
  1003. scenarioOps = si;
  1004. this->map = map;
  1005. for(int i=0;i<F_NUMBER;i++)
  1006. {
  1007. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1008. forts[i] = VLC->dobjinfo->castles[i];
  1009. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1010. }
  1011. //picking random factions for players
  1012. for(int i=0;i<scenarioOps->playerInfos.size();i++)
  1013. {
  1014. if(scenarioOps->playerInfos[i].castle==-1)
  1015. {
  1016. int f;
  1017. do
  1018. {
  1019. f = ran()%F_NUMBER;
  1020. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1021. scenarioOps->playerInfos[i].castle = f;
  1022. }
  1023. }
  1024. //randomizing objects
  1025. for(int no=0; no<map->objects.size(); ++no)
  1026. {
  1027. randomizeObject(map->objects[no]);
  1028. if(map->objects[no]->ID==26)
  1029. {
  1030. map->objects[no]->defInfo->handler=NULL;
  1031. map->removeBlockVisTiles(map->objects[no]);
  1032. map->objects[no]->defInfo->blockMap[5] = 255;
  1033. map->addBlockVisTiles(map->objects[no]);
  1034. }
  1035. map->objects[no]->hoverName = VLC->objh->names[map->objects[no]->ID];
  1036. }
  1037. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1038. /*********give starting hero****************************************/
  1039. for(int i=0;i<PLAYER_LIMIT;i++)
  1040. {
  1041. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE))
  1042. {
  1043. int3 hpos = map->players[i].posOfMainTown;
  1044. hpos.x+=1;// hpos.y+=1;
  1045. int j;
  1046. for(j=0; j<scenarioOps->playerInfos.size(); j++)
  1047. if(scenarioOps->playerInfos[j].color == i)
  1048. break;
  1049. if(j == scenarioOps->playerInfos.size())
  1050. continue;
  1051. int h=pickHero(i);
  1052. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(34,h,hpos,i));
  1053. nnn->id = map->objects.size();
  1054. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1055. for(int o=0;o<map->towns.size();o++) //find main town
  1056. {
  1057. if(map->towns[o]->pos == hpos)
  1058. {
  1059. map->towns[o]->visitingHero = nnn;
  1060. nnn->visitedTown = map->towns[o];
  1061. nnn->inTownGarrison = false;
  1062. break;
  1063. }
  1064. }
  1065. nnn->initHero();
  1066. map->heroes.push_back(nnn);
  1067. map->objects.push_back(nnn);
  1068. map->addBlockVisTiles(nnn);
  1069. }
  1070. }
  1071. /*********creating players entries in gs****************************************/
  1072. for (int i=0; i<scenarioOps->playerInfos.size();i++)
  1073. {
  1074. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1075. ins.second.color=ins.first;
  1076. ins.second.serial=i;
  1077. players.insert(ins);
  1078. }
  1079. /******************RESOURCES****************************************************/
  1080. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1081. std::vector<int> startres;
  1082. std::ifstream tis("config/startres.txt");
  1083. int k;
  1084. for (int j=0;j<scenarioOps->difficulty;j++)
  1085. {
  1086. tis >> k;
  1087. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1088. tis>>k;
  1089. }
  1090. tis >> k;
  1091. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1092. {
  1093. tis >> k;
  1094. startres.push_back(k);
  1095. }
  1096. tis.close();
  1097. tis.clear();
  1098. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1099. {
  1100. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1101. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1102. (*i).second.resources[x] = startres[x];
  1103. }
  1104. tis.open("config/resources.txt");
  1105. tis >> k;
  1106. int pom;
  1107. for(int i=0;i<k;i++)
  1108. {
  1109. tis >> pom;
  1110. resVals.push_back(pom);
  1111. }
  1112. /*************************HEROES************************************************/
  1113. std::set<int> hids;
  1114. for(int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1115. if(map->allowedHeroes[i])
  1116. hids.insert(i);
  1117. for (int i=0; i<map->heroes.size();i++) //heroes instances
  1118. {
  1119. if (map->heroes[i]->getOwner()<0)
  1120. {
  1121. tlog2 << "Warning - hero with uninitialized owner!\n";
  1122. continue;
  1123. }
  1124. CGHeroInstance * vhi = (map->heroes[i]);
  1125. vhi->initHero();
  1126. players[vhi->getOwner()].heroes.push_back(vhi);
  1127. hids.erase(vhi->subID);
  1128. }
  1129. for(int i=0; i<map->predefinedHeroes.size(); i++)
  1130. {
  1131. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1132. continue;
  1133. map->predefinedHeroes[i]->initHero();
  1134. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1135. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1136. hids.erase(map->predefinedHeroes[i]->subID);
  1137. }
  1138. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1139. {
  1140. CGHeroInstance * vhi = new CGHeroInstance();
  1141. vhi->initHero(hid);
  1142. hpool.heroesPool[hid] = vhi;
  1143. hpool.pavailable[hid] = 0xff;
  1144. }
  1145. for(int i=0; i<map->disposedHeroes.size(); i++)
  1146. {
  1147. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1148. }
  1149. /*************************FOG**OF**WAR******************************************/
  1150. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1151. {
  1152. k->second.fogOfWarMap.resize(map->width);
  1153. for(int g=0; g<map->width; ++g)
  1154. k->second.fogOfWarMap[g].resize(map->height);
  1155. for(int g=-0; g<map->width; ++g)
  1156. for(int h=0; h<map->height; ++h)
  1157. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1158. for(int g=0; g<map->width; ++g)
  1159. for(int h=0; h<map->height; ++h)
  1160. for(int v=0; v<map->twoLevel+1; ++v)
  1161. k->second.fogOfWarMap[g][h][v] = 0;
  1162. for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1163. {
  1164. for(int yd=0; yd<map->height; ++yd)
  1165. {
  1166. for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1167. {
  1168. int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1169. int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1170. if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1171. k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1172. }
  1173. }
  1174. }
  1175. //starting bonus
  1176. if(si->playerInfos[k->second.serial].bonus==brandom)
  1177. si->playerInfos[k->second.serial].bonus = ran()%3;
  1178. switch(si->playerInfos[k->second.serial].bonus)
  1179. {
  1180. case bgold:
  1181. k->second.resources[6] += 500 + (ran()%6)*100;
  1182. break;
  1183. case bresource:
  1184. {
  1185. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1186. if(res == 127)
  1187. {
  1188. k->second.resources[0] += 5 + ran()%6;
  1189. k->second.resources[2] += 5 + ran()%6;
  1190. }
  1191. else
  1192. {
  1193. k->second.resources[res] += 3 + ran()%4;
  1194. }
  1195. break;
  1196. }
  1197. case bartifact:
  1198. {
  1199. if(!k->second.heroes.size())
  1200. {
  1201. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1202. break;
  1203. }
  1204. CArtifact *toGive;
  1205. do
  1206. {
  1207. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1208. } while (!map->allowedArtifact[toGive->id]);
  1209. CGHeroInstance *hero = k->second.heroes[0];
  1210. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1211. if(slot!=toGive->possibleSlots.end())
  1212. hero->artifWorn[*slot] = toGive->id;
  1213. else
  1214. hero->artifacts.push_back(toGive->id);
  1215. }
  1216. }
  1217. }
  1218. /****************************TOWNS************************************************/
  1219. for (int i=0;i<map->towns.size();i++)
  1220. {
  1221. CGTownInstance * vti =(map->towns[i]);
  1222. if(!vti->town)
  1223. vti->town = &VLC->townh->towns[vti->subID];
  1224. if (vti->name.length()==0) // if town hasn't name we draw it
  1225. vti->name=vti->town->names[ran()%vti->town->names.size()];
  1226. //init buildings
  1227. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1228. {
  1229. vti->builtBuildings.erase(-50);
  1230. vti->builtBuildings.insert(10);
  1231. vti->builtBuildings.insert(5);
  1232. vti->builtBuildings.insert(30);
  1233. if(ran()%2)
  1234. vti->builtBuildings.insert(31);
  1235. }
  1236. //init spells
  1237. vti->spells.resize(SPELL_LEVELS);
  1238. CSpell *s;
  1239. for(int z=0; z<vti->obligatorySpells.size();z++)
  1240. {
  1241. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1242. vti->spells[s->level-1].push_back(s->id);
  1243. vti->possibleSpells -= s->id;
  1244. }
  1245. while(vti->possibleSpells.size())
  1246. {
  1247. ui32 total=0, sel=-1;
  1248. for(int ps=0;ps<vti->possibleSpells.size();ps++)
  1249. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1250. int r = (total)? ran()%total : -1;
  1251. for(int ps=0; ps<vti->possibleSpells.size();ps++)
  1252. {
  1253. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1254. if(r<0)
  1255. {
  1256. sel = ps;
  1257. break;
  1258. }
  1259. }
  1260. if(sel<0)
  1261. sel=0;
  1262. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1263. vti->spells[s->level-1].push_back(s->id);
  1264. vti->possibleSpells -= s->id;
  1265. }
  1266. //init garrisons
  1267. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1268. {
  1269. if(j->second.first > 196 && j->second.first < 211)
  1270. {
  1271. if(j->second.first%2)
  1272. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1273. else
  1274. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1275. }
  1276. }
  1277. players[vti->getOwner()].towns.push_back(vti);
  1278. }
  1279. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1280. {
  1281. if(k->first==-1 || k->first==255)
  1282. continue;
  1283. for(int xd=0; xd<map->width; ++xd) //revealing part of map around towns
  1284. {
  1285. for(int yd=0; yd<map->height; ++yd)
  1286. {
  1287. for(int ch=0; ch<k->second.towns.size(); ++ch)
  1288. {
  1289. int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
  1290. int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
  1291. if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
  1292. k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
  1293. }
  1294. }
  1295. }
  1296. //init visiting and garrisoned heroes
  1297. for(int l=0; l<k->second.heroes.size();l++)
  1298. {
  1299. for(int m=0; m<k->second.towns.size();m++)
  1300. {
  1301. int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
  1302. if(vistile == k->second.heroes[l]->pos || k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1303. {
  1304. k->second.towns[m]->visitingHero = k->second.heroes[l];
  1305. k->second.heroes[l]->visitedTown = k->second.towns[m];
  1306. k->second.heroes[l]->inTownGarrison = false;
  1307. if(k->second.heroes[l]->pos==k->second.towns[m]->pos)
  1308. k->second.heroes[l]->pos.x -= 1;
  1309. break;
  1310. }
  1311. //else if(k->second.heroes[l]->pos == k->second.towns[m]->pos)
  1312. //{
  1313. // k->second.towns[m]->garrisonHero = k->second.heroes[l];
  1314. // k->second.towns[m]->army = k->second.heroes[l]->army;
  1315. // k->second.heroes[l]->visitedTown = k->second.towns[m];
  1316. // k->second.heroes[l]->inTownGarrison = true;
  1317. // k->second.heroes[l]->pos.x -= 1;
  1318. // goto mainplheloop;
  1319. //}
  1320. }
  1321. }
  1322. }
  1323. }
  1324. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1325. {
  1326. return true;
  1327. }
  1328. int CGameState::battleGetStack(int pos)
  1329. {
  1330. if(!curB)
  1331. return -1;
  1332. for(int g=0; g<curB->stacks.size(); ++g)
  1333. {
  1334. if(curB->stacks[g]->position == pos ||
  1335. ( curB->stacks[g]->creature->isDoubleWide() &&
  1336. ( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos) ||
  1337. (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos)
  1338. )
  1339. )
  1340. )
  1341. return curB->stacks[g]->ID;
  1342. }
  1343. return -1;
  1344. }
  1345. UpgradeInfo CGameState::getUpgradeInfo(CArmedInstance *obj, int stackPos)
  1346. {
  1347. UpgradeInfo ret;
  1348. CCreature *base = &VLC->creh->creatures[obj->army.slots[stackPos].first];
  1349. if((obj->ID == 98) || ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1350. {
  1351. CGTownInstance * t;
  1352. if(obj->ID == 98)
  1353. t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
  1354. else
  1355. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1356. for(std::set<si32>::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1357. {
  1358. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1359. {
  1360. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1361. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1362. {
  1363. ret.newID.push_back(nid);
  1364. ret.cost.push_back(std::set<std::pair<int,int> >());
  1365. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1366. {
  1367. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1368. if(dif)
  1369. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1370. }
  1371. }
  1372. }
  1373. }//end for
  1374. }
  1375. //TODO: check if hero ability makes some upgrades possible
  1376. if(ret.newID.size())
  1377. ret.oldID = base->idNumber;
  1378. return ret;
  1379. }
  1380. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1381. {
  1382. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1383. if(mode) return -1; //todo - support other modes
  1384. int mcount = 0;
  1385. for(int i=0;i<players[player].towns.size();i++)
  1386. if(vstd::contains(players[player].towns[i]->builtBuildings,14))
  1387. mcount++;
  1388. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1389. return ret;
  1390. }
  1391. std::set<int3> CGameState::tilesToReveal(int3 pos, int radious, int player)
  1392. {
  1393. std::set<int3> ret;
  1394. int xbeg = pos.x - radious - 2;
  1395. if(xbeg < 0)
  1396. xbeg = 0;
  1397. int xend = pos.x + radious + 2;
  1398. if(xend >= map->width)
  1399. xend = map->width;
  1400. int ybeg = pos.y - radious - 2;
  1401. if(ybeg < 0)
  1402. ybeg = 0;
  1403. int yend = pos.y + radious + 2;
  1404. if(yend >= map->height)
  1405. yend = map->height;
  1406. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  1407. {
  1408. for(int yd=ybeg; yd<yend; ++yd)
  1409. {
  1410. int deltaX = (pos.x-xd)*(pos.x-xd);
  1411. int deltaY = (pos.y-yd)*(pos.y-yd);
  1412. if(deltaX+deltaY<radious*radious)
  1413. {
  1414. if(player<0 || players[player].fogOfWarMap[xd][yd][pos.z]==0)
  1415. {
  1416. ret.insert(int3(xd,yd,pos.z));
  1417. }
  1418. }
  1419. }
  1420. }
  1421. return ret;
  1422. }
  1423. int BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting)
  1424. {
  1425. int attackDefenseBonus = attacker->creature->attack + (attackerHero ? attackerHero->getPrimSkillLevel(0) : 0) - (defender->creature->defence + (defendingHero ? defendingHero->getPrimSkillLevel(1) : 0));
  1426. int damageBase = 0;
  1427. if(attacker->creature->damageMax == attacker->creature->damageMin) //constant damage
  1428. {
  1429. damageBase = attacker->creature->damageMin;
  1430. }
  1431. else
  1432. {
  1433. damageBase = rand()%(attacker->creature->damageMax - attacker->creature->damageMin) + attacker->creature->damageMin + 1;
  1434. }
  1435. float dmgBonusMultiplier = 1.0f;
  1436. if(attackDefenseBonus < 0) //decreasing dmg
  1437. {
  1438. if(0.02f * (-attackDefenseBonus) > 0.3f)
  1439. {
  1440. dmgBonusMultiplier += -0.3f;
  1441. }
  1442. else
  1443. {
  1444. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  1445. }
  1446. }
  1447. else //increasing dmg
  1448. {
  1449. if(0.05f * attackDefenseBonus > 4.0f)
  1450. {
  1451. dmgBonusMultiplier += 4.0f;
  1452. }
  1453. else
  1454. {
  1455. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  1456. }
  1457. }
  1458. //handling secondary abilities
  1459. if(attackerHero)
  1460. {
  1461. if(shooting)
  1462. {
  1463. switch(attackerHero->getSecSkillLevel(1)) //archery
  1464. {
  1465. case 1: //basic
  1466. dmgBonusMultiplier *= 1.1f;
  1467. break;
  1468. case 2: //advanced
  1469. dmgBonusMultiplier *= 1.25f;
  1470. break;
  1471. case 3: //expert
  1472. dmgBonusMultiplier *= 1.5f;
  1473. break;
  1474. }
  1475. }
  1476. else
  1477. {
  1478. switch(attackerHero->getSecSkillLevel(22)) //offence
  1479. {
  1480. case 1: //basic
  1481. dmgBonusMultiplier *= 1.1f;
  1482. break;
  1483. case 2: //advanced
  1484. dmgBonusMultiplier *= 1.2f;
  1485. break;
  1486. case 3: //expert
  1487. dmgBonusMultiplier *= 1.3f;
  1488. break;
  1489. }
  1490. }
  1491. }
  1492. if(defendingHero)
  1493. {
  1494. switch(defendingHero->getSecSkillLevel(23)) //armourer
  1495. {
  1496. case 1: //basic
  1497. dmgBonusMultiplier *= 0.95f;
  1498. break;
  1499. case 2: //advanced
  1500. dmgBonusMultiplier *= 0.9f;
  1501. break;
  1502. case 3: //expert
  1503. dmgBonusMultiplier *= 0.85f;
  1504. break;
  1505. }
  1506. }
  1507. return (float)damageBase * (float)attacker->amount * dmgBonusMultiplier;
  1508. }
  1509. void BattleInfo::calculateCasualties( std::set<std::pair<ui32,si32> > *casualties )
  1510. {
  1511. for(int i=0; i<stacks.size();i++)//setting casualties
  1512. {
  1513. if(!stacks[i]->alive())
  1514. {
  1515. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount));
  1516. }
  1517. else if(stacks[i]->amount != stacks[i]->baseAmount)
  1518. {
  1519. casualties[!stacks[i]->attackerOwned].insert(std::pair<ui32,si32>(stacks[i]->creature->idNumber,stacks[i]->baseAmount - stacks[i]->amount));
  1520. }
  1521. }
  1522. }