CGameState.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205
  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 convertHordes(CGTownInstance * town)//converting hordes from -36..-30 to 18 & 24
  1024. {
  1025. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1026. if (vstd::contains(town->builtBuildings,(-31-i))) //if we have horde for this level
  1027. {
  1028. town->builtBuildings.erase(-31-i);//remove old ID
  1029. if (town->town->hordeLvl[0] == i)//if town first horde is this one
  1030. {
  1031. town->builtBuildings.insert(18);//add it
  1032. if (vstd::contains(town->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1033. town->builtBuildings.insert(19);//add it as well
  1034. }
  1035. if (town->town->hordeLvl[1] == i)//if town second horde is this one
  1036. {
  1037. town->builtBuildings.insert(24);//add it
  1038. if (vstd::contains(town->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1039. town->builtBuildings.insert(25);//add it as well
  1040. }
  1041. }
  1042. }
  1043. void CGameState::randomizeObject(CGObjectInstance *cur)
  1044. {
  1045. std::pair<int,int> ran = pickObject(cur);
  1046. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1047. {
  1048. if(cur->ID==TOWNI_TYPE) //town - set def
  1049. {
  1050. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1051. if(t->hasCapitol())
  1052. t->defInfo = capitols[t->subID];
  1053. else if(t->hasFort())
  1054. t->defInfo = forts[t->subID];
  1055. else
  1056. t->defInfo = villages[t->subID];
  1057. convertHordes(t);
  1058. }
  1059. return;
  1060. }
  1061. else if(ran.first==HEROI_TYPE)//special code for hero
  1062. {
  1063. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1064. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1065. cur->ID = ran.first;
  1066. h->portrait = cur->subID = ran.second;
  1067. h->type = VLC->heroh->heroes[ran.second];
  1068. map->heroes.push_back(h);
  1069. return; //TODO: maybe we should do something with definfo?
  1070. }
  1071. else if(ran.first==TOWNI_TYPE)//special code for town
  1072. {
  1073. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1074. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1075. cur->ID = ran.first;
  1076. cur->subID = ran.second;
  1077. t->town = &VLC->townh->towns[ran.second];
  1078. if(t->hasCapitol())
  1079. t->defInfo = capitols[t->subID];
  1080. else if(t->hasFort())
  1081. t->defInfo = forts[t->subID];
  1082. else
  1083. t->defInfo = villages[t->subID];
  1084. convertHordes(t);
  1085. map->towns.push_back(t);
  1086. return;
  1087. }
  1088. //we have to replace normal random object
  1089. cur->ID = ran.first;
  1090. cur->subID = ran.second;
  1091. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1092. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1093. if(!cur->defInfo)
  1094. {
  1095. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1096. return;
  1097. }
  1098. map->addBlockVisTiles(cur);
  1099. }
  1100. int CGameState::getDate(int mode) const
  1101. {
  1102. int temp;
  1103. switch (mode)
  1104. {
  1105. case 0:
  1106. return day;
  1107. break;
  1108. case 1:
  1109. temp = (day)%7;
  1110. if (temp)
  1111. return temp;
  1112. else return 7;
  1113. break;
  1114. case 2:
  1115. temp = ((day-1)/7)+1;
  1116. if (!(temp%4))
  1117. return 4;
  1118. else
  1119. return (temp%4);
  1120. break;
  1121. case 3:
  1122. return ((day-1)/28)+1;
  1123. break;
  1124. }
  1125. return 0;
  1126. }
  1127. CGameState::CGameState()
  1128. {
  1129. mx = new boost::shared_mutex();
  1130. map = NULL;
  1131. curB = NULL;
  1132. scenarioOps = NULL;
  1133. applierGs = new CGSApplier;
  1134. objCaller = new CObjectCallersHandler;
  1135. }
  1136. CGameState::~CGameState()
  1137. {
  1138. delete mx;
  1139. delete map;
  1140. delete curB;
  1141. delete scenarioOps;
  1142. delete applierGs;
  1143. delete objCaller;
  1144. }
  1145. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1146. {
  1147. day = 0;
  1148. seed = Seed;
  1149. ran.seed((boost::int32_t)seed);
  1150. scenarioOps = si;
  1151. this->map = map;
  1152. loadTownDInfos();
  1153. //picking random factions for players
  1154. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1155. {
  1156. if(scenarioOps->playerInfos[i].castle==-1)
  1157. {
  1158. int f;
  1159. do
  1160. {
  1161. f = ran()%F_NUMBER;
  1162. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1163. scenarioOps->playerInfos[i].castle = f;
  1164. }
  1165. }
  1166. //randomizing objects
  1167. for(unsigned int no=0; no<map->objects.size(); ++no)
  1168. {
  1169. randomizeObject(map->objects[no]);
  1170. if(map->objects[no]->ID==26)
  1171. {
  1172. map->objects[no]->defInfo->handler=NULL;
  1173. }
  1174. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1175. }
  1176. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1177. /*********give starting hero****************************************/
  1178. for(int i=0;i<PLAYER_LIMIT;i++)
  1179. {
  1180. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1181. {
  1182. int3 hpos = map->players[i].posOfMainTown;
  1183. hpos.x+=1;// hpos.y+=1;
  1184. int j;
  1185. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1186. if(scenarioOps->playerInfos[j].color == i)
  1187. break;
  1188. if(j == scenarioOps->playerInfos.size())
  1189. continue;
  1190. int h=pickHero(i);
  1191. if(scenarioOps->playerInfos[j].hero == -1)
  1192. scenarioOps->playerInfos[j].hero = h;
  1193. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1194. nnn->id = map->objects.size();
  1195. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1196. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1197. {
  1198. if(map->towns[o]->pos == hpos)
  1199. {
  1200. map->towns[o]->visitingHero = nnn;
  1201. nnn->visitedTown = map->towns[o];
  1202. nnn->inTownGarrison = false;
  1203. break;
  1204. }
  1205. }
  1206. nnn->initHero();
  1207. map->heroes.push_back(nnn);
  1208. map->objects.push_back(nnn);
  1209. map->addBlockVisTiles(nnn);
  1210. }
  1211. }
  1212. /*********creating players entries in gs****************************************/
  1213. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1214. {
  1215. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1216. ins.second.color=ins.first;
  1217. ins.second.serial=i;
  1218. ins.second.human = scenarioOps->playerInfos[i].human;
  1219. players.insert(ins);
  1220. }
  1221. /******************RESOURCES****************************************************/
  1222. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1223. std::vector<int> startres;
  1224. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1225. int k;
  1226. for (int j=0;j<scenarioOps->difficulty;j++)
  1227. {
  1228. tis >> k;
  1229. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1230. tis>>k;
  1231. }
  1232. tis >> k;
  1233. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1234. {
  1235. tis >> k;
  1236. startres.push_back(k);
  1237. }
  1238. tis.close();
  1239. tis.clear();
  1240. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1241. {
  1242. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1243. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1244. (*i).second.resources[x] = startres[x];
  1245. }
  1246. tis.open(DATA_DIR "/config/resources.txt");
  1247. tis >> k;
  1248. int pom;
  1249. for(int i=0;i<k;i++)
  1250. {
  1251. tis >> pom;
  1252. resVals.push_back(pom);
  1253. }
  1254. /*************************HEROES************************************************/
  1255. std::set<int> hids;
  1256. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1257. if(map->allowedHeroes[i])
  1258. hids.insert(i);
  1259. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1260. {
  1261. if (map->heroes[i]->getOwner()<0)
  1262. {
  1263. tlog2 << "Warning - hero with uninitialized owner!\n";
  1264. continue;
  1265. }
  1266. CGHeroInstance * vhi = (map->heroes[i]);
  1267. vhi->initHero();
  1268. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1269. hids.erase(vhi->subID);
  1270. }
  1271. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1272. {
  1273. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1274. continue;
  1275. map->predefinedHeroes[i]->initHero();
  1276. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1277. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1278. hids.erase(map->predefinedHeroes[i]->subID);
  1279. }
  1280. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1281. {
  1282. CGHeroInstance * vhi = new CGHeroInstance();
  1283. vhi->initHero(hid);
  1284. hpool.heroesPool[hid] = vhi;
  1285. hpool.pavailable[hid] = 0xff;
  1286. }
  1287. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1288. {
  1289. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1290. }
  1291. /*************************FOG**OF**WAR******************************************/
  1292. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1293. {
  1294. k->second.fogOfWarMap.resize(map->width);
  1295. for(int g=0; g<map->width; ++g)
  1296. k->second.fogOfWarMap[g].resize(map->height);
  1297. for(int g=-0; g<map->width; ++g)
  1298. for(int h=0; h<map->height; ++h)
  1299. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1300. for(int g=0; g<map->width; ++g)
  1301. for(int h=0; h<map->height; ++h)
  1302. for(int v=0; v<map->twoLevel+1; ++v)
  1303. k->second.fogOfWarMap[g][h][v] = 0;
  1304. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1305. {
  1306. if(obj->tempOwner != k->first) continue; //not a flagged object
  1307. std::set<int3> tiles;
  1308. obj->getSightTiles(tiles);
  1309. BOOST_FOREACH(int3 tile, tiles)
  1310. {
  1311. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1312. }
  1313. }
  1314. //starting bonus
  1315. if(si->playerInfos[k->second.serial].bonus==brandom)
  1316. si->playerInfos[k->second.serial].bonus = ran()%3;
  1317. switch(si->playerInfos[k->second.serial].bonus)
  1318. {
  1319. case bgold:
  1320. k->second.resources[6] += 500 + (ran()%6)*100;
  1321. break;
  1322. case bresource:
  1323. {
  1324. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1325. if(res == 127)
  1326. {
  1327. k->second.resources[0] += 5 + ran()%6;
  1328. k->second.resources[2] += 5 + ran()%6;
  1329. }
  1330. else
  1331. {
  1332. k->second.resources[res] += 3 + ran()%4;
  1333. }
  1334. break;
  1335. }
  1336. case bartifact:
  1337. {
  1338. if(!k->second.heroes.size())
  1339. {
  1340. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1341. break;
  1342. }
  1343. CArtifact *toGive;
  1344. do
  1345. {
  1346. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1347. } while (!map->allowedArtifact[toGive->id]);
  1348. CGHeroInstance *hero = k->second.heroes[0];
  1349. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1350. if(slot!=toGive->possibleSlots.end())
  1351. {
  1352. hero->artifWorn[*slot] = toGive->id;
  1353. hero->recreateArtBonuses();
  1354. }
  1355. else
  1356. hero->giveArtifact(toGive->id);
  1357. }
  1358. }
  1359. }
  1360. /****************************TOWNS************************************************/
  1361. for (unsigned int i=0;i<map->towns.size();i++)
  1362. {
  1363. CGTownInstance * vti =(map->towns[i]);
  1364. if(!vti->town)
  1365. vti->town = &VLC->townh->towns[vti->subID];
  1366. if (vti->name.length()==0) // if town hasn't name we draw it
  1367. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1368. //init buildings
  1369. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1370. {
  1371. vti->builtBuildings.erase(-50);
  1372. vti->builtBuildings.insert(10);
  1373. vti->builtBuildings.insert(5);
  1374. vti->builtBuildings.insert(30);
  1375. if(ran()%2)
  1376. vti->builtBuildings.insert(31);
  1377. }
  1378. //init spells
  1379. vti->spells.resize(SPELL_LEVELS);
  1380. CSpell *s;
  1381. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1382. {
  1383. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1384. vti->spells[s->level-1].push_back(s->id);
  1385. vti->possibleSpells -= s->id;
  1386. }
  1387. while(vti->possibleSpells.size())
  1388. {
  1389. ui32 total=0, sel=-1;
  1390. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1391. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1392. int r = (total)? ran()%total : -1;
  1393. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1394. {
  1395. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1396. if(r<0)
  1397. {
  1398. sel = ps;
  1399. break;
  1400. }
  1401. }
  1402. if(sel<0)
  1403. sel=0;
  1404. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1405. vti->spells[s->level-1].push_back(s->id);
  1406. vti->possibleSpells -= s->id;
  1407. }
  1408. //init garrisons
  1409. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1410. {
  1411. if(j->second.first > 196 && j->second.first < 211)
  1412. {
  1413. if(j->second.first%2)
  1414. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1415. else
  1416. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1417. }
  1418. }
  1419. if(vti->getOwner() != 255)
  1420. getPlayer(vti->getOwner())->towns.push_back(vti);
  1421. }
  1422. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1423. {
  1424. if(k->first==-1 || k->first==255)
  1425. continue;
  1426. //init visiting and garrisoned heroes
  1427. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1428. {
  1429. CGHeroInstance *h = k->second.heroes[l];
  1430. for(unsigned int m=0; m<k->second.towns.size();m++)
  1431. {
  1432. CGTownInstance *t = k->second.towns[m];
  1433. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1434. if(vistile == h->pos || h->pos==t->pos)
  1435. {
  1436. t->visitingHero = h;
  1437. h->visitedTown = t;
  1438. h->inTownGarrison = false;
  1439. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1440. {
  1441. map->removeBlockVisTiles(h);
  1442. h->pos.x -= 1;
  1443. map->addBlockVisTiles(h);
  1444. }
  1445. break;
  1446. }
  1447. }
  1448. }
  1449. }
  1450. for(unsigned int i=0; i<map->defy.size(); i++)
  1451. {
  1452. map->defy[i]->serial = i;
  1453. }
  1454. objCaller->preInit();
  1455. for(unsigned int i=0; i<map->objects.size(); i++)
  1456. {
  1457. map->objects[i]->initObj();
  1458. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1459. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1460. }
  1461. objCaller->postInit();
  1462. }
  1463. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1464. {
  1465. return true;
  1466. }
  1467. bool CGameState::battleCanFlee(int player)
  1468. {
  1469. if(!curB) //there is no battle
  1470. return false;
  1471. if(curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1472. || curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1473. return false;
  1474. return true;
  1475. }
  1476. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1477. {
  1478. if(!curB)
  1479. return -1;
  1480. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1481. {
  1482. if((curB->stacks[g]->position == pos
  1483. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1484. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1485. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1486. ))
  1487. && (!onlyAlive || curB->stacks[g]->alive())
  1488. )
  1489. return curB->stacks[g]->ID;
  1490. }
  1491. return -1;
  1492. }
  1493. int CGameState::battleGetBattlefieldType(int3 tile)
  1494. {
  1495. if(tile==int3() && curB)
  1496. tile = curB->tile;
  1497. else if(tile==int3() && !curB)
  1498. return -1;
  1499. const std::vector <CGObjectInstance*> & objs = map->objects;
  1500. for(int g=0; g<objs.size(); ++g)
  1501. {
  1502. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1503. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1504. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1505. ) //look only for objects covering given tile
  1506. continue;
  1507. switch(objs[g]->ID)
  1508. {
  1509. case 222: //clover field
  1510. return 19;
  1511. case 21: case 223: //cursed ground
  1512. return 22;
  1513. case 224: //evil fog
  1514. return 20;
  1515. case 225: //favourable winds
  1516. return 21;
  1517. case 226: //fiery fields
  1518. return 14;
  1519. case 227: //holy ground
  1520. return 18;
  1521. case 228: //lucid pools
  1522. return 17;
  1523. case 229: //magic clouds
  1524. return 16;
  1525. case 46: case 230: //magic plains
  1526. return 9;
  1527. case 231: //rocklands
  1528. return 15;
  1529. }
  1530. }
  1531. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1532. {
  1533. case TerrainTile::dirt:
  1534. return rand()%3+3;
  1535. case TerrainTile::sand:
  1536. return 2; //TODO: coast support
  1537. case TerrainTile::grass:
  1538. return rand()%2+6;
  1539. case TerrainTile::snow:
  1540. return rand()%2+10;
  1541. case TerrainTile::swamp:
  1542. return 13;
  1543. case TerrainTile::rough:
  1544. return 23;
  1545. case TerrainTile::subterranean:
  1546. return 12;
  1547. case TerrainTile::lava:
  1548. return 8;
  1549. case TerrainTile::water:
  1550. return 25;
  1551. case TerrainTile::rock:
  1552. return 15;
  1553. default:
  1554. return -1;
  1555. }
  1556. }
  1557. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1558. {
  1559. if(!curB)
  1560. return NULL;
  1561. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1562. }
  1563. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1564. {
  1565. UpgradeInfo ret;
  1566. const CCreature *base = &VLC->creh->creatures[obj->army.slots.find(stackPos)->second.first];
  1567. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1568. {
  1569. const CGTownInstance * t;
  1570. if(obj->ID == TOWNI_TYPE)
  1571. t = static_cast<const CGTownInstance *>(obj);
  1572. else
  1573. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1574. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1575. {
  1576. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1577. {
  1578. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1579. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1580. {
  1581. ret.newID.push_back(nid);
  1582. ret.cost.push_back(std::set<std::pair<int,int> >());
  1583. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1584. {
  1585. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1586. if(dif)
  1587. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1588. }
  1589. }
  1590. }
  1591. }//end for
  1592. }
  1593. //TODO: check if hero ability makes some upgrades possible
  1594. if(ret.newID.size())
  1595. ret.oldID = base->idNumber;
  1596. return ret;
  1597. }
  1598. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1599. {
  1600. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1601. if(mode) return -1; //todo - support other modes
  1602. int mcount = 0;
  1603. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1604. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1605. mcount++;
  1606. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1607. return ret;
  1608. }
  1609. void CGameState::loadTownDInfos()
  1610. {
  1611. for(int i=0;i<F_NUMBER;i++)
  1612. {
  1613. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1614. forts[i] = VLC->dobjinfo->castles[i];
  1615. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1616. }
  1617. }
  1618. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1619. {
  1620. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1621. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1622. vec.clear();
  1623. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1624. {
  1625. const int3 hlp = tile + dirs[i];
  1626. if(!map->isInTheMap(hlp))
  1627. continue;
  1628. const TerrainTile &hlpt = map->getTile(hlp);
  1629. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1630. && hlpt.tertype!=9)
  1631. {
  1632. vec.push_back(hlp);
  1633. }
  1634. }
  1635. }
  1636. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1637. {
  1638. if(src == dest) //same tile
  1639. return 0;
  1640. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1641. &d = map->terrain[dest.x][dest.y][dest.z];
  1642. //get basic cost
  1643. int ret = h->getTileCost(d,s);
  1644. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1645. {
  1646. int old = ret;
  1647. ret *= 1.414213;
  1648. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1649. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1650. {
  1651. return remainingMovePoints;
  1652. }
  1653. }
  1654. int left = remainingMovePoints-ret;
  1655. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1656. {
  1657. std::vector<int3> vec;
  1658. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1659. for(size_t i=0; i < vec.size(); i++)
  1660. {
  1661. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1662. if(fcost <= left)
  1663. {
  1664. return ret;
  1665. }
  1666. }
  1667. ret = remainingMovePoints;
  1668. }
  1669. return ret;
  1670. }
  1671. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1672. {
  1673. std::set<int> used;
  1674. used.insert(ID);
  1675. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1676. while(true)
  1677. {
  1678. size_t noloop=0;
  1679. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1680. {
  1681. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1682. {
  1683. used.insert(*i);
  1684. for(
  1685. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1686. j!=VLC->townh->requirements[t->subID][*i].end();
  1687. j++)
  1688. {
  1689. reqs.insert(*j);//creating full list of requirements
  1690. }
  1691. }
  1692. else
  1693. {
  1694. noloop++;
  1695. }
  1696. }
  1697. if(noloop==reqs.size())
  1698. break;
  1699. }
  1700. return reqs;
  1701. }
  1702. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1703. {
  1704. int ret = 7; //allowed by default
  1705. if(t->builded >= MAX_BUILDING_PER_TURN)
  1706. ret = 5; //building limit
  1707. //checking resources
  1708. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1709. if(!pom)return 8;
  1710. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1711. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1712. {
  1713. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1714. ret = 6; //lack of res
  1715. }
  1716. //checking for requirements
  1717. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1718. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1719. {
  1720. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1721. ret = 8; //lack of requirements - cannot build
  1722. }
  1723. //can we build it?
  1724. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1725. ret = 2; //forbidden
  1726. if(ID == 13) //capitol
  1727. {
  1728. for(unsigned int in = 0; in < map->towns.size(); in++)
  1729. {
  1730. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1731. {
  1732. ret = 0; //no more than one capitol
  1733. break;
  1734. }
  1735. }
  1736. }
  1737. else if(ID == 6) //shipyard
  1738. {
  1739. int3 t1(t->pos + int3(-1,3,0)),
  1740. t2(t->pos + int3(-3,3,0));
  1741. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1742. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1743. ret = 1; //lack of water
  1744. }
  1745. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1746. ret = 4;
  1747. return ret;
  1748. }
  1749. void CGameState::apply(CPack *pack)
  1750. {
  1751. ui16 typ = typeList.getTypeID(pack);
  1752. assert(typ >= 0);
  1753. applierGs->apps[typ]->applyOnGS(this,pack);
  1754. }
  1755. PlayerState * CGameState::getPlayer( ui8 color )
  1756. {
  1757. if(vstd::contains(players,color))
  1758. {
  1759. return &players[color];
  1760. }
  1761. else
  1762. {
  1763. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1764. return NULL;
  1765. }
  1766. }
  1767. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1768. {
  1769. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1770. return false;
  1771. int3 hpos = hero->getPosition(false);
  1772. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1773. if (!hero->canWalkOnSea())
  1774. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1775. else
  1776. blockLandSea = boost::logic::indeterminate;
  1777. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1778. //graph initialization
  1779. std::vector< std::vector<CPathNode> > graph;
  1780. graph.resize(map->width);
  1781. for(size_t i=0; i<graph.size(); ++i)
  1782. {
  1783. graph[i].resize(map->height);
  1784. for(size_t j=0; j<graph[i].size(); ++j)
  1785. {
  1786. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1787. CPathNode &node = graph[i][j];
  1788. node.accessible = !tinfo->blocked;
  1789. node.dist = -1;
  1790. node.theNodeBefore = NULL;
  1791. node.visited = false;
  1792. node.coord.x = i;
  1793. node.coord.y = j;
  1794. node.coord.z = dest.z;
  1795. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1796. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1797. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1798. || !FoW[i][j][src.z] //tile is covered by the FoW
  1799. )
  1800. {
  1801. node.accessible = false;
  1802. }
  1803. }
  1804. }
  1805. //Special rules for the destination tile
  1806. {
  1807. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1808. CPathNode &d = graph[dest.x][dest.y];
  1809. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1810. if(t->visitable)
  1811. {
  1812. d.accessible = true; //for allowing visiting objects
  1813. }
  1814. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1815. {
  1816. size_t i = 0;
  1817. for(; i < t->visitableObjects.size(); i++)
  1818. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1819. break;
  1820. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1821. }
  1822. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1823. {
  1824. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1825. }
  1826. }
  1827. //graph initialized
  1828. //initial tile - set cost on 0 and add to the queue
  1829. graph[src.x][src.y].dist = 0;
  1830. std::queue<CPathNode> mq;
  1831. mq.push(graph[src.x][src.y]);
  1832. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1833. std::vector<int3> neighbours;
  1834. neighbours.reserve(8);
  1835. while(!mq.empty())
  1836. {
  1837. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1838. mq.pop();
  1839. if (cp.coord == dest) //it's destination tile
  1840. {
  1841. if (cp.dist < curDist) //that path is better than previous one
  1842. curDist = cp.dist;
  1843. continue;
  1844. }
  1845. else
  1846. {
  1847. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1848. continue;
  1849. }
  1850. //add accessible neighbouring nodes to the queue
  1851. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1852. for(unsigned int i=0; i < neighbours.size(); i++)
  1853. {
  1854. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1855. if(dp.accessible)
  1856. {
  1857. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1858. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1859. {
  1860. dp.dist = cp.dist + cost;
  1861. dp.theNodeBefore = &cp;
  1862. mq.push(dp);
  1863. }
  1864. }
  1865. }
  1866. }
  1867. CPathNode *curNode = &graph[dest.x][dest.y];
  1868. if(!curNode->theNodeBefore) //destination is not accessible
  1869. return false;
  1870. //fill ret with found path
  1871. ret.nodes.clear();
  1872. while(curNode->coord != graph[src.x][src.y].coord)
  1873. {
  1874. ret.nodes.push_back(*curNode);
  1875. curNode = curNode->theNodeBefore;
  1876. }
  1877. ret.nodes.push_back(graph[src.x][src.y]);
  1878. return true;
  1879. }
  1880. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1881. {
  1882. assert(hero);
  1883. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1884. if(src.x < 0)
  1885. src = hero->getPosition(false);
  1886. if(movement < 0)
  1887. movement = hero->movement;
  1888. out.hero = hero;
  1889. out.hpos = src;
  1890. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1891. {
  1892. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1893. return;
  1894. }
  1895. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1896. if (!hero->canWalkOnSea())
  1897. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1898. else
  1899. onLand = boost::logic::indeterminate;
  1900. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1901. //graph initialization
  1902. CGPathNode ***graph = out.nodes;
  1903. for(size_t i=0; i < out.sizes.x; ++i)
  1904. {
  1905. for(size_t j=0; j < out.sizes.y; ++j)
  1906. {
  1907. for(size_t k=0; k < out.sizes.z; ++k)
  1908. {
  1909. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1910. CGPathNode &node = graph[i][j][k];
  1911. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1912. node.turns = 0xff;
  1913. node.moveRemains = 0;
  1914. node.coord.x = i;
  1915. node.coord.y = j;
  1916. node.coord.z = k;
  1917. node.land = tinfo->tertype != TerrainTile::water;
  1918. node.theNodeBefore = NULL;
  1919. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1920. || onLand && !node.land //it's sea and we cannot walk on sea
  1921. || !onLand && node.land //it's land and we cannot walk on land
  1922. || !FoW[i][j][k] //tile is covered by the FoW
  1923. )
  1924. {
  1925. node.accessible = CGPathNode::BLOCKED;
  1926. }
  1927. else if(tinfo->visitable)
  1928. {
  1929. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1930. {
  1931. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1932. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1933. {
  1934. node.accessible = CGPathNode::ACCESSIBLE;
  1935. }
  1936. else if(obj->blockVisit)
  1937. {
  1938. node.accessible = CGPathNode::BLOCKVIS;
  1939. break;
  1940. }
  1941. else if(obj->ID != 26) //pathfinder should ignore placed events
  1942. {
  1943. node.accessible = CGPathNode::VISITABLE;
  1944. }
  1945. }
  1946. }
  1947. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1948. {
  1949. size_t i = 0;
  1950. for(; i < tinfo->visitableObjects.size(); i++)
  1951. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1952. break;
  1953. if(i < tinfo->visitableObjects.size())
  1954. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1955. }
  1956. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1957. {
  1958. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1959. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1960. }
  1961. }
  1962. }
  1963. }
  1964. //graph initialized
  1965. //initial tile - set cost on 0 and add to the queue
  1966. graph[src.x][src.y][src.z].turns = 0;
  1967. graph[src.x][src.y][src.z].moveRemains = movement;
  1968. std::queue<CGPathNode*> mq;
  1969. mq.push(&graph[src.x][src.y][src.z]);
  1970. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1971. std::vector<int3> neighbours;
  1972. neighbours.reserve(8);
  1973. while(!mq.empty())
  1974. {
  1975. CGPathNode *cp = mq.front();
  1976. mq.pop();
  1977. const TerrainTile &ct = map->getTile(cp->coord);
  1978. int movement = cp->moveRemains, turn = cp->turns;
  1979. if(!movement)
  1980. {
  1981. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1982. turn++;
  1983. }
  1984. //add accessible neighbouring nodes to the queue
  1985. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  1986. for(unsigned int i=0; i < neighbours.size(); i++)
  1987. {
  1988. int moveAtNextTile = movement;
  1989. int turnAtNextTile = turn;
  1990. const int3 &n = neighbours[i]; //current neighbor
  1991. CGPathNode & dp = graph[n.x][n.y][n.z];
  1992. if( !checkForVisitableDir(cp->coord, dp.coord)
  1993. || !checkForVisitableDir(dp.coord, cp->coord)
  1994. || dp.accessible == CGPathNode::BLOCKED )
  1995. {
  1996. continue;
  1997. }
  1998. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  1999. int remains = movement - cost;
  2000. if(remains < 0)
  2001. {
  2002. //occurs rarely, when hero with low movepoints tries to go leave the road
  2003. turnAtNextTile++;
  2004. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2005. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2006. remains = moveAtNextTile - cost;
  2007. }
  2008. if(dp.turns==0xff //we haven't been here before
  2009. || dp.turns > turnAtNextTile
  2010. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2011. {
  2012. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2013. dp.moveRemains = remains;
  2014. dp.turns = turnAtNextTile;
  2015. dp.theNodeBefore = cp;
  2016. if(dp.accessible == CGPathNode::ACCESSIBLE)
  2017. {
  2018. mq.push(&dp);
  2019. }
  2020. }
  2021. } //neighbours loop
  2022. } //queue loop
  2023. }
  2024. bool CGameState::isVisible(int3 pos, int player)
  2025. {
  2026. if(player == 255) //neutral player
  2027. return false;
  2028. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2029. }
  2030. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2031. {
  2032. if(player == 255) //neutral player
  2033. return false;
  2034. //object is visible when at least one blocked tile is visible
  2035. for(int fx=0; fx<8; ++fx)
  2036. {
  2037. for(int fy=0; fy<6; ++fy)
  2038. {
  2039. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2040. if(map->isInTheMap(pos)
  2041. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2042. && isVisible(pos, player) )
  2043. return true;
  2044. }
  2045. }
  2046. return false;
  2047. }
  2048. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2049. {
  2050. const TerrainTile * pom = &map->getTile(dst);
  2051. return checkForVisitableDir(src, pom, dst);
  2052. }
  2053. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2054. {
  2055. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2056. {
  2057. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2058. continue;
  2059. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2060. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2061. {
  2062. return false;
  2063. }
  2064. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2065. {
  2066. return false;
  2067. }
  2068. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2069. {
  2070. return false;
  2071. }
  2072. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2073. {
  2074. return false;
  2075. }
  2076. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2077. {
  2078. return false;
  2079. }
  2080. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2081. {
  2082. return false;
  2083. }
  2084. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2085. {
  2086. return false;
  2087. }
  2088. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2089. {
  2090. return false;
  2091. }
  2092. }
  2093. return true;
  2094. }
  2095. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2096. {
  2097. float attackDefenseBonus,
  2098. minDmg = attacker->creature->damageMin * attacker->amount,
  2099. maxDmg = attacker->creature->damageMax * attacker->amount;
  2100. if(attacker->creature->idNumber == 149) //arrow turret
  2101. {
  2102. switch(attacker->position)
  2103. {
  2104. case -2: //keep
  2105. minDmg = 15;
  2106. maxDmg = 15;
  2107. break;
  2108. case -3: case -4: //turrets
  2109. minDmg = 7.5f;
  2110. maxDmg = 7.5f;
  2111. break;
  2112. }
  2113. }
  2114. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON) && attacker->creature->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2115. { //minDmg and maxDmg are multiplied by hero attack + 1
  2116. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2117. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2118. }
  2119. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  2120. {
  2121. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  2122. }
  2123. else
  2124. {
  2125. attackDefenseBonus = attacker->Attack() - defender->Defense();
  2126. }
  2127. //calculating total attack/defense skills modifier
  2128. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  2129. {
  2130. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  2131. }
  2132. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  2133. {
  2134. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  2135. }
  2136. if(attacker->getEffect(55)) //slayer handling
  2137. {
  2138. std::vector<int> affectedIds;
  2139. switch(attacker->getEffect(55)->level)
  2140. {
  2141. case 3: //expert
  2142. {
  2143. affectedIds.push_back(40); //giant
  2144. affectedIds.push_back(41); //titan
  2145. affectedIds.push_back(152); //lord of thunder
  2146. } //continue adding ...
  2147. case 2: //advanced
  2148. {
  2149. affectedIds.push_back(12); //angel
  2150. affectedIds.push_back(13); //archangel
  2151. affectedIds.push_back(54); //devil
  2152. affectedIds.push_back(55); //arch devil
  2153. affectedIds.push_back(150); //supreme archangel
  2154. affectedIds.push_back(153); //antichrist
  2155. } //continue adding ...
  2156. case 0: case 1: //none and basic
  2157. {
  2158. affectedIds.push_back(26); //green dragon
  2159. affectedIds.push_back(27); //gold dragon
  2160. affectedIds.push_back(82); //red dragon
  2161. affectedIds.push_back(83); //black dragon
  2162. affectedIds.push_back(96); //behemot
  2163. affectedIds.push_back(97); //ancient behemot
  2164. affectedIds.push_back(110); //hydra
  2165. affectedIds.push_back(111); //chaos hydra
  2166. affectedIds.push_back(132); //azure dragon
  2167. affectedIds.push_back(133); //crystal dragon
  2168. affectedIds.push_back(134); //faerie dragon
  2169. affectedIds.push_back(135); //rust dragon
  2170. affectedIds.push_back(151); //diamond dragon
  2171. affectedIds.push_back(154); //blood dragon
  2172. affectedIds.push_back(155); //darkness dragon
  2173. affectedIds.push_back(156); //ghost behemoth
  2174. affectedIds.push_back(157); //hell hydra
  2175. break;
  2176. }
  2177. }
  2178. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2179. {
  2180. if(defender->creature->idNumber == affectedIds[g])
  2181. {
  2182. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2183. break;
  2184. }
  2185. }
  2186. }
  2187. float dmgBonusMultiplier = 1.0f;
  2188. //applying jousting bonus
  2189. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2190. dmgBonusMultiplier += charge * 0.05f;
  2191. //bonus from attack/defense skills
  2192. if(attackDefenseBonus < 0) //decreasing dmg
  2193. {
  2194. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2195. {
  2196. dmgBonusMultiplier += -0.3f;
  2197. }
  2198. else
  2199. {
  2200. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2201. }
  2202. }
  2203. else //increasing dmg
  2204. {
  2205. if(0.05f * attackDefenseBonus > 4.0f)
  2206. {
  2207. dmgBonusMultiplier += 4.0f;
  2208. }
  2209. else
  2210. {
  2211. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2212. }
  2213. }
  2214. //handling secondary abilities and artifacts giving premies to them
  2215. if(attackerHero)
  2216. {
  2217. if(shooting)
  2218. {
  2219. switch(attackerHero->getSecSkillLevel(1)) //archery
  2220. {
  2221. case 1: //basic
  2222. dmgBonusMultiplier += 0.1f;
  2223. break;
  2224. case 2: //advanced
  2225. dmgBonusMultiplier += 0.25f;
  2226. break;
  2227. case 3: //expert
  2228. dmgBonusMultiplier += 0.5f;
  2229. break;
  2230. }
  2231. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2232. {
  2233. //apply artifact premy to archery
  2234. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2235. }
  2236. }
  2237. else
  2238. {
  2239. switch(attackerHero->getSecSkillLevel(22)) //offense
  2240. {
  2241. case 1: //basic
  2242. dmgBonusMultiplier += 0.1f;
  2243. break;
  2244. case 2: //advanced
  2245. dmgBonusMultiplier += 0.2f;
  2246. break;
  2247. case 3: //expert
  2248. dmgBonusMultiplier += 0.3f;
  2249. break;
  2250. }
  2251. }
  2252. }
  2253. if(defendingHero)
  2254. {
  2255. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2256. {
  2257. case 1: //basic
  2258. dmgBonusMultiplier *= 0.95f;
  2259. break;
  2260. case 2: //advanced
  2261. dmgBonusMultiplier *= 0.9f;
  2262. break;
  2263. case 3: //expert
  2264. dmgBonusMultiplier *= 0.85f;
  2265. break;
  2266. }
  2267. }
  2268. //handling hate effect
  2269. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2270. dmgBonusMultiplier += 0.5f;
  2271. //handling spell effects
  2272. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2273. {
  2274. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2275. }
  2276. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2277. {
  2278. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2279. }
  2280. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2281. {
  2282. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2283. }
  2284. minDmg *= dmgBonusMultiplier;
  2285. maxDmg *= dmgBonusMultiplier;
  2286. if(attacker->getEffect(42)) //curse handling (rest)
  2287. {
  2288. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2289. return std::make_pair(int(minDmg), int(minDmg));
  2290. }
  2291. else if(attacker->getEffect(41)) //bless handling
  2292. {
  2293. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2294. return std::make_pair(int(maxDmg), int(maxDmg));
  2295. }
  2296. else
  2297. {
  2298. return std::make_pair(int(minDmg), int(maxDmg));
  2299. }
  2300. tlog1 << "We are too far in calculateDmg...\n";
  2301. return std::make_pair(0, 0);
  2302. }
  2303. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2304. {
  2305. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2306. if(range.first != range.second)
  2307. return range.first + rand() % (range.second - range.first + 1);
  2308. else
  2309. return range.first;
  2310. }
  2311. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2312. {
  2313. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2314. {
  2315. const CStack * const st = stacks[i];
  2316. si32 killed = (st->alive() ? st->baseAmount - st->amount : st->baseAmount);
  2317. amax(killed, 0);
  2318. if(killed)
  2319. casualties[!st->attackerOwned][st->creature->idNumber] += killed;
  2320. }
  2321. }
  2322. si8 CGameState::battleMaxSpellLevel()
  2323. {
  2324. if(!curB) //there is not battle
  2325. {
  2326. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2327. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2328. }
  2329. si8 levelLimit = SPELL_LEVELS;
  2330. const CGHeroInstance *h1 = curB->heroes[0];
  2331. if(h1)
  2332. {
  2333. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2334. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2335. amin(levelLimit, i->val);
  2336. }
  2337. const CGHeroInstance *h2 = curB->heroes[1];
  2338. if(h2)
  2339. {
  2340. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2341. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2342. amin(levelLimit, i->val);
  2343. }
  2344. return levelLimit;
  2345. }
  2346. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2347. {
  2348. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2349. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2350. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2351. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2352. {
  2353. for(int it=0; it<stacks.size(); ++it)
  2354. {
  2355. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2356. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2357. || (s->id == 26) //Armageddon
  2358. )
  2359. {
  2360. if(stacks[it]->alive())
  2361. attackedCres.insert(stacks[it]);
  2362. }
  2363. }
  2364. }
  2365. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2366. || 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
  2367. {
  2368. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2369. {
  2370. CStack * st = getStackT(destinationTile, onlyAlive);
  2371. if(st)
  2372. attackedCres.insert(st);
  2373. }
  2374. else
  2375. {
  2376. for(int it=0; it<stacks.size(); ++it)
  2377. {
  2378. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2379. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2380. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2381. )
  2382. {
  2383. if(!onlyAlive || stacks[it]->alive())
  2384. attackedCres.insert(stacks[it]);
  2385. }
  2386. }
  2387. } //if(caster->getSpellSchoolLevel(s) < 3)
  2388. }
  2389. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2390. {
  2391. CStack * st = getStackT(destinationTile, onlyAlive);
  2392. if(st)
  2393. attackedCres.insert(st);
  2394. }
  2395. else //custom range from attackedHexes
  2396. {
  2397. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2398. {
  2399. CStack * st = getStackT(*it, onlyAlive);
  2400. if(st)
  2401. attackedCres.insert(st);
  2402. }
  2403. }
  2404. return attackedCres;
  2405. }
  2406. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2407. {
  2408. switch(spell->id)
  2409. {
  2410. case 56: //frenzy
  2411. return 1;
  2412. default: //other spells
  2413. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2414. }
  2415. }
  2416. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2417. {
  2418. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2419. if(owner)
  2420. {
  2421. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2422. //base luck/morale calculations
  2423. ret->morale = owner->getCurrentMorale(slot, false);
  2424. ret->luck = owner->getCurrentLuck(slot, false);
  2425. //other bonuses
  2426. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2427. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2428. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2429. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2430. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2431. StackFeature::BONUS_FROM_HERO));
  2432. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2433. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2434. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2435. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2436. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2437. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2438. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2439. ret->firstHPleft = ret->MaxHealth();
  2440. }
  2441. else
  2442. {
  2443. ret->morale = 0;
  2444. ret->luck = 0;
  2445. }
  2446. //native terrain bonuses
  2447. int faction = ret->creature->faction;
  2448. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2449. {
  2450. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2451. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2452. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2453. }
  2454. ret->position = position;
  2455. return ret;
  2456. }
  2457. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2458. {
  2459. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2460. //checking for friendly stacks reducing cost of the spell
  2461. si32 manaReduction = 0;
  2462. for(int g=0; g<stacks.size(); ++g)
  2463. {
  2464. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2465. {
  2466. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2467. }
  2468. }
  2469. return ret + manaReduction;
  2470. }
  2471. int BattleInfo::hexToWallPart(int hex) const
  2472. {
  2473. if(siege == 0) //there is no battle!
  2474. return -1;
  2475. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2476. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2477. 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)};
  2478. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2479. {
  2480. if(attackable[g].first == hex)
  2481. return attackable[g].second;
  2482. }
  2483. return -1; //not found!
  2484. }
  2485. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2486. {
  2487. bool ac[BFIELD_SIZE];
  2488. std::set<int> occupyable;
  2489. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2490. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2491. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING), true);
  2492. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2493. for(int g=0; g<BFIELD_SIZE; ++g)
  2494. {
  2495. const CStack * atG = getStackT(g);
  2496. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2497. continue;
  2498. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2499. {
  2500. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2501. continue;
  2502. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2503. }
  2504. }
  2505. if(stackPairs.size() > 0)
  2506. {
  2507. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2508. minimalPairs.push_back(stackPairs[0]);
  2509. for(int b=1; b<stackPairs.size(); ++b)
  2510. {
  2511. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2512. {
  2513. minimalPairs.clear();
  2514. minimalPairs.push_back(stackPairs[b]);
  2515. }
  2516. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2517. {
  2518. minimalPairs.push_back(stackPairs[b]);
  2519. }
  2520. }
  2521. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2522. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2523. }
  2524. return std::make_pair<const CStack * , int>(NULL, -1);
  2525. }
  2526. ui32 BattleInfo::calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  2527. {
  2528. ui32 ret = 0; //value to return
  2529. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2530. //24 - death ripple, 25 - destroy undead, 26 - armageddon
  2531. 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);
  2532. //check if spell really does damage - if not, return 0
  2533. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2534. return 0;
  2535. ret = caster->getPrimSkillLevel(2) * dmgMultipliers[sp->id] + sp->powers[caster->getSpellSchoolLevel(sp)];
  2536. //applying sorcerery secondary skill
  2537. switch(caster->getSecSkillLevel(25))
  2538. {
  2539. case 1: //basic
  2540. ret *= 1.05f;
  2541. break;
  2542. case 2: //advanced
  2543. ret *= 1.1f;
  2544. break;
  2545. case 3: //expert
  2546. ret *= 1.15f;
  2547. break;
  2548. }
  2549. //applying hero bonuses
  2550. if(sp->air && caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) != 0)
  2551. {
  2552. ret *= (100.0f + caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) / 100.0f);
  2553. }
  2554. else if(sp->fire && caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) != 0)
  2555. {
  2556. ret *= (100.0f + caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) / 100.0f);
  2557. }
  2558. else if(sp->water && caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) != 0)
  2559. {
  2560. ret *= (100.0f + caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) / 100.0f);
  2561. }
  2562. else if(sp->earth && caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) != 0)
  2563. {
  2564. ret *= (100.0f + caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) / 100.0f);
  2565. }
  2566. //affected creature-specific part
  2567. if(affectedCreature)
  2568. {
  2569. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2570. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2571. {
  2572. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 0);
  2573. ret /= 100;
  2574. }
  2575. else if(sp->fire && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2576. {
  2577. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 1);
  2578. ret /= 100;
  2579. }
  2580. else if(sp->water && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2581. {
  2582. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 2);
  2583. ret /= 100;
  2584. }
  2585. else if (sp->earth && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2586. {
  2587. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 3);
  2588. ret /= 100;
  2589. }
  2590. //general spell dmg reduction
  2591. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2592. {
  2593. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, -1);
  2594. ret /= 100;
  2595. }
  2596. //dmg increasing
  2597. if( affectedCreature->hasFeatureOfType(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2598. {
  2599. ret *= 100 + affectedCreature->valOfFeatures(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id);
  2600. ret /= 100;
  2601. }
  2602. }
  2603. return ret;
  2604. }
  2605. bool CGameState::battleCanShoot(int ID, int dest)
  2606. {
  2607. if(!curB)
  2608. return false;
  2609. const CStack *our = curB->getStack(ID),
  2610. *dst = curB->getStackT(dest);
  2611. if(!our || !dst) return false;
  2612. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2613. if(our->hasFeatureOfType(StackFeature::FORGETFULL)) //forgetfulness
  2614. return false;
  2615. if(our->creature->idNumber == 145 && dst) //catapult cannot attack creatures
  2616. return false;
  2617. if(our->hasFeatureOfType(StackFeature::SHOOTER)//it's shooter
  2618. && our->owner != dst->owner
  2619. && dst->alive()
  2620. && (!curB->isStackBlocked(ID)
  2621. || ourHero->hasBonusOfType(HeroBonus::FREE_SHOOTING))
  2622. && our->shots
  2623. )
  2624. return true;
  2625. return false;
  2626. }
  2627. const CStack * BattleInfo::getNextStack() const
  2628. {
  2629. std::vector<const CStack *> hlp;
  2630. getStackQueue(hlp, 1, -1);
  2631. if(hlp.size())
  2632. return hlp[0];
  2633. else
  2634. return NULL;
  2635. }
  2636. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  2637. {
  2638. const CStack *ret = NULL;
  2639. unsigned i, //fastest stack
  2640. j; //fastest stack of the other side
  2641. for(i = 0; i < st.size(); i++)
  2642. if(st[i])
  2643. break;
  2644. //no stacks left
  2645. if(i == st.size())
  2646. return NULL;
  2647. const CStack *fastest = st[i], *other = NULL;
  2648. int bestSpeed = fastest->Speed(turn);
  2649. if(fastest->attackerOwned != curside)
  2650. {
  2651. ret = fastest;
  2652. }
  2653. else
  2654. {
  2655. for(j = i + 1; j < st.size(); j++)
  2656. {
  2657. if(!st[j]) continue;
  2658. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  2659. break;
  2660. }
  2661. if(j >= st.size())
  2662. {
  2663. ret = fastest;
  2664. }
  2665. else
  2666. {
  2667. other = st[j];
  2668. if(other->Speed(turn) != bestSpeed)
  2669. ret = fastest;
  2670. else
  2671. ret = other;
  2672. }
  2673. }
  2674. assert(ret);
  2675. if(ret == fastest)
  2676. st[i] = NULL;
  2677. else
  2678. st[j] = NULL;
  2679. curside = ret->attackerOwned;
  2680. return ret;
  2681. }
  2682. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  2683. {
  2684. //we'll split creatures with remaining movement to 4 parts
  2685. 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
  2686. int toMove = 0; //how many stacks still has move
  2687. const CStack *active = getStack(activeStack);
  2688. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  2689. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  2690. {
  2691. out.push_back(active);
  2692. if(out.size() == howMany)
  2693. return;
  2694. }
  2695. for(unsigned int i=0; i<stacks.size(); ++i)
  2696. {
  2697. const CStack * const s = stacks[i];
  2698. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  2699. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  2700. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  2701. {
  2702. continue;
  2703. }
  2704. int p = -1; //in which phase this tack will move?
  2705. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  2706. {
  2707. if(vstd::contains(s->state, HAD_MORALE))
  2708. p = 2;
  2709. else
  2710. p = 3;
  2711. }
  2712. else if(s->creature->idNumber == 145 || s->creature->idNumber == 149) //catapult and turrets are first
  2713. {
  2714. p = 0;
  2715. }
  2716. else
  2717. {
  2718. p = 1;
  2719. }
  2720. phase[p].push_back(s);
  2721. toMove++;
  2722. }
  2723. for(int i = 0; i < 4; i++)
  2724. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  2725. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  2726. out.push_back(phase[0][i]);
  2727. if(out.size() == howMany)
  2728. return;
  2729. if(lastMoved == -1)
  2730. {
  2731. if(active)
  2732. {
  2733. if(out.size() && out.front() == active)
  2734. lastMoved = active->attackerOwned;
  2735. else
  2736. lastMoved = active->attackerOwned;
  2737. }
  2738. else
  2739. {
  2740. lastMoved = 0;
  2741. }
  2742. }
  2743. int pi = 1;
  2744. while(out.size() < howMany)
  2745. {
  2746. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  2747. if(!hlp)
  2748. {
  2749. pi++;
  2750. if(pi > 3)
  2751. {
  2752. //if(turn != 2)
  2753. getStackQueue(out, howMany, turn + 1, lastMoved);
  2754. return;
  2755. }
  2756. }
  2757. else
  2758. {
  2759. out.push_back(hlp);
  2760. }
  2761. }
  2762. }
  2763. int3 CPath::startPos() const
  2764. {
  2765. return nodes[nodes.size()-1].coord;
  2766. }
  2767. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2768. {
  2769. if (mode==0)
  2770. {
  2771. for (unsigned int i=0;i<nodes.size();i++)
  2772. {
  2773. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2774. }
  2775. }
  2776. }
  2777. int3 CPath::endPos() const
  2778. {
  2779. return nodes[0].coord;
  2780. }
  2781. CGPathNode::CGPathNode()
  2782. :coord(-1,-1,-1)
  2783. {
  2784. accessible = 0;
  2785. land = 0;
  2786. moveRemains = 0;
  2787. turns = 255;
  2788. theNodeBefore = NULL;
  2789. }
  2790. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2791. {
  2792. out.nodes.clear();
  2793. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2794. if(!curnode->theNodeBefore)
  2795. return false;
  2796. while(curnode)
  2797. {
  2798. out.nodes.push_back(*curnode);
  2799. curnode = curnode->theNodeBefore;
  2800. }
  2801. return true;
  2802. }
  2803. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2804. :sizes(Sizes)
  2805. {
  2806. hero = NULL;
  2807. nodes = new CGPathNode**[sizes.x];
  2808. for(int i = 0; i < sizes.x; i++)
  2809. {
  2810. nodes[i] = new CGPathNode*[sizes.y];
  2811. for (int j = 0; j < sizes.y; j++)
  2812. {
  2813. nodes[i][j] = new CGPathNode[sizes.z];
  2814. }
  2815. }
  2816. }
  2817. CPathsInfo::~CPathsInfo()
  2818. {
  2819. for(int i = 0; i < sizes.x; i++)
  2820. {
  2821. for (int j = 0; j < sizes.y; j++)
  2822. {
  2823. delete [] nodes[i][j];
  2824. }
  2825. delete [] nodes[i];
  2826. }
  2827. delete [] nodes;
  2828. }
  2829. int3 CGPath::startPos() const
  2830. {
  2831. return nodes[nodes.size()-1].coord;
  2832. }
  2833. int3 CGPath::endPos() const
  2834. {
  2835. return nodes[0].coord;
  2836. }
  2837. void CGPath::convert( ui8 mode )
  2838. {
  2839. if(mode==0)
  2840. {
  2841. for(unsigned int i=0;i<nodes.size();i++)
  2842. {
  2843. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2844. }
  2845. }
  2846. }
  2847. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2848. {
  2849. switch(phase)
  2850. {
  2851. case 0: //catapult moves after turrets
  2852. return a->creature->idNumber < b->creature->idNumber; //catapult is 145 and turrets are 149
  2853. //TODO? turrets order
  2854. case 1: //fastest first, upper slot first
  2855. {
  2856. int as = a->Speed(turn), bs = b->Speed(turn);
  2857. if(as != bs)
  2858. return as > bs;
  2859. else
  2860. return a->slot < b->slot;
  2861. }
  2862. case 2: //fastest last, upper slot first
  2863. //TODO: should be replaced with order of receiving morale!
  2864. case 3: //fastest last, upper slot first
  2865. {
  2866. int as = a->Speed(turn), bs = b->Speed(turn);
  2867. if(as != bs)
  2868. return as < bs;
  2869. else
  2870. return a->slot < b->slot;
  2871. }
  2872. default:
  2873. assert(0);
  2874. return false;
  2875. }
  2876. }
  2877. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2878. {
  2879. phase = Phase;
  2880. turn = Turn;
  2881. }
  2882. PlayerState::PlayerState()
  2883. : color(-1), currentSelection(0xffffffff)
  2884. {
  2885. }