CGameState.cpp 108 KB

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