CGameState.cpp 84 KB

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