CGameState.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074
  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. CGCreature *c = new CGCreature();
  850. c->setOwner(1);
  851. c->putStack(0, new CStackInstance(69, 6));
  852. c->putStack(1, new CStackInstance(11, 3));
  853. c->subID = 34;
  854. c->initObj();
  855. heroes[0] = h;
  856. heroes[1] = NULL;
  857. armies[0] = h;
  858. armies[1] = c;
  859. curB = BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, false, town);
  860. curB->localInit();
  861. return;
  862. }
  863. break;
  864. default:
  865. tlog1 << "Wrong mode: " << (int)scenarioOps->mode << std::endl;
  866. return;
  867. }
  868. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  869. tlog0 << "Map loaded!" << std::endl;
  870. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  871. if(checksum)
  872. {
  873. tlog0 << "\tServer checksum for " << scenarioOps->mapname <<": "<< checksum << std::endl;
  874. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  875. if(map->checksum != checksum)
  876. {
  877. tlog1 << "Wrong map checksum!!!" << std::endl;
  878. throw std::string("Wrong checksum");
  879. }
  880. }
  881. day = 0;
  882. loadTownDInfos();
  883. //pick grail location
  884. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  885. {
  886. if(!map->grailRadious) //radius not given -> anywhere on map
  887. map->grailRadious = map->width * 2;
  888. std::vector<int3> allowedPos;
  889. // add all not blocked tiles in range
  890. for (int i = 0; i < map->width ; i++)
  891. {
  892. for (int j = 0; j < map->height ; j++)
  893. {
  894. for (int k = 0; k <= map->twoLevel ; k++)
  895. {
  896. const TerrainTile &t = map->terrain[i][j][k];
  897. if(!t.blocked
  898. && !t.visitable
  899. && t.tertype != TerrainTile::water
  900. && t.tertype != TerrainTile::rock
  901. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  902. allowedPos.push_back(int3(i,j,k));
  903. }
  904. }
  905. }
  906. //remove tiles with holes
  907. for(unsigned int no=0; no<map->objects.size(); ++no)
  908. if(map->objects[no]->ID == 124)
  909. allowedPos -= map->objects[no]->pos;
  910. if(allowedPos.size())
  911. map->grailPos = allowedPos[ran() % allowedPos.size()];
  912. else
  913. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  914. }
  915. //picking random factions for players
  916. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  917. it != scenarioOps->playerInfos.end(); ++it)
  918. {
  919. if(it->second.castle==-1)
  920. {
  921. int f;
  922. do
  923. {
  924. f = ran()%F_NUMBER;
  925. }while(!(map->players[it->first].allowedFactions & 1<<f));
  926. it->second.castle = f;
  927. }
  928. }
  929. //randomizing objects
  930. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  931. {
  932. randomizeObject(obj);
  933. obj->hoverName = VLC->generaltexth->names[obj->ID];
  934. //handle Favouring Winds - mark tiles under it
  935. if(obj->ID == 225)
  936. for (int i = 0; i < obj->getWidth() ; i++)
  937. for (int j = 0; j < obj->getHeight() ; j++)
  938. {
  939. int3 pos = obj->pos - int3(i,j,0);
  940. if(map->isInTheMap(pos))
  941. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  942. }
  943. }
  944. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  945. /*********creating players entries in gs****************************************/
  946. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  947. it != scenarioOps->playerInfos.end(); ++it)
  948. {
  949. std::pair<int,PlayerState> ins(it->first,PlayerState());
  950. ins.second.color=ins.first;
  951. ins.second.human = it->second.human;
  952. ins.second.team = map->players[ins.first].team;
  953. teams[ins.second.team].id = ins.second.team;//init team
  954. teams[ins.second.team].players.insert(ins.first);//add player to team
  955. players.insert(ins);
  956. }
  957. /*********give starting hero****************************************/
  958. for(int i=0;i<PLAYER_LIMIT;i++)
  959. {
  960. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  961. {
  962. int3 hpos = map->players[i].posOfMainTown;
  963. hpos.x+=1;// hpos.y+=1;
  964. if (scenarioOps->playerInfos.find(i) == scenarioOps->playerInfos.end())
  965. {
  966. continue;
  967. }
  968. int h=pickHero(i);
  969. if(scenarioOps->playerInfos[i].hero == -1)
  970. scenarioOps->playerInfos[i].hero = h;
  971. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  972. nnn->id = map->objects.size();
  973. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  974. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  975. {
  976. if(map->towns[o]->pos == hpos)
  977. {
  978. map->towns[o]->visitingHero = nnn;
  979. nnn->visitedTown = map->towns[o];
  980. nnn->inTownGarrison = false;
  981. break;
  982. }
  983. }
  984. nnn->initHero();
  985. map->heroes.push_back(nnn);
  986. map->objects.push_back(nnn);
  987. map->addBlockVisTiles(nnn);
  988. //give campaign bonus
  989. if (scenarioOps->mode == StartInfo::CAMPAIGN && getPlayer(nnn->tempOwner)->human)
  990. {
  991. HLP::giveCampaignBonusToHero(nnn, scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  992. }
  993. }
  994. }
  995. /*************************replace hero placeholders*****************************/
  996. if (campaign)
  997. {
  998. CScenarioTravel::STravelBonus bonus =
  999. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1000. std::vector<CGHeroInstance *> Xheroes;
  1001. if (bonus.type == 8) //hero crossover
  1002. {
  1003. Xheroes = campaign->camp->scenarios[bonus.info2].crossoverHeroes;
  1004. }
  1005. //selecting heroes by type
  1006. for(int g=0; g<map->objects.size(); ++g)
  1007. {
  1008. CGObjectInstance * obj = map->objects[g];
  1009. if (obj->ID != 214) //not a placeholder
  1010. {
  1011. continue;
  1012. }
  1013. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1014. if(hp->subID != 0xFF) //select by type
  1015. {
  1016. bool found = false;
  1017. BOOST_FOREACH(CGHeroInstance * ghi, Xheroes)
  1018. {
  1019. if (ghi->subID == hp->subID)
  1020. {
  1021. found = true;
  1022. HLP::replaceHero(this, g, ghi);
  1023. Xheroes -= ghi;
  1024. break;
  1025. }
  1026. }
  1027. if (!found)
  1028. {
  1029. //TODO: create new hero of this type
  1030. }
  1031. }
  1032. }
  1033. //selecting heroes by power
  1034. std::sort(Xheroes.begin(), Xheroes.end(), HLP::heroPowerSorter);
  1035. for(int g=0; g<map->objects.size(); ++g)
  1036. {
  1037. CGObjectInstance * obj = map->objects[g];
  1038. if (obj->ID != 214) //not a placeholder
  1039. {
  1040. continue;
  1041. }
  1042. CGHeroPlaceholder * hp = static_cast<CGHeroPlaceholder*>(obj);
  1043. if (hp->subID == 0xFF) //select by power
  1044. {
  1045. if(Xheroes.size() > hp->power - 1)
  1046. HLP::replaceHero(this, g, Xheroes[hp->power - 1]);
  1047. else
  1048. tlog2 << "Warning, to hero to replace!\n";
  1049. //we don't have to remove hero from Xheroes because it would destroy the order and duplicates shouldn't happen
  1050. }
  1051. }
  1052. }
  1053. /******************RESOURCES****************************************************/
  1054. std::vector<int> startresAI, startresHuman;
  1055. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1056. int k;
  1057. for (int j=0; j<scenarioOps->difficulty * 2; j++)
  1058. {
  1059. tis >> k;
  1060. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1061. tis>>k;
  1062. }
  1063. tis >> k;
  1064. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1065. {
  1066. tis >> k;
  1067. startresHuman.push_back(k);
  1068. }
  1069. tis >> k;
  1070. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1071. {
  1072. tis >> k;
  1073. startresAI.push_back(k);
  1074. }
  1075. tis.close();
  1076. tis.clear();
  1077. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1078. {
  1079. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1080. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1081. {
  1082. if (i->second.human)
  1083. {
  1084. (*i).second.resources[x] = startresHuman[x];
  1085. }
  1086. else
  1087. {
  1088. (*i).second.resources[x] = startresAI[x];
  1089. }
  1090. }
  1091. }
  1092. //give start resource bonus in case of campaign
  1093. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1094. {
  1095. CScenarioTravel::STravelBonus chosenBonus =
  1096. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1097. if(chosenBonus.type == 7) //resource
  1098. {
  1099. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(scenarioOps); //players we will give resource bonus
  1100. for (int b=0; b<people.size(); ++b)
  1101. {
  1102. std::vector<int> res; //resources we will give
  1103. switch (chosenBonus.info1)
  1104. {
  1105. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1106. res.push_back(chosenBonus.info1);
  1107. break;
  1108. case 0xFD: //wood+ore
  1109. res.push_back(0); res.push_back(2);
  1110. break;
  1111. case 0xFE: //rare
  1112. res.push_back(1); res.push_back(3); res.push_back(4); res.push_back(5);
  1113. break;
  1114. default:
  1115. assert(0);
  1116. break;
  1117. }
  1118. //increasing resource quantity
  1119. for (int n=0; n<res.size(); ++n)
  1120. {
  1121. players[people[b]->color].resources[res[n]] += chosenBonus.info2;
  1122. }
  1123. }
  1124. }
  1125. }
  1126. /*************************HEROES************************************************/
  1127. std::set<int> hids; //hero ids to create pool
  1128. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1129. if(map->allowedHeroes[i])
  1130. hids.insert(i);
  1131. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1132. {
  1133. if (map->heroes[i]->getOwner()<0)
  1134. {
  1135. tlog2 << "Warning - hero with uninitialized owner!\n";
  1136. continue;
  1137. }
  1138. CGHeroInstance * vhi = (map->heroes[i]);
  1139. vhi->initHero();
  1140. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1141. hids.erase(vhi->subID);
  1142. }
  1143. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1144. {
  1145. if (map->objects[i]->ID == 62)
  1146. hids.erase(map->objects[i]->subID);
  1147. }
  1148. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1149. {
  1150. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1151. continue;
  1152. map->predefinedHeroes[i]->initHero();
  1153. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1154. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1155. hids.erase(map->predefinedHeroes[i]->subID);
  1156. }
  1157. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1158. {
  1159. CGHeroInstance * vhi = new CGHeroInstance();
  1160. vhi->initHero(hid);
  1161. hpool.heroesPool[hid] = vhi;
  1162. hpool.pavailable[hid] = 0xff;
  1163. }
  1164. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1165. {
  1166. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1167. }
  1168. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1169. {
  1170. CScenarioTravel::STravelBonus chosenBonus =
  1171. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1172. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1173. {
  1174. //find human player
  1175. int humanPlayer;
  1176. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1177. {
  1178. if(it->second.human)
  1179. {
  1180. humanPlayer = it->first;
  1181. break;
  1182. }
  1183. }
  1184. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1185. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1186. {
  1187. int maxB = -1;
  1188. for (int b=0; b<heroes.size(); ++b)
  1189. {
  1190. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1191. {
  1192. maxB = b;
  1193. }
  1194. }
  1195. if(maxB < 0)
  1196. tlog2 << "Warning - cannot give bonus to hero cause there are no heroes!\n";
  1197. else
  1198. HLP::giveCampaignBonusToHero(heroes[maxB], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  1199. }
  1200. else //specific hero
  1201. {
  1202. for (int b=0; b<heroes.size(); ++b)
  1203. {
  1204. if (heroes[b]->subID == chosenBonus.info1)
  1205. {
  1206. HLP::giveCampaignBonusToHero(heroes[b], scenarioOps, campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions);
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /*************************FOG**OF**WAR******************************************/
  1214. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1215. {
  1216. k->second.fogOfWarMap.resize(map->width);
  1217. for(int g=0; g<map->width; ++g)
  1218. k->second.fogOfWarMap[g].resize(map->height);
  1219. for(int g=-0; g<map->width; ++g)
  1220. for(int h=0; h<map->height; ++h)
  1221. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1222. for(int g=0; g<map->width; ++g)
  1223. for(int h=0; h<map->height; ++h)
  1224. for(int v=0; v<map->twoLevel+1; ++v)
  1225. k->second.fogOfWarMap[g][h][v] = 0;
  1226. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1227. {
  1228. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1229. std::set<int3> tiles;
  1230. obj->getSightTiles(tiles);
  1231. BOOST_FOREACH(int3 tile, tiles)
  1232. {
  1233. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1234. }
  1235. }
  1236. }
  1237. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1238. {
  1239. //starting bonus
  1240. if(scenarioOps->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1241. scenarioOps->playerInfos[k->first].bonus = ran()%3;
  1242. switch(scenarioOps->playerInfos[k->first].bonus)
  1243. {
  1244. case PlayerSettings::bgold:
  1245. k->second.resources[6] += 500 + (ran()%6)*100;
  1246. break;
  1247. case PlayerSettings::bresource:
  1248. {
  1249. int res = VLC->townh->towns[scenarioOps->playerInfos[k->first].castle].primaryRes;
  1250. if(res == 127)
  1251. {
  1252. k->second.resources[0] += 5 + ran()%6;
  1253. k->second.resources[2] += 5 + ran()%6;
  1254. }
  1255. else
  1256. {
  1257. k->second.resources[res] += 3 + ran()%4;
  1258. }
  1259. break;
  1260. }
  1261. case PlayerSettings::bartifact:
  1262. {
  1263. if(!k->second.heroes.size())
  1264. {
  1265. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1266. break;
  1267. }
  1268. CArtifact *toGive;
  1269. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1270. CGHeroInstance *hero = k->second.heroes[0];
  1271. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  1272. if(slot != toGive->possibleSlots.end())
  1273. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive);
  1274. else
  1275. hero->giveArtifact(toGive->id);
  1276. }
  1277. }
  1278. }
  1279. /****************************TOWNS************************************************/
  1280. for ( int i=0; i<4; i++)
  1281. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1282. for (unsigned int i=0;i<map->towns.size();i++)
  1283. {
  1284. CGTownInstance * vti =(map->towns[i]);
  1285. if(!vti->town)
  1286. vti->town = &VLC->townh->towns[vti->subID];
  1287. if (vti->name.length()==0) // if town hasn't name we draw it
  1288. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1289. //init buildings
  1290. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1291. {
  1292. vti->builtBuildings.erase(-50);
  1293. vti->builtBuildings.insert(10);
  1294. vti->builtBuildings.insert(5);
  1295. vti->builtBuildings.insert(30);
  1296. if(ran()%2)
  1297. vti->builtBuildings.insert(31);
  1298. }
  1299. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1300. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1301. //init hordes
  1302. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1303. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1304. {
  1305. vti->builtBuildings.erase(-31-i);//remove old ID
  1306. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1307. {
  1308. vti->builtBuildings.insert(18);//add it
  1309. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1310. vti->builtBuildings.insert(19);//add it as well
  1311. }
  1312. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1313. {
  1314. vti->builtBuildings.insert(24);
  1315. if (vstd::contains(vti->builtBuildings,(37+i)))
  1316. vti->builtBuildings.insert(25);
  1317. }
  1318. }
  1319. for (std::list<CCastleEvent*>::iterator ev=vti->events.begin(); ev!=vti->events.end(); ev++)
  1320. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1321. if (vstd::contains((*ev)->buildings,(-31-i))) //if we have horde for this level
  1322. {
  1323. (*ev)->buildings.erase(-31-i);
  1324. if (vti->town->hordeLvl[0] == i)
  1325. (*ev)->buildings.insert(18);
  1326. if (vti->town->hordeLvl[1] == i)
  1327. (*ev)->buildings.insert(24);
  1328. }
  1329. //init spells
  1330. vti->spells.resize(SPELL_LEVELS);
  1331. CSpell *s;
  1332. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1333. {
  1334. s = VLC->spellh->spells[vti->obligatorySpells[z]];
  1335. vti->spells[s->level-1].push_back(s->id);
  1336. vti->possibleSpells -= s->id;
  1337. }
  1338. while(vti->possibleSpells.size())
  1339. {
  1340. ui32 total=0;
  1341. int sel = -1;
  1342. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1343. total += VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1344. int r = (total)? ran()%total : -1;
  1345. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1346. {
  1347. r -= VLC->spellh->spells[vti->possibleSpells[ps]]->probabilities[vti->subID];
  1348. if(r<0)
  1349. {
  1350. sel = ps;
  1351. break;
  1352. }
  1353. }
  1354. if(sel<0)
  1355. sel=0;
  1356. CSpell *s = VLC->spellh->spells[vti->possibleSpells[sel]];
  1357. vti->spells[s->level-1].push_back(s->id);
  1358. vti->possibleSpells -= s->id;
  1359. }
  1360. if(vti->getOwner() != 255)
  1361. getPlayer(vti->getOwner())->towns.push_back(vti);
  1362. }
  1363. //campaign bonuses for towns
  1364. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1365. {
  1366. CScenarioTravel::STravelBonus chosenBonus =
  1367. campaign->camp->scenarios[scenarioOps->whichMapInCampaign].travelOptions.bonusesToChoose[scenarioOps->choosenCampaignBonus];
  1368. if (chosenBonus.type == 2)
  1369. {
  1370. for (int g=0; g<map->towns.size(); ++g)
  1371. {
  1372. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1373. PlayerInfo & pi = map->players[owner->color];
  1374. if (owner->human && //human-owned
  1375. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1376. {
  1377. map->towns[g]->builtBuildings.insert(
  1378. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1379. break;
  1380. }
  1381. }
  1382. }
  1383. }
  1384. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1385. {
  1386. if(k->first==-1 || k->first==255)
  1387. continue;
  1388. //init visiting and garrisoned heroes
  1389. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1390. {
  1391. CGHeroInstance *h = k->second.heroes[l];
  1392. for(unsigned int m=0; m<k->second.towns.size();m++)
  1393. {
  1394. CGTownInstance *t = k->second.towns[m];
  1395. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1396. if(vistile == h->pos || h->pos==t->pos)
  1397. {
  1398. t->visitingHero = h;
  1399. h->visitedTown = t;
  1400. h->inTownGarrison = false;
  1401. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1402. {
  1403. map->removeBlockVisTiles(h);
  1404. h->pos.x -= 1;
  1405. map->addBlockVisTiles(h);
  1406. }
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. objCaller->preInit();
  1413. for(unsigned int i=0; i<map->objects.size(); i++)
  1414. {
  1415. map->objects[i]->initObj();
  1416. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1417. static_cast<CGHeroInstance*>(map->objects[i].get())->initHero();
  1418. }
  1419. CGTeleport::postInit(); //pairing subterranean gates
  1420. }
  1421. int CGameState::battleGetBattlefieldType(int3 tile)
  1422. {
  1423. if(tile==int3() && curB)
  1424. tile = curB->tile;
  1425. else if(tile==int3() && !curB)
  1426. return -1;
  1427. const TerrainTile &t = map->getTile(tile);
  1428. //fight in mine -> subterranean
  1429. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1430. return 12;
  1431. const std::vector <ConstTransitivePtr<CGObjectInstance> > & objs = map->objects;
  1432. for(int g=0; g<objs.size(); ++g)
  1433. {
  1434. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1435. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1436. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1437. ) //look only for objects covering given tile
  1438. continue;
  1439. switch(objs[g]->ID)
  1440. {
  1441. case 222: //clover field
  1442. return 19;
  1443. case 21: case 223: //cursed ground
  1444. return 22;
  1445. case 224: //evil fog
  1446. return 20;
  1447. case 225: //favourable winds
  1448. return 21;
  1449. case 226: //fiery fields
  1450. return 14;
  1451. case 227: //holy ground
  1452. return 18;
  1453. case 228: //lucid pools
  1454. return 17;
  1455. case 229: //magic clouds
  1456. return 16;
  1457. case 46: case 230: //magic plains
  1458. return 9;
  1459. case 231: //rocklands
  1460. return 15;
  1461. }
  1462. }
  1463. switch(t.tertype)
  1464. {
  1465. case TerrainTile::dirt:
  1466. return rand()%3+3;
  1467. case TerrainTile::sand:
  1468. return 2; //TODO: coast support
  1469. case TerrainTile::grass:
  1470. return rand()%2+6;
  1471. case TerrainTile::snow:
  1472. return rand()%2+10;
  1473. case TerrainTile::swamp:
  1474. return 13;
  1475. case TerrainTile::rough:
  1476. return 23;
  1477. case TerrainTile::subterranean:
  1478. return 12;
  1479. case TerrainTile::lava:
  1480. return 8;
  1481. case TerrainTile::water:
  1482. return 25;
  1483. case TerrainTile::rock:
  1484. return 15;
  1485. default:
  1486. return -1;
  1487. }
  1488. }
  1489. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1490. {
  1491. std::set<std::pair<int, int> > ret;
  1492. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1493. {
  1494. assert(a[j] >= b[j]);
  1495. if(int dif = modifier * (a[j] - b[j]) / 100)
  1496. ret.insert(std::make_pair(j,dif));
  1497. }
  1498. return ret;
  1499. }
  1500. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1501. {
  1502. UpgradeInfo ret;
  1503. const CCreature *base = stack.type;
  1504. const CGHeroInstance *h = stack.armyObj->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1505. const CGTownInstance *t = NULL;
  1506. if(stack.armyObj->ID == TOWNI_TYPE)
  1507. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1508. else if(h)
  1509. { //hero speciality
  1510. BonusList lista = h->speciality.getBonuses(Selector::typeSybtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1511. BOOST_FOREACH(const Bonus *it, lista)
  1512. {
  1513. ui16 nid = it->additionalInfo;
  1514. if (nid != base->idNumber) //in very specific case the upgrade is avaliable by default (?)
  1515. {
  1516. ret.newID.push_back(nid);
  1517. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1518. }
  1519. }
  1520. t = h->visitedTown;
  1521. }
  1522. if(t)
  1523. {
  1524. BOOST_FOREACH(si32 bid, t->builtBuildings)
  1525. {
  1526. if( bid >= 37 && bid < 44 ) //upgraded creature dwelling
  1527. {
  1528. int nid = t->town->upgradedCreatures[bid-37]; //upgrade offered by that building
  1529. if(vstd::contains(base->upgrades, nid)) //possible upgrade
  1530. {
  1531. ret.newID.push_back(nid);
  1532. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1533. }
  1534. }
  1535. }
  1536. }
  1537. //hero is visiting Hill Fort
  1538. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1539. {
  1540. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1541. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1542. BOOST_FOREACH(si32 nid, base->upgrades)
  1543. {
  1544. ret.newID.push_back(nid);
  1545. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost, costModifier));
  1546. }
  1547. }
  1548. if(ret.newID.size())
  1549. ret.oldID = base->idNumber;
  1550. return ret;
  1551. }
  1552. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1553. {
  1554. if ( color1 == color2 )
  1555. return 2;
  1556. const TeamState * ts = getPlayerTeam(color1);
  1557. if (ts && vstd::contains(ts->players, color2))
  1558. return 1;
  1559. return 0;
  1560. }
  1561. void CGameState::loadTownDInfos()
  1562. {
  1563. for(int i=0;i<F_NUMBER;i++)
  1564. {
  1565. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1566. forts[i] = VLC->dobjinfo->castles[i];
  1567. map->defy.push_back(forts[i]);
  1568. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1569. }
  1570. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  1571. int ccc;
  1572. ifs>>ccc;
  1573. for(int i=0; i < ccc*2; i++)
  1574. {
  1575. CGDefInfo *n;
  1576. if(i<ccc)
  1577. n = villages[i];
  1578. else
  1579. n = capitols[i%ccc];
  1580. ifs >> n->name;
  1581. map->defy.push_back(n);
  1582. }
  1583. }
  1584. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1585. {
  1586. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1587. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1588. vec.clear();
  1589. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1590. {
  1591. const int3 hlp = tile + dirs[i];
  1592. if(!map->isInTheMap(hlp))
  1593. continue;
  1594. const TerrainTile &hlpt = map->getTile(hlp);
  1595. //we cannot visit things from blocked tiles
  1596. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1597. {
  1598. continue;
  1599. }
  1600. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1601. {
  1602. int3 hlp1 = tile,
  1603. hlp2 = tile;
  1604. hlp1.x += dirs[i].x;
  1605. hlp2.y += dirs[i].y;
  1606. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1607. continue;
  1608. }
  1609. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1610. && hlpt.tertype != TerrainTile::rock)
  1611. {
  1612. vec.push_back(hlp);
  1613. }
  1614. }
  1615. }
  1616. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1617. {
  1618. if(src == dest) //same tile
  1619. return 0;
  1620. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1621. &d = map->terrain[dest.x][dest.y][dest.z];
  1622. //get basic cost
  1623. int ret = h->getTileCost(d,s);
  1624. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1625. {
  1626. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1627. if(!freeFlying)
  1628. {
  1629. ret *= 1.4f; //40% penalty for movement over blocked tile
  1630. }
  1631. }
  1632. else if (d.tertype == TerrainTile::water)
  1633. {
  1634. if(h->boat && s.siodmyTajemniczyBajt & 128 && d.siodmyTajemniczyBajt & 128) //Favourable Winds
  1635. ret *= 0.666f;
  1636. else if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1637. ret *= 1.4f; //40% penalty for water walking
  1638. }
  1639. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1640. {
  1641. int old = ret;
  1642. ret *= 1.414213;
  1643. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1644. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1645. {
  1646. return remainingMovePoints;
  1647. }
  1648. }
  1649. int left = remainingMovePoints-ret;
  1650. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1651. {
  1652. std::vector<int3> vec;
  1653. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1654. for(size_t i=0; i < vec.size(); i++)
  1655. {
  1656. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1657. if(fcost <= left)
  1658. {
  1659. return ret;
  1660. }
  1661. }
  1662. ret = remainingMovePoints;
  1663. }
  1664. return ret;
  1665. }
  1666. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1667. {
  1668. std::set<int> used;
  1669. used.insert(ID);
  1670. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1671. while(true)
  1672. {
  1673. size_t noloop=0;
  1674. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1675. {
  1676. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1677. {
  1678. used.insert(*i);
  1679. for(
  1680. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1681. j!=VLC->townh->requirements[t->subID][*i].end();
  1682. j++)
  1683. {
  1684. reqs.insert(*j);//creating full list of requirements
  1685. }
  1686. }
  1687. else
  1688. {
  1689. noloop++;
  1690. }
  1691. }
  1692. if(noloop==reqs.size())
  1693. break;
  1694. }
  1695. return reqs;
  1696. }
  1697. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1698. {
  1699. int ret = 7; //allowed by default
  1700. if(t->builded >= MAX_BUILDING_PER_TURN)
  1701. ret = 5; //building limit
  1702. //checking resources
  1703. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1704. if(!pom)
  1705. return 8;
  1706. // if(pom->Name().size()==0||pom->resources.size()==0)
  1707. // return 2;//TODO: why does this happen?
  1708. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1709. {
  1710. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1711. ret = 6; //lack of res
  1712. }
  1713. //checking for requirements
  1714. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1715. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1716. {
  1717. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1718. ret = 8; //lack of requirements - cannot build
  1719. }
  1720. //can we build it?
  1721. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1722. ret = 2; //forbidden
  1723. if(ID == 13) //capitol
  1724. {
  1725. for(unsigned int in = 0; in < map->towns.size(); in++)
  1726. {
  1727. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1728. {
  1729. ret = 0; //no more than one capitol
  1730. break;
  1731. }
  1732. }
  1733. }
  1734. else if(ID == 6) //shipyard
  1735. {
  1736. int3 t1(t->pos + int3(-1,3,0)),
  1737. t2(t->pos + int3(-3,3,0));
  1738. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1739. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1740. ret = 1; //lack of water
  1741. }
  1742. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1743. ret = 4;
  1744. return ret;
  1745. }
  1746. void CGameState::apply(CPack *pack)
  1747. {
  1748. ui16 typ = typeList.getTypeID(pack);
  1749. applierGs->apps[typ]->applyOnGS(this,pack);
  1750. }
  1751. TeamState *CGameState::getTeam(ui8 teamID)
  1752. {
  1753. if(vstd::contains(teams,teamID))
  1754. {
  1755. return &teams[teamID];
  1756. }
  1757. else
  1758. {
  1759. tlog2 << "Warning: Cannot find info for team " << int(teamID) << std::endl;
  1760. return NULL;
  1761. }
  1762. }
  1763. TeamState *CGameState::getPlayerTeam(ui8 color)
  1764. {
  1765. PlayerState * ps = getPlayer(color);
  1766. if (ps)
  1767. return getTeam(ps->team);
  1768. return NULL;
  1769. }
  1770. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1771. {
  1772. if(vstd::contains(players,color))
  1773. {
  1774. return &players[color];
  1775. }
  1776. else
  1777. {
  1778. if(verbose)
  1779. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1780. return NULL;
  1781. }
  1782. }
  1783. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1784. {
  1785. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1786. }
  1787. const TeamState * CGameState::getTeam( ui8 teamID ) const
  1788. {
  1789. return (const_cast<CGameState *>(this))->getTeam(teamID);
  1790. }
  1791. const TeamState * CGameState::getPlayerTeam( ui8 teamID ) const
  1792. {
  1793. return (const_cast<CGameState *>(this))->getPlayerTeam(teamID);
  1794. }
  1795. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1796. {
  1797. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1798. return false;
  1799. int3 hpos = hero->getPosition(false);
  1800. bool flying = false; //hero is under flying effect TODO
  1801. bool waterWalking = false; //hero is on land and can walk on water TODO
  1802. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1803. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1804. //
  1805. // if (!hero->canWalkOnSea())
  1806. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1807. // else
  1808. // blockLandSea = boost::logic::indeterminate;
  1809. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  1810. //graph initialization
  1811. std::vector< std::vector<CPathNode> > graph;
  1812. graph.resize(map->width);
  1813. for(size_t i=0; i<graph.size(); ++i)
  1814. {
  1815. graph[i].resize(map->height);
  1816. for(size_t j=0; j<graph[i].size(); ++j)
  1817. {
  1818. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1819. CPathNode &node = graph[i][j];
  1820. node.accessible = !tinfo->blocked;
  1821. node.dist = -1;
  1822. node.theNodeBefore = NULL;
  1823. node.visited = false;
  1824. node.coord.x = i;
  1825. node.coord.y = j;
  1826. node.coord.z = dest.z;
  1827. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1828. || !FoW[i][j][src.z] //tile is covered by the FoW
  1829. )
  1830. {
  1831. node.accessible = false;
  1832. }
  1833. }
  1834. }
  1835. //Special rules for the destination tile
  1836. {
  1837. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1838. CPathNode &d = graph[dest.x][dest.y];
  1839. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1840. if(t->visitable)
  1841. {
  1842. d.accessible = true; //for allowing visiting objects
  1843. }
  1844. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1845. {
  1846. size_t i = 0;
  1847. for(; i < t->visitableObjects.size(); i++)
  1848. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1849. break;
  1850. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1851. }
  1852. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1853. {
  1854. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1855. }
  1856. }
  1857. //graph initialized
  1858. //initial tile - set cost on 0 and add to the queue
  1859. graph[src.x][src.y].dist = 0;
  1860. std::queue<CPathNode> mq;
  1861. mq.push(graph[src.x][src.y]);
  1862. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1863. std::vector<int3> neighbours;
  1864. neighbours.reserve(8);
  1865. while(!mq.empty())
  1866. {
  1867. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1868. mq.pop();
  1869. if (cp.coord == dest) //it's destination tile
  1870. {
  1871. if (cp.dist < curDist) //that path is better than previous one
  1872. curDist = cp.dist;
  1873. continue;
  1874. }
  1875. else
  1876. {
  1877. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1878. continue;
  1879. }
  1880. //add accessible neighbouring nodes to the queue
  1881. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate, true);
  1882. for(unsigned int i=0; i < neighbours.size(); i++)
  1883. {
  1884. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1885. if(dp.accessible)
  1886. {
  1887. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1888. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1889. {
  1890. dp.dist = cp.dist + cost;
  1891. dp.theNodeBefore = &cp;
  1892. mq.push(dp);
  1893. }
  1894. }
  1895. }
  1896. }
  1897. CPathNode *curNode = &graph[dest.x][dest.y];
  1898. if(!curNode->theNodeBefore) //destination is not accessible
  1899. return false;
  1900. //fill ret with found path
  1901. ret.nodes.clear();
  1902. while(curNode->coord != graph[src.x][src.y].coord)
  1903. {
  1904. ret.nodes.push_back(*curNode);
  1905. curNode = curNode->theNodeBefore;
  1906. }
  1907. ret.nodes.push_back(graph[src.x][src.y]);
  1908. return true;
  1909. }
  1910. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1911. {
  1912. assert(hero);
  1913. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1914. if(src.x < 0)
  1915. src = hero->getPosition(false);
  1916. if(movement < 0)
  1917. movement = hero->movement;
  1918. out.hero = hero;
  1919. out.hpos = src;
  1920. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1921. {
  1922. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1923. return;
  1924. }
  1925. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1926. if (!hero->canWalkOnSea())
  1927. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1928. else
  1929. onLand = boost::logic::indeterminate;
  1930. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  1931. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1932. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  1933. //graph initialization
  1934. CGPathNode ***graph = out.nodes;
  1935. for(size_t i=0; i < out.sizes.x; ++i)
  1936. {
  1937. for(size_t j=0; j < out.sizes.y; ++j)
  1938. {
  1939. for(size_t k=0; k < out.sizes.z; ++k)
  1940. {
  1941. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1942. CGPathNode &node = graph[i][j][k];
  1943. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  1944. if(!flying && node.accessible == CGPathNode::FLYABLE)
  1945. {
  1946. node.accessible = CGPathNode::BLOCKED;
  1947. }
  1948. node.turns = 0xff;
  1949. node.moveRemains = 0;
  1950. node.coord.x = i;
  1951. node.coord.y = j;
  1952. node.coord.z = k;
  1953. node.land = tinfo->tertype != TerrainTile::water;
  1954. node.theNodeBefore = NULL;
  1955. bool leaveAsBlocked = false;
  1956. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  1957. {
  1958. if (waterWalk || flying)
  1959. {
  1960. node.accessible = CGPathNode::FLYABLE;
  1961. }
  1962. else
  1963. {
  1964. node.accessible = CGPathNode::BLOCKED;
  1965. leaveAsBlocked = true;
  1966. }
  1967. }
  1968. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1969. || (!onLand && node.land) //it's land and we cannot walk on land (complementary condition is handled above)
  1970. || !FoW[i][j][k] //tile is covered by the FoW
  1971. || leaveAsBlocked
  1972. )
  1973. {
  1974. node.accessible = CGPathNode::BLOCKED;
  1975. }
  1976. else if(tinfo->visitable)
  1977. {
  1978. //hero is protected in Sanctuary
  1979. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner)
  1980. node.accessible = CGPathNode::BLOCKED;
  1981. else
  1982. {
  1983. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1984. {
  1985. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1986. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1987. {
  1988. node.accessible = CGPathNode::ACCESSIBLE;
  1989. }
  1990. else if(obj->blockVisit)
  1991. {
  1992. node.accessible = CGPathNode::BLOCKVIS;
  1993. break;
  1994. }
  1995. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1996. {
  1997. node.accessible = CGPathNode::VISITABLE;
  1998. }
  1999. }
  2000. }
  2001. }
  2002. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  2003. && tinfo->blockingObjects.size() == 0)
  2004. {
  2005. // Monster close by; blocked visit for battle.
  2006. node.accessible = CGPathNode::BLOCKVIS;
  2007. }
  2008. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2009. {
  2010. size_t i = 0;
  2011. for(; i < tinfo->visitableObjects.size(); i++)
  2012. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2013. break;
  2014. if(i < tinfo->visitableObjects.size())
  2015. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2016. }
  2017. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  2018. {
  2019. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2020. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2021. }
  2022. }
  2023. }
  2024. }
  2025. //graph initialized
  2026. //initial tile - set cost on 0 and add to the queue
  2027. graph[src.x][src.y][src.z].turns = 0;
  2028. graph[src.x][src.y][src.z].moveRemains = movement;
  2029. std::queue<CGPathNode*> mq;
  2030. mq.push(&graph[src.x][src.y][src.z]);
  2031. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2032. std::vector<int3> neighbours;
  2033. neighbours.reserve(8);
  2034. while(!mq.empty())
  2035. {
  2036. CGPathNode *cp = mq.front();
  2037. mq.pop();
  2038. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2039. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2040. const TerrainTile &ct = map->getTile(cp->coord);
  2041. int movement = cp->moveRemains, turn = cp->turns;
  2042. if(!movement)
  2043. {
  2044. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2045. turn++;
  2046. }
  2047. //add accessible neighbouring nodes to the queue
  2048. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate, !onLand);
  2049. for(unsigned int i=0; i < neighbours.size(); i++)
  2050. {
  2051. int moveAtNextTile = movement;
  2052. int turnAtNextTile = turn;
  2053. const int3 &n = neighbours[i]; //current neighbor
  2054. CGPathNode & dp = graph[n.x][n.y][n.z];
  2055. if( !checkForVisitableDir(cp->coord, dp.coord)
  2056. || !checkForVisitableDir(dp.coord, cp->coord)
  2057. || dp.accessible == CGPathNode::BLOCKED )
  2058. {
  2059. continue;
  2060. }
  2061. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2062. int remains = movement - cost;
  2063. if(remains < 0)
  2064. {
  2065. //occurs rarely, when hero with low movepoints tries to go leave the road
  2066. turnAtNextTile++;
  2067. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2068. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2069. remains = moveAtNextTile - cost;
  2070. }
  2071. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2072. if((dp.turns==0xff //we haven't been here before
  2073. || dp.turns > turnAtNextTile
  2074. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2075. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2076. {
  2077. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2078. dp.moveRemains = remains;
  2079. dp.turns = turnAtNextTile;
  2080. dp.theNodeBefore = cp;
  2081. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2082. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2083. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2084. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2085. {
  2086. mq.push(&dp);
  2087. }
  2088. }
  2089. } //neighbours loop
  2090. } //queue loop
  2091. }
  2092. /**
  2093. * Tells if the tile is guarded by a monster as well as the position
  2094. * of the monster that will attack on it.
  2095. *
  2096. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2097. * the monster guarding the tile.
  2098. */
  2099. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2100. {
  2101. const int3 originalPos = pos;
  2102. // Give monster at position priority.
  2103. if (!map->isInTheMap(pos))
  2104. return int3(-1, -1, -1);
  2105. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2106. if (posTile.visitable)
  2107. {
  2108. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2109. {
  2110. if(obj->blockVisit)
  2111. {
  2112. if (obj->ID == 54) // Monster
  2113. return pos;
  2114. else
  2115. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2116. }
  2117. }
  2118. }
  2119. // See if there are any monsters adjacent.
  2120. pos -= int3(1, 1, 0); // Start with top left.
  2121. for (int dx = 0; dx < 3; dx++)
  2122. {
  2123. for (int dy = 0; dy < 3; dy++)
  2124. {
  2125. if (map->isInTheMap(pos))
  2126. {
  2127. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2128. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  2129. {
  2130. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2131. {
  2132. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2133. {
  2134. return pos;
  2135. }
  2136. }
  2137. }
  2138. }
  2139. pos.y++;
  2140. }
  2141. pos.y -= 3;
  2142. pos.x++;
  2143. }
  2144. return int3(-1, -1, -1);
  2145. }
  2146. bool CGameState::isVisible(int3 pos, int player)
  2147. {
  2148. if(player == 255) //neutral player
  2149. return false;
  2150. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  2151. }
  2152. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2153. {
  2154. if(player == 255) //neutral player
  2155. return false;
  2156. //object is visible when at least one blocked tile is visible
  2157. for(int fx=0; fx<8; ++fx)
  2158. {
  2159. for(int fy=0; fy<6; ++fy)
  2160. {
  2161. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2162. if(map->isInTheMap(pos)
  2163. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2164. && isVisible(pos, player) )
  2165. return true;
  2166. }
  2167. }
  2168. return false;
  2169. }
  2170. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2171. {
  2172. const TerrainTile * pom = &map->getTile(dst);
  2173. return checkForVisitableDir(src, pom, dst);
  2174. }
  2175. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2176. {
  2177. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2178. {
  2179. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2180. continue;
  2181. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2182. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2183. {
  2184. return false;
  2185. }
  2186. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2187. {
  2188. return false;
  2189. }
  2190. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2191. {
  2192. return false;
  2193. }
  2194. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2195. {
  2196. return false;
  2197. }
  2198. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2199. {
  2200. return false;
  2201. }
  2202. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2203. {
  2204. return false;
  2205. }
  2206. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2207. {
  2208. return false;
  2209. }
  2210. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2211. {
  2212. return false;
  2213. }
  2214. }
  2215. return true;
  2216. }
  2217. int CGameState::victoryCheck( ui8 player ) const
  2218. {
  2219. const PlayerState *p = getPlayer(player);
  2220. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2221. if(player == checkForStandardWin())
  2222. return -1;
  2223. if (p->enteredWinningCheatCode)
  2224. { //cheater or tester, but has entered the code...
  2225. return 1;
  2226. }
  2227. if(p->human || map->victoryCondition.appliesToAI)
  2228. {
  2229. switch(map->victoryCondition.condition)
  2230. {
  2231. case artifact:
  2232. //check if any hero has winning artifact
  2233. for(size_t i = 0; i < p->heroes.size(); i++)
  2234. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2235. return 1;
  2236. break;
  2237. case gatherTroop:
  2238. {
  2239. //check if in players armies there is enough creatures
  2240. int total = 0; //creature counter
  2241. for(size_t i = 0; i < map->objects.size(); i++)
  2242. {
  2243. const CArmedInstance *ai = NULL;
  2244. if(map->objects[i]
  2245. && map->objects[i]->tempOwner == player //object controlled by player
  2246. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  2247. {
  2248. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2249. if(i->second->type->idNumber == map->victoryCondition.ID) //it's searched creature
  2250. total += i->second->count;
  2251. }
  2252. }
  2253. if(total >= map->victoryCondition.count)
  2254. return 1;
  2255. }
  2256. break;
  2257. case gatherResource:
  2258. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2259. return 1;
  2260. break;
  2261. case buildCity:
  2262. {
  2263. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2264. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2265. return 1;
  2266. }
  2267. break;
  2268. case buildGrail:
  2269. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  2270. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2271. && t->tempOwner == player
  2272. && vstd::contains(t->builtBuildings, 26))
  2273. return 1;
  2274. break;
  2275. case beatHero:
  2276. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2277. return 1;
  2278. break;
  2279. case captureCity:
  2280. {
  2281. if(map->victoryCondition.obj->tempOwner == player)
  2282. return 1;
  2283. }
  2284. break;
  2285. case beatMonster:
  2286. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2287. return 1;
  2288. break;
  2289. case takeDwellings:
  2290. for(size_t i = 0; i < map->objects.size(); i++)
  2291. {
  2292. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2293. {
  2294. switch(map->objects[i]->ID)
  2295. {
  2296. case 17: case 18: case 19: case 20: //dwellings
  2297. case 216: case 217: case 218:
  2298. return 0; //found not flagged dwelling - player not won
  2299. }
  2300. }
  2301. }
  2302. return 1;
  2303. break;
  2304. case takeMines:
  2305. for(size_t i = 0; i < map->objects.size(); i++)
  2306. {
  2307. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2308. {
  2309. switch(map->objects[i]->ID)
  2310. {
  2311. case 53: case 220:
  2312. return 0; //found not flagged mine - player not won
  2313. }
  2314. }
  2315. }
  2316. return 1;
  2317. break;
  2318. case transportItem:
  2319. {
  2320. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2321. if((t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID))
  2322. || (t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID)))
  2323. {
  2324. return 1;
  2325. }
  2326. }
  2327. break;
  2328. }
  2329. }
  2330. return 0;
  2331. }
  2332. ui8 CGameState::checkForStandardWin() const
  2333. {
  2334. //std victory condition is:
  2335. //all enemies lost
  2336. ui8 supposedWinner = 255, winnerTeam = 255;
  2337. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2338. {
  2339. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2340. {
  2341. if(supposedWinner == 255)
  2342. {
  2343. //first player remaining ingame - candidate for victory
  2344. supposedWinner = i->second.color;
  2345. winnerTeam = i->second.team;
  2346. }
  2347. else if(winnerTeam != i->second.team)
  2348. {
  2349. //current candidate has enemy remaining in game -> no vicotry
  2350. return 255;
  2351. }
  2352. }
  2353. }
  2354. return supposedWinner;
  2355. }
  2356. bool CGameState::checkForStandardLoss( ui8 player ) const
  2357. {
  2358. //std loss condition is: player lost all towns and heroes
  2359. const PlayerState &p = *getPlayer(player);
  2360. return !p.heroes.size() && !p.towns.size();
  2361. }
  2362. struct statsHLP
  2363. {
  2364. typedef std::pair< ui8, si64 > TStat;
  2365. //converts [<player's color, value>] to vec[place] -> platers
  2366. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2367. {
  2368. std::sort(stats.begin(), stats.end(), statsHLP());
  2369. //put first element
  2370. std::vector< std::list<ui8> > ret;
  2371. std::list<ui8> tmp;
  2372. tmp.push_back( stats[0].first );
  2373. ret.push_back( tmp );
  2374. //the rest of elements
  2375. for(int g=1; g<stats.size(); ++g)
  2376. {
  2377. if(stats[g].second == stats[g-1].second)
  2378. {
  2379. (ret.end()-1)->push_back( stats[g].first );
  2380. }
  2381. else
  2382. {
  2383. //create next occupied rank
  2384. std::list<ui8> tmp;
  2385. tmp.push_back(stats[g].first);
  2386. ret.push_back(tmp);
  2387. }
  2388. }
  2389. return ret;
  2390. }
  2391. bool operator()(const TStat & a, const TStat & b) const
  2392. {
  2393. return a.second > b.second;
  2394. }
  2395. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2396. {
  2397. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2398. if(!h.size())
  2399. return NULL;
  2400. //best hero will be that with highest exp
  2401. int best = 0;
  2402. for(int b=1; b<h.size(); ++b)
  2403. {
  2404. if(h[b]->exp > h[best]->exp)
  2405. {
  2406. best = b;
  2407. }
  2408. }
  2409. return h[best];
  2410. }
  2411. //calculates total number of artifacts that belong to given player
  2412. static int getNumberOfArts(const PlayerState * ps)
  2413. {
  2414. int ret = 0;
  2415. for(int g=0; g<ps->heroes.size(); ++g)
  2416. {
  2417. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2418. }
  2419. return ret;
  2420. }
  2421. };
  2422. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2423. {
  2424. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2425. { \
  2426. std::vector< std::pair< ui8, si64 > > stats; \
  2427. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2428. { \
  2429. if(g->second.color == 255) \
  2430. continue; \
  2431. std::pair< ui8, si64 > stat; \
  2432. stat.first = g->second.color; \
  2433. stat.second = VAL_GETTER; \
  2434. stats.push_back(stat); \
  2435. } \
  2436. tgi.FIELD = statsHLP::getRank(stats); \
  2437. }
  2438. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2439. {
  2440. if(g->second.color != 255)
  2441. tgi.playerColors.push_back(g->second.color);
  2442. }
  2443. if(level >= 1) //num of towns & num of heroes
  2444. {
  2445. //num of towns
  2446. FILL_FIELD(numOfTowns, g->second.towns.size())
  2447. //num of heroes
  2448. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2449. //best hero's portrait
  2450. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2451. {
  2452. if(g->second.color == 255)
  2453. continue;
  2454. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2455. InfoAboutHero iah;
  2456. iah.initFromHero(best, level >= 8);
  2457. iah.army.clear();
  2458. tgi.colorToBestHero[g->second.color] = iah;
  2459. }
  2460. }
  2461. if(level >= 2) //gold
  2462. {
  2463. FILL_FIELD(gold, g->second.resources[6])
  2464. }
  2465. if(level >= 2) //wood & ore
  2466. {
  2467. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2468. }
  2469. if(level >= 3) //mercury, sulfur, crystal, gems
  2470. {
  2471. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2472. }
  2473. if(level >= 4) //obelisks found
  2474. {
  2475. //TODO
  2476. }
  2477. if(level >= 5) //artifacts
  2478. {
  2479. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2480. }
  2481. if(level >= 6) //army strength
  2482. {
  2483. //TODO
  2484. }
  2485. if(level >= 7) //income
  2486. {
  2487. //TODO
  2488. }
  2489. if(level >= 8) //best hero's stats
  2490. {
  2491. //already set in lvl 1 handling
  2492. }
  2493. if(level >= 9) //personality
  2494. {
  2495. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2496. {
  2497. if(g->second.color == 255) //do nothing for neutral player
  2498. continue;
  2499. if(g->second.human)
  2500. {
  2501. tgi.personality[g->second.color] = -1;
  2502. }
  2503. else //AI
  2504. {
  2505. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  2506. }
  2507. }
  2508. }
  2509. if(level >= 10) //best creature
  2510. {
  2511. //best creatures belonging to player (highest AI value)
  2512. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2513. {
  2514. if(g->second.color == 255) //do nothing for neutral player
  2515. continue;
  2516. int bestCre = -1; //best creature's ID
  2517. for(int b=0; b<g->second.heroes.size(); ++b)
  2518. {
  2519. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  2520. {
  2521. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2522. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2523. {
  2524. bestCre = toCmp;
  2525. }
  2526. }
  2527. }
  2528. tgi.bestCreature[g->second.color] = bestCre;
  2529. }
  2530. }
  2531. #undef FILL_FIELD
  2532. }
  2533. int CGameState::lossCheck( ui8 player ) const
  2534. {
  2535. const PlayerState *p = getPlayer(player);
  2536. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2537. if(checkForStandardLoss(player))
  2538. return -1;
  2539. if (p->enteredLosingCheatCode)
  2540. {
  2541. return 1;
  2542. }
  2543. if(p->human) //special loss condition applies only to human player
  2544. {
  2545. switch(map->lossCondition.typeOfLossCon)
  2546. {
  2547. case lossCastle:
  2548. {
  2549. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  2550. assert(t);
  2551. if(t->tempOwner != player)
  2552. return 1;
  2553. }
  2554. break;
  2555. case lossHero:
  2556. {
  2557. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  2558. assert(h);
  2559. if(h->tempOwner != player)
  2560. return 1;
  2561. }
  2562. break;
  2563. case timeExpires:
  2564. if(map->lossCondition.timeLimit < day)
  2565. return 1;
  2566. break;
  2567. }
  2568. }
  2569. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  2570. return 2;
  2571. return false;
  2572. }
  2573. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2574. {
  2575. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2576. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  2577. for(std::vector< ConstTransitivePtr<CGHeroInstance> >::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2578. if(*j)
  2579. pool.erase((**j).subID);
  2580. return pool;
  2581. }
  2582. void CGameState::buildGameLogicTree()
  2583. {
  2584. }
  2585. int3 CPath::startPos() const
  2586. {
  2587. return nodes[nodes.size()-1].coord;
  2588. }
  2589. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2590. {
  2591. if (mode==0)
  2592. {
  2593. for (unsigned int i=0;i<nodes.size();i++)
  2594. {
  2595. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2596. }
  2597. }
  2598. }
  2599. int3 CPath::endPos() const
  2600. {
  2601. return nodes[0].coord;
  2602. }
  2603. CGPathNode::CGPathNode()
  2604. :coord(-1,-1,-1)
  2605. {
  2606. accessible = 0;
  2607. land = 0;
  2608. moveRemains = 0;
  2609. turns = 255;
  2610. theNodeBefore = NULL;
  2611. }
  2612. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2613. {
  2614. out.nodes.clear();
  2615. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2616. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  2617. return false;
  2618. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  2619. bool transition01 = false;
  2620. while(curnode)
  2621. {
  2622. CGPathNode cpn = *curnode;
  2623. if(transition01)
  2624. {
  2625. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  2626. {
  2627. transition01 = false;
  2628. }
  2629. else if (curnode->accessible == CGPathNode::FLYABLE)
  2630. {
  2631. cpn.turns = 1;
  2632. }
  2633. }
  2634. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  2635. {
  2636. transition01 = true;
  2637. }
  2638. curnode = curnode->theNodeBefore;
  2639. out.nodes.push_back(cpn);
  2640. }
  2641. return true;
  2642. }
  2643. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2644. :sizes(Sizes)
  2645. {
  2646. hero = NULL;
  2647. nodes = new CGPathNode**[sizes.x];
  2648. for(int i = 0; i < sizes.x; i++)
  2649. {
  2650. nodes[i] = new CGPathNode*[sizes.y];
  2651. for (int j = 0; j < sizes.y; j++)
  2652. {
  2653. nodes[i][j] = new CGPathNode[sizes.z];
  2654. }
  2655. }
  2656. }
  2657. CPathsInfo::~CPathsInfo()
  2658. {
  2659. for(int i = 0; i < sizes.x; i++)
  2660. {
  2661. for (int j = 0; j < sizes.y; j++)
  2662. {
  2663. delete [] nodes[i][j];
  2664. }
  2665. delete [] nodes[i];
  2666. }
  2667. delete [] nodes;
  2668. }
  2669. int3 CGPath::startPos() const
  2670. {
  2671. return nodes[nodes.size()-1].coord;
  2672. }
  2673. int3 CGPath::endPos() const
  2674. {
  2675. return nodes[0].coord;
  2676. }
  2677. void CGPath::convert( ui8 mode )
  2678. {
  2679. if(mode==0)
  2680. {
  2681. for(unsigned int i=0;i<nodes.size();i++)
  2682. {
  2683. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2684. }
  2685. }
  2686. }
  2687. PlayerState::PlayerState()
  2688. : color(-1), currentSelection(0xffffffff), enteredWinningCheatCode(0),
  2689. enteredLosingCheatCode(0), status(INGAME), daysWithoutCastle(0)
  2690. {
  2691. }
  2692. std::string PlayerState::nodeName() const
  2693. {
  2694. return "Player " + (color < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color] : boost::lexical_cast<std::string>(color));
  2695. }
  2696. // void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  2697. // {
  2698. // return; //no loops possible
  2699. // }
  2700. //
  2701. // void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  2702. // {
  2703. // for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); it++)
  2704. // {
  2705. // if (*it != root)
  2706. // (*it)->getBonuses(out, selector, this);
  2707. // }
  2708. // }
  2709. InfoAboutHero::InfoAboutHero()
  2710. {
  2711. details = NULL;
  2712. hclass = NULL;
  2713. portrait = -1;
  2714. }
  2715. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  2716. {
  2717. assign(iah);
  2718. }
  2719. InfoAboutHero::~InfoAboutHero()
  2720. {
  2721. delete details;
  2722. }
  2723. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  2724. {
  2725. if(!h) return;
  2726. owner = h->tempOwner;
  2727. hclass = h->type->heroClass;
  2728. name = h->name;
  2729. portrait = h->portrait;
  2730. army = ArmyDescriptor(h, detailed);
  2731. if(detailed)
  2732. {
  2733. //include details about hero
  2734. details = new Details;
  2735. details->luck = h->LuckVal();
  2736. details->morale = h->MoraleVal();
  2737. details->mana = h->mana;
  2738. details->primskills.resize(PRIMARY_SKILLS);
  2739. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  2740. {
  2741. details->primskills[i] = h->getPrimSkillLevel(i);
  2742. }
  2743. }
  2744. }
  2745. void InfoAboutHero::assign( const InfoAboutHero & iah )
  2746. {
  2747. army = iah.army;
  2748. details = (iah.details ? new Details(*iah.details) : NULL);
  2749. hclass = iah.hclass;
  2750. name = iah.name;
  2751. owner = iah.owner;
  2752. portrait = iah.portrait;
  2753. }
  2754. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  2755. {
  2756. assign(iah);
  2757. return *this;
  2758. }
  2759. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2760. {
  2761. for(TSlots::const_iterator i = army->Slots().begin(); i != army->Slots().end(); i++)
  2762. {
  2763. if(detailed)
  2764. (*this)[i->first] = *i->second;
  2765. else
  2766. (*this)[i->first] = CStackBasicDescriptor(i->second->type, i->second->getQuantityID());
  2767. }
  2768. }
  2769. ArmyDescriptor::ArmyDescriptor()
  2770. {
  2771. }