2
0

CGameState.cpp 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include <boost/random/linear_congruential.hpp>
  4. #include "CCampaignHandler.h"
  5. #include "CDefObjInfoHandler.h"
  6. #include "CArtHandler.h"
  7. #include "CBuildingHandler.h"
  8. #include "CGeneralTextHandler.h"
  9. #include "CTownHandler.h"
  10. #include "CSpellHandler.h"
  11. #include "CHeroHandler.h"
  12. #include "CObjectHandler.h"
  13. #include "CCreatureHandler.h"
  14. #include "VCMI_Lib.h"
  15. #include "Connection.h"
  16. #include "map.h"
  17. #include "StartInfo.h"
  18. #include "NetPacks.h"
  19. #include "RegisterTypes.h"
  20. #include "CMapInfo.h"
  21. #include "BattleState.h"
  22. #include "../lib/JsonNode.h"
  23. #include "GameConstants.h"
  24. 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, CGameState *gs )
  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. gs->giveHeroArtifact(hero, 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. DuelParameters dp;
  867. try
  868. {
  869. CLoadFile lf(scenarioOps->mapname);
  870. lf >> dp;
  871. }
  872. catch(...)
  873. {}
  874. const CArmedInstance *armies[2] = {0};
  875. const CGHeroInstance *heroes[2] = {0};
  876. CGTownInstance *town = NULL;
  877. for(int i = 0; i < 2; i++)
  878. {
  879. CArmedInstance *obj = NULL;
  880. if(dp.sides[i].heroId >= 0)
  881. {
  882. CGHeroInstance *h = new CGHeroInstance();
  883. armies[i] = heroes[i] = h;
  884. obj = h;
  885. h->subID = dp.sides[i].heroId;
  886. h->initHero(h->subID);
  887. }
  888. else
  889. {
  890. CGCreature *c = new CGCreature();
  891. armies[i] = obj = c;
  892. c->subID = 34;
  893. }
  894. obj->initObj();
  895. obj->setOwner(i);
  896. for(int j = 0; j < ARRAY_COUNT(dp.sides[i].stacks); j++)
  897. {
  898. int cre = dp.sides[i].stacks[j].type, count = dp.sides[i].stacks[j].count;
  899. if(count || obj->hasStackAtSlot(j))
  900. obj->setCreature(j, cre, count);
  901. }
  902. }
  903. curB = BattleInfo::setupBattle(int3(), dp.bfieldType, dp.terType, armies, heroes, false, town);
  904. curB->localInit();
  905. return;
  906. }
  907. break;
  908. default:
  909. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  910. return;
  911. }
  912. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  913. tlog0 << "Map loaded!" << std::endl;
  914. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  915. if(checksum)
  916. {
  917. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< checksum << std::endl;
  918. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  919. if(map->checksum != checksum)
  920. {
  921. tlog1 << "Wrong map checksum!!!" << std::endl;
  922. throw std::string("Wrong checksum");
  923. }
  924. }
  925. day = 0;
  926. loadTownDInfos();
  927. //pick grail location
  928. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  929. {
  930. if(!map->grailRadious) //radius not given -> anywhere on map
  931. map->grailRadious = map->width * 2;
  932. std::vector<int3> allowedPos;
  933. // add all not blocked tiles in range
  934. for (int i = 0; i < map->width ; i++)
  935. {
  936. for (int j = 0; j < map->height ; j++)
  937. {
  938. for (int k = 0; k <= map->twoLevel ; k++)
  939. {
  940. const TerrainTile &t = map->terrain[i][j][k];
  941. if(!t.blocked
  942. && !t.visitable
  943. && t.tertype != TerrainTile::water
  944. && t.tertype != TerrainTile::rock
  945. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  946. allowedPos.push_back(int3(i,j,k));
  947. }
  948. }
  949. }
  950. //remove tiles with holes
  951. for(ui32 no=0; no<map->objects.size(); ++no)
  952. if(map->objects[no]->ID == 124)
  953. allowedPos -= map->objects[no]->pos;
  954. if(allowedPos.size())
  955. map->grailPos = allowedPos[ran() % allowedPos.size()];
  956. else
  957. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  958. }
  959. //picking random factions for players
  960. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  961. it != scenarioOps->playerInfos.end(); ++it)
  962. {
  963. if(it->second.castle==-1)
  964. {
  965. int f;
  966. do
  967. {
  968. f = ran()%GameConstants::F_NUMBER;
  969. }while(!(map->players[it->first].allowedFactions & 1<<f));
  970. it->second.castle = f;
  971. }
  972. }
  973. //randomizing objects
  974. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  975. {
  976. randomizeObject(obj);
  977. obj->hoverName = VLC->generaltexth->names[obj->ID];
  978. //handle Favouring Winds - mark tiles under it
  979. if(obj->ID == 225)
  980. for (int i = 0; i < obj->getWidth() ; i++)
  981. for (int j = 0; j < obj->getHeight() ; j++)
  982. {
  983. int3 pos = obj->pos - int3(i,j,0);
  984. if(map->isInTheMap(pos))
  985. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  986. }
  987. }
  988. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  989. /*********creating players entries in gs****************************************/
  990. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  991. it != scenarioOps->playerInfos.end(); ++it)
  992. {
  993. std::pair<int,PlayerState> ins(it->first,PlayerState());
  994. ins.second.color=ins.first;
  995. ins.second.human = it->second.human;
  996. ins.second.team = map->players[ins.first].team;
  997. teams[ins.second.team].id = ins.second.team;//init team
  998. teams[ins.second.team].players.insert(ins.first);//add player to team
  999. players.insert(ins);
  1000. }
  1001. /*********give starting hero****************************************/
  1002. for(int i=0;i<GameConstants::PLAYER_LIMIT;i++)
  1003. {
  1004. const PlayerInfo &p = map->players[i];
  1005. bool generateHero = (p.generateHeroAtMainTown && p.hasMainTown);
  1006. if(generateHero && vstd::contains(scenarioOps->playerInfos, i))
  1007. {
  1008. int3 hpos = p.posOfMainTown;
  1009. hpos.x+=1;
  1010. int h = pickHero(i);
  1011. if(scenarioOps->playerInfos[i].hero == -1)
  1012. scenarioOps->playerInfos[i].hero = h;
  1013. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(GameConstants::HEROI_TYPE,h,hpos,i));
  1014. nnn->id = map->objects.size();
  1015. nnn->initHero();
  1016. map->heroes.push_back(nnn);
  1017. map->objects.push_back(nnn);
  1018. map->addBlockVisTiles(nnn);
  1019. }
  1020. }
  1021. /*************************replace hero placeholders*****************************/
  1022. if (campaign)
  1023. {
  1024. CScenarioTravel::STravelBonus bonus =
  1025. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1026. std::vector<CGHeroInstance *> Xheroes;
  1027. if (bonus.type == 8) //hero crossover
  1028. {
  1029. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  1030. }
  1031. //selecting heroes by type
  1032. for(int g=0; g<map->objects.size(); ++g)
  1033. {
  1034. CGObjectInstance * obj = map->objects[g];
  1035. if (obj->ID != 214) //not a placeholder
  1036. {
  1037. continue;
  1038. }
  1039. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1040. if(hp->subID != 0xFF) //select by type
  1041. {
  1042. bool found = false;
  1043. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  1044. {
  1045. if (ghi->subID == hp->subID)
  1046. {
  1047. found = true;
  1048. HLP::replaceHero(this, g, ghi);
  1049. Xheroes -= ghi;
  1050. break;
  1051. }
  1052. }
  1053. if (!found)
  1054. {
  1055. //TODO: create new hero of this type
  1056. }
  1057. }
  1058. }
  1059. //selecting heroes by power
  1060. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  1061. for(int g=0; g<map->objects.size(); ++g)
  1062. {
  1063. CGObjectInstance * obj = map->objects[g];
  1064. if (obj->ID != 214) //not a placeholder
  1065. {
  1066. continue;
  1067. }
  1068. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1069. if (hp->subID == 0xFF) //select by power
  1070. {
  1071. if(Xheroes.size() > hp->power - 1)
  1072. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  1073. else
  1074. tlog2 << "Warning, to hero to replace!\n";
  1075. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1076. }
  1077. }
  1078. }
  1079. /******************RESOURCES****************************************************/
  1080. TResources startresAI, startresHuman;
  1081. const JsonNode config(GameConstants::DATA_DIR + "/config/startres.json");
  1082. const JsonVector &vector = config["difficulty"].Vector();
  1083. const JsonNode &level = vector[scenarioOps->difficulty];
  1084. const JsonNode &human = level["human"];
  1085. const JsonNode &ai = level["ai"];
  1086. startresHuman[0] = human["wood"].Float();
  1087. startresHuman[1] = human["mercury"].Float();
  1088. startresHuman[2] = human["ore"].Float();
  1089. startresHuman[3] = human["sulfur"].Float();
  1090. startresHuman[4] = human["crystal"].Float();
  1091. startresHuman[5] = human["gems"].Float();
  1092. startresHuman[6] = human["gold"].Float();
  1093. startresHuman[7] = human["mithril"].Float();
  1094. startresAI[0] = ai["wood"].Float();
  1095. startresAI[1] = ai["mercury"].Float();
  1096. startresAI[2] = ai["ore"].Float();
  1097. startresAI[3] = ai["sulfur"].Float();
  1098. startresAI[4] = ai["crystal"].Float();
  1099. startresAI[5] = ai["gems"].Float();
  1100. startresAI[6] = ai["gold"].Float();
  1101. startresAI[7] = ai["mithril"].Float();
  1102. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1103. {
  1104. PlayerState &p = i->second;
  1105. if (p.human)
  1106. p.resources = startresHuman;
  1107. else
  1108. p.resources = startresAI;
  1109. }
  1110. //give start resource bonus in case of campaign
  1111. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1112. {
  1113. CScenarioTravel::STravelBonus chosenBonus =
  1114. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1115. if(chosenBonus.type == 7) //resource
  1116. {
  1117. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  1118. BOOST_FOREACH(const PlayerSettings *ps, people)
  1119. {
  1120. std::vector<int> res; //resources we will give
  1121. switch (chosenBonus.info1)
  1122. {
  1123. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1124. res.push_back(chosenBonus.info1);
  1125. break;
  1126. case 0xFD: //wood+ore
  1127. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1128. break;
  1129. case 0xFE: //rare
  1130. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1131. break;
  1132. default:
  1133. assert(0);
  1134. break;
  1135. }
  1136. //increasing resource quantity
  1137. for (int n=0; n<res.size(); ++n)
  1138. {
  1139. players[ps->color].resources[res[n]] += chosenBonus.info2;
  1140. }
  1141. }
  1142. }
  1143. }
  1144. /*************************HEROES************************************************/
  1145. std::set<int> hids; //hero ids to create pool
  1146. for(ui32 i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1147. if(map->allowedHeroes[i])
  1148. hids.insert(i);
  1149. for (ui32 i=0; i<map->heroes.size();i++) //heroes instances initialization
  1150. {
  1151. if (map->heroes[i]->getOwner()<0)
  1152. {
  1153. tlog2 << "Warning - hero with uninitialized owner!\n";
  1154. continue;
  1155. }
  1156. CGHeroInstance * vhi = (map->heroes[i]);
  1157. vhi->initHero();
  1158. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1159. hids.erase(vhi->subID);
  1160. }
  1161. for (ui32 i=0; i<map->objects.size();i++) //prisons
  1162. {
  1163. if (map->objects[i]->ID == 62)
  1164. hids.erase(map->objects[i]->subID);
  1165. }
  1166. for(ui32 i=0; i<map->predefinedHeroes.size(); i++)
  1167. {
  1168. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1169. continue;
  1170. map->predefinedHeroes[i]->initHero();
  1171. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1172. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1173. hids.erase(map->predefinedHeroes[i]->subID);
  1174. }
  1175. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1176. {
  1177. CGHeroInstance * vhi = new CGHeroInstance();
  1178. vhi->initHero(hid);
  1179. hpool.heroesPool[hid] = vhi;
  1180. hpool.pavailable[hid] = 0xff;
  1181. }
  1182. for(ui32 i=0; i<map->disposedHeroes.size(); i++)
  1183. {
  1184. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1185. }
  1186. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1187. {
  1188. CScenarioTravel::STravelBonus chosenBonus =
  1189. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1190. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1191. {
  1192. //find human player
  1193. int humanPlayer;
  1194. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1195. {
  1196. if(it->second.human)
  1197. {
  1198. humanPlayer = it->first;
  1199. break;
  1200. }
  1201. }
  1202. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1203. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1204. {
  1205. int maxB = -1;
  1206. for (int b=0; b<heroes.size(); ++b)
  1207. {
  1208. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1209. {
  1210. maxB = b;
  1211. }
  1212. }
  1213. if(maxB < 0)
  1214. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1215. else
  1216. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1217. }
  1218. else //specific hero
  1219. {
  1220. for (int b=0; b<heroes.size(); ++b)
  1221. {
  1222. if (heroes[b]->subID == chosenBonus.info1)
  1223. {
  1224. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions, this);
  1225. break;
  1226. }
  1227. }
  1228. }
  1229. }
  1230. }
  1231. /*************************FOG**OF**WAR******************************************/
  1232. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1233. {
  1234. k->second.fogOfWarMap.resize(map->width);
  1235. for(int g=0; g<map->width; ++g)
  1236. k->second.fogOfWarMap[g].resize(map->height);
  1237. for(int g=-0; g<map->width; ++g)
  1238. for(int h=0; h<map->height; ++h)
  1239. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1240. for(int g=0; g<map->width; ++g)
  1241. for(int h=0; h<map->height; ++h)
  1242. for(int v=0; v<map->twoLevel+1; ++v)
  1243. k->second.fogOfWarMap[g][h][v] = 0;
  1244. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1245. {
  1246. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1247. boost::unordered_set<int3, ShashInt3> tiles;
  1248. obj->getSightTiles(tiles);
  1249. BOOST_FOREACH(int3 tile, tiles)
  1250. {
  1251. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1252. }
  1253. }
  1254. }
  1255. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1256. {
  1257. //starting bonus
  1258. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1259. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1260. switch(scenarioOps->playerInfos[k->first].bonus)
  1261. {
  1262. case PlayerSettings::bgold:
  1263. k->second.resources[Res::GOLD] += 500 + (ran()%6)*100;
  1264. break;
  1265. case PlayerSettings::bresource:
  1266. {
  1267. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1268. if(res == 127)
  1269. {
  1270. k->second.resources[Res::WOOD] += 5 + ran()%6;
  1271. k->second.resources[Res::ORE] += 5 + ran()%6;
  1272. }
  1273. else
  1274. {
  1275. k->second.resources[res] += 3 + ran()%4;
  1276. }
  1277. break;
  1278. }
  1279. case PlayerSettings::bartifact:
  1280. {
  1281. if(!k->second.heroes.size())
  1282. {
  1283. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1284. break;
  1285. }
  1286. CArtifact *toGive;
  1287. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1288. CGHeroInstance *hero = k->second.heroes[0];
  1289. giveHeroArtifact(hero, toGive->id);
  1290. }
  1291. break;
  1292. }
  1293. }
  1294. /****************************TOWNS************************************************/
  1295. for ( int i=0; i<4; i++)
  1296. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1297. for (ui32 i=0;i<map->towns.size();i++)
  1298. {
  1299. CGTownInstance * vti =(map->towns[i]);
  1300. if(!vti->town)
  1301. vti->town = &VLC->townh->towns[vti->subID];
  1302. if (vti->name.length()==0) // if town hasn't name we draw it
  1303. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1304. //init buildings
  1305. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1306. {
  1307. vti->builtBuildings.erase(-50);
  1308. vti->builtBuildings.insert(10);
  1309. vti->builtBuildings.insert(5);
  1310. vti->builtBuildings.insert(30);
  1311. if(ran()%2)
  1312. vti->builtBuildings.insert(31);
  1313. }
  1314. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1315. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1316. //init hordes
  1317. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1318. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1319. {
  1320. vti->builtBuildings.erase(-31-i);//remove old ID
  1321. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1322. {
  1323. vti->builtBuildings.insert(18);//add it
  1324. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1325. vti->builtBuildings.insert(19);//add it as well
  1326. }
  1327. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1328. {
  1329. vti->builtBuildings.insert(24);
  1330. if (vstd::contains(vti->builtBuildings,(37+i)))
  1331. vti->builtBuildings.insert(25);
  1332. }
  1333. }
  1334. //town events
  1335. BOOST_FOREACH(CCastleEvent *ev, vti->events)
  1336. {
  1337. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1338. if (vstd::contains(ev->buildings,(-31-i))) //if we have horde for this level
  1339. {
  1340. ev->buildings.erase(-31-i);
  1341. if (vti->town->hordeLvl[0] == i)
  1342. ev->buildings.insert(18);
  1343. if (vti->town->hordeLvl[1] == i)
  1344. ev->buildings.insert(24);
  1345. }
  1346. }
  1347. //init spells
  1348. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1349. CSpell *s;
  1350. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1351. {
  1352. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1353. vti->spells[s->level-1].push_back(s->id);
  1354. vti->possibleSpells -= s->id;
  1355. }
  1356. while(vti->possibleSpells.size())
  1357. {
  1358. ui32 total=0;
  1359. int sel = -1;
  1360. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1361. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1362. int r = (total)? ran()%total : -1;
  1363. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1364. {
  1365. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1366. if(r<0)
  1367. {
  1368. sel = ps;
  1369. break;
  1370. }
  1371. }
  1372. if(sel<0)
  1373. sel=0;
  1374. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1375. vti->spells[s->level-1].push_back(s->id);
  1376. vti->possibleSpells -= s->id;
  1377. }
  1378. if(vti->getOwner() != 255)
  1379. getPlayer(vti->getOwner())->towns.push_back(vti);
  1380. }
  1381. //campaign bonuses for towns
  1382. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1383. {
  1384. CScenarioTravel::STravelBonus chosenBonus =
  1385. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1386. if (chosenBonus.type == 2)
  1387. {
  1388. for (int g=0; g<map->towns.size(); ++g)
  1389. {
  1390. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1391. if (owner)
  1392. {
  1393. PlayerInfo & pi = map->players[owner->color];
  1394. if (owner->human && //human-owned
  1395. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1396. {
  1397. map->towns[g]->builtBuildings.insert(
  1398. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. objCaller->preInit();
  1406. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1407. {
  1408. obj->initObj();
  1409. if(obj->ID == 62) //prison also needs to initialize hero
  1410. static_cast<CGHeroInstance*>(obj)->initHero();
  1411. }
  1412. CGTeleport::postInit(); //pairing subterranean gates
  1413. buildBonusSystemTree();
  1414. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1415. {
  1416. if(k->first==-1 || k->first==255)
  1417. continue;
  1418. //init visiting and garrisoned heroes
  1419. BOOST_FOREACH(CGHeroInstance *h, k->second.heroes)
  1420. {
  1421. BOOST_FOREACH(CGTownInstance *t, k->second.towns)
  1422. {
  1423. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1424. if(vistile == h->pos || h->pos==t->pos)
  1425. {
  1426. t->setVisitingHero(h);
  1427. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1428. {
  1429. map->removeBlockVisTiles(h);
  1430. h->pos.x -= 1;
  1431. map->addBlockVisTiles(h);
  1432. }
  1433. break;
  1434. }
  1435. }
  1436. }
  1437. }
  1438. map->checkForObjectives(); //needs to be run when all objects are properly placed
  1439. }
  1440. int CGameState::battleGetBattlefieldType(int3 tile)
  1441. {
  1442. if(tile==int3() && curB)
  1443. tile = curB->tile;
  1444. else if(tile==int3() && !curB)
  1445. return -1;
  1446. const TerrainTile &t = map->getTile(tile);
  1447. //fight in mine -> subterranean
  1448. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1449. return 12;
  1450. const std::vector <ConstTransitivePtr<CGObjectInstance> > & objs = map->objects;
  1451. for(int g=0; g<objs.size(); ++g)
  1452. {
  1453. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1454. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1455. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1456. ) //look only for objects covering given tile
  1457. continue;
  1458. switch(objs[g]->ID)
  1459. {
  1460. case 222: //clover field
  1461. return 19;
  1462. case 21: case 223: //cursed ground
  1463. return 22;
  1464. case 224: //evil fog
  1465. return 20;
  1466. case 225: //favourable winds
  1467. return 21;
  1468. case 226: //fiery fields
  1469. return 14;
  1470. case 227: //holy ground
  1471. return 18;
  1472. case 228: //lucid pools
  1473. return 17;
  1474. case 229: //magic clouds
  1475. return 16;
  1476. case 46: case 230: //magic plains
  1477. return 9;
  1478. case 231: //rocklands
  1479. return 15;
  1480. }
  1481. }
  1482. switch(t.tertype)
  1483. {
  1484. case TerrainTile::dirt:
  1485. return rand()%3+3;
  1486. case TerrainTile::sand:
  1487. return 2; //TODO: coast support
  1488. case TerrainTile::grass:
  1489. return rand()%2+6;
  1490. case TerrainTile::snow:
  1491. return rand()%2+10;
  1492. case TerrainTile::swamp:
  1493. return 13;
  1494. case TerrainTile::rough:
  1495. return 23;
  1496. case TerrainTile::subterranean:
  1497. return 12;
  1498. case TerrainTile::lava:
  1499. return 8;
  1500. case TerrainTile::water:
  1501. return 25;
  1502. case TerrainTile::rock:
  1503. return 15;
  1504. default:
  1505. return -1;
  1506. }
  1507. }
  1508. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1509. {
  1510. std::set<std::pair<int, int> > ret;
  1511. for(int j=0;j<GameConstants::RESOURCE_QUANTITY;j++)
  1512. {
  1513. assert(a[j] >= b[j]);
  1514. if(int dif = modifier * (a[j] - b[j]) / 100)
  1515. ret.insert(std::make_pair(j,dif));
  1516. }
  1517. return ret;
  1518. }
  1519. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1520. {
  1521. UpgradeInfo ret;
  1522. const CCreature *base = stack.type;
  1523. const CGHeroInstance *h = stack.armyObj->ID == GameConstants::HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1524. const CGTownInstance *t = NULL;
  1525. if(stack.armyObj->ID == GameConstants::TOWNI_TYPE)
  1526. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1527. else if(h)
  1528. { //hero speciality
  1529. TBonusListPtr lista = h->speciality.getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1530. BOOST_FOREACH(const Bonus *it, *lista)
  1531. {
  1532. ui16 nid = it->additionalInfo;
  1533. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1534. {
  1535. ret.newID.push_back(nid);
  1536. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1537. }
  1538. }
  1539. t = h->visitedTown;
  1540. }
  1541. if(t)
  1542. {
  1543. BOOST_FOREACH(const CGTownInstance::TCreaturesSet::value_type & dwelling, t->creatures)
  1544. {
  1545. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1546. {
  1547. BOOST_FOREACH(ui32 upgrID, dwelling.second)
  1548. {
  1549. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1550. {
  1551. ret.newID.push_back(upgrID);
  1552. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1553. }
  1554. }
  1555. }
  1556. }
  1557. }
  1558. //hero is visiting Hill Fort
  1559. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1560. {
  1561. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1562. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1563. BOOST_FOREACH(si32 nid, base->upgrades)
  1564. {
  1565. ret.newID.push_back(nid);
  1566. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1567. }
  1568. }
  1569. if(ret.newID.size())
  1570. ret.oldID = base->idNumber;
  1571. return ret;
  1572. }
  1573. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1574. {
  1575. if ( color1 == color2 )
  1576. return 2;
  1577. if(color1 == 255 || color2 == 255) //neutral player has no friends
  1578. return 0;
  1579. const TeamState * ts = getPlayerTeam(color1);
  1580. if (ts && vstd::contains(ts->players, color2))
  1581. return 1;
  1582. return 0;
  1583. }
  1584. void CGameState::loadTownDInfos()
  1585. {
  1586. int i;
  1587. const JsonNode config(GameConstants::DATA_DIR + "/config/towns_defs.json");
  1588. assert(config["town_defnames"].Vector().size() == GameConstants::F_NUMBER);
  1589. i = 0;
  1590. BOOST_FOREACH(const JsonNode &t, config["town_defnames"].Vector())
  1591. {
  1592. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1593. villages[i]->name = t["village"].String();
  1594. map->defy.push_back(villages[i]);
  1595. forts[i] = VLC->dobjinfo->castles[i];
  1596. map->defy.push_back(forts[i]);
  1597. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1598. capitols[i]->name = t["capitol"].String();
  1599. map->defy.push_back(capitols[i]);
  1600. ++i;
  1601. }
  1602. }
  1603. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1604. {
  1605. static const int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1606. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1607. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1608. {
  1609. const int3 hlp = tile + dirs[i];
  1610. if(!map->isInTheMap(hlp))
  1611. continue;
  1612. const TerrainTile &hlpt = map->getTile(hlp);
  1613. // //we cannot visit things from blocked tiles
  1614. // if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1615. // {
  1616. // continue;
  1617. // }
  1618. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1619. {
  1620. int3 hlp1 = tile,
  1621. hlp2 = tile;
  1622. hlp1.x += dirs[i].x;
  1623. hlp2.y += dirs[i].y;
  1624. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1625. continue;
  1626. }
  1627. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1628. && hlpt.tertype != TerrainTile::rock)
  1629. {
  1630. vec.push_back(hlp);
  1631. }
  1632. }
  1633. }
  1634. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1635. {
  1636. if(src == dest) //same tile
  1637. return 0;
  1638. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1639. &d = map->terrain[dest.x][dest.y][dest.z];
  1640. //get basic cost
  1641. int ret = h->getTileCost(d,s);
  1642. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1643. {
  1644. bool freeFlying = h->getBonusesCount(Selector::typeSubtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1645. if(!freeFlying)
  1646. {
  1647. ret *= 1.4; //40% penalty for movement over blocked tile
  1648. }
  1649. }
  1650. else if (d.tertype == TerrainTile::water)
  1651. {
  1652. if(h->boat && s.hasFavourableWinds() && d.hasFavourableWinds()) //Favourable Winds
  1653. ret *= 0.666;
  1654. else if (!h->boat && h->getBonusesCount(Selector::typeSubtype(Bonus::WATER_WALKING, 1)) > 0)
  1655. ret *= 1.4; //40% penalty for water walking
  1656. }
  1657. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1658. {
  1659. int old = ret;
  1660. ret *= 1.414213;
  1661. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1662. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1663. {
  1664. return remainingMovePoints;
  1665. }
  1666. }
  1667. int left = remainingMovePoints-ret;
  1668. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1669. {
  1670. std::vector<int3> vec;
  1671. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1672. for(size_t i=0; i < vec.size(); i++)
  1673. {
  1674. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1675. if(fcost <= left)
  1676. {
  1677. return ret;
  1678. }
  1679. }
  1680. ret = remainingMovePoints;
  1681. }
  1682. return ret;
  1683. }
  1684. void CGameState::apply(CPack *pack)
  1685. {
  1686. ui16 typ = typeList.getTypeID(pack);
  1687. applierGs->apps[typ]->applyOnGS(this,pack);
  1688. }
  1689. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1690. {
  1691. //the old pathfinder is not supported anymore!
  1692. assert(0);
  1693. return false;
  1694. }
  1695. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1696. {
  1697. CPathfinder pathfinder(out, this, hero);
  1698. pathfinder.calculatePaths(src, movement);
  1699. }
  1700. /**
  1701. * Tells if the tile is guarded by a monster as well as the position
  1702. * of the monster that will attack on it.
  1703. *
  1704. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1705. * the monster guarding the tile.
  1706. */
  1707. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1708. {
  1709. const int3 originalPos = pos;
  1710. // Give monster at position priority.
  1711. if (!map->isInTheMap(pos))
  1712. return int3(-1, -1, -1);
  1713. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  1714. if (posTile.visitable)
  1715. {
  1716. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  1717. {
  1718. if(obj->blockVisit)
  1719. {
  1720. if (obj->ID == 54) // Monster
  1721. return pos;
  1722. else
  1723. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  1724. }
  1725. }
  1726. }
  1727. // See if there are any monsters adjacent.
  1728. pos -= int3(1, 1, 0); // Start with top left.
  1729. for (int dx = 0; dx < 3; dx++)
  1730. {
  1731. for (int dy = 0; dy < 3; dy++)
  1732. {
  1733. if (map->isInTheMap(pos))
  1734. {
  1735. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  1736. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  1737. {
  1738. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  1739. {
  1740. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1741. {
  1742. return pos;
  1743. }
  1744. }
  1745. }
  1746. }
  1747. pos.y++;
  1748. }
  1749. pos.y -= 3;
  1750. pos.x++;
  1751. }
  1752. return int3(-1, -1, -1);
  1753. }
  1754. bool CGameState::isVisible(int3 pos, int player)
  1755. {
  1756. if(player == 255) //neutral player
  1757. return false;
  1758. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1759. }
  1760. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1761. {
  1762. if(player == -1)
  1763. return true;
  1764. if(player == 255) //neutral player -> TODO ??? needed?
  1765. return false;
  1766. //object is visible when at least one blocked tile is visible
  1767. for(int fx=0; fx<8; ++fx)
  1768. {
  1769. for(int fy=0; fy<6; ++fy)
  1770. {
  1771. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1772. if(map->isInTheMap(pos)
  1773. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1774. && isVisible(pos, player) )
  1775. return true;
  1776. }
  1777. }
  1778. return false;
  1779. }
  1780. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1781. {
  1782. const TerrainTile * pom = &map->getTile(dst);
  1783. return checkForVisitableDir(src, pom, dst);
  1784. }
  1785. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1786. {
  1787. for(ui32 b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1788. {
  1789. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  1790. continue;
  1791. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  1792. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  1793. {
  1794. return false;
  1795. }
  1796. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  1797. {
  1798. return false;
  1799. }
  1800. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  1801. {
  1802. return false;
  1803. }
  1804. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  1805. {
  1806. return false;
  1807. }
  1808. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  1809. {
  1810. return false;
  1811. }
  1812. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  1813. {
  1814. return false;
  1815. }
  1816. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  1817. {
  1818. return false;
  1819. }
  1820. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  1821. {
  1822. return false;
  1823. }
  1824. }
  1825. return true;
  1826. }
  1827. int CGameState::victoryCheck( ui8 player ) const
  1828. {
  1829. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1830. if(map->victoryCondition.condition == EVictoryConditionType::WINSTANDARD || map->victoryCondition.allowNormalVictory
  1831. || (!p->human && !map->victoryCondition.appliesToAI)) //if the special victory condition applies only to human, AI has the standard)
  1832. {
  1833. if(player == checkForStandardWin())
  1834. return -1;
  1835. }
  1836. if (p->enteredWinningCheatCode)
  1837. { //cheater or tester, but has entered the code...
  1838. return 1;
  1839. }
  1840. if(p->human || map->victoryCondition.appliesToAI)
  1841. {
  1842. switch(map->victoryCondition.condition)
  1843. {
  1844. case EVictoryConditionType::ARTIFACT:
  1845. //check if any hero has winning artifact
  1846. for(size_t i = 0; i < p->heroes.size(); i++)
  1847. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  1848. return 1;
  1849. break;
  1850. case EVictoryConditionType::GATHERTROOP:
  1851. {
  1852. //check if in players armies there is enough creatures
  1853. int total = 0; //creature counter
  1854. for(size_t i = 0; i < map->objects.size(); i++)
  1855. {
  1856. const CArmedInstance *ai = NULL;
  1857. if(map->objects[i]
  1858. && map->objects[i]->tempOwner == player //object controlled by player
  1859. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1860. {
  1861. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  1862. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  1863. total += i->second->count;
  1864. }
  1865. }
  1866. if(total >= map->victoryCondition.count)
  1867. return 1;
  1868. }
  1869. break;
  1870. case EVictoryConditionType::GATHERRESOURCE:
  1871. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  1872. return 1;
  1873. break;
  1874. case EVictoryConditionType::BUILDCITY:
  1875. {
  1876. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1877. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  1878. return 1;
  1879. }
  1880. break;
  1881. case EVictoryConditionType::BUILDGRAIL:
  1882. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  1883. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  1884. && t->tempOwner == player
  1885. && vstd::contains(t->builtBuildings, 26))
  1886. return 1;
  1887. break;
  1888. case EVictoryConditionType::BEATHERO:
  1889. if(map->victoryCondition.obj->tempOwner >= GameConstants::PLAYER_LIMIT) //target hero not present on map
  1890. return 1;
  1891. break;
  1892. case EVictoryConditionType::CAPTURECITY:
  1893. {
  1894. if(map->victoryCondition.obj->tempOwner == player)
  1895. return 1;
  1896. }
  1897. break;
  1898. case EVictoryConditionType::BEATMONSTER:
  1899. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  1900. return 1;
  1901. break;
  1902. case EVictoryConditionType::TAKEDWELLINGS:
  1903. for(size_t i = 0; i < map->objects.size(); i++)
  1904. {
  1905. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1906. {
  1907. switch(map->objects[i]->ID)
  1908. {
  1909. case 17: case 18: case 19: case 20: //dwellings
  1910. case 216: case 217: case 218:
  1911. return 0; //found not flagged dwelling - player not won
  1912. }
  1913. }
  1914. }
  1915. return 1;
  1916. break;
  1917. case EVictoryConditionType::TAKEMINES:
  1918. for(size_t i = 0; i < map->objects.size(); i++)
  1919. {
  1920. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  1921. {
  1922. switch(map->objects[i]->ID)
  1923. {
  1924. case 53: case 220:
  1925. return 0; //found not flagged mine - player not won
  1926. }
  1927. }
  1928. }
  1929. return 1;
  1930. break;
  1931. case EVictoryConditionType::TRANSPORTITEM:
  1932. {
  1933. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  1934. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  1935. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  1936. {
  1937. return 1;
  1938. }
  1939. }
  1940. break;
  1941. }
  1942. }
  1943. return 0;
  1944. }
  1945. ui8 CGameState::checkForStandardWin() const
  1946. {
  1947. //std victory condition is:
  1948. //all enemies lost
  1949. ui8 supposedWinner = 255, winnerTeam = 255;
  1950. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  1951. {
  1952. if(i->second.status == PlayerState::INGAME && i->first < GameConstants::PLAYER_LIMIT)
  1953. {
  1954. if(supposedWinner == 255)
  1955. {
  1956. //first player remaining ingame - candidate for victory
  1957. supposedWinner = i->second.color;
  1958. winnerTeam = i->second.team;
  1959. }
  1960. else if(winnerTeam != i->second.team)
  1961. {
  1962. //current candidate has enemy remaining in game -> no vicotry
  1963. return 255;
  1964. }
  1965. }
  1966. }
  1967. return supposedWinner;
  1968. }
  1969. bool CGameState::checkForStandardLoss( ui8 player ) const
  1970. {
  1971. //std loss condition is: player lost all towns and heroes
  1972. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  1973. return !p.heroes.size() && !p.towns.size();
  1974. }
  1975. struct statsHLP
  1976. {
  1977. typedef std::pair< ui8, si64 > TStat;
  1978. //converts [<player's color, value>] to vec[place] -> platers
  1979. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  1980. {
  1981. std::sort(stats.begin(), stats.end(), statsHLP());
  1982. //put first element
  1983. std::vector< std::list<ui8> > ret;
  1984. std::list<ui8> tmp;
  1985. tmp.push_back( stats[0].first );
  1986. ret.push_back( tmp );
  1987. //the rest of elements
  1988. for(int g=1; g<stats.size(); ++g)
  1989. {
  1990. if(stats[g].second == stats[g-1].second)
  1991. {
  1992. (ret.end()-1)->push_back( stats[g].first );
  1993. }
  1994. else
  1995. {
  1996. //create next occupied rank
  1997. std::list<ui8> tmp;
  1998. tmp.push_back(stats[g].first);
  1999. ret.push_back(tmp);
  2000. }
  2001. }
  2002. return ret;
  2003. }
  2004. bool operator()(const TStat & a, const TStat & b) const
  2005. {
  2006. return a.second > b.second;
  2007. }
  2008. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2009. {
  2010. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2011. if(!h.size())
  2012. return NULL;
  2013. //best hero will be that with highest exp
  2014. int best = 0;
  2015. for(int b=1; b<h.size(); ++b)
  2016. {
  2017. if(h[b]->exp > h[best]->exp)
  2018. {
  2019. best = b;
  2020. }
  2021. }
  2022. return h[best];
  2023. }
  2024. //calculates total number of artifacts that belong to given player
  2025. static int getNumberOfArts(const PlayerState * ps)
  2026. {
  2027. int ret = 0;
  2028. for(int g=0; g<ps->heroes.size(); ++g)
  2029. {
  2030. ret += ps->heroes[g]->artifactsInBackpack.size() + ps->heroes[g]->artifactsWorn.size();
  2031. }
  2032. return ret;
  2033. }
  2034. };
  2035. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2036. {
  2037. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2038. { \
  2039. std::vector< std::pair< ui8, si64 > > stats; \
  2040. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2041. { \
  2042. if(g->second.color == 255) \
  2043. continue; \
  2044. std::pair< ui8, si64 > stat; \
  2045. stat.first = g->second.color; \
  2046. stat.second = VAL_GETTER; \
  2047. stats.push_back(stat); \
  2048. } \
  2049. tgi.FIELD = statsHLP::getRank(stats); \
  2050. }
  2051. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2052. {
  2053. if(g->second.color != 255)
  2054. tgi.playerColors.push_back(g->second.color);
  2055. }
  2056. if(level >= 1) //num of towns & num of heroes
  2057. {
  2058. //num of towns
  2059. FILL_FIELD(numOfTowns, g->second.towns.size())
  2060. //num of heroes
  2061. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2062. //best hero's portrait
  2063. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2064. {
  2065. if(g->second.color == 255)
  2066. continue;
  2067. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2068. InfoAboutHero iah;
  2069. iah.initFromHero(best, level >= 8);
  2070. iah.army.clear();
  2071. tgi.colorToBestHero[g->second.color] = iah;
  2072. }
  2073. }
  2074. if(level >= 2) //gold
  2075. {
  2076. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2077. }
  2078. if(level >= 2) //wood & ore
  2079. {
  2080. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2081. }
  2082. if(level >= 3) //mercury, sulfur, crystal, gems
  2083. {
  2084. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2085. }
  2086. if(level >= 4) //obelisks found
  2087. {
  2088. //TODO
  2089. }
  2090. if(level >= 5) //artifacts
  2091. {
  2092. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2093. }
  2094. if(level >= 6) //army strength
  2095. {
  2096. //TODO
  2097. }
  2098. if(level >= 7) //income
  2099. {
  2100. //TODO
  2101. }
  2102. if(level >= 8) //best hero's stats
  2103. {
  2104. //already set in lvl 1 handling
  2105. }
  2106. if(level >= 9) //personality
  2107. {
  2108. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2109. {
  2110. if(g->second.color == 255) //do nothing for neutral player
  2111. continue;
  2112. if(g->second.human)
  2113. {
  2114. tgi.personality[g->second.color] = -1;
  2115. }
  2116. else //AI
  2117. {
  2118. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2119. }
  2120. }
  2121. }
  2122. if(level >= 10) //best creature
  2123. {
  2124. //best creatures belonging to player (highest AI value)
  2125. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2126. {
  2127. if(g->second.color == 255) //do nothing for neutral player
  2128. continue;
  2129. int bestCre = -1; //best creature's ID
  2130. for(int b=0; b<g->second.heroes.size(); ++b)
  2131. {
  2132. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2133. {
  2134. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2135. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2136. {
  2137. bestCre = toCmp;
  2138. }
  2139. }
  2140. }
  2141. tgi.bestCreature[g->second.color] = bestCre;
  2142. }
  2143. }
  2144. #undef FILL_FIELD
  2145. }
  2146. int CGameState::lossCheck( ui8 player ) const
  2147. {
  2148. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  2149. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2150. if(checkForStandardLoss(player))
  2151. return -1;
  2152. if (p->enteredLosingCheatCode)
  2153. {
  2154. return 1;
  2155. }
  2156. if(p->human) //special loss condition applies only to human player
  2157. {
  2158. switch(map->lossCondition.typeOfLossCon)
  2159. {
  2160. case ELossConditionType::LOSSCASTLE:
  2161. {
  2162. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2163. assert(t);
  2164. if(t->tempOwner != player)
  2165. return 1;
  2166. }
  2167. break;
  2168. case ELossConditionType::LOSSHERO:
  2169. {
  2170. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2171. assert(h);
  2172. if(h->tempOwner != player)
  2173. return 1;
  2174. }
  2175. break;
  2176. case ELossConditionType::TIMEEXPIRES:
  2177. if(map->lossCondition.timeLimit < day)
  2178. return 1;
  2179. break;
  2180. }
  2181. }
  2182. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2183. return 2;
  2184. return false;
  2185. }
  2186. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2187. {
  2188. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2189. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  2190. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2191. if(*j)
  2192. pool.erase((**j).subID);
  2193. return pool;
  2194. }
  2195. void CGameState::buildBonusSystemTree()
  2196. {
  2197. buildGlobalTeamPlayerTree();
  2198. attachArmedObjects();
  2199. BOOST_FOREACH(CGTownInstance *t, map->towns)
  2200. {
  2201. t->deserializationFix();
  2202. }
  2203. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2204. // are provided on initializing / deserializing
  2205. }
  2206. void CGameState::deserializationFix()
  2207. {
  2208. buildGlobalTeamPlayerTree();
  2209. attachArmedObjects();
  2210. }
  2211. void CGameState::buildGlobalTeamPlayerTree()
  2212. {
  2213. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  2214. {
  2215. TeamState *t = &k->second;
  2216. t->attachTo(&globalEffects);
  2217. BOOST_FOREACH(ui8 teamMember, k->second.players)
  2218. {
  2219. PlayerState *p = getPlayer(teamMember);
  2220. assert(p);
  2221. p->attachTo(t);
  2222. }
  2223. }
  2224. }
  2225. void CGameState::attachArmedObjects()
  2226. {
  2227. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  2228. {
  2229. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2230. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2231. }
  2232. }
  2233. void CGameState::giveHeroArtifact(CGHeroInstance *h, int aid)
  2234. {
  2235. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2236. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2237. map->addNewArtifactInstance(ai);
  2238. ai->putAt(h, ai->firstAvailableSlot(h));
  2239. }
  2240. int3 CPath::startPos() const
  2241. {
  2242. return nodes[nodes.size()-1].coord;
  2243. }
  2244. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2245. {
  2246. if (mode==0)
  2247. {
  2248. for (ui32 i=0;i<nodes.size();i++)
  2249. {
  2250. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2251. }
  2252. }
  2253. }
  2254. int3 CPath::endPos() const
  2255. {
  2256. return nodes[0].coord;
  2257. }
  2258. CGPathNode::CGPathNode()
  2259. :coord(-1,-1,-1)
  2260. {
  2261. accessible = 0;
  2262. land = 0;
  2263. moveRemains = 0;
  2264. turns = 255;
  2265. theNodeBefore = NULL;
  2266. }
  2267. bool CGPathNode::reachable() const
  2268. {
  2269. return turns < 255;
  2270. }
  2271. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2272. {
  2273. assert(isValid);
  2274. out.nodes.clear();
  2275. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2276. if(!curnode->theNodeBefore)
  2277. return false;
  2278. while(curnode)
  2279. {
  2280. CGPathNode cpn = *curnode;
  2281. curnode = curnode->theNodeBefore;
  2282. out.nodes.push_back(cpn);
  2283. }
  2284. return true;
  2285. }
  2286. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2287. :sizes(Sizes)
  2288. {
  2289. hero = NULL;
  2290. nodes = new CGPathNode**[sizes.x];
  2291. for(int i = 0; i < sizes.x; i++)
  2292. {
  2293. nodes[i] = new CGPathNode*[sizes.y];
  2294. for (int j = 0; j < sizes.y; j++)
  2295. {
  2296. nodes[i][j] = new CGPathNode[sizes.z];
  2297. }
  2298. }
  2299. }
  2300. CPathsInfo::~CPathsInfo()
  2301. {
  2302. for(int i = 0; i < sizes.x; i++)
  2303. {
  2304. for (int j = 0; j < sizes.y; j++)
  2305. {
  2306. delete [] nodes[i][j];
  2307. }
  2308. delete [] nodes[i];
  2309. }
  2310. delete [] nodes;
  2311. }
  2312. int3 CGPath::startPos() const
  2313. {
  2314. return nodes[nodes.size()-1].coord;
  2315. }
  2316. int3 CGPath::endPos() const
  2317. {
  2318. return nodes[0].coord;
  2319. }
  2320. void CGPath::convert( ui8 mode )
  2321. {
  2322. if(mode==0)
  2323. {
  2324. for(ui32 i=0;i<nodes.size();i++)
  2325. {
  2326. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2327. }
  2328. }
  2329. }
  2330. PlayerState::PlayerState()
  2331. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2332. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2333. {
  2334. setNodeType(PLAYER);
  2335. }
  2336. std::string PlayerState::nodeName() const
  2337. {
  2338. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2339. }
  2340. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2341. // {
  2342. // return; //no loops possible
  2343. // }
  2344. //
  2345. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2346. // {
  2347. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2348. // {
  2349. // if (*it != root)
  2350. // (*it)->getBonuses(out, selector, this);
  2351. // }
  2352. // }
  2353. InfoAboutHero::InfoAboutHero()
  2354. {
  2355. details = NULL;
  2356. hclass = NULL;
  2357. portrait = -1;
  2358. }
  2359. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  2360. {
  2361. assign(iah);
  2362. }
  2363. InfoAboutHero::~InfoAboutHero()
  2364. {
  2365. delete details;
  2366. }
  2367. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  2368. {
  2369. if(!h) return;
  2370. owner = h->tempOwner;
  2371. hclass = h->type->heroClass;
  2372. name = h->name;
  2373. portrait = h->portrait;
  2374. army = ArmyDescriptor(h, detailed);
  2375. if(detailed)
  2376. {
  2377. //include details about hero
  2378. details = new Details;
  2379. details->luck = h->LuckVal();
  2380. details->morale = h->MoraleVal();
  2381. details->mana = h->mana;
  2382. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2383. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2384. {
  2385. details->primskills[i] = h->getPrimSkillLevel(i);
  2386. }
  2387. }
  2388. }
  2389. void InfoAboutHero::assign( const InfoAboutHero & iah )
  2390. {
  2391. army = iah.army;
  2392. details = (iah.details ? new Details(*iah.details) : NULL);
  2393. hclass = iah.hclass;
  2394. name = iah.name;
  2395. owner = iah.owner;
  2396. portrait = iah.portrait;
  2397. }
  2398. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  2399. {
  2400. assign(iah);
  2401. return *this;
  2402. }
  2403. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed) : isDetailed(detailed)
  2404. {
  2405. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2406. {
  2407. if(detailed)
  2408. (*this)[i->first] = *i->second;
  2409. else
  2410. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2411. }
  2412. }
  2413. ArmyDescriptor::ArmyDescriptor() : isDetailed(true)
  2414. {
  2415. }
  2416. int ArmyDescriptor::getStrength() const
  2417. {
  2418. ui64 ret = 0;
  2419. if(isDetailed)
  2420. {
  2421. for(const_iterator i = begin(); i != end(); i++)
  2422. ret += i->second.type->AIValue * i->second.count;
  2423. }
  2424. else
  2425. {
  2426. for(const_iterator i = begin(); i != end(); i++)
  2427. ret += i->second.type->AIValue * CCreature::estimateCreatureCount(i->second.count);
  2428. }
  2429. return ret;
  2430. }
  2431. DuelParameters::SideSettings::StackSettings::StackSettings()
  2432. : type(-1), count(0)
  2433. {
  2434. }
  2435. DuelParameters::SideSettings::StackSettings::StackSettings(si32 Type, si32 Count)
  2436. : type(Type), count(Count)
  2437. {
  2438. }
  2439. DuelParameters::SideSettings::SideSettings()
  2440. {
  2441. heroId = -1;
  2442. }
  2443. DuelParameters::DuelParameters()
  2444. {
  2445. terType = TerrainTile::dirt;
  2446. bfieldType = 15;
  2447. }
  2448. TeamState::TeamState()
  2449. {
  2450. setNodeType(TEAM);
  2451. }
  2452. void CPathfinder::initializeGraph()
  2453. {
  2454. CGPathNode ***graph = out.nodes;
  2455. for(size_t i=0; i < out.sizes.x; ++i)
  2456. {
  2457. for(size_t j=0; j < out.sizes.y; ++j)
  2458. {
  2459. for(size_t k=0; k < out.sizes.z; ++k)
  2460. {
  2461. curPos = int3(i,j,k);
  2462. const TerrainTile *tinfo = &gs->map->terrain[i][j][k];
  2463. CGPathNode &node = graph[i][j][k];
  2464. node.accessible = evaluateAccessibility(tinfo);
  2465. node.turns = 0xff;
  2466. node.moveRemains = 0;
  2467. node.coord.x = i;
  2468. node.coord.y = j;
  2469. node.coord.z = k;
  2470. node.land = tinfo->tertype != TerrainTile::water;
  2471. node.theNodeBefore = NULL;
  2472. }
  2473. }
  2474. }
  2475. }
  2476. void CPathfinder::calculatePaths(int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/)
  2477. {
  2478. assert(hero);
  2479. assert(hero == getHero(hero->id));
  2480. if(src.x < 0)
  2481. src = hero->getPosition(false);
  2482. if(movement < 0)
  2483. movement = hero->movement;
  2484. out.hero = hero;
  2485. out.hpos = src;
  2486. if(!gs->map->isInTheMap(src)/* || !gs->map->isInTheMap(dest)*/) //check input
  2487. {
  2488. tlog1 << "CGameState::calculatePaths: Hero outside the gs->map? How dare you...\n";
  2489. return;
  2490. }
  2491. initializeGraph();
  2492. //initial tile - set cost on 0 and add to the queue
  2493. CGPathNode &initialNode = *getNode(src);
  2494. initialNode.turns = 0;
  2495. initialNode.moveRemains = movement;
  2496. mq.push_back(&initialNode);
  2497. std::vector<int3> neighbours;
  2498. neighbours.reserve(16);
  2499. while(!mq.empty())
  2500. {
  2501. cp = mq.front();
  2502. mq.pop_front();
  2503. const int3 sourceGuardPosition = guardingCreaturePosition(cp->coord);
  2504. bool guardedSource = (sourceGuardPosition != int3(-1, -1, -1) && cp->coord != src);
  2505. ct = &gs->map->getTile(cp->coord);
  2506. int movement = cp->moveRemains, turn = cp->turns;
  2507. if(!movement)
  2508. {
  2509. movement = hero->maxMovePoints(cp->land);
  2510. turn++;
  2511. }
  2512. //add accessible neighbouring nodes to the queue
  2513. neighbours.clear();
  2514. //handling subterranean gate => it's exit is the only neighbour
  2515. bool subterraneanEntry = (ct->topVisitableID() == GameConstants::SUBTERRANEAN_GATE_TYPE && useSubterraneanGates);
  2516. if(subterraneanEntry)
  2517. {
  2518. //try finding the exit gate
  2519. if(const CGObjectInstance *outGate = getObj(CGTeleport::getMatchingGate(ct->visitableObjects.back()->id), false))
  2520. {
  2521. const int3 outPos = outGate->visitablePos();
  2522. //gs->getNeighbours(*getTile(outPos), outPos, neighbours, boost::logic::indeterminate, !cp->land);
  2523. neighbours.push_back(outPos);
  2524. }
  2525. else
  2526. {
  2527. //gate with no exit (blocked) -> do nothing with this node
  2528. continue;
  2529. }
  2530. }
  2531. gs->getNeighbours(*ct, cp->coord, neighbours, boost::logic::indeterminate, !cp->land);
  2532. for(ui32 i=0; i < neighbours.size(); i++)
  2533. {
  2534. const int3 &n = neighbours[i]; //current neighbor
  2535. dp = getNode(n);
  2536. dt = &gs->map->getTile(n);
  2537. destTopVisObjID = dt->topVisitableID();
  2538. useEmbarkCost = 0; //0 - usual movement; 1 - embark; 2 - disembark
  2539. int moveAtNextTile = movement;
  2540. int turnAtNextTile = turn;
  2541. const bool destIsGuardian = sourceGuardPosition == n;
  2542. if(!goodForLandSeaTransition())
  2543. continue;
  2544. if(!canMoveBetween(cp->coord, dp->coord) || dp->accessible == CGPathNode::BLOCKED )
  2545. continue;
  2546. //special case -> hero embarked a boat standing on a guarded tile -> we must allow to move away from that tile
  2547. if(cp->accessible == CGPathNode::VISITABLE && guardedSource && cp->theNodeBefore->land && ct->topVisitableID() == GameConstants::BOATI_TYPE)
  2548. guardedSource = false;
  2549. int cost = gs->getMovementCost(hero, cp->coord, dp->coord, movement);
  2550. //special case -> moving from src Subterranean gate to dest gate -> it's free
  2551. if(subterraneanEntry && destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE && cp->coord.z != dp->coord.z)
  2552. cost = 0;
  2553. int remains = movement - cost;
  2554. if(useEmbarkCost)
  2555. {
  2556. remains = hero->movementPointsAfterEmbark(movement, cost, useEmbarkCost - 1);
  2557. cost = movement - remains;
  2558. }
  2559. if(remains < 0)
  2560. {
  2561. //occurs rarely, when hero with low movepoints tries to leave the road
  2562. turnAtNextTile++;
  2563. moveAtNextTile = hero->maxMovePoints(cp->land);
  2564. cost = gs->getMovementCost(hero, cp->coord, dp->coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2565. remains = moveAtNextTile - cost;
  2566. }
  2567. if((dp->turns==0xff //we haven't been here before
  2568. || dp->turns > turnAtNextTile
  2569. || (dp->turns >= turnAtNextTile && dp->moveRemains < remains)) //this route is faster
  2570. && (!guardedSource || destIsGuardian)) // Can step into tile of guard
  2571. {
  2572. assert(dp != cp->theNodeBefore); //two tiles can't point to each other
  2573. dp->moveRemains = remains;
  2574. dp->turns = turnAtNextTile;
  2575. dp->theNodeBefore = cp;
  2576. const bool guardedDst = guardingCreaturePosition(dp->coord) != int3(-1, -1, -1)
  2577. && dp->accessible == CGPathNode::BLOCKVIS;
  2578. if (dp->accessible == CGPathNode::ACCESSIBLE
  2579. || (useEmbarkCost && allowEmbarkAndDisembark)
  2580. || destTopVisObjID == GameConstants::SUBTERRANEAN_GATE_TYPE
  2581. || (guardedDst && !guardedSource)) // Can step into a hostile tile once.
  2582. {
  2583. mq.push_back(dp);
  2584. }
  2585. }
  2586. } //neighbours loop
  2587. } //queue loop
  2588. out.isValid = true;
  2589. }
  2590. CGPathNode *CPathfinder::getNode(const int3 &coord)
  2591. {
  2592. return &out.nodes[coord.x][coord.y][coord.z];
  2593. }
  2594. bool CPathfinder::canMoveBetween(const int3 &a, const int3 &b) const
  2595. {
  2596. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  2597. }
  2598. bool CPathfinder::canStepOntoDst() const
  2599. {
  2600. //TODO remove
  2601. assert(0);
  2602. return false;
  2603. }
  2604. CGPathNode::EAccessibility CPathfinder::evaluateAccessibility(const TerrainTile *tinfo) const
  2605. {
  2606. CGPathNode::EAccessibility ret = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  2607. if(tinfo->tertype == TerrainTile::rock || !FoW[curPos.x][curPos.y][curPos.z])
  2608. return CGPathNode::BLOCKED;
  2609. if(tinfo->visitable)
  2610. {
  2611. 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
  2612. {
  2613. return CGPathNode::BLOCKED;
  2614. }
  2615. else
  2616. {
  2617. BOOST_FOREACH(const CGObjectInstance *obj, tinfo->visitableObjects)
  2618. {
  2619. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2620. {
  2621. ret = CGPathNode::ACCESSIBLE;
  2622. }
  2623. else if(obj->blockVisit)
  2624. {
  2625. return CGPathNode::BLOCKVIS;
  2626. }
  2627. else if(obj->ID != GameConstants::EVENTI_TYPE) //pathfinder should ignore placed events
  2628. {
  2629. ret = CGPathNode::VISITABLE;
  2630. }
  2631. }
  2632. }
  2633. }
  2634. else if (gs->map->isInTheMap(guardingCreaturePosition(curPos))
  2635. && !tinfo->blocked)
  2636. {
  2637. // Monster close by; blocked visit for battle.
  2638. return CGPathNode::BLOCKVIS;
  2639. }
  2640. return ret;
  2641. }
  2642. bool CPathfinder::goodForLandSeaTransition()
  2643. {
  2644. if(cp->land != dp->land) //hero can traverse land<->sea only in special circumstances
  2645. {
  2646. if(cp->land) //from land to sea -> embark or assault hero on boat
  2647. {
  2648. if(dp->accessible == CGPathNode::ACCESSIBLE || destTopVisObjID < 0) //cannot enter empty water tile from land -> it has to be visitable
  2649. return false;
  2650. if(destTopVisObjID != GameConstants::HEROI_TYPE && destTopVisObjID != GameConstants::BOATI_TYPE) //only boat or hero can be accessed from land
  2651. return false;
  2652. if(destTopVisObjID == GameConstants::BOATI_TYPE)
  2653. useEmbarkCost = 1;
  2654. }
  2655. else //disembark
  2656. {
  2657. //can disembark only on coastal tiles
  2658. if(!dt->isCoastal())
  2659. return false;
  2660. //tile must be accessible -> exception: unblocked blockvis tiles -> clear but guarded by nearby monster coast
  2661. if( (dp->accessible != CGPathNode::ACCESSIBLE && (dp->accessible != CGPathNode::BLOCKVIS || dt->blocked))
  2662. || dt->visitable) //TODO: passableness problem -> town says it's passable (thus accessible) but we obviously can't disembark onto town gate
  2663. return false;;
  2664. useEmbarkCost = 2;
  2665. }
  2666. }
  2667. return true;
  2668. }
  2669. CPathfinder::CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero) : CGameInfoCallback(_gs, -1), out(_out), hero(_hero), FoW(getPlayerTeam(hero->tempOwner)->fogOfWarMap)
  2670. {
  2671. useSubterraneanGates = true;
  2672. allowEmbarkAndDisembark = true;
  2673. }