CGameState.cpp 59 KB

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