CGameState.cpp 111 KB

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