CGameState.cpp 86 KB

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