CGameState.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136
  1. #define VCMI_DLL
  2. #include "CCampaignHandler.h"
  3. #include <algorithm>
  4. #include <queue>
  5. #include <fstream>
  6. #include "CGameState.h"
  7. #include <boost/random/linear_congruential.hpp>
  8. #include "CDefObjInfoHandler.h"
  9. #include "CArtHandler.h"
  10. #include "CBuildingHandler.h"
  11. #include "CGeneralTextHandler.h"
  12. #include "CTownHandler.h"
  13. #include "CSpellHandler.h"
  14. #include "CHeroHandler.h"
  15. #include "CObjectHandler.h"
  16. #include "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. #include "CMapInfo.h"
  32. #include "BattleState.h"
  33. boost::rand48 ran;
  34. class CGObjectInstance;
  35. #ifdef min
  36. #undef min
  37. #endif
  38. #ifdef max
  39. #undef max
  40. #endif
  41. /*
  42. * CGameState.cpp, part of VCMI engine
  43. *
  44. * Authors: listed in file AUTHORS in main folder
  45. *
  46. * License: GNU General Public License v2.0 or later
  47. * Full text of license available in license.txt file, in main folder
  48. *
  49. */
  50. void foofoofoo()
  51. {
  52. //never called function to force instantation of templates
  53. int *ccc = NULL;
  54. registerTypes((CISer<CConnection>&)*ccc);
  55. registerTypes((COSer<CConnection>&)*ccc);
  56. registerTypes((CSaveFile&)*ccc);
  57. registerTypes((CLoadFile&)*ccc);
  58. registerTypes((CTypeList&)*ccc);
  59. }
  60. template <typename T> class CApplyOnGS;
  61. class CBaseForGSApply
  62. {
  63. public:
  64. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  65. virtual ~CBaseForGSApply(){};
  66. template<typename U> static CBaseForGSApply *getApplier(const U * t=NULL)
  67. {
  68. return new CApplyOnGS<U>;
  69. }
  70. };
  71. template <typename T> class CApplyOnGS : public CBaseForGSApply
  72. {
  73. public:
  74. void applyOnGS(CGameState *gs, void *pack) const
  75. {
  76. T *ptr = static_cast<T*>(pack);
  77. while(!gs->mx->try_lock())
  78. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  79. ptr->applyGs(gs);
  80. gs->mx->unlock();
  81. }
  82. };
  83. static CApplier<CBaseForGSApply> *applierGs = NULL;
  84. class IObjectCaller
  85. {
  86. public:
  87. virtual void preInit()=0;
  88. virtual void postInit()=0;
  89. };
  90. template <typename T>
  91. class CObjectCaller : public IObjectCaller
  92. {
  93. public:
  94. void preInit()
  95. {
  96. //T::preInit();
  97. }
  98. void postInit()
  99. {
  100. //T::postInit();
  101. }
  102. };
  103. class CObjectCallersHandler
  104. {
  105. public:
  106. std::vector<IObjectCaller*> apps;
  107. template<typename T> void registerType(const T * t=NULL)
  108. {
  109. apps.push_back(new CObjectCaller<T>);
  110. }
  111. CObjectCallersHandler()
  112. {
  113. registerTypes1(*this);
  114. }
  115. ~CObjectCallersHandler()
  116. {
  117. for (size_t i = 0; i < apps.size(); i++)
  118. delete apps[i];
  119. }
  120. void preInit()
  121. {
  122. // for (size_t i = 0; i < apps.size(); i++)
  123. // apps[i]->preInit();
  124. }
  125. void postInit()
  126. {
  127. //for (size_t i = 0; i < apps.size(); i++)
  128. //apps[i]->postInit();
  129. }
  130. } *objCaller = NULL;
  131. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  132. {
  133. int type = txt.first, ser = txt.second;
  134. if(type == ART_NAMES)
  135. {
  136. dst = VLC->arth->artifacts[ser]->Name();
  137. }
  138. else if(type == CRE_PL_NAMES)
  139. {
  140. dst = VLC->creh->creatures[ser]->namePl;
  141. }
  142. else if(type == MINE_NAMES)
  143. {
  144. dst = VLC->generaltexth->mines[ser].first;
  145. }
  146. else if(type == MINE_EVNTS)
  147. {
  148. dst = VLC->generaltexth->mines[ser].second;
  149. }
  150. else if(type == SPELL_NAME)
  151. {
  152. dst = VLC->spellh->spells[ser]->name;
  153. }
  154. else if(type == CRE_SING_NAMES)
  155. {
  156. dst = VLC->creh->creatures[ser]->nameSing;
  157. }
  158. else if(type == ART_DESCR)
  159. {
  160. dst = VLC->arth->artifacts[ser]->Description();
  161. }
  162. else
  163. {
  164. std::vector<std::string> *vec;
  165. switch(type)
  166. {
  167. case GENERAL_TXT:
  168. vec = &VLC->generaltexth->allTexts;
  169. break;
  170. case XTRAINFO_TXT:
  171. vec = &VLC->generaltexth->xtrainfo;
  172. break;
  173. case OBJ_NAMES:
  174. vec = &VLC->generaltexth->names;
  175. break;
  176. case RES_NAMES:
  177. vec = &VLC->generaltexth->restypes;
  178. break;
  179. case ARRAY_TXT:
  180. vec = &VLC->generaltexth->arraytxt;
  181. break;
  182. case CREGENS:
  183. vec = &VLC->generaltexth->creGens;
  184. break;
  185. case CREGENS4:
  186. vec = &VLC->generaltexth->creGens4;
  187. break;
  188. case ADVOB_TXT:
  189. vec = &VLC->generaltexth->advobtxt;
  190. break;
  191. case ART_EVNTS:
  192. vec = &VLC->generaltexth->artifEvents;
  193. break;
  194. case SEC_SKILL_NAME:
  195. vec = &VLC->generaltexth->skillName;
  196. break;
  197. case COLOR:
  198. vec = &VLC->generaltexth->capColors;
  199. break;
  200. }
  201. dst = (*vec)[ser];
  202. }
  203. }
  204. DLL_EXPORT void MetaString::toString(std::string &dst) const
  205. {
  206. size_t exSt = 0, loSt = 0, nums = 0;
  207. dst.clear();
  208. for(size_t i=0;i<message.size();++i)
  209. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  210. switch(message[i])
  211. {
  212. case TEXACT_STRING:
  213. dst += exactStrings[exSt++];
  214. break;
  215. case TLOCAL_STRING:
  216. {
  217. std::string hlp;
  218. getLocalString(localStrings[loSt++], hlp);
  219. dst += hlp;
  220. }
  221. break;
  222. case TNUMBER:
  223. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  224. break;
  225. case TREPLACE_ESTRING:
  226. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  227. break;
  228. case TREPLACE_LSTRING:
  229. {
  230. std::string hlp;
  231. getLocalString(localStrings[loSt++], hlp);
  232. dst.replace (dst.find("%s"), 2, hlp);
  233. }
  234. break;
  235. case TREPLACE_NUMBER:
  236. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  237. break;
  238. case TREPLACE_PLUSNUMBER:
  239. dst.replace (dst.find("%+d"), 3, '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  240. break;
  241. default:
  242. tlog1 << "MetaString processing error!\n";
  243. break;
  244. }
  245. }
  246. }
  247. DLL_EXPORT std::string MetaString::toString() const
  248. {
  249. std::string ret;
  250. toString(ret);
  251. return ret;
  252. }
  253. DLL_EXPORT std::string MetaString::buildList () const
  254. ///used to handle loot from creature bank
  255. {
  256. size_t exSt = 0, loSt = 0, nums = 0;
  257. std::string lista;
  258. for (int i = 0; i < message.size(); ++i)
  259. {
  260. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  261. {
  262. if (exSt == exactStrings.size() - 1)
  263. lista += VLC->generaltexth->allTexts[141]; //" and "
  264. else
  265. lista += ", ";
  266. }
  267. switch (message[i])
  268. {
  269. case TEXACT_STRING:
  270. lista += exactStrings[exSt++];
  271. break;
  272. case TLOCAL_STRING:
  273. {
  274. std::string hlp;
  275. getLocalString (localStrings[loSt++], hlp);
  276. lista += hlp;
  277. }
  278. break;
  279. case TNUMBER:
  280. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  281. break;
  282. case TREPLACE_ESTRING:
  283. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  284. break;
  285. case TREPLACE_LSTRING:
  286. {
  287. std::string hlp;
  288. getLocalString (localStrings[loSt++], hlp);
  289. lista.replace (lista.find("%s"), 2, hlp);
  290. }
  291. break;
  292. case TREPLACE_NUMBER:
  293. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  294. break;
  295. default:
  296. tlog1 << "MetaString processing error!\n";
  297. }
  298. }
  299. return lista;
  300. }
  301. void MetaString::addCreReplacement(TCreature id, TQuantity count) //adds sing or plural name;
  302. {
  303. assert(count);
  304. if (count == 1)
  305. addReplacement (CRE_SING_NAMES, id);
  306. else
  307. addReplacement (CRE_PL_NAMES, id);
  308. }
  309. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  310. {
  311. assert(stack.count); //valid count
  312. assert(stack.type); //valid type
  313. addCreReplacement(stack.type->idNumber, stack.count);
  314. }
  315. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  316. {
  317. CGObjectInstance * nobj;
  318. switch(id)
  319. {
  320. case HEROI_TYPE: //hero
  321. {
  322. CGHeroInstance * nobj = new CGHeroInstance();
  323. nobj->pos = pos;
  324. nobj->tempOwner = owner;
  325. nobj->subID = subid;
  326. //nobj->initHero(ran);
  327. return nobj;
  328. }
  329. case TOWNI_TYPE: //town
  330. nobj = new CGTownInstance;
  331. break;
  332. default: //rest of objects
  333. nobj = new CGObjectInstance;
  334. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  335. break;
  336. }
  337. nobj->ID = id;
  338. nobj->subID = subid;
  339. if(!nobj->defInfo)
  340. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  341. nobj->pos = pos;
  342. //nobj->state = NULL;//new CLuaObjectScript();
  343. nobj->tempOwner = owner;
  344. nobj->defInfo->id = id;
  345. nobj->defInfo->subid = subid;
  346. //assigning defhandler
  347. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  348. return nobj;
  349. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  350. return nobj;
  351. }
  352. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass /*= NULL*/) const
  353. {
  354. CGHeroInstance *ret = NULL;
  355. if(player<0 || player>=PLAYER_LIMIT)
  356. {
  357. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  358. return NULL;
  359. }
  360. std::vector<CGHeroInstance *> pool;
  361. if(native)
  362. {
  363. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  364. {
  365. if(pavailable.find(i->first)->second & 1<<player
  366. && i->second->type->heroType/2 == town->typeID)
  367. {
  368. pool.push_back(i->second); //get all avaliable heroes
  369. }
  370. }
  371. if(!pool.size())
  372. {
  373. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  374. return pickHeroFor(false, player, town, available);
  375. }
  376. else
  377. {
  378. ret = pool[rand()%pool.size()];
  379. }
  380. }
  381. else
  382. {
  383. int sum=0, r;
  384. for(bmap<ui32, ConstTransitivePtr<CGHeroInstance> >::iterator i=available.begin(); i!=available.end(); i++)
  385. {
  386. if(pavailable.find(i->first)->second & 1<<player
  387. && !bannedClass || i->second->type->heroClass != bannedClass)
  388. {
  389. pool.push_back(i->second);
  390. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  391. }
  392. }
  393. if(!pool.size())
  394. {
  395. tlog1 << "There are no heroes available for player " << player<<"!\n";
  396. return NULL;
  397. }
  398. r = rand()%sum;
  399. for (unsigned int i=0; i<pool.size(); i++)
  400. {
  401. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  402. if(r < 0)
  403. {
  404. ret = pool[i];
  405. break;
  406. }
  407. }
  408. if(!ret)
  409. ret = pool.back();
  410. }
  411. available.erase(ret->subID);
  412. return ret;
  413. }
  414. //void CGameState::apply(CPack * pack)
  415. //{
  416. // while(!mx->try_lock())
  417. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  418. // //applyNL(pack);
  419. // mx->unlock();
  420. //}
  421. int CGameState::pickHero(int owner)
  422. {
  423. int h=-1;
  424. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  425. if(!map->getHero(h = ps.hero,0) && h>=0) //we haven't used selected hero
  426. return h;
  427. int i=0;
  428. do //try to find free hero of our faction
  429. {
  430. i++;
  431. h = ps.castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  432. } while( map->getHero(h) && i<175);
  433. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  434. {
  435. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  436. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  437. if(!map->getHero(j))
  438. h=j;
  439. }
  440. return h;
  441. }
  442. CGHeroInstance *CGameState::getHero(int objid)
  443. {
  444. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  445. return NULL;
  446. return static_cast<CGHeroInstance *>(map->objects[objid].get());
  447. }
  448. const CGHeroInstance * CGameState::getHero( int objid ) const
  449. {
  450. return (const_cast<CGameState *>(this))->getHero(objid);
  451. }
  452. CGTownInstance *CGameState::getTown(int objid)
  453. {
  454. if(objid<0 || objid>=map->objects.size())
  455. return NULL;
  456. CGObjectInstance *obj = map->objects[objid];
  457. if(obj->ID != TOWNI_TYPE)
  458. return NULL;
  459. return static_cast<CGTownInstance *>(obj);
  460. }
  461. const CGTownInstance * CGameState::getTown( int objid ) const
  462. {
  463. return (const_cast<CGameState *>(this))->getTown(objid);
  464. }
  465. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  466. {
  467. switch(obj->ID)
  468. {
  469. case 65:
  470. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  471. case 66: //random treasure artifact
  472. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_TREASURE));
  473. case 67: //random minor artifact
  474. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MINOR));
  475. case 68: //random major artifact
  476. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_MAJOR));
  477. case 69: //random relic artifact
  478. return std::pair<int,int>(5, VLC->arth->getRandomArt (CArtifact::ART_RELIC));
  479. case 70: //random hero
  480. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  481. case 71: //random monster
  482. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran)));
  483. case 72: //random monster lvl1
  484. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 1));
  485. case 73: //random monster lvl2
  486. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 2));
  487. case 74: //random monster lvl3
  488. return std::pair<int,int>(54,VLC->creh->pickRandomMonster(boost::ref(ran), 3));
  489. case 75: //random monster lvl4
  490. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 4));
  491. case 76: //random resource
  492. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  493. case 77: //random town
  494. {
  495. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  496. f;
  497. if(align>PLAYER_LIMIT-1)//same as owner / random
  498. {
  499. if(obj->tempOwner > PLAYER_LIMIT-1)
  500. f = -1; //random
  501. else
  502. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  503. }
  504. else
  505. {
  506. f = scenarioOps->getIthPlayersSettings(align).castle;
  507. }
  508. if(f<0) f = ran()%VLC->townh->towns.size();
  509. return std::pair<int,int>(TOWNI_TYPE,f);
  510. }
  511. case 162: //random monster lvl5
  512. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 5));
  513. case 163: //random monster lvl6
  514. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 6));
  515. case 164: //random monster lvl7
  516. return std::pair<int,int>(54, VLC->creh->pickRandomMonster(boost::ref(ran), 7));
  517. case 216: //random dwelling
  518. {
  519. int faction = ran()%F_NUMBER;
  520. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  521. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  522. if (info->asCastle)
  523. {
  524. for(unsigned int i=0;i<map->objects.size();i++)
  525. {
  526. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  527. {
  528. randomizeObject(map->objects[i]); //we have to randomize the castle first
  529. faction = map->objects[i]->subID;
  530. break;
  531. }
  532. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  533. {
  534. faction = map->objects[i]->subID;
  535. break;
  536. }
  537. }
  538. }
  539. else
  540. {
  541. while((!(info->castles[0]&(1<<faction))))
  542. {
  543. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  544. break;
  545. faction = ran()%F_NUMBER;
  546. }
  547. }
  548. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  549. int cid = VLC->townh->towns[faction].basicCreatures[level];
  550. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  551. if(VLC->objh->cregens[i]==cid)
  552. return std::pair<int,int>(17,i);
  553. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  554. return std::pair<int,int>(17,0);
  555. delete dwl->info;
  556. dwl->info = NULL;
  557. }
  558. case 217:
  559. {
  560. int faction = ran()%F_NUMBER;
  561. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  562. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  563. if (info->asCastle)
  564. {
  565. for(unsigned int i=0;i<map->objects.size();i++)
  566. {
  567. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  568. {
  569. randomizeObject(map->objects[i]); //we have to randomize the castle first
  570. faction = map->objects[i]->subID;
  571. break;
  572. }
  573. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i].get())->identifier == info->identifier)
  574. {
  575. faction = map->objects[i]->subID;
  576. break;
  577. }
  578. }
  579. }
  580. else
  581. {
  582. while((!(info->castles[0]&(1<<faction))))
  583. {
  584. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  585. break;
  586. faction = ran()%F_NUMBER;
  587. }
  588. }
  589. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  590. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  591. if(VLC->objh->cregens[i]==cid)
  592. return std::pair<int,int>(17,i);
  593. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  594. return std::pair<int,int>(17,0);
  595. delete dwl->info;
  596. dwl->info = NULL;
  597. }
  598. case 218:
  599. {
  600. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  601. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  602. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  603. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  604. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  605. if(VLC->objh->cregens[i]==cid)
  606. return std::pair<int,int>(17,i);
  607. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  608. return std::pair<int,int>(17,0);
  609. delete dwl->info;
  610. dwl->info = NULL;
  611. }
  612. }
  613. return std::pair<int,int>(-1,-1);
  614. }
  615. void CGameState::randomizeObject(CGObjectInstance *cur)
  616. {
  617. std::pair<int,int> ran = pickObject(cur);
  618. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  619. {
  620. if(cur->ID==TOWNI_TYPE) //town - set def
  621. {
  622. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  623. t->town = &VLC->townh->towns[t->subID];
  624. if(t->hasCapitol())
  625. t->defInfo = capitols[t->subID];
  626. else if(t->hasFort())
  627. t->defInfo = forts[t->subID];
  628. else
  629. t->defInfo = villages[t->subID];
  630. }
  631. return;
  632. }
  633. else if(ran.first==HEROI_TYPE)//special code for hero
  634. {
  635. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  636. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  637. cur->ID = ran.first;
  638. h->portrait = cur->subID = ran.second;
  639. h->type = VLC->heroh->heroes[ran.second];
  640. h->randomizeArmy(h->type->heroType/2);
  641. map->heroes.push_back(h);
  642. return; //TODO: maybe we should do something with definfo?
  643. }
  644. else if(ran.first==TOWNI_TYPE)//special code for town
  645. {
  646. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  647. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  648. cur->ID = ran.first;
  649. cur->subID = ran.second;
  650. t->town = &VLC->townh->towns[ran.second];
  651. if(t->hasCapitol())
  652. t->defInfo = capitols[t->subID];
  653. else if(t->hasFort())
  654. t->defInfo = forts[t->subID];
  655. else
  656. t->defInfo = villages[t->subID];
  657. t->randomizeArmy(t->subID);
  658. map->towns.push_back(t);
  659. return;
  660. }
  661. //we have to replace normal random object
  662. cur->ID = ran.first;
  663. cur->subID = ran.second;
  664. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  665. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  666. if(!cur->defInfo)
  667. {
  668. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  669. return;
  670. }
  671. map->addBlockVisTiles(cur);
  672. }
  673. int CGameState::getDate(int mode) const
  674. {
  675. int temp;
  676. switch (mode)
  677. {
  678. case 0: //day number
  679. return day;
  680. break;
  681. case 1: //day of week
  682. temp = (day)%7; // 1 - Monday, 7 - Sunday
  683. if (temp)
  684. return temp;
  685. else return 7;
  686. break;
  687. case 2: //current week
  688. temp = ((day-1)/7)+1;
  689. if (!(temp%4))
  690. return 4;
  691. else
  692. return (temp%4);
  693. break;
  694. case 3: //current month
  695. return ((day-1)/28)+1;
  696. break;
  697. case 4: //day of month
  698. temp = (day)%28;
  699. if (temp)
  700. return temp;
  701. else return 28;
  702. break;
  703. }
  704. return 0;
  705. }
  706. CGameState::CGameState()
  707. {
  708. mx = new boost::shared_mutex();
  709. applierGs = new CApplier<CBaseForGSApply>;
  710. registerTypes2(*applierGs);
  711. objCaller = new CObjectCallersHandler;
  712. globalEffects.description = "Global effects";
  713. }
  714. CGameState::~CGameState()
  715. {
  716. delete mx;
  717. map.dellNull();
  718. curB.dellNull();
  719. //delete scenarioOps; //TODO: fix for loading ind delete
  720. //delete initialOpts;
  721. delete applierGs;
  722. delete objCaller;
  723. //TODO: delete properly that definfos
  724. villages.clear();
  725. capitols.clear();
  726. }
  727. BattleInfo * CGameState::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town)
  728. {
  729. int terrain = map->getTile(tile).tertype;
  730. int terType = battleGetBattlefieldType(tile);
  731. return BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  732. }
  733. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  734. {
  735. struct HLP
  736. {
  737. //it's assumed that given hero should receive the bonus
  738. static void giveCampaignBonusToHero(CGHeroInstance * hero, const StartInfo * si, const CScenarioTravel & st )
  739. {
  740. const CScenarioTravel::STravelBonus & curBonus = st.bonusesToChoose[si->choosenCampaignBonus];
  741. if(curBonus.isBonusForHero())
  742. {
  743. //apply bonus
  744. switch (curBonus.type)
  745. {
  746. case 0: //spell
  747. hero->spells.insert(curBonus.info2);
  748. break;
  749. case 1: //monster
  750. {
  751. for(int i=0; i<ARMY_SIZE; i++)
  752. {
  753. if(hero->slotEmpty(i))
  754. {
  755. hero->addToSlot(i, curBonus.info2, curBonus.info3);
  756. break;
  757. }
  758. }
  759. }
  760. break;
  761. case 3: //artifact
  762. hero->giveArtifact(curBonus.info2);
  763. break;
  764. case 4: //spell scroll
  765. {
  766. CArtifactInstance * scroll = CArtifactInstance::createScroll(VLC->spellh->spells[curBonus.info2]);
  767. scroll->putAt(hero, scroll->firstAvailableSlot(hero));
  768. }
  769. break;
  770. case 5: //prim skill
  771. {
  772. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus.info2);
  773. for (int g=0; g<PRIMARY_SKILLS; ++g)
  774. {
  775. int val = ptr[g];
  776. if (val == 0)
  777. {
  778. continue;
  779. }
  780. Bonus *bb = new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, si->whichMapInCampaign, g);
  781. hero->addNewBonus(bb);
  782. }
  783. }
  784. break;
  785. case 6: //sec skills
  786. hero->setSecSkillLevel(static_cast<CGHeroInstance::SecondarySkill>(curBonus.info2), curBonus.info3, true);
  787. break;
  788. }
  789. }
  790. }
  791. static std::vector<const PlayerSettings *> getHumanPlayerInfo(const StartInfo * si)
  792. {
  793. std::vector<const PlayerSettings *> ret;
  794. for(std::map<int, PlayerSettings>::const_iterator it = si->playerInfos.begin();
  795. it != si->playerInfos.end(); ++it)
  796. {
  797. if(it->second.human)
  798. ret.push_back(&it->second);
  799. }
  800. return ret;
  801. }
  802. static void replaceHero( CGameState * gs, int objId, CGHeroInstance * ghi )
  803. {
  804. ghi->id = objId;
  805. gs->map->objects[objId] = ghi;
  806. gs->map->heroes.push_back(ghi);
  807. }
  808. //sort in descending order by power
  809. static bool heroPowerSorter(const CGHeroInstance * a, const CGHeroInstance * b)
  810. {
  811. return a->getHeroStrength() > b->getHeroStrength();
  812. }
  813. };
  814. seed = Seed;
  815. ran.seed((boost::int32_t)seed);
  816. scenarioOps = new StartInfo(*si);
  817. initialOpts = new StartInfo(*si);
  818. si = NULL;
  819. switch(scenarioOps->mode)
  820. {
  821. case StartInfo::NEW_GAME:
  822. map = new Mapa(scenarioOps->mapname);
  823. break;
  824. case StartInfo::CAMPAIGN:
  825. {
  826. campaign = new CCampaignState();
  827. campaign->initNewCampaign(*scenarioOps);
  828. assert(vstd::contains(campaign->camp->mapPieces, scenarioOps->whichMapInCampaign));
  829. std::string &mapContent = campaign->camp->mapPieces[scenarioOps->whichMapInCampaign];
  830. map = new Mapa();
  831. map->initFromBytes((const unsigned char*)mapContent.c_str());
  832. }
  833. break;
  834. case StartInfo::DUEL:
  835. {
  836. bool success = false;
  837. DuelParameters dp;
  838. try
  839. {
  840. CLoadFile lf(scenarioOps->mapname);
  841. lf >> dp;
  842. success = true;
  843. }
  844. catch(...)
  845. {}
  846. const CArmedInstance *armies[2] = {0};
  847. const CGHeroInstance *heroes[2] = {0};
  848. CGTownInstance *town = NULL;
  849. for(int i = 0; i < 2; i++)
  850. {
  851. CArmedInstance *obj = NULL;
  852. if(dp.sides[i].heroId >= 0)
  853. {
  854. CGHeroInstance *h = new CGHeroInstance();
  855. armies[i] = heroes[i] = h;
  856. obj = h;
  857. h->subID = dp.sides[i].heroId;
  858. h->initHero(h->subID);
  859. }
  860. else
  861. {
  862. CGCreature *c = new CGCreature();
  863. armies[i] = obj = c;
  864. c->subID = 34;
  865. }
  866. obj->initObj();
  867. obj->setOwner(i);
  868. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  869. {
  870. int cre = dp.sides[i].stacks[j].type, count = dp.sides[i].stacks[j].count;
  871. if(!count && obj->hasStackAtSlot(j)
  872. || count)
  873. obj->setCreature(j, cre, count);
  874. }
  875. }
  876. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  877. curB->localInit();
  878. return;
  879. }
  880. break;
  881. default:
  882. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  883. return;
  884. }
  885. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  886. tlog0 << "Map loaded!" << std::endl;
  887. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  888. if(checksum)
  889. {
  890. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< checksum << std::endl;
  891. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  892. if(map->checksum != checksum)
  893. {
  894. tlog1 << "Wrong map checksum!!!" << std::endl;
  895. throw std::string("Wrong checksum");
  896. }
  897. }
  898. day = 0;
  899. loadTownDInfos();
  900. //pick grail location
  901. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  902. {
  903. if(!map->grailRadious) //radius not given -> anywhere on map
  904. map->grailRadious = map->width * 2;
  905. std::vector<int3> allowedPos;
  906. // add all not blocked tiles in range
  907. for (int i = 0; i < map->width ; i++)
  908. {
  909. for (int j = 0; j < map->height ; j++)
  910. {
  911. for (int k = 0; k <= map->twoLevel ; k++)
  912. {
  913. const TerrainTile &t = map->terrain[i][j][k];
  914. if(!t.blocked
  915. && !t.visitable
  916. && t.tertype != TerrainTile::water
  917. && t.tertype != TerrainTile::rock
  918. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  919. allowedPos.push_back(int3(i,j,k));
  920. }
  921. }
  922. }
  923. //remove tiles with holes
  924. for(unsigned int no=0; no<map->objects.size(); ++no)
  925. if(map->objects[no]->ID == 124)
  926. allowedPos -= map->objects[no]->pos;
  927. if(allowedPos.size())
  928. map->grailPos = allowedPos[ran() % allowedPos.size()];
  929. else
  930. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  931. }
  932. //picking random factions for players
  933. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  934. it != scenarioOps->playerInfos.end(); ++it)
  935. {
  936. if(it->second.castle==-1)
  937. {
  938. int f;
  939. do
  940. {
  941. f = ran()%F_NUMBER;
  942. }while(!(map->players[it->first].allowedFactions & 1<<f));
  943. it->second.castle = f;
  944. }
  945. }
  946. //randomizing objects
  947. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  948. {
  949. randomizeObject(obj);
  950. obj->hoverName = VLC->generaltexth->names[obj->ID];
  951. //handle Favouring Winds - mark tiles under it
  952. if(obj->ID == 225)
  953. for (int i = 0; i < obj->getWidth() ; i++)
  954. for (int j = 0; j < obj->getHeight() ; j++)
  955. {
  956. int3 pos = obj->pos - int3(i,j,0);
  957. if(map->isInTheMap(pos))
  958. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  959. }
  960. }
  961. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  962. /*********creating players entries in gs****************************************/
  963. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  964. it != scenarioOps->playerInfos.end(); ++it)
  965. {
  966. std::pair<int,PlayerState> ins(it->first,PlayerState());
  967. ins.second.color=ins.first;
  968. ins.second.human = it->second.human;
  969. ins.second.team = map->players[ins.first].team;
  970. teams[ins.second.team].id = ins.second.team;//init team
  971. teams[ins.second.team].players.insert(ins.first);//add player to team
  972. players.insert(ins);
  973. }
  974. /*********give starting hero****************************************/
  975. for(int i=0;i<PLAYER_LIMIT;i++)
  976. {
  977. const PlayerInfo &p = map->players[i];
  978. bool generateHero = (p.generateHeroAtMainTown && p.hasMainTown) || (p.hasMainTown && map->version==CMapHeader::RoE);
  979. if(generateHero && vstd::contains(scenarioOps->playerInfos, i))
  980. {
  981. int3 hpos = p.posOfMainTown;
  982. hpos.x+=1;
  983. int h = pickHero(i);
  984. if(scenarioOps->playerInfos[i].hero == -1)
  985. scenarioOps->playerInfos[i].hero = h;
  986. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  987. nnn->id = map->objects.size();
  988. nnn->initHero();
  989. map->heroes.push_back(nnn);
  990. map->objects.push_back(nnn);
  991. map->addBlockVisTiles(nnn);
  992. }
  993. }
  994. /*************************replace hero placeholders*****************************/
  995. if (campaign)
  996. {
  997. CScenarioTravel::STravelBonus bonus =
  998. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  999. std::vector<CGHeroInstance *> Xheroes;
  1000. if (bonus.type == 8) //hero crossover
  1001. {
  1002. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  1003. }
  1004. //selecting heroes by type
  1005. for(int g=0; g<map->objects.size(); ++g)
  1006. {
  1007. CGObjectInstance * obj = map->objects[g];
  1008. if (obj->ID != 214) //not a placeholder
  1009. {
  1010. continue;
  1011. }
  1012. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1013. if(hp->subID != 0xFF) //select by type
  1014. {
  1015. bool found = false;
  1016. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  1017. {
  1018. if (ghi->subID == hp->subID)
  1019. {
  1020. found = true;
  1021. HLP::replaceHero(this, g, ghi);
  1022. Xheroes -= ghi;
  1023. break;
  1024. }
  1025. }
  1026. if (!found)
  1027. {
  1028. //TODO: create new hero of this type
  1029. }
  1030. }
  1031. }
  1032. //selecting heroes by power
  1033. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  1034. for(int g=0; g<map->objects.size(); ++g)
  1035. {
  1036. CGObjectInstance * obj = map->objects[g];
  1037. if (obj->ID != 214) //not a placeholder
  1038. {
  1039. continue;
  1040. }
  1041. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1042. if (hp->subID == 0xFF) //select by power
  1043. {
  1044. if(Xheroes.size() > hp->power - 1)
  1045. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  1046. else
  1047. tlog2 << "Warning, to hero to replace!\n";
  1048. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1049. }
  1050. }
  1051. }
  1052. /******************RESOURCES****************************************************/
  1053. std::vector<int> startresAI, startresHuman;
  1054. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1055. int k;
  1056. for (int j=0; j<scenarioOps->difficulty * 2; j++)
  1057. {
  1058. tis >> k;
  1059. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1060. tis>>k;
  1061. }
  1062. tis >> k;
  1063. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1064. {
  1065. tis >> k;
  1066. startresHuman.push_back(k);
  1067. }
  1068. tis >> k;
  1069. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1070. {
  1071. tis >> k;
  1072. startresAI.push_back(k);
  1073. }
  1074. tis.close();
  1075. tis.clear();
  1076. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1077. {
  1078. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1079. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1080. {
  1081. if (i->second.human)
  1082. {
  1083. (*i).second.resources[x] = startresHuman[x];
  1084. }
  1085. else
  1086. {
  1087. (*i).second.resources[x] = startresAI[x];
  1088. }
  1089. }
  1090. }
  1091. //give start resource bonus in case of campaign
  1092. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1093. {
  1094. CScenarioTravel::STravelBonus chosenBonus =
  1095. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1096. if(chosenBonus.type == 7) //resource
  1097. {
  1098. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  1099. for (int b=0; b<people.size(); ++b)
  1100. {
  1101. std::vector<int> res; //resources we will give
  1102. switch (chosenBonus.info1)
  1103. {
  1104. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1105. res.push_back(chosenBonus.info1);
  1106. break;
  1107. case 0xFD: //wood+ore
  1108. res.push_back(0); res.push_back(2);
  1109. break;
  1110. case 0xFE: //rare
  1111. res.push_back(1); res.push_back(3); res.push_back(4); res.push_back(5);
  1112. break;
  1113. default:
  1114. assert(0);
  1115. break;
  1116. }
  1117. //increasing resource quantity
  1118. for (int n=0; n<res.size(); ++n)
  1119. {
  1120. players[people[b]->color].resources[res[n]] += chosenBonus.info2;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. /*************************HEROES************************************************/
  1126. std::set<int> hids; //hero ids to create pool
  1127. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1128. if(map->allowedHeroes[i])
  1129. hids.insert(i);
  1130. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1131. {
  1132. if (map->heroes[i]->getOwner()<0)
  1133. {
  1134. tlog2 << "Warning - hero with uninitialized owner!\n";
  1135. continue;
  1136. }
  1137. CGHeroInstance * vhi = (map->heroes[i]);
  1138. vhi->initHero();
  1139. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1140. hids.erase(vhi->subID);
  1141. }
  1142. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1143. {
  1144. if (map->objects[i]->ID == 62)
  1145. hids.erase(map->objects[i]->subID);
  1146. }
  1147. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1148. {
  1149. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1150. continue;
  1151. map->predefinedHeroes[i]->initHero();
  1152. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1153. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1154. hids.erase(map->predefinedHeroes[i]->subID);
  1155. }
  1156. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1157. {
  1158. CGHeroInstance * vhi = new CGHeroInstance();
  1159. vhi->initHero(hid);
  1160. hpool.heroesPool[hid] = vhi;
  1161. hpool.pavailable[hid] = 0xff;
  1162. }
  1163. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1164. {
  1165. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1166. }
  1167. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1168. {
  1169. CScenarioTravel::STravelBonus chosenBonus =
  1170. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1171. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1172. {
  1173. //find human player
  1174. int humanPlayer;
  1175. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1176. {
  1177. if(it->second.human)
  1178. {
  1179. humanPlayer = it->first;
  1180. break;
  1181. }
  1182. }
  1183. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1184. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1185. {
  1186. int maxB = -1;
  1187. for (int b=0; b<heroes.size(); ++b)
  1188. {
  1189. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1190. {
  1191. maxB = b;
  1192. }
  1193. }
  1194. if(maxB < 0)
  1195. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1196. else
  1197. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  1198. }
  1199. else //specific hero
  1200. {
  1201. for (int b=0; b<heroes.size(); ++b)
  1202. {
  1203. if (heroes[b]->subID == chosenBonus.info1)
  1204. {
  1205. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  1206. break;
  1207. }
  1208. }
  1209. }
  1210. }
  1211. }
  1212. /*************************FOG**OF**WAR******************************************/
  1213. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1214. {
  1215. k->second.fogOfWarMap.resize(map->width);
  1216. for(int g=0; g<map->width; ++g)
  1217. k->second.fogOfWarMap[g].resize(map->height);
  1218. for(int g=-0; g<map->width; ++g)
  1219. for(int h=0; h<map->height; ++h)
  1220. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1221. for(int g=0; g<map->width; ++g)
  1222. for(int h=0; h<map->height; ++h)
  1223. for(int v=0; v<map->twoLevel+1; ++v)
  1224. k->second.fogOfWarMap[g][h][v] = 0;
  1225. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1226. {
  1227. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1228. boost::unordered_set<int3, ShashInt3> tiles;
  1229. obj->getSightTiles(tiles);
  1230. BOOST_FOREACH(int3 tile, tiles)
  1231. {
  1232. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1233. }
  1234. }
  1235. }
  1236. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1237. {
  1238. //starting bonus
  1239. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1240. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1241. switch(scenarioOps->playerInfos[k->first].bonus)
  1242. {
  1243. case PlayerSettings::bgold:
  1244. k->second.resources[6] += 500 + (ran()%6)*100;
  1245. break;
  1246. case PlayerSettings::bresource:
  1247. {
  1248. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1249. if(res == 127)
  1250. {
  1251. k->second.resources[0] += 5 + ran()%6;
  1252. k->second.resources[2] += 5 + ran()%6;
  1253. }
  1254. else
  1255. {
  1256. k->second.resources[res] += 3 + ran()%4;
  1257. }
  1258. break;
  1259. }
  1260. case PlayerSettings::bartifact:
  1261. {
  1262. if(!k->second.heroes.size())
  1263. {
  1264. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1265. break;
  1266. }
  1267. CArtifact *toGive;
  1268. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1269. CGHeroInstance *hero = k->second.heroes[0];
  1270. hero->giveArtifact(toGive->id);
  1271. }
  1272. }
  1273. }
  1274. /****************************TOWNS************************************************/
  1275. for ( int i=0; i<4; i++)
  1276. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1277. for (unsigned int i=0;i<map->towns.size();i++)
  1278. {
  1279. CGTownInstance * vti =(map->towns[i]);
  1280. if(!vti->town)
  1281. vti->town = &VLC->townh->towns[vti->subID];
  1282. if (vti->name.length()==0) // if town hasn't name we draw it
  1283. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1284. //init buildings
  1285. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1286. {
  1287. vti->builtBuildings.erase(-50);
  1288. vti->builtBuildings.insert(10);
  1289. vti->builtBuildings.insert(5);
  1290. vti->builtBuildings.insert(30);
  1291. if(ran()%2)
  1292. vti->builtBuildings.insert(31);
  1293. }
  1294. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1295. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1296. //init hordes
  1297. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1298. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1299. {
  1300. vti->builtBuildings.erase(-31-i);//remove old ID
  1301. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1302. {
  1303. vti->builtBuildings.insert(18);//add it
  1304. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1305. vti->builtBuildings.insert(19);//add it as well
  1306. }
  1307. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1308. {
  1309. vti->builtBuildings.insert(24);
  1310. if (vstd::contains(vti->builtBuildings,(37+i)))
  1311. vti->builtBuildings.insert(25);
  1312. }
  1313. }
  1314. for (std::list<CCastleEvent*>::iterator ev=vti->events.begin(); ev!=vti->events.end(); ev++)
  1315. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1316. if (vstd::contains((*ev)->buildings,(-31-i))) //if we have horde for this level
  1317. {
  1318. (*ev)->buildings.erase(-31-i);
  1319. if (vti->town->hordeLvl[0] == i)
  1320. (*ev)->buildings.insert(18);
  1321. if (vti->town->hordeLvl[1] == i)
  1322. (*ev)->buildings.insert(24);
  1323. }
  1324. //init spells
  1325. vti->spells.resize(SPELL_LEVELS);
  1326. CSpell *s;
  1327. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1328. {
  1329. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1330. vti->spells[s->level-1].push_back(s->id);
  1331. vti->possibleSpells -= s->id;
  1332. }
  1333. while(vti->possibleSpells.size())
  1334. {
  1335. ui32 total=0;
  1336. int sel = -1;
  1337. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1338. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1339. int r = (total)? ran()%total : -1;
  1340. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1341. {
  1342. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1343. if(r<0)
  1344. {
  1345. sel = ps;
  1346. break;
  1347. }
  1348. }
  1349. if(sel<0)
  1350. sel=0;
  1351. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1352. vti->spells[s->level-1].push_back(s->id);
  1353. vti->possibleSpells -= s->id;
  1354. }
  1355. if(vti->getOwner() != 255)
  1356. getPlayer(vti->getOwner())->towns.push_back(vti);
  1357. }
  1358. //campaign bonuses for towns
  1359. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1360. {
  1361. CScenarioTravel::STravelBonus chosenBonus =
  1362. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1363. if (chosenBonus.type == 2)
  1364. {
  1365. for (int g=0; g<map->towns.size(); ++g)
  1366. {
  1367. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1368. PlayerInfo & pi = map->players[owner->color];
  1369. if (owner->human && //human-owned
  1370. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1371. {
  1372. map->towns[g]->builtBuildings.insert(
  1373. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1374. break;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. objCaller->preInit();
  1380. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1381. {
  1382. obj->initObj();
  1383. if(obj->ID == 62) //prison also needs to initialize hero
  1384. static_cast<CGHeroInstance*>(obj)->initHero();
  1385. }
  1386. CGTeleport::postInit(); //pairing subterranean gates
  1387. buildBonusSystemTree();
  1388. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1389. {
  1390. if(k->first==-1 || k->first==255)
  1391. continue;
  1392. //init visiting and garrisoned heroes
  1393. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1394. {
  1395. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1396. {
  1397. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1398. if(vistile == h->pos || h->pos==t->pos)
  1399. {
  1400. t->setVisitingHero(h);
  1401. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1402. {
  1403. map->removeBlockVisTiles(h);
  1404. h->pos.x -= 1;
  1405. map->addBlockVisTiles(h);
  1406. }
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. }
  1413. int CGameState::battleGetBattlefieldType(int3 tile)
  1414. {
  1415. if(tile==int3() && curB)
  1416. tile = curB->tile;
  1417. else if(tile==int3() && !curB)
  1418. return -1;
  1419. const TerrainTile &t = map->getTile(tile);
  1420. //fight in mine -> subterranean
  1421. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1422. return 12;
  1423. const std::vector <ConstTransitivePtr<CGObjectInstance> > & objs = map->objects;
  1424. for(int g=0; g<objs.size(); ++g)
  1425. {
  1426. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1427. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1428. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1429. ) //look only for objects covering given tile
  1430. continue;
  1431. switch(objs[g]->ID)
  1432. {
  1433. case 222: //clover field
  1434. return 19;
  1435. case 21: case 223: //cursed ground
  1436. return 22;
  1437. case 224: //evil fog
  1438. return 20;
  1439. case 225: //favourable winds
  1440. return 21;
  1441. case 226: //fiery fields
  1442. return 14;
  1443. case 227: //holy ground
  1444. return 18;
  1445. case 228: //lucid pools
  1446. return 17;
  1447. case 229: //magic clouds
  1448. return 16;
  1449. case 46: case 230: //magic plains
  1450. return 9;
  1451. case 231: //rocklands
  1452. return 15;
  1453. }
  1454. }
  1455. switch(t.tertype)
  1456. {
  1457. case TerrainTile::dirt:
  1458. return rand()%3+3;
  1459. case TerrainTile::sand:
  1460. return 2; //TODO: coast support
  1461. case TerrainTile::grass:
  1462. return rand()%2+6;
  1463. case TerrainTile::snow:
  1464. return rand()%2+10;
  1465. case TerrainTile::swamp:
  1466. return 13;
  1467. case TerrainTile::rough:
  1468. return 23;
  1469. case TerrainTile::subterranean:
  1470. return 12;
  1471. case TerrainTile::lava:
  1472. return 8;
  1473. case TerrainTile::water:
  1474. return 25;
  1475. case TerrainTile::rock:
  1476. return 15;
  1477. default:
  1478. return -1;
  1479. }
  1480. }
  1481. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1482. {
  1483. std::set<std::pair<int, int> > ret;
  1484. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1485. {
  1486. assert(a[j] >= b[j]);
  1487. if(int dif = modifier * (a[j] - b[j]) / 100)
  1488. ret.insert(std::make_pair(j,dif));
  1489. }
  1490. return ret;
  1491. }
  1492. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1493. {
  1494. UpgradeInfo ret;
  1495. const CCreature *base = stack.type;
  1496. const CGHeroInstance *h = stack.armyObj->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1497. const CGTownInstance *t = NULL;
  1498. if(stack.armyObj->ID == TOWNI_TYPE)
  1499. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1500. else if(h)
  1501. { //hero speciality
  1502. BonusList lista = h->speciality.getBonuses(Selector::typeSybtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1503. BOOST_FOREACH(const Bonus *it, lista)
  1504. {
  1505. ui16 nid = it->additionalInfo;
  1506. if (nid != base->idNumber) //in very specific case the upgrade is avaliable by default (?)
  1507. {
  1508. ret.newID.push_back(nid);
  1509. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1510. }
  1511. }
  1512. t = h->visitedTown;
  1513. }
  1514. if(t)
  1515. {
  1516. BOOST_FOREACH(si32 bid, t->builtBuildings)
  1517. {
  1518. if( bid >= 37 && bid < 44 ) //upgraded creature dwelling
  1519. {
  1520. int nid = t->town->upgradedCreatures[bid-37]; //upgrade offered by that building
  1521. if(vstd::contains(base->upgrades, nid)) //possible upgrade
  1522. {
  1523. ret.newID.push_back(nid);
  1524. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1525. }
  1526. }
  1527. }
  1528. }
  1529. //hero is visiting Hill Fort
  1530. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1531. {
  1532. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1533. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1534. BOOST_FOREACH(si32 nid, base->upgrades)
  1535. {
  1536. ret.newID.push_back(nid);
  1537. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost, costModifier));
  1538. }
  1539. }
  1540. if(ret.newID.size())
  1541. ret.oldID = base->idNumber;
  1542. return ret;
  1543. }
  1544. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1545. {
  1546. if ( color1 == color2 )
  1547. return 2;
  1548. const TeamState * ts = getPlayerTeam(color1);
  1549. if (ts && vstd::contains(ts->players, color2))
  1550. return 1;
  1551. return 0;
  1552. }
  1553. void CGameState::loadTownDInfos()
  1554. {
  1555. for(int i=0;i<F_NUMBER;i++)
  1556. {
  1557. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1558. forts[i] = VLC->dobjinfo->castles[i];
  1559. map->defy.push_back(forts[i]);
  1560. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1561. }
  1562. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  1563. int ccc;
  1564. ifs>>ccc;
  1565. for(int i=0; i < ccc*2; i++)
  1566. {
  1567. CGDefInfo *n;
  1568. if(i<ccc)
  1569. n = villages[i];
  1570. else
  1571. n = capitols[i%ccc];
  1572. ifs >> n->name;
  1573. map->defy.push_back(n);
  1574. }
  1575. }
  1576. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1577. {
  1578. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1579. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1580. vec.clear();
  1581. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1582. {
  1583. const int3 hlp = tile + dirs[i];
  1584. if(!map->isInTheMap(hlp))
  1585. continue;
  1586. const TerrainTile &hlpt = map->getTile(hlp);
  1587. //we cannot visit things from blocked tiles
  1588. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1589. {
  1590. continue;
  1591. }
  1592. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1593. {
  1594. int3 hlp1 = tile,
  1595. hlp2 = tile;
  1596. hlp1.x += dirs[i].x;
  1597. hlp2.y += dirs[i].y;
  1598. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1599. continue;
  1600. }
  1601. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1602. && hlpt.tertype != TerrainTile::rock)
  1603. {
  1604. vec.push_back(hlp);
  1605. }
  1606. }
  1607. }
  1608. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1609. {
  1610. if(src == dest) //same tile
  1611. return 0;
  1612. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1613. &d = map->terrain[dest.x][dest.y][dest.z];
  1614. //get basic cost
  1615. int ret = h->getTileCost(d,s);
  1616. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1617. {
  1618. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1619. if(!freeFlying)
  1620. {
  1621. ret *= 1.4f; //40% penalty for movement over blocked tile
  1622. }
  1623. }
  1624. else if (d.tertype == TerrainTile::water)
  1625. {
  1626. if(h->boat && s.siodmyTajemniczyBajt & 128 && d.siodmyTajemniczyBajt & 128) //Favourable Winds
  1627. ret *= 0.666f;
  1628. else if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1629. ret *= 1.4f; //40% penalty for water walking
  1630. }
  1631. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1632. {
  1633. int old = ret;
  1634. ret *= 1.414213;
  1635. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1636. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1637. {
  1638. return remainingMovePoints;
  1639. }
  1640. }
  1641. int left = remainingMovePoints-ret;
  1642. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1643. {
  1644. std::vector<int3> vec;
  1645. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1646. for(size_t i=0; i < vec.size(); i++)
  1647. {
  1648. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1649. if(fcost <= left)
  1650. {
  1651. return ret;
  1652. }
  1653. }
  1654. ret = remainingMovePoints;
  1655. }
  1656. return ret;
  1657. }
  1658. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1659. {
  1660. std::set<int> used;
  1661. used.insert(ID);
  1662. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1663. while(true)
  1664. {
  1665. size_t noloop=0;
  1666. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1667. {
  1668. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1669. {
  1670. used.insert(*i);
  1671. for(
  1672. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1673. j!=VLC->townh->requirements[t->subID][*i].end();
  1674. j++)
  1675. {
  1676. reqs.insert(*j);//creating full list of requirements
  1677. }
  1678. }
  1679. else
  1680. {
  1681. noloop++;
  1682. }
  1683. }
  1684. if(noloop==reqs.size())
  1685. break;
  1686. }
  1687. return reqs;
  1688. }
  1689. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1690. {
  1691. int ret = 7; //allowed by default
  1692. if(t->builded >= MAX_BUILDING_PER_TURN)
  1693. ret = 5; //building limit
  1694. //checking resources
  1695. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1696. if(!pom)
  1697. return 8;
  1698. // if(pom->Name().size()==0||pom->resources.size()==0)
  1699. // return 2;//TODO: why does this happen?
  1700. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1701. {
  1702. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1703. ret = 6; //lack of res
  1704. }
  1705. //checking for requirements
  1706. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1707. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1708. {
  1709. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1710. ret = 8; //lack of requirements - cannot build
  1711. }
  1712. //can we build it?
  1713. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1714. ret = 2; //forbidden
  1715. if(ID == 13) //capitol
  1716. {
  1717. for(unsigned int in = 0; in < map->towns.size(); in++)
  1718. {
  1719. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1720. {
  1721. ret = 0; //no more than one capitol
  1722. break;
  1723. }
  1724. }
  1725. }
  1726. else if(ID == 6) //shipyard
  1727. {
  1728. int3 t1(t->pos + int3(-1,3,0)),
  1729. t2(t->pos + int3(-3,3,0));
  1730. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1731. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1732. ret = 1; //lack of water
  1733. }
  1734. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1735. ret = 4;
  1736. return ret;
  1737. }
  1738. void CGameState::apply(CPack *pack)
  1739. {
  1740. ui16 typ = typeList.getTypeID(pack);
  1741. applierGs->apps[typ]->applyOnGS(this,pack);
  1742. }
  1743. TeamState *CGameState::getTeam(ui8 teamID)
  1744. {
  1745. if(vstd::contains(teams,teamID))
  1746. {
  1747. return &teams[teamID];
  1748. }
  1749. else
  1750. {
  1751. tlog2 << "Warning: Cannot find info for team " << int(teamID) << std::endl;
  1752. return NULL;
  1753. }
  1754. }
  1755. TeamState *CGameState::getPlayerTeam(ui8 color)
  1756. {
  1757. PlayerState * ps = getPlayer(color);
  1758. if (ps)
  1759. return getTeam(ps->team);
  1760. return NULL;
  1761. }
  1762. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1763. {
  1764. if(vstd::contains(players,color))
  1765. {
  1766. return &players[color];
  1767. }
  1768. else
  1769. {
  1770. if(verbose)
  1771. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1772. return NULL;
  1773. }
  1774. }
  1775. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1776. {
  1777. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1778. }
  1779. const TeamState * CGameState::getTeam( ui8 teamID ) const
  1780. {
  1781. return (const_cast<CGameState *>(this))->getTeam(teamID);
  1782. }
  1783. const TeamState * CGameState::getPlayerTeam( ui8 teamID ) const
  1784. {
  1785. return (const_cast<CGameState *>(this))->getPlayerTeam(teamID);
  1786. }
  1787. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1788. {
  1789. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1790. return false;
  1791. int3 hpos = hero->getPosition(false);
  1792. bool flying = false; //hero is under flying effect TODO
  1793. bool waterWalking = false; //hero is on land and can walk on water TODO
  1794. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1795. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1796. //
  1797. // if (!hero->canWalkOnSea())
  1798. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1799. // else
  1800. // blockLandSea = boost::logic::indeterminate;
  1801. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  1802. //graph initialization
  1803. std::vector< std::vector<CPathNode> > graph;
  1804. graph.resize(map->width);
  1805. for(size_t i=0; i<graph.size(); ++i)
  1806. {
  1807. graph[i].resize(map->height);
  1808. for(size_t j=0; j<graph[i].size(); ++j)
  1809. {
  1810. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1811. CPathNode &node = graph[i][j];
  1812. node.accessible = !tinfo->blocked;
  1813. node.dist = -1;
  1814. node.theNodeBefore = NULL;
  1815. node.visited = false;
  1816. node.coord.x = i;
  1817. node.coord.y = j;
  1818. node.coord.z = dest.z;
  1819. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1820. || !FoW[i][j][src.z] //tile is covered by the FoW
  1821. )
  1822. {
  1823. node.accessible = false;
  1824. }
  1825. }
  1826. }
  1827. //Special rules for the destination tile
  1828. {
  1829. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1830. CPathNode &d = graph[dest.x][dest.y];
  1831. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1832. if(t->visitable)
  1833. {
  1834. d.accessible = true; //for allowing visiting objects
  1835. }
  1836. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1837. {
  1838. size_t i = 0;
  1839. for(; i < t->visitableObjects.size(); i++)
  1840. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1841. break;
  1842. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1843. }
  1844. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1845. {
  1846. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1847. }
  1848. }
  1849. //graph initialized
  1850. //initial tile - set cost on 0 and add to the queue
  1851. graph[src.x][src.y].dist = 0;
  1852. std::queue<CPathNode> mq;
  1853. mq.push(graph[src.x][src.y]);
  1854. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1855. std::vector<int3> neighbours;
  1856. neighbours.reserve(8);
  1857. while(!mq.empty())
  1858. {
  1859. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1860. mq.pop();
  1861. if (cp.coord == dest) //it's destination tile
  1862. {
  1863. if (cp.dist < curDist) //that path is better than previous one
  1864. curDist = cp.dist;
  1865. continue;
  1866. }
  1867. else
  1868. {
  1869. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1870. continue;
  1871. }
  1872. //add accessible neighbouring nodes to the queue
  1873. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate, true);
  1874. for(unsigned int i=0; i < neighbours.size(); i++)
  1875. {
  1876. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1877. if(dp.accessible)
  1878. {
  1879. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1880. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1881. {
  1882. dp.dist = cp.dist + cost;
  1883. dp.theNodeBefore = &cp;
  1884. mq.push(dp);
  1885. }
  1886. }
  1887. }
  1888. }
  1889. CPathNode *curNode = &graph[dest.x][dest.y];
  1890. if(!curNode->theNodeBefore) //destination is not accessible
  1891. return false;
  1892. //fill ret with found path
  1893. ret.nodes.clear();
  1894. while(curNode->coord != graph[src.x][src.y].coord)
  1895. {
  1896. ret.nodes.push_back(*curNode);
  1897. curNode = curNode->theNodeBefore;
  1898. }
  1899. ret.nodes.push_back(graph[src.x][src.y]);
  1900. return true;
  1901. }
  1902. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1903. {
  1904. assert(hero);
  1905. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1906. if(src.x < 0)
  1907. src = hero->getPosition(false);
  1908. if(movement < 0)
  1909. movement = hero->movement;
  1910. out.hero = hero;
  1911. out.hpos = src;
  1912. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1913. {
  1914. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1915. return;
  1916. }
  1917. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1918. if (!hero->canWalkOnSea())
  1919. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1920. else
  1921. onLand = boost::logic::indeterminate;
  1922. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  1923. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1924. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  1925. //graph initialization
  1926. CGPathNode ***graph = out.nodes;
  1927. for(size_t i=0; i < out.sizes.x; ++i)
  1928. {
  1929. for(size_t j=0; j < out.sizes.y; ++j)
  1930. {
  1931. for(size_t k=0; k < out.sizes.z; ++k)
  1932. {
  1933. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1934. CGPathNode &node = graph[i][j][k];
  1935. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  1936. if(!flying && node.accessible == CGPathNode::FLYABLE)
  1937. {
  1938. node.accessible = CGPathNode::BLOCKED;
  1939. }
  1940. node.turns = 0xff;
  1941. node.moveRemains = 0;
  1942. node.coord.x = i;
  1943. node.coord.y = j;
  1944. node.coord.z = k;
  1945. node.land = tinfo->tertype != TerrainTile::water;
  1946. node.theNodeBefore = NULL;
  1947. bool leaveAsBlocked = false;
  1948. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  1949. {
  1950. if (waterWalk || flying)
  1951. {
  1952. node.accessible = CGPathNode::FLYABLE;
  1953. }
  1954. else
  1955. {
  1956. node.accessible = CGPathNode::BLOCKED;
  1957. leaveAsBlocked = true;
  1958. }
  1959. }
  1960. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1961. || (!onLand && node.land) //it's land and we cannot walk on land (complementary condition is handled above)
  1962. || !FoW[i][j][k] //tile is covered by the FoW
  1963. || leaveAsBlocked
  1964. )
  1965. {
  1966. node.accessible = CGPathNode::BLOCKED;
  1967. }
  1968. else if(tinfo->visitable)
  1969. {
  1970. //hero is protected in Sanctuary
  1971. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner)
  1972. node.accessible = CGPathNode::BLOCKED;
  1973. else
  1974. {
  1975. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1976. {
  1977. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1978. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1979. {
  1980. node.accessible = CGPathNode::ACCESSIBLE;
  1981. }
  1982. else if(obj->blockVisit)
  1983. {
  1984. node.accessible = CGPathNode::BLOCKVIS;
  1985. break;
  1986. }
  1987. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1988. {
  1989. node.accessible = CGPathNode::VISITABLE;
  1990. }
  1991. }
  1992. }
  1993. }
  1994. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  1995. && tinfo->blockingObjects.size() == 0)
  1996. {
  1997. // Monster close by; blocked visit for battle.
  1998. node.accessible = CGPathNode::BLOCKVIS;
  1999. }
  2000. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2001. {
  2002. size_t i = 0;
  2003. for(; i < tinfo->visitableObjects.size(); i++)
  2004. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2005. break;
  2006. if(i < tinfo->visitableObjects.size())
  2007. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2008. }
  2009. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  2010. {
  2011. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2012. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2013. }
  2014. }
  2015. }
  2016. }
  2017. //graph initialized
  2018. //initial tile - set cost on 0 and add to the queue
  2019. graph[src.x][src.y][src.z].turns = 0;
  2020. graph[src.x][src.y][src.z].moveRemains = movement;
  2021. std::queue<CGPathNode*> mq;
  2022. mq.push(&graph[src.x][src.y][src.z]);
  2023. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2024. std::vector<int3> neighbours;
  2025. neighbours.reserve(8);
  2026. while(!mq.empty())
  2027. {
  2028. CGPathNode *cp = mq.front();
  2029. mq.pop();
  2030. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2031. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2032. const TerrainTile &ct = map->getTile(cp->coord);
  2033. int movement = cp->moveRemains, turn = cp->turns;
  2034. if(!movement)
  2035. {
  2036. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2037. turn++;
  2038. }
  2039. //add accessible neighbouring nodes to the queue
  2040. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate, !onLand);
  2041. for(unsigned int i=0; i < neighbours.size(); i++)
  2042. {
  2043. int moveAtNextTile = movement;
  2044. int turnAtNextTile = turn;
  2045. const int3 &n = neighbours[i]; //current neighbor
  2046. CGPathNode & dp = graph[n.x][n.y][n.z];
  2047. if( !checkForVisitableDir(cp->coord, dp.coord)
  2048. || !checkForVisitableDir(dp.coord, cp->coord)
  2049. || dp.accessible == CGPathNode::BLOCKED )
  2050. {
  2051. continue;
  2052. }
  2053. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2054. int remains = movement - cost;
  2055. if(remains < 0)
  2056. {
  2057. //occurs rarely, when hero with low movepoints tries to go leave the road
  2058. turnAtNextTile++;
  2059. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2060. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2061. remains = moveAtNextTile - cost;
  2062. }
  2063. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2064. if((dp.turns==0xff //we haven't been here before
  2065. || dp.turns > turnAtNextTile
  2066. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2067. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2068. {
  2069. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2070. dp.moveRemains = remains;
  2071. dp.turns = turnAtNextTile;
  2072. dp.theNodeBefore = cp;
  2073. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2074. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2075. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2076. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2077. {
  2078. mq.push(&dp);
  2079. }
  2080. }
  2081. } //neighbours loop
  2082. } //queue loop
  2083. }
  2084. /**
  2085. * Tells if the tile is guarded by a monster as well as the position
  2086. * of the monster that will attack on it.
  2087. *
  2088. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2089. * the monster guarding the tile.
  2090. */
  2091. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2092. {
  2093. const int3 originalPos = pos;
  2094. // Give monster at position priority.
  2095. if (!map->isInTheMap(pos))
  2096. return int3(-1, -1, -1);
  2097. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2098. if (posTile.visitable)
  2099. {
  2100. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2101. {
  2102. if(obj->blockVisit)
  2103. {
  2104. if (obj->ID == 54) // Monster
  2105. return pos;
  2106. else
  2107. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2108. }
  2109. }
  2110. }
  2111. // See if there are any monsters adjacent.
  2112. pos -= int3(1, 1, 0); // Start with top left.
  2113. for (int dx = 0; dx < 3; dx++)
  2114. {
  2115. for (int dy = 0; dy < 3; dy++)
  2116. {
  2117. if (map->isInTheMap(pos))
  2118. {
  2119. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2120. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  2121. {
  2122. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2123. {
  2124. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2125. {
  2126. return pos;
  2127. }
  2128. }
  2129. }
  2130. }
  2131. pos.y++;
  2132. }
  2133. pos.y -= 3;
  2134. pos.x++;
  2135. }
  2136. return int3(-1, -1, -1);
  2137. }
  2138. bool CGameState::isVisible(int3 pos, int player)
  2139. {
  2140. if(player == 255) //neutral player
  2141. return false;
  2142. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  2143. }
  2144. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2145. {
  2146. if(player == 255) //neutral player
  2147. return false;
  2148. //object is visible when at least one blocked tile is visible
  2149. for(int fx=0; fx<8; ++fx)
  2150. {
  2151. for(int fy=0; fy<6; ++fy)
  2152. {
  2153. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2154. if(map->isInTheMap(pos)
  2155. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2156. && isVisible(pos, player) )
  2157. return true;
  2158. }
  2159. }
  2160. return false;
  2161. }
  2162. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2163. {
  2164. const TerrainTile * pom = &map->getTile(dst);
  2165. return checkForVisitableDir(src, pom, dst);
  2166. }
  2167. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2168. {
  2169. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2170. {
  2171. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2172. continue;
  2173. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2174. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2175. {
  2176. return false;
  2177. }
  2178. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2179. {
  2180. return false;
  2181. }
  2182. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2183. {
  2184. return false;
  2185. }
  2186. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2187. {
  2188. return false;
  2189. }
  2190. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2191. {
  2192. return false;
  2193. }
  2194. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2195. {
  2196. return false;
  2197. }
  2198. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2199. {
  2200. return false;
  2201. }
  2202. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2203. {
  2204. return false;
  2205. }
  2206. }
  2207. return true;
  2208. }
  2209. int CGameState::victoryCheck( ui8 player ) const
  2210. {
  2211. const PlayerState *p = getPlayer(player);
  2212. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2213. if(player == checkForStandardWin())
  2214. return -1;
  2215. if (p->enteredWinningCheatCode)
  2216. { //cheater or tester, but has entered the code...
  2217. return 1;
  2218. }
  2219. if(p->human || map->victoryCondition.appliesToAI)
  2220. {
  2221. switch(map->victoryCondition.condition)
  2222. {
  2223. case artifact:
  2224. //check if any hero has winning artifact
  2225. for(size_t i = 0; i < p->heroes.size(); i++)
  2226. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2227. return 1;
  2228. break;
  2229. case gatherTroop:
  2230. {
  2231. //check if in players armies there is enough creatures
  2232. int total = 0; //creature counter
  2233. for(size_t i = 0; i < map->objects.size(); i++)
  2234. {
  2235. const CArmedInstance *ai = NULL;
  2236. if(map->objects[i]
  2237. && map->objects[i]->tempOwner == player //object controlled by player
  2238. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2239. {
  2240. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2241. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  2242. total += i->second->count;
  2243. }
  2244. }
  2245. if(total >= map->victoryCondition.count)
  2246. return 1;
  2247. }
  2248. break;
  2249. case gatherResource:
  2250. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2251. return 1;
  2252. break;
  2253. case buildCity:
  2254. {
  2255. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2256. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2257. return 1;
  2258. }
  2259. break;
  2260. case buildGrail:
  2261. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  2262. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2263. && t->tempOwner == player
  2264. && vstd::contains(t->builtBuildings, 26))
  2265. return 1;
  2266. break;
  2267. case beatHero:
  2268. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2269. return 1;
  2270. break;
  2271. case captureCity:
  2272. {
  2273. if(map->victoryCondition.obj->tempOwner == player)
  2274. return 1;
  2275. }
  2276. break;
  2277. case beatMonster:
  2278. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2279. return 1;
  2280. break;
  2281. case takeDwellings:
  2282. for(size_t i = 0; i < map->objects.size(); i++)
  2283. {
  2284. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2285. {
  2286. switch(map->objects[i]->ID)
  2287. {
  2288. case 17: case 18: case 19: case 20: //dwellings
  2289. case 216: case 217: case 218:
  2290. return 0; //found not flagged dwelling - player not won
  2291. }
  2292. }
  2293. }
  2294. return 1;
  2295. break;
  2296. case takeMines:
  2297. for(size_t i = 0; i < map->objects.size(); i++)
  2298. {
  2299. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2300. {
  2301. switch(map->objects[i]->ID)
  2302. {
  2303. case 53: case 220:
  2304. return 0; //found not flagged mine - player not won
  2305. }
  2306. }
  2307. }
  2308. return 1;
  2309. break;
  2310. case transportItem:
  2311. {
  2312. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2313. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  2314. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  2315. {
  2316. return 1;
  2317. }
  2318. }
  2319. break;
  2320. }
  2321. }
  2322. return 0;
  2323. }
  2324. ui8 CGameState::checkForStandardWin() const
  2325. {
  2326. //std victory condition is:
  2327. //all enemies lost
  2328. ui8 supposedWinner = 255, winnerTeam = 255;
  2329. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2330. {
  2331. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2332. {
  2333. if(supposedWinner == 255)
  2334. {
  2335. //first player remaining ingame - candidate for victory
  2336. supposedWinner = i->second.color;
  2337. winnerTeam = i->second.team;
  2338. }
  2339. else if(winnerTeam != i->second.team)
  2340. {
  2341. //current candidate has enemy remaining in game -> no vicotry
  2342. return 255;
  2343. }
  2344. }
  2345. }
  2346. return supposedWinner;
  2347. }
  2348. bool CGameState::checkForStandardLoss( ui8 player ) const
  2349. {
  2350. //std loss condition is: player lost all towns and heroes
  2351. const PlayerState &p = *getPlayer(player);
  2352. return !p.heroes.size() && !p.towns.size();
  2353. }
  2354. struct statsHLP
  2355. {
  2356. typedef std::pair< ui8, si64 > TStat;
  2357. //converts [<player's color, value>] to vec[place] -> platers
  2358. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2359. {
  2360. std::sort(stats.begin(), stats.end(), statsHLP());
  2361. //put first element
  2362. std::vector< std::list<ui8> > ret;
  2363. std::list<ui8> tmp;
  2364. tmp.push_back( stats[0].first );
  2365. ret.push_back( tmp );
  2366. //the rest of elements
  2367. for(int g=1; g<stats.size(); ++g)
  2368. {
  2369. if(stats[g].second == stats[g-1].second)
  2370. {
  2371. (ret.end()-1)->push_back( stats[g].first );
  2372. }
  2373. else
  2374. {
  2375. //create next occupied rank
  2376. std::list<ui8> tmp;
  2377. tmp.push_back(stats[g].first);
  2378. ret.push_back(tmp);
  2379. }
  2380. }
  2381. return ret;
  2382. }
  2383. bool operator()(const TStat & a, const TStat & b) const
  2384. {
  2385. return a.second > b.second;
  2386. }
  2387. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2388. {
  2389. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2390. if(!h.size())
  2391. return NULL;
  2392. //best hero will be that with highest exp
  2393. int best = 0;
  2394. for(int b=1; b<h.size(); ++b)
  2395. {
  2396. if(h[b]->exp > h[best]->exp)
  2397. {
  2398. best = b;
  2399. }
  2400. }
  2401. return h[best];
  2402. }
  2403. //calculates total number of artifacts that belong to given player
  2404. static int getNumberOfArts(const PlayerState * ps)
  2405. {
  2406. int ret = 0;
  2407. for(int g=0; g<ps->heroes.size(); ++g)
  2408. {
  2409. ret += ps->heroes[g]->artifactsInBackpack.size() + ps->heroes[g]->artifactsWorn.size();
  2410. }
  2411. return ret;
  2412. }
  2413. };
  2414. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2415. {
  2416. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2417. { \
  2418. std::vector< std::pair< ui8, si64 > > stats; \
  2419. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2420. { \
  2421. if(g->second.color == 255) \
  2422. continue; \
  2423. std::pair< ui8, si64 > stat; \
  2424. stat.first = g->second.color; \
  2425. stat.second = VAL_GETTER; \
  2426. stats.push_back(stat); \
  2427. } \
  2428. tgi.FIELD = statsHLP::getRank(stats); \
  2429. }
  2430. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2431. {
  2432. if(g->second.color != 255)
  2433. tgi.playerColors.push_back(g->second.color);
  2434. }
  2435. if(level >= 1) //num of towns & num of heroes
  2436. {
  2437. //num of towns
  2438. FILL_FIELD(numOfTowns, g->second.towns.size())
  2439. //num of heroes
  2440. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2441. //best hero's portrait
  2442. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2443. {
  2444. if(g->second.color == 255)
  2445. continue;
  2446. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2447. InfoAboutHero iah;
  2448. iah.initFromHero(best, level >= 8);
  2449. iah.army.clear();
  2450. tgi.colorToBestHero[g->second.color] = iah;
  2451. }
  2452. }
  2453. if(level >= 2) //gold
  2454. {
  2455. FILL_FIELD(gold, g->second.resources[6])
  2456. }
  2457. if(level >= 2) //wood & ore
  2458. {
  2459. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2460. }
  2461. if(level >= 3) //mercury, sulfur, crystal, gems
  2462. {
  2463. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2464. }
  2465. if(level >= 4) //obelisks found
  2466. {
  2467. //TODO
  2468. }
  2469. if(level >= 5) //artifacts
  2470. {
  2471. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2472. }
  2473. if(level >= 6) //army strength
  2474. {
  2475. //TODO
  2476. }
  2477. if(level >= 7) //income
  2478. {
  2479. //TODO
  2480. }
  2481. if(level >= 8) //best hero's stats
  2482. {
  2483. //already set in lvl 1 handling
  2484. }
  2485. if(level >= 9) //personality
  2486. {
  2487. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2488. {
  2489. if(g->second.color == 255) //do nothing for neutral player
  2490. continue;
  2491. if(g->second.human)
  2492. {
  2493. tgi.personality[g->second.color] = -1;
  2494. }
  2495. else //AI
  2496. {
  2497. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2498. }
  2499. }
  2500. }
  2501. if(level >= 10) //best creature
  2502. {
  2503. //best creatures belonging to player (highest AI value)
  2504. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2505. {
  2506. if(g->second.color == 255) //do nothing for neutral player
  2507. continue;
  2508. int bestCre = -1; //best creature's ID
  2509. for(int b=0; b<g->second.heroes.size(); ++b)
  2510. {
  2511. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2512. {
  2513. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2514. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2515. {
  2516. bestCre = toCmp;
  2517. }
  2518. }
  2519. }
  2520. tgi.bestCreature[g->second.color] = bestCre;
  2521. }
  2522. }
  2523. #undef FILL_FIELD
  2524. }
  2525. int CGameState::lossCheck( ui8 player ) const
  2526. {
  2527. const PlayerState *p = getPlayer(player);
  2528. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2529. if(checkForStandardLoss(player))
  2530. return -1;
  2531. if (p->enteredLosingCheatCode)
  2532. {
  2533. return 1;
  2534. }
  2535. if(p->human) //special loss condition applies only to human player
  2536. {
  2537. switch(map->lossCondition.typeOfLossCon)
  2538. {
  2539. case lossCastle:
  2540. {
  2541. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2542. assert(t);
  2543. if(t->tempOwner != player)
  2544. return 1;
  2545. }
  2546. break;
  2547. case lossHero:
  2548. {
  2549. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2550. assert(h);
  2551. if(h->tempOwner != player)
  2552. return 1;
  2553. }
  2554. break;
  2555. case timeExpires:
  2556. if(map->lossCondition.timeLimit < day)
  2557. return 1;
  2558. break;
  2559. }
  2560. }
  2561. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2562. return 2;
  2563. return false;
  2564. }
  2565. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2566. {
  2567. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2568. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  2569. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2570. if(*j)
  2571. pool.erase((**j).subID);
  2572. return pool;
  2573. }
  2574. void CGameState::buildBonusSystemTree()
  2575. {
  2576. buildGlobalTeamPlayerTree();
  2577. attachArmedObjects();
  2578. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2579. {
  2580. t->deserializationFix();
  2581. }
  2582. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2583. // are provided on initializing / deserializing
  2584. }
  2585. void CGameState::deserializationFix()
  2586. {
  2587. buildGlobalTeamPlayerTree();
  2588. attachArmedObjects();
  2589. }
  2590. void CGameState::buildGlobalTeamPlayerTree()
  2591. {
  2592. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  2593. {
  2594. TeamState *t = &k->second;
  2595. t->attachTo(&globalEffects);
  2596. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2597. {
  2598. PlayerState *p = getPlayer(teamMember);
  2599. assert(p);
  2600. p->attachTo(t);
  2601. }
  2602. }
  2603. }
  2604. void CGameState::attachArmedObjects()
  2605. {
  2606. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2607. {
  2608. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2609. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2610. }
  2611. }
  2612. int3 CPath::startPos() const
  2613. {
  2614. return nodes[nodes.size()-1].coord;
  2615. }
  2616. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2617. {
  2618. if (mode==0)
  2619. {
  2620. for (unsigned int i=0;i<nodes.size();i++)
  2621. {
  2622. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2623. }
  2624. }
  2625. }
  2626. int3 CPath::endPos() const
  2627. {
  2628. return nodes[0].coord;
  2629. }
  2630. CGPathNode::CGPathNode()
  2631. :coord(-1,-1,-1)
  2632. {
  2633. accessible = 0;
  2634. land = 0;
  2635. moveRemains = 0;
  2636. turns = 255;
  2637. theNodeBefore = NULL;
  2638. }
  2639. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2640. {
  2641. out.nodes.clear();
  2642. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2643. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  2644. return false;
  2645. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  2646. bool transition01 = false;
  2647. while(curnode)
  2648. {
  2649. CGPathNode cpn = *curnode;
  2650. if(transition01)
  2651. {
  2652. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  2653. {
  2654. transition01 = false;
  2655. }
  2656. else if (curnode->accessible == CGPathNode::FLYABLE)
  2657. {
  2658. cpn.turns = 1;
  2659. }
  2660. }
  2661. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  2662. {
  2663. transition01 = true;
  2664. }
  2665. curnode = curnode->theNodeBefore;
  2666. out.nodes.push_back(cpn);
  2667. }
  2668. return true;
  2669. }
  2670. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2671. :sizes(Sizes)
  2672. {
  2673. hero = NULL;
  2674. nodes = new CGPathNode**[sizes.x];
  2675. for(int i = 0; i < sizes.x; i++)
  2676. {
  2677. nodes[i] = new CGPathNode*[sizes.y];
  2678. for (int j = 0; j < sizes.y; j++)
  2679. {
  2680. nodes[i][j] = new CGPathNode[sizes.z];
  2681. }
  2682. }
  2683. }
  2684. CPathsInfo::~CPathsInfo()
  2685. {
  2686. for(int i = 0; i < sizes.x; i++)
  2687. {
  2688. for (int j = 0; j < sizes.y; j++)
  2689. {
  2690. delete [] nodes[i][j];
  2691. }
  2692. delete [] nodes[i];
  2693. }
  2694. delete [] nodes;
  2695. }
  2696. int3 CGPath::startPos() const
  2697. {
  2698. return nodes[nodes.size()-1].coord;
  2699. }
  2700. int3 CGPath::endPos() const
  2701. {
  2702. return nodes[0].coord;
  2703. }
  2704. void CGPath::convert( ui8 mode )
  2705. {
  2706. if(mode==0)
  2707. {
  2708. for(unsigned int i=0;i<nodes.size();i++)
  2709. {
  2710. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2711. }
  2712. }
  2713. }
  2714. PlayerState::PlayerState()
  2715. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2716. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2717. {
  2718. nodeType = PLAYER;
  2719. }
  2720. std::string PlayerState::nodeName() const
  2721. {
  2722. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2723. }
  2724. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2725. // {
  2726. // return; //no loops possible
  2727. // }
  2728. //
  2729. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2730. // {
  2731. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2732. // {
  2733. // if (*it != root)
  2734. // (*it)->getBonuses(out, selector, this);
  2735. // }
  2736. // }
  2737. InfoAboutHero::InfoAboutHero()
  2738. {
  2739. details = NULL;
  2740. hclass = NULL;
  2741. portrait = -1;
  2742. }
  2743. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  2744. {
  2745. assign(iah);
  2746. }
  2747. InfoAboutHero::~InfoAboutHero()
  2748. {
  2749. delete details;
  2750. }
  2751. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  2752. {
  2753. if(!h) return;
  2754. owner = h->tempOwner;
  2755. hclass = h->type->heroClass;
  2756. name = h->name;
  2757. portrait = h->portrait;
  2758. army = ArmyDescriptor(h, detailed);
  2759. if(detailed)
  2760. {
  2761. //include details about hero
  2762. details = new Details;
  2763. details->luck = h->LuckVal();
  2764. details->morale = h->MoraleVal();
  2765. details->mana = h->mana;
  2766. details->primskills.resize(PRIMARY_SKILLS);
  2767. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  2768. {
  2769. details->primskills[i] = h->getPrimSkillLevel(i);
  2770. }
  2771. }
  2772. }
  2773. void InfoAboutHero::assign( const InfoAboutHero & iah )
  2774. {
  2775. army = iah.army;
  2776. details = (iah.details ? new Details(*iah.details) : NULL);
  2777. hclass = iah.hclass;
  2778. name = iah.name;
  2779. owner = iah.owner;
  2780. portrait = iah.portrait;
  2781. }
  2782. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  2783. {
  2784. assign(iah);
  2785. return *this;
  2786. }
  2787. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2788. {
  2789. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2790. {
  2791. if(detailed)
  2792. (*this)[i->first] = *i->second;
  2793. else
  2794. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2795. }
  2796. }
  2797. ArmyDescriptor::ArmyDescriptor()
  2798. {
  2799. }
  2800. DuelParameters::SideSettings::StackSettings::StackSettings()
  2801. : type(-1), count(0)
  2802. {
  2803. }
  2804. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2805. : type(Type), count(Count)
  2806. {
  2807. }
  2808. DuelParameters::SideSettings::SideSettings()
  2809. {
  2810. heroId = -1;
  2811. }
  2812. DuelParameters::DuelParameters()
  2813. {
  2814. terType = TerrainTile::dirt;
  2815. bfieldType = 15;
  2816. }
  2817. TeamState::TeamState()
  2818. {
  2819. nodeType = TEAM;
  2820. }