CGameState.cpp 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include <boost/assign/list_of.hpp>
  26. #include "RegisterTypes.cpp"
  27. boost::rand48 ran;
  28. #ifdef min
  29. #undef min
  30. #endif
  31. #ifdef max
  32. #undef max
  33. #endif
  34. /*
  35. * CGameState.cpp, part of VCMI engine
  36. *
  37. * Authors: listed in file AUTHORS in main folder
  38. *
  39. * License: GNU General Public License v2.0 or later
  40. * Full text of license available in license.txt file, in main folder
  41. *
  42. */
  43. void foofoofoo()
  44. {
  45. //never called function to force instantation of templates
  46. int *ccc = NULL;
  47. registerTypes((CISer<CConnection>&)*ccc);
  48. registerTypes((COSer<CConnection>&)*ccc);
  49. registerTypes((CSaveFile&)*ccc);
  50. registerTypes((CLoadFile&)*ccc);
  51. registerTypes((CTypeList&)*ccc);
  52. }
  53. class CBaseForGSApply
  54. {
  55. public:
  56. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  57. };
  58. template <typename T> class CApplyOnGS : public CBaseForGSApply
  59. {
  60. public:
  61. void applyOnGS(CGameState *gs, void *pack) const
  62. {
  63. T *ptr = static_cast<T*>(pack);
  64. while(!gs->mx->try_lock())
  65. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  66. ptr->applyGs(gs);
  67. gs->mx->unlock();
  68. }
  69. };
  70. class CGSApplier
  71. {
  72. public:
  73. std::map<ui16,CBaseForGSApply*> apps;
  74. CGSApplier()
  75. {
  76. registerTypes2(*this);
  77. }
  78. template<typename T> void registerType(const T * t=NULL)
  79. {
  80. ui16 ID = typeList.registerType(t);
  81. apps[ID] = new CApplyOnGS<T>;
  82. }
  83. } *applierGs = NULL;
  84. class IObjectCaller
  85. {
  86. public:
  87. virtual void preInit()=0;
  88. virtual void postInit()=0;
  89. };
  90. template <typename T>
  91. class CObjectCaller : public IObjectCaller
  92. {
  93. public:
  94. void preInit()
  95. {
  96. T::preInit();
  97. }
  98. void postInit()
  99. {
  100. T::postInit();
  101. }
  102. };
  103. class CObjectCallersHandler
  104. {
  105. public:
  106. std::vector<IObjectCaller*> apps;
  107. template<typename T> void registerType(const T * t=NULL)
  108. {
  109. apps.push_back(new CObjectCaller<T>);
  110. }
  111. CObjectCallersHandler()
  112. {
  113. registerTypes1(*this);
  114. }
  115. ~CObjectCallersHandler()
  116. {
  117. for (size_t i = 0; i < apps.size(); i++)
  118. delete apps[i];
  119. }
  120. void preInit()
  121. {
  122. for (size_t i = 0; i < apps.size(); i++)
  123. apps[i]->preInit();
  124. }
  125. void postInit()
  126. {
  127. for (size_t i = 0; i < apps.size(); i++)
  128. apps[i]->postInit();
  129. }
  130. } *objCaller = NULL;
  131. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  132. {
  133. int type = txt.first, ser = txt.second;
  134. if(type == ART_NAMES)
  135. {
  136. dst = VLC->arth->artifacts[ser].Name();
  137. }
  138. else if(type == CRE_PL_NAMES)
  139. {
  140. dst = VLC->creh->creatures[ser].namePl;
  141. }
  142. else if(type == MINE_NAMES)
  143. {
  144. dst = VLC->generaltexth->mines[ser].first;
  145. }
  146. else if(type == MINE_EVNTS)
  147. {
  148. dst = VLC->generaltexth->mines[ser].second;
  149. }
  150. else if(type == SPELL_NAME)
  151. {
  152. dst = VLC->spellh->spells[ser].name;
  153. }
  154. else if(type == CRE_SING_NAMES)
  155. {
  156. dst = VLC->creh->creatures[ser].nameSing;
  157. }
  158. else
  159. {
  160. std::vector<std::string> *vec;
  161. switch(type)
  162. {
  163. case GENERAL_TXT:
  164. vec = &VLC->generaltexth->allTexts;
  165. break;
  166. case XTRAINFO_TXT:
  167. vec = &VLC->generaltexth->xtrainfo;
  168. break;
  169. case OBJ_NAMES:
  170. vec = &VLC->generaltexth->names;
  171. break;
  172. case RES_NAMES:
  173. vec = &VLC->generaltexth->restypes;
  174. break;
  175. case ARRAY_TXT:
  176. vec = &VLC->generaltexth->arraytxt;
  177. break;
  178. case CREGENS:
  179. vec = &VLC->generaltexth->creGens;
  180. break;
  181. case CREGENS4:
  182. vec = &VLC->generaltexth->creGens4;
  183. break;
  184. case ADVOB_TXT:
  185. vec = &VLC->generaltexth->advobtxt;
  186. break;
  187. case ART_EVNTS:
  188. vec = &VLC->generaltexth->artifEvents;
  189. break;
  190. case SEC_SKILL_NAME:
  191. vec = &VLC->generaltexth->skillName;
  192. break;
  193. }
  194. dst = (*vec)[ser];
  195. }
  196. }
  197. DLL_EXPORT void MetaString::toString(std::string &dst) const
  198. {
  199. size_t exSt = 0, loSt = 0, nums = 0;
  200. dst.clear();
  201. for(size_t i=0;i<message.size();++i)
  202. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  203. switch(message[i])
  204. {
  205. case TEXACT_STRING:
  206. dst += exactStrings[exSt++];
  207. break;
  208. case TLOCAL_STRING:
  209. {
  210. std::string hlp;
  211. getLocalString(localStrings[loSt++], hlp);
  212. dst += hlp;
  213. }
  214. break;
  215. case TNUMBER:
  216. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  217. break;
  218. case TREPLACE_ESTRING:
  219. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  220. break;
  221. case TREPLACE_LSTRING:
  222. {
  223. std::string hlp;
  224. getLocalString(localStrings[loSt++], hlp);
  225. dst.replace (dst.find("%s"), 2, hlp);
  226. }
  227. break;
  228. case TREPLACE_NUMBER:
  229. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  230. break;
  231. default:
  232. tlog1 << "MetaString processing error!\n";
  233. break;
  234. }
  235. }
  236. }
  237. DLL_EXPORT std::string MetaString::buildList () const
  238. ///used to handle loot from creature bank
  239. {
  240. size_t exSt = 0, loSt = 0, nums = 0;
  241. std::string lista;
  242. for (int i = 0; i < message.size(); ++i)
  243. {
  244. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  245. {
  246. if (exSt == exactStrings.size() - 1)
  247. lista += VLC->generaltexth->allTexts[141]; //" and "
  248. else
  249. lista += ", ";
  250. }
  251. switch (message[i])
  252. {
  253. case TEXACT_STRING:
  254. lista += exactStrings[exSt++];
  255. break;
  256. case TLOCAL_STRING:
  257. {
  258. std::string hlp;
  259. getLocalString (localStrings[loSt++], hlp);
  260. lista += hlp;
  261. }
  262. break;
  263. case TNUMBER:
  264. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  265. break;
  266. case TREPLACE_ESTRING:
  267. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  268. break;
  269. case TREPLACE_LSTRING:
  270. {
  271. std::string hlp;
  272. getLocalString (localStrings[loSt++], hlp);
  273. lista.replace (lista.find("%s"), 2, hlp);
  274. }
  275. break;
  276. case TREPLACE_NUMBER:
  277. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  278. break;
  279. default:
  280. tlog1 << "MetaString processing error!\n";
  281. }
  282. }
  283. return lista;
  284. }
  285. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  286. {
  287. CGObjectInstance * nobj;
  288. switch(id)
  289. {
  290. case HEROI_TYPE: //hero
  291. {
  292. CGHeroInstance * nobj = new CGHeroInstance();
  293. nobj->pos = pos;
  294. nobj->tempOwner = owner;
  295. nobj->subID = subid;
  296. //nobj->initHero(ran);
  297. return nobj;
  298. }
  299. case TOWNI_TYPE: //town
  300. nobj = new CGTownInstance;
  301. break;
  302. default: //rest of objects
  303. nobj = new CGObjectInstance;
  304. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  305. break;
  306. }
  307. nobj->ID = id;
  308. nobj->subID = subid;
  309. if(!nobj->defInfo)
  310. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  311. nobj->pos = pos;
  312. //nobj->state = NULL;//new CLuaObjectScript();
  313. nobj->tempOwner = owner;
  314. nobj->info = NULL;
  315. nobj->defInfo->id = id;
  316. nobj->defInfo->subid = subid;
  317. //assigning defhandler
  318. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  319. return nobj;
  320. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  321. return nobj;
  322. }
  323. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  324. {
  325. for(unsigned int g=0; g<stacks.size(); ++g)
  326. {
  327. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  328. return stacks[g];
  329. }
  330. return NULL;
  331. }
  332. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  333. {
  334. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  335. }
  336. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  337. {
  338. for(unsigned int g=0; g<stacks.size(); ++g)
  339. {
  340. if(stacks[g]->position == tileID
  341. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  342. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  343. {
  344. if(!onlyAlive || stacks[g]->alive())
  345. {
  346. return stacks[g];
  347. }
  348. }
  349. }
  350. return NULL;
  351. }
  352. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  353. {
  354. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  355. }
  356. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  357. {
  358. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  359. //removing accessibility for side columns of hexes
  360. for(int v = 0; v < BFIELD_SIZE; ++v)
  361. {
  362. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  363. accessibility[v] = false;
  364. }
  365. for(unsigned int g=0; g<stacks.size(); ++g)
  366. {
  367. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  368. continue;
  369. accessibility[stacks[g]->position] = false;
  370. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  371. {
  372. if(stacks[g]->attackerOwned)
  373. accessibility[stacks[g]->position-1] = false;
  374. else
  375. accessibility[stacks[g]->position+1] = false;
  376. }
  377. }
  378. //obstacles
  379. for(unsigned int b=0; b<obstacles.size(); ++b)
  380. {
  381. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  382. for(unsigned int c=0; c<blocked.size(); ++c)
  383. {
  384. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  385. accessibility[blocked[c]] = false;
  386. }
  387. }
  388. //walls
  389. if(siege > 0)
  390. {
  391. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  392. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  393. {
  394. accessibility[permanentlyLocked[b]] = false;
  395. }
  396. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  397. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  398. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  399. {
  400. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  401. {
  402. accessibility[lockedIfNotDestroyed[b].second] = false;
  403. }
  404. }
  405. //gate
  406. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  407. {
  408. accessibility[95] = accessibility[96] = false; //block gate's hexes
  409. }
  410. }
  411. //occupyability
  412. if(addOccupiable && twoHex)
  413. {
  414. std::set<int> rem; //tiles to unlock
  415. for(int h=0; h<BFIELD_HEIGHT; ++h)
  416. {
  417. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  418. {
  419. int hex = h * BFIELD_WIDTH + w;
  420. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  421. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  422. )
  423. rem.insert(hex);
  424. }
  425. }
  426. occupyable = rem;
  427. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  428. {
  429. accessibility[*it] = true;
  430. }*/
  431. }
  432. }
  433. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  434. {
  435. if(flying && !lastPos)
  436. return true;
  437. if(twoHex)
  438. {
  439. //if given hex is accessible and appropriate adjacent one is free too
  440. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  441. }
  442. else
  443. {
  444. return accessibility[hex];
  445. }
  446. }
  447. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  448. {
  449. //inits
  450. for(int b=0; b<BFIELD_SIZE; ++b)
  451. predecessor[b] = -1;
  452. for(int g=0; g<BFIELD_SIZE; ++g)
  453. dists[g] = 100000000;
  454. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  455. hexq.push(std::make_pair(start, true));
  456. dists[hexq.front().first] = 0;
  457. int curNext = -1; //for bfs loop only (helper var)
  458. while(!hexq.empty()) //bfs loop
  459. {
  460. std::pair<int, bool> curHex = hexq.front();
  461. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  462. hexq.pop();
  463. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  464. {
  465. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  466. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  467. if( dists[curHex.first]+1 >= dists[curNext] )
  468. continue;
  469. if(accessible && curHex.second)
  470. {
  471. hexq.push(std::make_pair(curNext, true));
  472. dists[curNext] = dists[curHex.first] + 1;
  473. }
  474. else if(fillPredecessors && !(accessible && !curHex.second))
  475. {
  476. hexq.push(std::make_pair(curNext, false));
  477. dists[curNext] = dists[curHex.first] + 1;
  478. }
  479. predecessor[curNext] = curHex.first;
  480. }
  481. }
  482. };
  483. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  484. {
  485. std::vector<int> ret;
  486. bool ac[BFIELD_SIZE];
  487. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  488. if(s->position < 0) //turrets
  489. return std::vector<int>();
  490. std::set<int> occupyable;
  491. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  492. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  493. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), false);
  494. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  495. {
  496. if(!addOccupiable)
  497. {
  498. std::vector<int> rem;
  499. for(int b=0; b<BFIELD_SIZE; ++b)
  500. {
  501. //don't take into account most left and most right columns of hexes
  502. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  503. continue;
  504. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  505. {
  506. rem.push_back(b);
  507. }
  508. }
  509. for(unsigned int g=0; g<rem.size(); ++g)
  510. {
  511. ac[rem[g]] = false;
  512. }
  513. //removing accessibility for side hexes
  514. for(int v=0; v<BFIELD_SIZE; ++v)
  515. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  516. ac[v] = false;
  517. }
  518. }
  519. for (int i=0; i < BFIELD_SIZE ; ++i) {
  520. if(
  521. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  522. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  523. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  524. )
  525. {
  526. ret.push_back(i);
  527. }
  528. }
  529. return ret;
  530. }
  531. bool BattleInfo::isStackBlocked(int ID)
  532. {
  533. CStack *our = getStack(ID);
  534. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  535. return false;
  536. for(unsigned int i=0; i<stacks.size();i++)
  537. {
  538. if( !stacks[i]->alive()
  539. || stacks[i]->owner==our->owner
  540. )
  541. continue; //we omit dead and allied stacks
  542. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  543. {
  544. if( mutualPosition(stacks[i]->position, our->position) >= 0
  545. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  546. return true;
  547. }
  548. else
  549. {
  550. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  551. return true;
  552. }
  553. }
  554. return false;
  555. }
  556. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  557. {
  558. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  559. return 0;
  560. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  561. return 1;
  562. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  563. return 5;
  564. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  565. return 2;
  566. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  567. return 4;
  568. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  569. return 3;
  570. return -1;
  571. }
  572. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  573. {
  574. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  575. std::vector<int> ret;
  576. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  577. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  578. CHECK_AND_PUSH(hex - 1);
  579. CHECK_AND_PUSH(hex + 1);
  580. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  581. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  582. #undef CHECK_AND_PUSH
  583. return ret;
  584. }
  585. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  586. {
  587. int predecessor[BFIELD_SIZE]; //for getting the Path
  588. int dist[BFIELD_SIZE]; //calculated distances
  589. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  590. if(predecessor[dest] == -1) //cannot reach destination
  591. {
  592. return std::make_pair(std::vector<int>(), 0);
  593. }
  594. //making the Path
  595. std::vector<int> path;
  596. int curElem = dest;
  597. while(curElem != start)
  598. {
  599. path.push_back(curElem);
  600. curElem = predecessor[curElem];
  601. }
  602. return std::make_pair(path, dist[dest]);
  603. }
  604. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype, int turn) const
  605. {
  606. int ret = 0;
  607. if(subtype == -1024) //any subtype
  608. {
  609. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  610. if(i->type == type && (!turn || i->turnsRemain > turn))
  611. ret += i->value;
  612. }
  613. else //given subtype
  614. {
  615. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  616. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  617. ret += i->value;
  618. }
  619. return ret;
  620. }
  621. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype, int turn) const
  622. {
  623. if(subtype == -1024) //any subtype
  624. {
  625. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  626. if(i->type == type && (!turn || i->turnsRemain > turn))
  627. return true;
  628. }
  629. else //given subtype
  630. {
  631. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  632. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  633. return true;
  634. }
  635. return false;
  636. }
  637. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  638. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  639. counterAttacks(1), shots(C->shots), features(C->abilities)
  640. {
  641. //additional retaliations
  642. for(int h=0; h<C->abilities.size(); ++h)
  643. {
  644. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  645. {
  646. counterAttacks += C->abilities[h].value;
  647. }
  648. }
  649. //alive state indication
  650. state.insert(ALIVE);
  651. }
  652. ui32 CStack::Speed( int turn /*= 0*/ ) const
  653. {
  654. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON, -1024, turn)) //war machnes cannot move
  655. return 0;
  656. int speed = creature->speed;
  657. speed += valOfFeatures(StackFeature::SPEED_BONUS, -1024, turn);
  658. int percentBonus = 0;
  659. for(int g=0; g<features.size(); ++g)
  660. {
  661. if(features[g].type == StackFeature::SPEED_BONUS)
  662. {
  663. percentBonus += features[g].additionalInfo;
  664. }
  665. }
  666. speed = ((100 + percentBonus) * speed)/100;
  667. //bind effect check
  668. if(getEffect(72))
  669. {
  670. return 0;
  671. }
  672. return speed;
  673. }
  674. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  675. {
  676. for (unsigned int i=0; i< effects.size(); i++)
  677. if(effects[i].id == id)
  678. if(!turn || effects[i].turnsRemain > turn)
  679. return &effects[i];
  680. return NULL;
  681. }
  682. ui8 CStack::howManyEffectsSet(ui16 id) const
  683. {
  684. ui8 ret = 0;
  685. for (unsigned int i=0; i< effects.size(); i++)
  686. if(effects[i].id == id) //effect found
  687. {
  688. ++ret;
  689. }
  690. return ret;
  691. }
  692. si8 CStack::Morale() const
  693. {
  694. si8 ret = morale;
  695. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  696. return 0;
  697. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  698. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  699. {
  700. ret = std::max<si8>(ret, +1);
  701. }
  702. if(ret > 3) ret = 3;
  703. if(ret < -3) ret = -3;
  704. return ret;
  705. }
  706. si8 CStack::Luck() const
  707. {
  708. si8 ret = luck;
  709. if(hasFeatureOfType(StackFeature::NO_LUCK))
  710. return 0;
  711. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  712. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  713. {
  714. ret = std::max<si8>(ret, +1);
  715. }
  716. if(ret > 3) ret = 3;
  717. if(ret < -3) ret = -3;
  718. return ret;
  719. }
  720. si32 CStack::Attack() const
  721. {
  722. si32 ret = creature->attack; //value to be returned
  723. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  724. {
  725. ret += si32(VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  726. }
  727. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  728. return ret;
  729. }
  730. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  731. {
  732. si32 ret = creature->defence;
  733. if(withFrenzy && getEffect(56)) //frenzy for defender
  734. {
  735. return 0;
  736. }
  737. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  738. return ret;
  739. }
  740. ui16 CStack::MaxHealth() const
  741. {
  742. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  743. }
  744. bool CStack::willMove(int turn /*= 0*/) const
  745. {
  746. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  747. && !moved(turn)
  748. && canMove(turn);
  749. }
  750. bool CStack::canMove( int turn /*= 0*/ ) const
  751. {
  752. return alive()
  753. && !hasFeatureOfType(StackFeature::NOT_ACTIVE, -1024, turn); //eg. Ammo Cart
  754. }
  755. bool CStack::moved( int turn /*= 0*/ ) const
  756. {
  757. if(!turn)
  758. return vstd::contains(state, MOVED);
  759. else
  760. return false;
  761. }
  762. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  763. {
  764. CGHeroInstance *ret = NULL;
  765. if(player<0 || player>=PLAYER_LIMIT)
  766. {
  767. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  768. return NULL;
  769. }
  770. std::vector<CGHeroInstance *> pool;
  771. if(native)
  772. {
  773. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  774. {
  775. if(pavailable.find(i->first)->second & 1<<player
  776. && i->second->type->heroType/2 == town->typeID)
  777. {
  778. pool.push_back(i->second); //get all avaliable heroes
  779. }
  780. }
  781. if(!pool.size())
  782. {
  783. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  784. return pickHeroFor(false, player, town, available);
  785. }
  786. else
  787. {
  788. ret = pool[rand()%pool.size()];
  789. }
  790. }
  791. else
  792. {
  793. int sum=0, r;
  794. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  795. {
  796. if(pavailable.find(i->first)->second & 1<<player)
  797. {
  798. pool.push_back(i->second);
  799. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  800. }
  801. }
  802. if(!pool.size())
  803. {
  804. tlog1 << "There are no heroes available for player " << player<<"!\n";
  805. return NULL;
  806. }
  807. r = rand()%sum;
  808. for (unsigned int i=0; i<pool.size(); i++)
  809. {
  810. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  811. if(r < 0)
  812. {
  813. ret = pool[i];
  814. break;
  815. }
  816. }
  817. if(!ret)
  818. ret = pool.back();
  819. }
  820. available.erase(ret->subID);
  821. return ret;
  822. }
  823. //void CGameState::apply(CPack * pack)
  824. //{
  825. // while(!mx->try_lock())
  826. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  827. // //applyNL(pack);
  828. // mx->unlock();
  829. //}
  830. int CGameState::pickHero(int owner)
  831. {
  832. int h=-1;
  833. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  834. return h;
  835. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  836. int i=0;
  837. do //try to find free hero of our faction
  838. {
  839. i++;
  840. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  841. } while( map->getHero(h) && i<175);
  842. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  843. {
  844. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  845. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  846. if(!map->getHero(j))
  847. h=j;
  848. }
  849. return h;
  850. }
  851. CGHeroInstance *CGameState::getHero(int objid)
  852. {
  853. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  854. return NULL;
  855. return static_cast<CGHeroInstance *>(map->objects[objid]);
  856. }
  857. CGTownInstance *CGameState::getTown(int objid)
  858. {
  859. if(objid<0 || objid>=map->objects.size())
  860. return NULL;
  861. return static_cast<CGTownInstance *>(map->objects[objid]);
  862. }
  863. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  864. {
  865. switch(obj->ID)
  866. {
  867. case 65: //random artifact
  868. return std::pair<int,int>(5,(ran()%136)+7); //the only reasonable range - there are siege weapons and blanks we must ommit
  869. case 66: //random treasure artifact
  870. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  871. case 67: //random minor artifact
  872. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  873. case 68: //random major artifact
  874. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  875. case 69: //random relic artifact
  876. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  877. /*case 65: //random artifact //TODO: apply new randndomization system
  878. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  879. case 66: //random treasure artifact
  880. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE));
  881. case 67: //random minor artifact
  882. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MINOR));
  883. case 68: //random major artifact
  884. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MAJOR));
  885. case 69: //random relic artifact
  886. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_RELIC));*/
  887. case 70: //random hero
  888. {
  889. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  890. }
  891. case 71: //random monster
  892. {
  893. int r;
  894. do
  895. {
  896. r = ran()%197;
  897. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  898. return std::pair<int,int>(54,r);
  899. }
  900. case 72: //random monster lvl1
  901. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  902. case 73: //random monster lvl2
  903. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  904. case 74: //random monster lvl3
  905. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  906. case 75: //random monster lvl4
  907. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  908. case 76: //random resource
  909. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  910. case 77: //random town
  911. {
  912. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  913. f;
  914. if(align>PLAYER_LIMIT-1)//same as owner / random
  915. {
  916. if(obj->tempOwner > PLAYER_LIMIT-1)
  917. f = -1; //random
  918. else
  919. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  920. }
  921. else
  922. {
  923. f = scenarioOps->getIthPlayersSettings(align).castle;
  924. }
  925. if(f<0) f = ran()%VLC->townh->towns.size();
  926. return std::pair<int,int>(TOWNI_TYPE,f);
  927. }
  928. case 162: //random monster lvl5
  929. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  930. case 163: //random monster lvl6
  931. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  932. case 164: //random monster lvl7
  933. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  934. case 216: //random dwelling
  935. {
  936. int faction = ran()%F_NUMBER;
  937. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  938. if (info->asCastle)
  939. {
  940. for(unsigned int i=0;i<map->objects.size();i++)
  941. {
  942. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  943. {
  944. randomizeObject(map->objects[i]); //we have to randomize the castle first
  945. faction = map->objects[i]->subID;
  946. break;
  947. }
  948. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  949. {
  950. faction = map->objects[i]->subID;
  951. break;
  952. }
  953. }
  954. }
  955. else
  956. {
  957. while((!(info->castles[0]&(1<<faction))))
  958. {
  959. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  960. break;
  961. faction = ran()%F_NUMBER;
  962. }
  963. }
  964. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  965. int cid = VLC->townh->towns[faction].basicCreatures[level];
  966. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  967. if(VLC->objh->cregens[i]==cid)
  968. return std::pair<int,int>(17,i);
  969. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  970. return std::pair<int,int>(17,0);
  971. }
  972. case 217:
  973. {
  974. int faction = ran()%F_NUMBER;
  975. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  976. if (info->asCastle)
  977. {
  978. for(unsigned int i=0;i<map->objects.size();i++)
  979. {
  980. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  981. {
  982. randomizeObject(map->objects[i]); //we have to randomize the castle first
  983. faction = map->objects[i]->subID;
  984. break;
  985. }
  986. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  987. {
  988. faction = map->objects[i]->subID;
  989. break;
  990. }
  991. }
  992. }
  993. else
  994. {
  995. while((!(info->castles[0]&(1<<faction))))
  996. {
  997. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  998. break;
  999. faction = ran()%F_NUMBER;
  1000. }
  1001. }
  1002. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  1003. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1004. if(VLC->objh->cregens[i]==cid)
  1005. return std::pair<int,int>(17,i);
  1006. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1007. return std::pair<int,int>(17,0);
  1008. }
  1009. case 218:
  1010. {
  1011. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  1012. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1013. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1014. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1015. if(VLC->objh->cregens[i]==cid)
  1016. return std::pair<int,int>(17,i);
  1017. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1018. return std::pair<int,int>(17,0);
  1019. }
  1020. }
  1021. return std::pair<int,int>(-1,-1);
  1022. }
  1023. void CGameState::randomizeObject(CGObjectInstance *cur)
  1024. {
  1025. std::pair<int,int> ran = pickObject(cur);
  1026. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1027. {
  1028. if(cur->ID==TOWNI_TYPE) //town - set def
  1029. {
  1030. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1031. if(t->hasCapitol())
  1032. t->defInfo = capitols[t->subID];
  1033. else if(t->hasFort())
  1034. t->defInfo = forts[t->subID];
  1035. else
  1036. t->defInfo = villages[t->subID];
  1037. }
  1038. return;
  1039. }
  1040. else if(ran.first==HEROI_TYPE)//special code for hero
  1041. {
  1042. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1043. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1044. cur->ID = ran.first;
  1045. h->portrait = cur->subID = ran.second;
  1046. h->type = VLC->heroh->heroes[ran.second];
  1047. map->heroes.push_back(h);
  1048. return; //TODO: maybe we should do something with definfo?
  1049. }
  1050. else if(ran.first==TOWNI_TYPE)//special code for town
  1051. {
  1052. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1053. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1054. cur->ID = ran.first;
  1055. cur->subID = ran.second;
  1056. t->town = &VLC->townh->towns[ran.second];
  1057. if(t->hasCapitol())
  1058. t->defInfo = capitols[t->subID];
  1059. else if(t->hasFort())
  1060. t->defInfo = forts[t->subID];
  1061. else
  1062. t->defInfo = villages[t->subID];
  1063. map->towns.push_back(t);
  1064. return;
  1065. }
  1066. //we have to replace normal random object
  1067. cur->ID = ran.first;
  1068. cur->subID = ran.second;
  1069. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1070. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1071. if(!cur->defInfo)
  1072. {
  1073. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1074. return;
  1075. }
  1076. map->addBlockVisTiles(cur);
  1077. }
  1078. int CGameState::getDate(int mode) const
  1079. {
  1080. int temp;
  1081. switch (mode)
  1082. {
  1083. case 0:
  1084. return day;
  1085. break;
  1086. case 1:
  1087. temp = (day)%7;
  1088. if (temp)
  1089. return temp;
  1090. else return 7;
  1091. break;
  1092. case 2:
  1093. temp = ((day-1)/7)+1;
  1094. if (!(temp%4))
  1095. return 4;
  1096. else
  1097. return (temp%4);
  1098. break;
  1099. case 3:
  1100. return ((day-1)/28)+1;
  1101. break;
  1102. }
  1103. return 0;
  1104. }
  1105. CGameState::CGameState()
  1106. {
  1107. mx = new boost::shared_mutex();
  1108. map = NULL;
  1109. curB = NULL;
  1110. scenarioOps = NULL;
  1111. applierGs = new CGSApplier;
  1112. objCaller = new CObjectCallersHandler;
  1113. }
  1114. CGameState::~CGameState()
  1115. {
  1116. delete mx;
  1117. delete map;
  1118. delete curB;
  1119. delete scenarioOps;
  1120. delete applierGs;
  1121. delete objCaller;
  1122. }
  1123. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1124. {
  1125. day = 0;
  1126. seed = Seed;
  1127. ran.seed((boost::int32_t)seed);
  1128. scenarioOps = si;
  1129. this->map = map;
  1130. loadTownDInfos();
  1131. //picking random factions for players
  1132. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1133. {
  1134. if(scenarioOps->playerInfos[i].castle==-1)
  1135. {
  1136. int f;
  1137. do
  1138. {
  1139. f = ran()%F_NUMBER;
  1140. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1141. scenarioOps->playerInfos[i].castle = f;
  1142. }
  1143. }
  1144. //randomizing objects
  1145. for(unsigned int no=0; no<map->objects.size(); ++no)
  1146. {
  1147. randomizeObject(map->objects[no]);
  1148. if(map->objects[no]->ID==26)
  1149. {
  1150. map->objects[no]->defInfo->handler=NULL;
  1151. }
  1152. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1153. }
  1154. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1155. /*********give starting hero****************************************/
  1156. for(int i=0;i<PLAYER_LIMIT;i++)
  1157. {
  1158. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1159. {
  1160. int3 hpos = map->players[i].posOfMainTown;
  1161. hpos.x+=1;// hpos.y+=1;
  1162. int j;
  1163. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1164. if(scenarioOps->playerInfos[j].color == i)
  1165. break;
  1166. if(j == scenarioOps->playerInfos.size())
  1167. continue;
  1168. int h=pickHero(i);
  1169. if(scenarioOps->playerInfos[j].hero == -1)
  1170. scenarioOps->playerInfos[j].hero = h;
  1171. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1172. nnn->id = map->objects.size();
  1173. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1174. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1175. {
  1176. if(map->towns[o]->pos == hpos)
  1177. {
  1178. map->towns[o]->visitingHero = nnn;
  1179. nnn->visitedTown = map->towns[o];
  1180. nnn->inTownGarrison = false;
  1181. break;
  1182. }
  1183. }
  1184. nnn->initHero();
  1185. map->heroes.push_back(nnn);
  1186. map->objects.push_back(nnn);
  1187. map->addBlockVisTiles(nnn);
  1188. }
  1189. }
  1190. /*********creating players entries in gs****************************************/
  1191. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1192. {
  1193. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1194. ins.second.color=ins.first;
  1195. ins.second.serial=i;
  1196. ins.second.human = scenarioOps->playerInfos[i].human;
  1197. players.insert(ins);
  1198. }
  1199. /******************RESOURCES****************************************************/
  1200. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1201. std::vector<int> startres;
  1202. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1203. int k;
  1204. for (int j=0;j<scenarioOps->difficulty;j++)
  1205. {
  1206. tis >> k;
  1207. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1208. tis>>k;
  1209. }
  1210. tis >> k;
  1211. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1212. {
  1213. tis >> k;
  1214. startres.push_back(k);
  1215. }
  1216. tis.close();
  1217. tis.clear();
  1218. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1219. {
  1220. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1221. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1222. (*i).second.resources[x] = startres[x];
  1223. }
  1224. tis.open(DATA_DIR "/config/resources.txt");
  1225. tis >> k;
  1226. int pom;
  1227. for(int i=0;i<k;i++)
  1228. {
  1229. tis >> pom;
  1230. resVals.push_back(pom);
  1231. }
  1232. /*************************HEROES************************************************/
  1233. std::set<int> hids;
  1234. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1235. if(map->allowedHeroes[i])
  1236. hids.insert(i);
  1237. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1238. {
  1239. if (map->heroes[i]->getOwner()<0)
  1240. {
  1241. tlog2 << "Warning - hero with uninitialized owner!\n";
  1242. continue;
  1243. }
  1244. CGHeroInstance * vhi = (map->heroes[i]);
  1245. vhi->initHero();
  1246. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1247. hids.erase(vhi->subID);
  1248. }
  1249. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1250. {
  1251. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1252. continue;
  1253. map->predefinedHeroes[i]->initHero();
  1254. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1255. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1256. hids.erase(map->predefinedHeroes[i]->subID);
  1257. }
  1258. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1259. {
  1260. CGHeroInstance * vhi = new CGHeroInstance();
  1261. vhi->initHero(hid);
  1262. hpool.heroesPool[hid] = vhi;
  1263. hpool.pavailable[hid] = 0xff;
  1264. }
  1265. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1266. {
  1267. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1268. }
  1269. /*************************FOG**OF**WAR******************************************/
  1270. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1271. {
  1272. k->second.fogOfWarMap.resize(map->width);
  1273. for(int g=0; g<map->width; ++g)
  1274. k->second.fogOfWarMap[g].resize(map->height);
  1275. for(int g=-0; g<map->width; ++g)
  1276. for(int h=0; h<map->height; ++h)
  1277. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1278. for(int g=0; g<map->width; ++g)
  1279. for(int h=0; h<map->height; ++h)
  1280. for(int v=0; v<map->twoLevel+1; ++v)
  1281. k->second.fogOfWarMap[g][h][v] = 0;
  1282. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1283. {
  1284. if(obj->tempOwner != k->first) continue; //not a flagged object
  1285. /*
  1286. int3 objCenter = obj->getSightCenter();
  1287. int radious = obj->getSightRadious();
  1288. if (radious == -1) //maybe better handle it via getTilesInRange as below?
  1289. radious = map->width + map->height;
  1290. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1291. {
  1292. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1293. {
  1294. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1295. if(distance <= radious)
  1296. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1297. }
  1298. }
  1299. */
  1300. std::set<int3> tiles;
  1301. obj->getSightTiles(tiles);
  1302. BOOST_FOREACH(int3 tile, tiles)
  1303. {
  1304. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1305. }
  1306. }
  1307. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1308. //{
  1309. // for(int yd=0; yd<map->height; ++yd)
  1310. // {
  1311. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1312. // {
  1313. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1314. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1315. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1316. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1317. // }
  1318. // }
  1319. //}
  1320. //starting bonus
  1321. if(si->playerInfos[k->second.serial].bonus==brandom)
  1322. si->playerInfos[k->second.serial].bonus = ran()%3;
  1323. switch(si->playerInfos[k->second.serial].bonus)
  1324. {
  1325. case bgold:
  1326. k->second.resources[6] += 500 + (ran()%6)*100;
  1327. break;
  1328. case bresource:
  1329. {
  1330. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1331. if(res == 127)
  1332. {
  1333. k->second.resources[0] += 5 + ran()%6;
  1334. k->second.resources[2] += 5 + ran()%6;
  1335. }
  1336. else
  1337. {
  1338. k->second.resources[res] += 3 + ran()%4;
  1339. }
  1340. break;
  1341. }
  1342. case bartifact:
  1343. {
  1344. if(!k->second.heroes.size())
  1345. {
  1346. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1347. break;
  1348. }
  1349. CArtifact *toGive;
  1350. do
  1351. {
  1352. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1353. } while (!map->allowedArtifact[toGive->id]);
  1354. CGHeroInstance *hero = k->second.heroes[0];
  1355. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1356. if(slot!=toGive->possibleSlots.end())
  1357. {
  1358. hero->artifWorn[*slot] = toGive->id;
  1359. hero->recreateArtBonuses();
  1360. }
  1361. else
  1362. hero->artifacts.push_back(toGive->id);
  1363. }
  1364. }
  1365. }
  1366. /****************************TOWNS************************************************/
  1367. for (unsigned int i=0;i<map->towns.size();i++)
  1368. {
  1369. CGTownInstance * vti =(map->towns[i]);
  1370. if(!vti->town)
  1371. vti->town = &VLC->townh->towns[vti->subID];
  1372. if (vti->name.length()==0) // if town hasn't name we draw it
  1373. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1374. //init buildings
  1375. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1376. {
  1377. vti->builtBuildings.erase(-50);
  1378. vti->builtBuildings.insert(10);
  1379. vti->builtBuildings.insert(5);
  1380. vti->builtBuildings.insert(30);
  1381. if(ran()%2)
  1382. vti->builtBuildings.insert(31);
  1383. }
  1384. //init spells
  1385. vti->spells.resize(SPELL_LEVELS);
  1386. CSpell *s;
  1387. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1388. {
  1389. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1390. vti->spells[s->level-1].push_back(s->id);
  1391. vti->possibleSpells -= s->id;
  1392. }
  1393. while(vti->possibleSpells.size())
  1394. {
  1395. ui32 total=0, sel=-1;
  1396. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1397. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1398. int r = (total)? ran()%total : -1;
  1399. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1400. {
  1401. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1402. if(r<0)
  1403. {
  1404. sel = ps;
  1405. break;
  1406. }
  1407. }
  1408. if(sel<0)
  1409. sel=0;
  1410. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1411. vti->spells[s->level-1].push_back(s->id);
  1412. vti->possibleSpells -= s->id;
  1413. }
  1414. //init garrisons
  1415. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1416. {
  1417. if(j->second.first > 196 && j->second.first < 211)
  1418. {
  1419. if(j->second.first%2)
  1420. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1421. else
  1422. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1423. }
  1424. }
  1425. if(vti->getOwner() != 255)
  1426. getPlayer(vti->getOwner())->towns.push_back(vti);
  1427. }
  1428. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1429. {
  1430. if(k->first==-1 || k->first==255)
  1431. continue;
  1432. //init visiting and garrisoned heroes
  1433. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1434. {
  1435. CGHeroInstance *h = k->second.heroes[l];
  1436. for(unsigned int m=0; m<k->second.towns.size();m++)
  1437. {
  1438. CGTownInstance *t = k->second.towns[m];
  1439. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1440. if(vistile == h->pos || h->pos==t->pos)
  1441. {
  1442. t->visitingHero = h;
  1443. h->visitedTown = t;
  1444. h->inTownGarrison = false;
  1445. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1446. {
  1447. map->removeBlockVisTiles(h);
  1448. h->pos.x -= 1;
  1449. map->addBlockVisTiles(h);
  1450. }
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. }
  1456. for(unsigned int i=0; i<map->defy.size(); i++)
  1457. {
  1458. map->defy[i]->serial = i;
  1459. }
  1460. objCaller->preInit();
  1461. for(unsigned int i=0; i<map->objects.size(); i++)
  1462. {
  1463. map->objects[i]->initObj();
  1464. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1465. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1466. }
  1467. objCaller->postInit();
  1468. }
  1469. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1470. {
  1471. return true;
  1472. }
  1473. bool CGameState::battleCanFlee(int player)
  1474. {
  1475. if(!curB) //there is no battle
  1476. return false;
  1477. if(curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1478. || curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1479. return false;
  1480. return true;
  1481. }
  1482. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1483. {
  1484. if(!curB)
  1485. return -1;
  1486. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1487. {
  1488. if((curB->stacks[g]->position == pos
  1489. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1490. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1491. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1492. ))
  1493. && (!onlyAlive || curB->stacks[g]->alive())
  1494. )
  1495. return curB->stacks[g]->ID;
  1496. }
  1497. return -1;
  1498. }
  1499. int CGameState::battleGetBattlefieldType(int3 tile)
  1500. {
  1501. if(tile==int3() && curB)
  1502. tile = curB->tile;
  1503. else if(tile==int3() && !curB)
  1504. return -1;
  1505. const std::vector <CGObjectInstance*> & objs = map->objects;
  1506. for(int g=0; g<objs.size(); ++g)
  1507. {
  1508. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1509. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1510. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1511. ) //look only for objects covering given tile
  1512. continue;
  1513. switch(objs[g]->ID)
  1514. {
  1515. case 222: //clover field
  1516. return 19;
  1517. case 21: case 223: //cursed ground
  1518. return 22;
  1519. case 224: //evil fog
  1520. return 20;
  1521. case 225: //favourable winds
  1522. return 21;
  1523. case 226: //fiery fields
  1524. return 14;
  1525. case 227: //holy ground
  1526. return 18;
  1527. case 228: //lucid pools
  1528. return 17;
  1529. case 229: //magic clouds
  1530. return 16;
  1531. case 46: case 230: //magic plains
  1532. return 9;
  1533. case 231: //rocklands
  1534. return 15;
  1535. }
  1536. }
  1537. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1538. {
  1539. case TerrainTile::dirt:
  1540. return rand()%3+3;
  1541. case TerrainTile::sand:
  1542. return 2; //TODO: coast support
  1543. case TerrainTile::grass:
  1544. return rand()%2+6;
  1545. case TerrainTile::snow:
  1546. return rand()%2+10;
  1547. case TerrainTile::swamp:
  1548. return 13;
  1549. case TerrainTile::rough:
  1550. return 23;
  1551. case TerrainTile::subterranean:
  1552. return 12;
  1553. case TerrainTile::lava:
  1554. return 8;
  1555. case TerrainTile::water:
  1556. return 25;
  1557. case TerrainTile::rock:
  1558. return 15;
  1559. default:
  1560. return -1;
  1561. }
  1562. }
  1563. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1564. {
  1565. if(!curB)
  1566. return NULL;
  1567. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1568. }
  1569. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1570. {
  1571. UpgradeInfo ret;
  1572. const CCreature *base = &VLC->creh->creatures[obj->army.slots.find(stackPos)->second.first];
  1573. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1574. {
  1575. const CGTownInstance * t;
  1576. if(obj->ID == TOWNI_TYPE)
  1577. t = static_cast<const CGTownInstance *>(obj);
  1578. else
  1579. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1580. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1581. {
  1582. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1583. {
  1584. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1585. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1586. {
  1587. ret.newID.push_back(nid);
  1588. ret.cost.push_back(std::set<std::pair<int,int> >());
  1589. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1590. {
  1591. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1592. if(dif)
  1593. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1594. }
  1595. }
  1596. }
  1597. }//end for
  1598. }
  1599. //TODO: check if hero ability makes some upgrades possible
  1600. if(ret.newID.size())
  1601. ret.oldID = base->idNumber;
  1602. return ret;
  1603. }
  1604. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1605. {
  1606. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1607. if(mode) return -1; //todo - support other modes
  1608. int mcount = 0;
  1609. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1610. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1611. mcount++;
  1612. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1613. return ret;
  1614. }
  1615. void CGameState::loadTownDInfos()
  1616. {
  1617. for(int i=0;i<F_NUMBER;i++)
  1618. {
  1619. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1620. forts[i] = VLC->dobjinfo->castles[i];
  1621. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1622. }
  1623. }
  1624. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1625. {
  1626. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1627. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1628. vec.clear();
  1629. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1630. {
  1631. const int3 hlp = tile + dirs[i];
  1632. if(!map->isInTheMap(hlp))
  1633. continue;
  1634. const TerrainTile &hlpt = map->getTile(hlp);
  1635. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1636. && hlpt.tertype!=9)
  1637. {
  1638. vec.push_back(hlp);
  1639. }
  1640. }
  1641. }
  1642. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1643. {
  1644. if(src == dest) //same tile
  1645. return 0;
  1646. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1647. &d = map->terrain[dest.x][dest.y][dest.z];
  1648. //get basic cost
  1649. int ret = h->getTileCost(d,s);
  1650. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1651. {
  1652. int old = ret;
  1653. ret *= 1.414213;
  1654. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1655. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1656. {
  1657. return remainingMovePoints;
  1658. }
  1659. }
  1660. int left = remainingMovePoints-ret;
  1661. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1662. {
  1663. std::vector<int3> vec;
  1664. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1665. for(size_t i=0; i < vec.size(); i++)
  1666. {
  1667. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1668. if(fcost <= left)
  1669. {
  1670. return ret;
  1671. }
  1672. }
  1673. ret = remainingMovePoints;
  1674. }
  1675. return ret;
  1676. }
  1677. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1678. {
  1679. int ret = 7; //allowed by default
  1680. //checking resources
  1681. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1682. if(!pom)return 8;
  1683. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1684. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1685. {
  1686. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1687. ret = 6; //lack of res
  1688. }
  1689. //checking for requirements
  1690. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1691. ri != VLC->townh->requirements[t->subID][ID].end();
  1692. ri++ )
  1693. {
  1694. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1695. ret = 8; //lack of requirements - cannot build
  1696. }
  1697. //can we build it?
  1698. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1699. ret = 2; //forbidden
  1700. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1701. ret = 5; //building limit
  1702. if(ID == 13) //capitol
  1703. {
  1704. for(unsigned int in = 0; in < map->towns.size(); in++)
  1705. {
  1706. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1707. {
  1708. ret = 0; //no more than one capitol
  1709. break;
  1710. }
  1711. }
  1712. }
  1713. else if(ID == 6) //shipyard
  1714. {
  1715. int3 t1(t->pos + int3(-1,3,0)),
  1716. t2(t->pos + int3(-3,3,0));
  1717. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1718. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1719. ret = 1; //lack of water
  1720. }
  1721. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1722. ret = 4;
  1723. return ret;
  1724. }
  1725. void CGameState::apply(CPack *pack)
  1726. {
  1727. ui16 typ = typeList.getTypeID(pack);
  1728. assert(typ >= 0);
  1729. applierGs->apps[typ]->applyOnGS(this,pack);
  1730. }
  1731. PlayerState * CGameState::getPlayer( ui8 color )
  1732. {
  1733. if(vstd::contains(players,color))
  1734. {
  1735. return &players[color];
  1736. }
  1737. else
  1738. {
  1739. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1740. return NULL;
  1741. }
  1742. }
  1743. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1744. {
  1745. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1746. return false;
  1747. int3 hpos = hero->getPosition(false);
  1748. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1749. if (!hero->canWalkOnSea())
  1750. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1751. else
  1752. blockLandSea = boost::logic::indeterminate;
  1753. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1754. //graph initialization
  1755. std::vector< std::vector<CPathNode> > graph;
  1756. graph.resize(map->width);
  1757. for(size_t i=0; i<graph.size(); ++i)
  1758. {
  1759. graph[i].resize(map->height);
  1760. for(size_t j=0; j<graph[i].size(); ++j)
  1761. {
  1762. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1763. CPathNode &node = graph[i][j];
  1764. node.accessible = !tinfo->blocked;
  1765. node.dist = -1;
  1766. node.theNodeBefore = NULL;
  1767. node.visited = false;
  1768. node.coord.x = i;
  1769. node.coord.y = j;
  1770. node.coord.z = dest.z;
  1771. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1772. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1773. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1774. || !FoW[i][j][src.z] //tile is covered by the FoW
  1775. )
  1776. {
  1777. node.accessible = false;
  1778. }
  1779. }
  1780. }
  1781. //Special rules for the destination tile
  1782. {
  1783. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1784. CPathNode &d = graph[dest.x][dest.y];
  1785. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1786. if(t->visitable)
  1787. {
  1788. d.accessible = true; //for allowing visiting objects
  1789. }
  1790. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1791. {
  1792. size_t i = 0;
  1793. for(; i < t->visitableObjects.size(); i++)
  1794. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1795. break;
  1796. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1797. }
  1798. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1799. {
  1800. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1801. }
  1802. }
  1803. //graph initialized
  1804. //initial tile - set cost on 0 and add to the queue
  1805. graph[src.x][src.y].dist = 0;
  1806. std::queue<CPathNode> mq;
  1807. mq.push(graph[src.x][src.y]);
  1808. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1809. std::vector<int3> neighbours;
  1810. neighbours.reserve(8);
  1811. while(!mq.empty())
  1812. {
  1813. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1814. mq.pop();
  1815. if (cp.coord == dest) //it's destination tile
  1816. {
  1817. if (cp.dist < curDist) //that path is better than previous one
  1818. curDist = cp.dist;
  1819. continue;
  1820. }
  1821. else
  1822. {
  1823. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1824. continue;
  1825. }
  1826. //add accessible neighbouring nodes to the queue
  1827. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1828. for(unsigned int i=0; i < neighbours.size(); i++)
  1829. {
  1830. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1831. if(dp.accessible)
  1832. {
  1833. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1834. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1835. {
  1836. dp.dist = cp.dist + cost;
  1837. dp.theNodeBefore = &cp;
  1838. mq.push(dp);
  1839. }
  1840. }
  1841. }
  1842. }
  1843. CPathNode *curNode = &graph[dest.x][dest.y];
  1844. if(!curNode->theNodeBefore) //destination is not accessible
  1845. return false;
  1846. //fill ret with found path
  1847. ret.nodes.clear();
  1848. while(curNode->coord != graph[src.x][src.y].coord)
  1849. {
  1850. ret.nodes.push_back(*curNode);
  1851. curNode = curNode->theNodeBefore;
  1852. }
  1853. ret.nodes.push_back(graph[src.x][src.y]);
  1854. return true;
  1855. }
  1856. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1857. {
  1858. assert(hero);
  1859. if(src.x < 0)
  1860. src = hero->getPosition(false);
  1861. if(movement < 0)
  1862. movement = hero->movement;
  1863. out.hero = hero;
  1864. out.hpos = src;
  1865. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1866. {
  1867. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1868. return;
  1869. }
  1870. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1871. if (!hero->canWalkOnSea())
  1872. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1873. else
  1874. onLand = boost::logic::indeterminate;
  1875. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1876. //graph initialization
  1877. CGPathNode ***graph = out.nodes;
  1878. for(size_t i=0; i < out.sizes.x; ++i)
  1879. {
  1880. for(size_t j=0; j < out.sizes.y; ++j)
  1881. {
  1882. for(size_t k=0; k < out.sizes.z; ++k)
  1883. {
  1884. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1885. CGPathNode &node = graph[i][j][k];
  1886. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1887. node.turns = 0xff;
  1888. node.moveRemains = 0;
  1889. node.coord.x = i;
  1890. node.coord.y = j;
  1891. node.coord.z = k;
  1892. node.land = tinfo->tertype != TerrainTile::water;
  1893. node.theNodeBefore = NULL;
  1894. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1895. || onLand && !node.land //it's sea and we cannot walk on sea
  1896. || !onLand && node.land //it's land and we cannot walk on land
  1897. || !FoW[i][j][k] //tile is covered by the FoW
  1898. )
  1899. {
  1900. node.accessible = CGPathNode::BLOCKED;
  1901. }
  1902. else if(tinfo->visitable)
  1903. {
  1904. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1905. {
  1906. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1907. if(obj->blockVisit)
  1908. {
  1909. node.accessible = CGPathNode::BLOCKVIS;
  1910. break;
  1911. }
  1912. else if(obj->ID != 26) //pathfinder should ignore placed events
  1913. {
  1914. node.accessible = CGPathNode::VISITABLE;
  1915. }
  1916. }
  1917. }
  1918. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1919. {
  1920. size_t i = 0;
  1921. for(; i < tinfo->visitableObjects.size(); i++)
  1922. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1923. break;
  1924. if(i < tinfo->visitableObjects.size())
  1925. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1926. }
  1927. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1928. {
  1929. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1930. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1931. }
  1932. }
  1933. }
  1934. }
  1935. //graph initialized
  1936. //initial tile - set cost on 0 and add to the queue
  1937. graph[src.x][src.y][src.z].turns = 0;
  1938. graph[src.x][src.y][src.z].moveRemains = movement;
  1939. std::queue<CGPathNode*> mq;
  1940. mq.push(&graph[src.x][src.y][src.z]);
  1941. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1942. std::vector<int3> neighbours;
  1943. neighbours.reserve(8);
  1944. while(!mq.empty())
  1945. {
  1946. CGPathNode *cp = mq.front();
  1947. mq.pop();
  1948. const TerrainTile &ct = map->getTile(cp->coord);
  1949. int movement = cp->moveRemains, turn = cp->turns;
  1950. if(!movement)
  1951. {
  1952. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1953. turn++;
  1954. }
  1955. //add accessible neighbouring nodes to the queue
  1956. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  1957. for(unsigned int i=0; i < neighbours.size(); i++)
  1958. {
  1959. int moveAtNextTile = movement;
  1960. int turnAtNextTile = turn;
  1961. const int3 &n = neighbours[i]; //current neighbor
  1962. CGPathNode & dp = graph[n.x][n.y][n.z];
  1963. if( !checkForVisitableDir(cp->coord, dp.coord)
  1964. || !checkForVisitableDir(dp.coord, cp->coord)
  1965. || dp.accessible == CGPathNode::BLOCKED )
  1966. {
  1967. continue;
  1968. }
  1969. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  1970. int remains = movement - cost;
  1971. if(remains < 0)
  1972. {
  1973. //occurs rarely, when hero with low movepoints tries to go leave the road
  1974. turnAtNextTile++;
  1975. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1976. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  1977. remains = moveAtNextTile - cost;
  1978. }
  1979. if(dp.turns==0xff //we haven't been here before
  1980. || dp.turns > turnAtNextTile
  1981. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  1982. {
  1983. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  1984. dp.moveRemains = remains;
  1985. dp.turns = turnAtNextTile;
  1986. dp.theNodeBefore = cp;
  1987. if(dp.accessible == CGPathNode::ACCESSIBLE)
  1988. {
  1989. mq.push(&dp);
  1990. }
  1991. }
  1992. } //neighbours loop
  1993. } //queue loop
  1994. }
  1995. bool CGameState::isVisible(int3 pos, int player)
  1996. {
  1997. if(player == 255) //neutral player
  1998. return false;
  1999. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2000. }
  2001. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2002. {
  2003. if(player == 255) //neutral player
  2004. return false;
  2005. //object is visible when at least one blocked tile is visible
  2006. for(int fx=0; fx<8; ++fx)
  2007. {
  2008. for(int fy=0; fy<6; ++fy)
  2009. {
  2010. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2011. if(map->isInTheMap(pos)
  2012. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2013. && isVisible(pos, player) )
  2014. return true;
  2015. }
  2016. }
  2017. return false;
  2018. }
  2019. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2020. {
  2021. const TerrainTile * pom = &map->getTile(dst);
  2022. return checkForVisitableDir(src, pom, dst);
  2023. }
  2024. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2025. {
  2026. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2027. {
  2028. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2029. continue;
  2030. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2031. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2032. {
  2033. return false;
  2034. }
  2035. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2036. {
  2037. return false;
  2038. }
  2039. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2040. {
  2041. return false;
  2042. }
  2043. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2044. {
  2045. return false;
  2046. }
  2047. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2048. {
  2049. return false;
  2050. }
  2051. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2052. {
  2053. return false;
  2054. }
  2055. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2056. {
  2057. return false;
  2058. }
  2059. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2060. {
  2061. return false;
  2062. }
  2063. }
  2064. return true;
  2065. }
  2066. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2067. {
  2068. float attackDefenseBonus,
  2069. minDmg = attacker->creature->damageMin * attacker->amount,
  2070. maxDmg = attacker->creature->damageMax * attacker->amount;
  2071. if(attacker->creature->idNumber == 149) //arrow turret
  2072. {
  2073. switch(attacker->position)
  2074. {
  2075. case -2: //keep
  2076. minDmg = 15;
  2077. maxDmg = 15;
  2078. break;
  2079. case -3: case -4: //turrets
  2080. minDmg = 7.5f;
  2081. maxDmg = 7.5f;
  2082. break;
  2083. }
  2084. }
  2085. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON) && attacker->creature->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2086. { //minDmg and maxDmg are multiplied by hero attack + 1
  2087. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2088. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2089. }
  2090. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  2091. {
  2092. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  2093. }
  2094. else
  2095. {
  2096. attackDefenseBonus = attacker->Attack() - defender->Defense();
  2097. }
  2098. //calculating total attack/defense skills modifier
  2099. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  2100. {
  2101. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  2102. }
  2103. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  2104. {
  2105. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  2106. }
  2107. if(attacker->getEffect(55)) //slayer handling
  2108. {
  2109. std::vector<int> affectedIds;
  2110. switch(attacker->getEffect(55)->level)
  2111. {
  2112. case 3: //expert
  2113. {
  2114. affectedIds.push_back(40); //giant
  2115. affectedIds.push_back(41); //titan
  2116. affectedIds.push_back(152); //lord of thunder
  2117. } //continue adding ...
  2118. case 2: //advanced
  2119. {
  2120. affectedIds.push_back(12); //angel
  2121. affectedIds.push_back(13); //archangel
  2122. affectedIds.push_back(54); //devil
  2123. affectedIds.push_back(55); //arch devil
  2124. affectedIds.push_back(150); //supreme archangel
  2125. affectedIds.push_back(153); //antichrist
  2126. } //continue adding ...
  2127. case 0: case 1: //none and basic
  2128. {
  2129. affectedIds.push_back(26); //green dragon
  2130. affectedIds.push_back(27); //gold dragon
  2131. affectedIds.push_back(82); //red dragon
  2132. affectedIds.push_back(83); //black dragon
  2133. affectedIds.push_back(96); //behemot
  2134. affectedIds.push_back(97); //ancient behemot
  2135. affectedIds.push_back(110); //hydra
  2136. affectedIds.push_back(111); //chaos hydra
  2137. affectedIds.push_back(132); //azure dragon
  2138. affectedIds.push_back(133); //crystal dragon
  2139. affectedIds.push_back(134); //faerie dragon
  2140. affectedIds.push_back(135); //rust dragon
  2141. affectedIds.push_back(151); //diamond dragon
  2142. affectedIds.push_back(154); //blood dragon
  2143. affectedIds.push_back(155); //darkness dragon
  2144. affectedIds.push_back(156); //ghost behemoth
  2145. affectedIds.push_back(157); //hell hydra
  2146. break;
  2147. }
  2148. }
  2149. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2150. {
  2151. if(defender->creature->idNumber == affectedIds[g])
  2152. {
  2153. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2154. break;
  2155. }
  2156. }
  2157. }
  2158. float dmgBonusMultiplier = 1.0f;
  2159. //applying jousting bonus
  2160. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2161. dmgBonusMultiplier += charge * 0.05f;
  2162. //bonus from attack/defense skills
  2163. if(attackDefenseBonus < 0) //decreasing dmg
  2164. {
  2165. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2166. {
  2167. dmgBonusMultiplier += -0.3f;
  2168. }
  2169. else
  2170. {
  2171. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2172. }
  2173. }
  2174. else //increasing dmg
  2175. {
  2176. if(0.05f * attackDefenseBonus > 4.0f)
  2177. {
  2178. dmgBonusMultiplier += 4.0f;
  2179. }
  2180. else
  2181. {
  2182. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2183. }
  2184. }
  2185. //handling secondary abilities and artifacts giving premies to them
  2186. if(attackerHero)
  2187. {
  2188. if(shooting)
  2189. {
  2190. switch(attackerHero->getSecSkillLevel(1)) //archery
  2191. {
  2192. case 1: //basic
  2193. dmgBonusMultiplier += 0.1f;
  2194. break;
  2195. case 2: //advanced
  2196. dmgBonusMultiplier += 0.25f;
  2197. break;
  2198. case 3: //expert
  2199. dmgBonusMultiplier += 0.5f;
  2200. break;
  2201. }
  2202. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2203. {
  2204. //apply artifact premy to archery
  2205. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2206. }
  2207. }
  2208. else
  2209. {
  2210. switch(attackerHero->getSecSkillLevel(22)) //offense
  2211. {
  2212. case 1: //basic
  2213. dmgBonusMultiplier += 0.1f;
  2214. break;
  2215. case 2: //advanced
  2216. dmgBonusMultiplier += 0.2f;
  2217. break;
  2218. case 3: //expert
  2219. dmgBonusMultiplier += 0.3f;
  2220. break;
  2221. }
  2222. }
  2223. }
  2224. if(defendingHero)
  2225. {
  2226. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2227. {
  2228. case 1: //basic
  2229. dmgBonusMultiplier *= 0.95f;
  2230. break;
  2231. case 2: //advanced
  2232. dmgBonusMultiplier *= 0.9f;
  2233. break;
  2234. case 3: //expert
  2235. dmgBonusMultiplier *= 0.85f;
  2236. break;
  2237. }
  2238. }
  2239. //handling hate effect
  2240. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2241. dmgBonusMultiplier += 0.5f;
  2242. //handling spell effects
  2243. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2244. {
  2245. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2246. }
  2247. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2248. {
  2249. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2250. }
  2251. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2252. {
  2253. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2254. }
  2255. minDmg *= dmgBonusMultiplier;
  2256. maxDmg *= dmgBonusMultiplier;
  2257. if(attacker->getEffect(42)) //curse handling (rest)
  2258. {
  2259. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2260. return std::make_pair(int(minDmg), int(minDmg));
  2261. }
  2262. else if(attacker->getEffect(41)) //bless handling
  2263. {
  2264. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2265. return std::make_pair(int(maxDmg), int(maxDmg));
  2266. }
  2267. else
  2268. {
  2269. return std::make_pair(int(minDmg), int(maxDmg));
  2270. }
  2271. tlog1 << "We are too far in calculateDmg...\n";
  2272. return std::make_pair(0, 0);
  2273. }
  2274. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2275. {
  2276. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2277. if(range.first != range.second)
  2278. return range.first + rand() % (range.second - range.first + 1);
  2279. else
  2280. return range.first;
  2281. }
  2282. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2283. {
  2284. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2285. {
  2286. const CStack * const st = stacks[i];
  2287. si32 killed = (st->alive() ? st->baseAmount - st->amount : st->baseAmount);
  2288. amax(killed, 0);
  2289. if(killed)
  2290. casualties[!st->attackerOwned][st->creature->idNumber] += killed;
  2291. }
  2292. }
  2293. si8 CGameState::battleMaxSpellLevel()
  2294. {
  2295. if(!curB) //there is not battle
  2296. {
  2297. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2298. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2299. }
  2300. si8 levelLimit = SPELL_LEVELS;
  2301. const CGHeroInstance *h1 = curB->heroes[0];
  2302. if(h1)
  2303. {
  2304. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2305. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2306. amin(levelLimit, i->val);
  2307. }
  2308. const CGHeroInstance *h2 = curB->heroes[1];
  2309. if(h2)
  2310. {
  2311. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2312. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2313. amin(levelLimit, i->val);
  2314. }
  2315. return levelLimit;
  2316. }
  2317. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2318. {
  2319. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2320. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2321. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2322. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2323. {
  2324. for(int it=0; it<stacks.size(); ++it)
  2325. {
  2326. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2327. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2328. || (s->id == 26) //Armageddon
  2329. )
  2330. {
  2331. if(stacks[it]->alive())
  2332. attackedCres.insert(stacks[it]);
  2333. }
  2334. }
  2335. }
  2336. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2337. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2338. {
  2339. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2340. {
  2341. CStack * st = getStackT(destinationTile, onlyAlive);
  2342. if(st)
  2343. attackedCres.insert(st);
  2344. }
  2345. else
  2346. {
  2347. for(int it=0; it<stacks.size(); ++it)
  2348. {
  2349. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2350. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2351. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2352. )
  2353. {
  2354. if(!onlyAlive || stacks[it]->alive())
  2355. attackedCres.insert(stacks[it]);
  2356. }
  2357. }
  2358. } //if(caster->getSpellSchoolLevel(s) < 3)
  2359. }
  2360. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2361. {
  2362. CStack * st = getStackT(destinationTile, onlyAlive);
  2363. if(st)
  2364. attackedCres.insert(st);
  2365. }
  2366. else //custom range from attackedHexes
  2367. {
  2368. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2369. {
  2370. CStack * st = getStackT(*it, onlyAlive);
  2371. if(st)
  2372. attackedCres.insert(st);
  2373. }
  2374. }
  2375. return attackedCres;
  2376. }
  2377. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2378. {
  2379. switch(spell->id)
  2380. {
  2381. case 56: //frenzy
  2382. return 1;
  2383. default: //other spells
  2384. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2385. }
  2386. }
  2387. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2388. {
  2389. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2390. if(owner)
  2391. {
  2392. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2393. //base luck/morale calculations
  2394. ret->morale = owner->getCurrentMorale(slot, false);
  2395. ret->luck = owner->getCurrentLuck(slot, false);
  2396. //other bonuses
  2397. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2398. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2399. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2400. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2401. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2402. StackFeature::BONUS_FROM_HERO));
  2403. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2404. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2405. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2406. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2407. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2408. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2409. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2410. ret->firstHPleft = ret->MaxHealth();
  2411. }
  2412. else
  2413. {
  2414. ret->morale = 0;
  2415. ret->luck = 0;
  2416. }
  2417. //native terrain bonuses
  2418. int faction = ret->creature->faction;
  2419. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2420. {
  2421. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2422. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2423. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2424. }
  2425. ret->position = position;
  2426. return ret;
  2427. }
  2428. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2429. {
  2430. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2431. //checking for friendly stacks reducing cost of the spell
  2432. si32 manaReduction = 0;
  2433. for(int g=0; g<stacks.size(); ++g)
  2434. {
  2435. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2436. {
  2437. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2438. }
  2439. }
  2440. return ret + manaReduction;
  2441. }
  2442. int BattleInfo::hexToWallPart(int hex) const
  2443. {
  2444. if(siege == 0) //there is no battle!
  2445. return -1;
  2446. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2447. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2448. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2449. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2450. {
  2451. if(attackable[g].first == hex)
  2452. return attackable[g].second;
  2453. }
  2454. return -1; //not found!
  2455. }
  2456. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2457. {
  2458. bool ac[BFIELD_SIZE];
  2459. std::set<int> occupyable;
  2460. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2461. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2462. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING), true);
  2463. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2464. for(int g=0; g<BFIELD_SIZE; ++g)
  2465. {
  2466. const CStack * atG = getStackT(g);
  2467. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2468. continue;
  2469. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2470. {
  2471. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2472. continue;
  2473. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2474. }
  2475. }
  2476. if(stackPairs.size() > 0)
  2477. {
  2478. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2479. minimalPairs.push_back(stackPairs[0]);
  2480. for(int b=1; b<stackPairs.size(); ++b)
  2481. {
  2482. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2483. {
  2484. minimalPairs.clear();
  2485. minimalPairs.push_back(stackPairs[b]);
  2486. }
  2487. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2488. {
  2489. minimalPairs.push_back(stackPairs[b]);
  2490. }
  2491. }
  2492. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2493. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2494. }
  2495. return std::make_pair<const CStack * , int>(NULL, -1);
  2496. }
  2497. ui32 BattleInfo::calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  2498. {
  2499. ui32 ret = 0; //value to return
  2500. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2501. //24 - death ripple, 25 - destroy undead, 26 - armageddon
  2502. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50);
  2503. //check if spell really does damage - if not, return 0
  2504. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2505. return 0;
  2506. ret = caster->getPrimSkillLevel(2) * dmgMultipliers[sp->id] + sp->powers[caster->getSpellSchoolLevel(sp)];
  2507. //applying sorcerery secondary skill
  2508. switch(caster->getSecSkillLevel(25))
  2509. {
  2510. case 1: //basic
  2511. ret *= 1.05f;
  2512. break;
  2513. case 2: //advanced
  2514. ret *= 1.1f;
  2515. break;
  2516. case 3: //expert
  2517. ret *= 1.15f;
  2518. break;
  2519. }
  2520. //applying hero bonuses
  2521. if(sp->air && caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) != 0)
  2522. {
  2523. ret *= (100.0f + caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) / 100.0f);
  2524. }
  2525. else if(sp->fire && caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) != 0)
  2526. {
  2527. ret *= (100.0f + caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) / 100.0f);
  2528. }
  2529. else if(sp->water && caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) != 0)
  2530. {
  2531. ret *= (100.0f + caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) / 100.0f);
  2532. }
  2533. else if(sp->earth && caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) != 0)
  2534. {
  2535. ret *= (100.0f + caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) / 100.0f);
  2536. }
  2537. //affected creature-specific part
  2538. if(affectedCreature)
  2539. {
  2540. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2541. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2542. {
  2543. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 0);
  2544. ret /= 100;
  2545. }
  2546. else if(sp->fire && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2547. {
  2548. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 1);
  2549. ret /= 100;
  2550. }
  2551. else if(sp->water && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2552. {
  2553. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 2);
  2554. ret /= 100;
  2555. }
  2556. else if (sp->earth && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2557. {
  2558. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 3);
  2559. ret /= 100;
  2560. }
  2561. //general spell dmg reduction
  2562. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2563. {
  2564. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, -1);
  2565. ret /= 100;
  2566. }
  2567. //dmg increasing
  2568. if( affectedCreature->hasFeatureOfType(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2569. {
  2570. ret *= 100 + affectedCreature->valOfFeatures(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id);
  2571. ret /= 100;
  2572. }
  2573. }
  2574. return ret;
  2575. }
  2576. bool CGameState::battleCanShoot(int ID, int dest)
  2577. {
  2578. if(!curB)
  2579. return false;
  2580. const CStack *our = curB->getStack(ID),
  2581. *dst = curB->getStackT(dest);
  2582. if(!our || !dst) return false;
  2583. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2584. if(our->hasFeatureOfType(StackFeature::FORGETFULL)) //forgetfulness
  2585. return false;
  2586. if(our->hasFeatureOfType(StackFeature::SHOOTER)//it's shooter
  2587. && our->owner != dst->owner
  2588. && dst->alive()
  2589. && (!curB->isStackBlocked(ID)
  2590. || ourHero->hasBonusOfType(HeroBonus::FREE_SHOOTING))
  2591. && our->shots
  2592. )
  2593. return true;
  2594. return false;
  2595. }
  2596. const CStack * BattleInfo::getNextStack() const
  2597. {
  2598. std::vector<const CStack *> hlp;
  2599. getStackQueue(hlp, 1, -1);
  2600. if(hlp.size())
  2601. return hlp[0];
  2602. else
  2603. return NULL;
  2604. }
  2605. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  2606. {
  2607. const CStack *ret = NULL;
  2608. unsigned i, //fastest stack
  2609. j; //fastest stack of the other side
  2610. for(i = 0; i < st.size(); i++)
  2611. if(st[i])
  2612. break;
  2613. //no stacks left
  2614. if(i == st.size())
  2615. return NULL;
  2616. const CStack *fastest = st[i], *other = NULL;
  2617. int bestSpeed = fastest->Speed(turn);
  2618. if(fastest->attackerOwned != curside)
  2619. {
  2620. ret = fastest;
  2621. }
  2622. else
  2623. {
  2624. for(j = i + 1; j < st.size(); j++)
  2625. {
  2626. if(!st[j]) continue;
  2627. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  2628. break;
  2629. }
  2630. if(j >= st.size())
  2631. {
  2632. ret = fastest;
  2633. }
  2634. else
  2635. {
  2636. other = st[j];
  2637. if(other->Speed(turn) != bestSpeed)
  2638. ret = fastest;
  2639. else
  2640. ret = other;
  2641. }
  2642. }
  2643. assert(ret);
  2644. if(ret == fastest)
  2645. st[i] = NULL;
  2646. else
  2647. st[j] = NULL;
  2648. curside = ret->attackerOwned;
  2649. return ret;
  2650. }
  2651. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  2652. {
  2653. //we'll split creatures with remaining movement to 4 parts
  2654. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  2655. int toMove = 0; //how many stacks still has move
  2656. const CStack *active = getStack(activeStack);
  2657. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  2658. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  2659. {
  2660. out.push_back(active);
  2661. if(out.size() == howMany)
  2662. return;
  2663. }
  2664. for(unsigned int i=0; i<stacks.size(); ++i)
  2665. {
  2666. const CStack * const s = stacks[i];
  2667. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  2668. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  2669. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  2670. {
  2671. continue;
  2672. }
  2673. int p = -1; //in which phase this tack will move?
  2674. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  2675. {
  2676. if(vstd::contains(s->state, HAD_MORALE))
  2677. p = 2;
  2678. else
  2679. p = 3;
  2680. }
  2681. else if(s->creature->idNumber == 145 || s->creature->idNumber == 149) //catapult and turrets are first
  2682. {
  2683. p = 0;
  2684. }
  2685. else
  2686. {
  2687. p = 1;
  2688. }
  2689. phase[p].push_back(s);
  2690. toMove++;
  2691. }
  2692. for(int i = 0; i < 4; i++)
  2693. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  2694. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  2695. out.push_back(phase[0][i]);
  2696. if(out.size() == howMany)
  2697. return;
  2698. if(lastMoved == -1)
  2699. {
  2700. if(active)
  2701. {
  2702. if(out.size() && out.front() == active)
  2703. lastMoved = active->attackerOwned;
  2704. else
  2705. lastMoved = active->attackerOwned;
  2706. }
  2707. else
  2708. {
  2709. lastMoved = 0;
  2710. }
  2711. }
  2712. int pi = 1;
  2713. while(out.size() < howMany)
  2714. {
  2715. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  2716. if(!hlp)
  2717. {
  2718. pi++;
  2719. if(pi > 3)
  2720. {
  2721. //if(turn != 2)
  2722. getStackQueue(out, howMany, turn + 1, lastMoved);
  2723. return;
  2724. }
  2725. }
  2726. else
  2727. {
  2728. out.push_back(hlp);
  2729. }
  2730. }
  2731. }
  2732. int3 CPath::startPos() const
  2733. {
  2734. return nodes[nodes.size()-1].coord;
  2735. }
  2736. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2737. {
  2738. if (mode==0)
  2739. {
  2740. for (unsigned int i=0;i<nodes.size();i++)
  2741. {
  2742. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2743. }
  2744. }
  2745. }
  2746. int3 CPath::endPos() const
  2747. {
  2748. return nodes[0].coord;
  2749. }
  2750. CGPathNode::CGPathNode()
  2751. :coord(-1,-1,-1)
  2752. {
  2753. accessible = 0;
  2754. land = 0;
  2755. moveRemains = 0;
  2756. turns = 255;
  2757. theNodeBefore = NULL;
  2758. }
  2759. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2760. {
  2761. out.nodes.clear();
  2762. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2763. if(!curnode->theNodeBefore)
  2764. return false;
  2765. while(curnode)
  2766. {
  2767. out.nodes.push_back(*curnode);
  2768. curnode = curnode->theNodeBefore;
  2769. }
  2770. return true;
  2771. }
  2772. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2773. :sizes(Sizes)
  2774. {
  2775. hero = NULL;
  2776. nodes = new CGPathNode**[sizes.x];
  2777. for(int i = 0; i < sizes.x; i++)
  2778. {
  2779. nodes[i] = new CGPathNode*[sizes.y];
  2780. for (int j = 0; j < sizes.y; j++)
  2781. {
  2782. nodes[i][j] = new CGPathNode[sizes.z];
  2783. }
  2784. }
  2785. }
  2786. CPathsInfo::~CPathsInfo()
  2787. {
  2788. for(int i = 0; i < sizes.x; i++)
  2789. {
  2790. for (int j = 0; j < sizes.y; j++)
  2791. {
  2792. delete [] nodes[i][j];
  2793. }
  2794. delete [] nodes[i];
  2795. }
  2796. delete [] nodes;
  2797. }
  2798. int3 CGPath::startPos() const
  2799. {
  2800. return nodes[nodes.size()-1].coord;
  2801. }
  2802. int3 CGPath::endPos() const
  2803. {
  2804. return nodes[0].coord;
  2805. }
  2806. void CGPath::convert( ui8 mode )
  2807. {
  2808. if(mode==0)
  2809. {
  2810. for(unsigned int i=0;i<nodes.size();i++)
  2811. {
  2812. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2813. }
  2814. }
  2815. }
  2816. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2817. {
  2818. switch(phase)
  2819. {
  2820. case 0: //catapult moves after turrets
  2821. return a->creature->idNumber < b->creature->idNumber; //catapult is 145 and turrets are 149
  2822. //TODO? turrets order
  2823. case 1: //fastest first, upper slot first
  2824. {
  2825. int as = a->Speed(turn), bs = b->Speed(turn);
  2826. if(as != bs)
  2827. return as > bs;
  2828. else
  2829. return a->slot < b->slot;
  2830. }
  2831. case 2: //fastest last, upper slot first
  2832. //TODO: should be replaced with order of receiving morale!
  2833. case 3: //fastest last, upper slot first
  2834. {
  2835. int as = a->Speed(turn), bs = b->Speed(turn);
  2836. if(as != bs)
  2837. return as < bs;
  2838. else
  2839. return a->slot < b->slot;
  2840. }
  2841. default:
  2842. assert(0);
  2843. return false;
  2844. }
  2845. }
  2846. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2847. {
  2848. phase = Phase;
  2849. turn = Turn;
  2850. }
  2851. PlayerState::PlayerState()
  2852. : color(-1), currentSelection(0xffffffff)
  2853. {
  2854. }