CGameState.cpp 85 KB

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