CGameState.cpp 102 KB

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