CGameState.cpp 54 KB

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