CGameState.cpp 81 KB

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