CGameState.cpp 81 KB

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