CGameState.cpp 37 KB

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