2
0

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