CGameState.cpp 55 KB

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