CGameState.cpp 81 KB

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