CGameState.cpp 92 KB

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