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