CGameState.cpp 35 KB

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