CGameState.cpp 81 KB

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