CGameState.cpp 39 KB

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