CGameState.cpp 55 KB

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