CGameState.cpp 39 KB

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