CGameState.cpp 93 KB

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