2
0

CGameState.cpp 81 KB

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