CGameState.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include <boost/assign/list_of.hpp>
  26. #include "RegisterTypes.cpp"
  27. boost::rand48 ran;
  28. #ifdef min
  29. #undef min
  30. #endif
  31. #ifdef max
  32. #undef max
  33. #endif
  34. /*
  35. * CGameState.cpp, part of VCMI engine
  36. *
  37. * Authors: listed in file AUTHORS in main folder
  38. *
  39. * License: GNU General Public License v2.0 or later
  40. * Full text of license available in license.txt file, in main folder
  41. *
  42. */
  43. void foofoofoo()
  44. {
  45. //never called function to force instantation of templates
  46. int *ccc = NULL;
  47. registerTypes((CISer<CConnection>&)*ccc);
  48. registerTypes((COSer<CConnection>&)*ccc);
  49. registerTypes((CSaveFile&)*ccc);
  50. registerTypes((CLoadFile&)*ccc);
  51. registerTypes((CTypeList&)*ccc);
  52. }
  53. class CBaseForGSApply
  54. {
  55. public:
  56. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  57. virtual ~CBaseForGSApply(){};
  58. };
  59. template <typename T> class CApplyOnGS : public CBaseForGSApply
  60. {
  61. public:
  62. void applyOnGS(CGameState *gs, void *pack) const
  63. {
  64. T *ptr = static_cast<T*>(pack);
  65. while(!gs->mx->try_lock())
  66. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  67. ptr->applyGs(gs);
  68. gs->mx->unlock();
  69. }
  70. };
  71. class CGSApplier
  72. {
  73. public:
  74. std::map<ui16,CBaseForGSApply*> apps;
  75. CGSApplier()
  76. {
  77. registerTypes2(*this);
  78. }
  79. ~CGSApplier()
  80. {
  81. std::map<ui16,CBaseForGSApply*>::iterator iter;
  82. for(iter = apps.begin(); iter != apps.end(); iter++)
  83. delete iter->second;
  84. }
  85. template<typename T> void registerType(const T * t=NULL)
  86. {
  87. ui16 ID = typeList.registerType(t);
  88. apps[ID] = new CApplyOnGS<T>;
  89. }
  90. } *applierGs = NULL;
  91. class IObjectCaller
  92. {
  93. public:
  94. virtual void preInit()=0;
  95. virtual void postInit()=0;
  96. };
  97. template <typename T>
  98. class CObjectCaller : public IObjectCaller
  99. {
  100. public:
  101. void preInit()
  102. {
  103. T::preInit();
  104. }
  105. void postInit()
  106. {
  107. T::postInit();
  108. }
  109. };
  110. class CObjectCallersHandler
  111. {
  112. public:
  113. std::vector<IObjectCaller*> apps;
  114. template<typename T> void registerType(const T * t=NULL)
  115. {
  116. apps.push_back(new CObjectCaller<T>);
  117. }
  118. CObjectCallersHandler()
  119. {
  120. registerTypes1(*this);
  121. }
  122. ~CObjectCallersHandler()
  123. {
  124. for (size_t i = 0; i < apps.size(); i++)
  125. delete apps[i];
  126. }
  127. void preInit()
  128. {
  129. for (size_t i = 0; i < apps.size(); i++)
  130. apps[i]->preInit();
  131. }
  132. void postInit()
  133. {
  134. for (size_t i = 0; i < apps.size(); i++)
  135. apps[i]->postInit();
  136. }
  137. } *objCaller = NULL;
  138. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  139. {
  140. int type = txt.first, ser = txt.second;
  141. if(type == ART_NAMES)
  142. {
  143. dst = VLC->arth->artifacts[ser].Name();
  144. }
  145. else if(type == CRE_PL_NAMES)
  146. {
  147. dst = VLC->creh->creatures[ser].namePl;
  148. }
  149. else if(type == MINE_NAMES)
  150. {
  151. dst = VLC->generaltexth->mines[ser].first;
  152. }
  153. else if(type == MINE_EVNTS)
  154. {
  155. dst = VLC->generaltexth->mines[ser].second;
  156. }
  157. else if(type == SPELL_NAME)
  158. {
  159. dst = VLC->spellh->spells[ser].name;
  160. }
  161. else if(type == CRE_SING_NAMES)
  162. {
  163. dst = VLC->creh->creatures[ser].nameSing;
  164. }
  165. else
  166. {
  167. std::vector<std::string> *vec;
  168. switch(type)
  169. {
  170. case GENERAL_TXT:
  171. vec = &VLC->generaltexth->allTexts;
  172. break;
  173. case XTRAINFO_TXT:
  174. vec = &VLC->generaltexth->xtrainfo;
  175. break;
  176. case OBJ_NAMES:
  177. vec = &VLC->generaltexth->names;
  178. break;
  179. case RES_NAMES:
  180. vec = &VLC->generaltexth->restypes;
  181. break;
  182. case ARRAY_TXT:
  183. vec = &VLC->generaltexth->arraytxt;
  184. break;
  185. case CREGENS:
  186. vec = &VLC->generaltexth->creGens;
  187. break;
  188. case CREGENS4:
  189. vec = &VLC->generaltexth->creGens4;
  190. break;
  191. case ADVOB_TXT:
  192. vec = &VLC->generaltexth->advobtxt;
  193. break;
  194. case ART_EVNTS:
  195. vec = &VLC->generaltexth->artifEvents;
  196. break;
  197. case SEC_SKILL_NAME:
  198. vec = &VLC->generaltexth->skillName;
  199. break;
  200. case COLOR:
  201. vec = &VLC->generaltexth->capColors;
  202. break;
  203. }
  204. dst = (*vec)[ser];
  205. }
  206. }
  207. DLL_EXPORT void MetaString::toString(std::string &dst) const
  208. {
  209. size_t exSt = 0, loSt = 0, nums = 0;
  210. dst.clear();
  211. for(size_t i=0;i<message.size();++i)
  212. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  213. switch(message[i])
  214. {
  215. case TEXACT_STRING:
  216. dst += exactStrings[exSt++];
  217. break;
  218. case TLOCAL_STRING:
  219. {
  220. std::string hlp;
  221. getLocalString(localStrings[loSt++], hlp);
  222. dst += hlp;
  223. }
  224. break;
  225. case TNUMBER:
  226. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  227. break;
  228. case TREPLACE_ESTRING:
  229. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  230. break;
  231. case TREPLACE_LSTRING:
  232. {
  233. std::string hlp;
  234. getLocalString(localStrings[loSt++], hlp);
  235. dst.replace (dst.find("%s"), 2, hlp);
  236. }
  237. break;
  238. case TREPLACE_NUMBER:
  239. dst.replace (dst.find("%d"), 2, 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::buildList () const
  248. ///used to handle loot from creature bank
  249. {
  250. size_t exSt = 0, loSt = 0, nums = 0;
  251. std::string lista;
  252. for (int i = 0; i < message.size(); ++i)
  253. {
  254. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  255. {
  256. if (exSt == exactStrings.size() - 1)
  257. lista += VLC->generaltexth->allTexts[141]; //" and "
  258. else
  259. lista += ", ";
  260. }
  261. switch (message[i])
  262. {
  263. case TEXACT_STRING:
  264. lista += exactStrings[exSt++];
  265. break;
  266. case TLOCAL_STRING:
  267. {
  268. std::string hlp;
  269. getLocalString (localStrings[loSt++], hlp);
  270. lista += hlp;
  271. }
  272. break;
  273. case TNUMBER:
  274. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  275. break;
  276. case TREPLACE_ESTRING:
  277. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  278. break;
  279. case TREPLACE_LSTRING:
  280. {
  281. std::string hlp;
  282. getLocalString (localStrings[loSt++], hlp);
  283. lista.replace (lista.find("%s"), 2, hlp);
  284. }
  285. break;
  286. case TREPLACE_NUMBER:
  287. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  288. break;
  289. default:
  290. tlog1 << "MetaString processing error!\n";
  291. }
  292. }
  293. return lista;
  294. }
  295. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  296. {
  297. CGObjectInstance * nobj;
  298. switch(id)
  299. {
  300. case HEROI_TYPE: //hero
  301. {
  302. CGHeroInstance * nobj = new CGHeroInstance();
  303. nobj->pos = pos;
  304. nobj->tempOwner = owner;
  305. nobj->subID = subid;
  306. //nobj->initHero(ran);
  307. return nobj;
  308. }
  309. case TOWNI_TYPE: //town
  310. nobj = new CGTownInstance;
  311. break;
  312. default: //rest of objects
  313. nobj = new CGObjectInstance;
  314. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  315. break;
  316. }
  317. nobj->ID = id;
  318. nobj->subID = subid;
  319. if(!nobj->defInfo)
  320. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  321. nobj->pos = pos;
  322. //nobj->state = NULL;//new CLuaObjectScript();
  323. nobj->tempOwner = owner;
  324. nobj->info = NULL;
  325. nobj->defInfo->id = id;
  326. nobj->defInfo->subid = subid;
  327. //assigning defhandler
  328. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  329. return nobj;
  330. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  331. return nobj;
  332. }
  333. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  334. {
  335. for(unsigned int g=0; g<stacks.size(); ++g)
  336. {
  337. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  338. return stacks[g];
  339. }
  340. return NULL;
  341. }
  342. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  343. {
  344. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  345. }
  346. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  347. {
  348. for(unsigned int g=0; g<stacks.size(); ++g)
  349. {
  350. if(stacks[g]->position == tileID
  351. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  352. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  353. {
  354. if(!onlyAlive || stacks[g]->alive())
  355. {
  356. return stacks[g];
  357. }
  358. }
  359. }
  360. return NULL;
  361. }
  362. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  363. {
  364. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  365. }
  366. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  367. {
  368. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  369. //removing accessibility for side columns of hexes
  370. for(int v = 0; v < BFIELD_SIZE; ++v)
  371. {
  372. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  373. accessibility[v] = false;
  374. }
  375. for(unsigned int g=0; g<stacks.size(); ++g)
  376. {
  377. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  378. continue;
  379. accessibility[stacks[g]->position] = false;
  380. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  381. {
  382. if(stacks[g]->attackerOwned)
  383. accessibility[stacks[g]->position-1] = false;
  384. else
  385. accessibility[stacks[g]->position+1] = false;
  386. }
  387. }
  388. //obstacles
  389. for(unsigned int b=0; b<obstacles.size(); ++b)
  390. {
  391. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  392. for(unsigned int c=0; c<blocked.size(); ++c)
  393. {
  394. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  395. accessibility[blocked[c]] = false;
  396. }
  397. }
  398. //walls
  399. if(siege > 0)
  400. {
  401. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  402. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  403. {
  404. accessibility[permanentlyLocked[b]] = false;
  405. }
  406. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  407. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  408. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  409. {
  410. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  411. {
  412. accessibility[lockedIfNotDestroyed[b].second] = false;
  413. }
  414. }
  415. //gate
  416. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  417. {
  418. accessibility[95] = accessibility[96] = false; //block gate's hexes
  419. }
  420. }
  421. //occupyability
  422. if(addOccupiable && twoHex)
  423. {
  424. std::set<int> rem; //tiles to unlock
  425. for(int h=0; h<BFIELD_HEIGHT; ++h)
  426. {
  427. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  428. {
  429. int hex = h * BFIELD_WIDTH + w;
  430. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  431. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  432. )
  433. rem.insert(hex);
  434. }
  435. }
  436. occupyable = rem;
  437. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  438. {
  439. accessibility[*it] = true;
  440. }*/
  441. }
  442. }
  443. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  444. {
  445. if(flying && !lastPos)
  446. return true;
  447. if(twoHex)
  448. {
  449. //if given hex is accessible and appropriate adjacent one is free too
  450. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  451. }
  452. else
  453. {
  454. return accessibility[hex];
  455. }
  456. }
  457. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  458. {
  459. //inits
  460. for(int b=0; b<BFIELD_SIZE; ++b)
  461. predecessor[b] = -1;
  462. for(int g=0; g<BFIELD_SIZE; ++g)
  463. dists[g] = 100000000;
  464. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  465. hexq.push(std::make_pair(start, true));
  466. dists[hexq.front().first] = 0;
  467. int curNext = -1; //for bfs loop only (helper var)
  468. while(!hexq.empty()) //bfs loop
  469. {
  470. std::pair<int, bool> curHex = hexq.front();
  471. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  472. hexq.pop();
  473. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  474. {
  475. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  476. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  477. if( dists[curHex.first]+1 >= dists[curNext] )
  478. continue;
  479. if(accessible && curHex.second)
  480. {
  481. hexq.push(std::make_pair(curNext, true));
  482. dists[curNext] = dists[curHex.first] + 1;
  483. }
  484. else if(fillPredecessors && !(accessible && !curHex.second))
  485. {
  486. hexq.push(std::make_pair(curNext, false));
  487. dists[curNext] = dists[curHex.first] + 1;
  488. }
  489. predecessor[curNext] = curHex.first;
  490. }
  491. }
  492. };
  493. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  494. {
  495. std::vector<int> ret;
  496. bool ac[BFIELD_SIZE];
  497. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  498. if(s->position < 0) //turrets
  499. return std::vector<int>();
  500. std::set<int> occupyable;
  501. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  502. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  503. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), false);
  504. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  505. {
  506. if(!addOccupiable)
  507. {
  508. std::vector<int> rem;
  509. for(int b=0; b<BFIELD_SIZE; ++b)
  510. {
  511. //don't take into account most left and most right columns of hexes
  512. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  513. continue;
  514. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  515. {
  516. rem.push_back(b);
  517. }
  518. }
  519. for(unsigned int g=0; g<rem.size(); ++g)
  520. {
  521. ac[rem[g]] = false;
  522. }
  523. //removing accessibility for side hexes
  524. for(int v=0; v<BFIELD_SIZE; ++v)
  525. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  526. ac[v] = false;
  527. }
  528. }
  529. for (int i=0; i < BFIELD_SIZE ; ++i) {
  530. if(
  531. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  532. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  533. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  534. )
  535. {
  536. ret.push_back(i);
  537. }
  538. }
  539. return ret;
  540. }
  541. bool BattleInfo::isStackBlocked(int ID)
  542. {
  543. CStack *our = getStack(ID);
  544. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  545. return false;
  546. for(unsigned int i=0; i<stacks.size();i++)
  547. {
  548. if( !stacks[i]->alive()
  549. || stacks[i]->owner==our->owner
  550. )
  551. continue; //we omit dead and allied stacks
  552. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  553. {
  554. if( mutualPosition(stacks[i]->position, our->position) >= 0
  555. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  556. return true;
  557. }
  558. else
  559. {
  560. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  561. return true;
  562. }
  563. }
  564. return false;
  565. }
  566. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  567. {
  568. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  569. return 0;
  570. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  571. return 1;
  572. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  573. return 5;
  574. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  575. return 2;
  576. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  577. return 4;
  578. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  579. return 3;
  580. return -1;
  581. }
  582. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  583. {
  584. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  585. std::vector<int> ret;
  586. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  587. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  588. CHECK_AND_PUSH(hex - 1);
  589. CHECK_AND_PUSH(hex + 1);
  590. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  591. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  592. #undef CHECK_AND_PUSH
  593. return ret;
  594. }
  595. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  596. {
  597. int predecessor[BFIELD_SIZE]; //for getting the Path
  598. int dist[BFIELD_SIZE]; //calculated distances
  599. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  600. if(predecessor[dest] == -1) //cannot reach destination
  601. {
  602. return std::make_pair(std::vector<int>(), 0);
  603. }
  604. //making the Path
  605. std::vector<int> path;
  606. int curElem = dest;
  607. while(curElem != start)
  608. {
  609. path.push_back(curElem);
  610. curElem = predecessor[curElem];
  611. }
  612. return std::make_pair(path, dist[dest]);
  613. }
  614. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype, int turn) const
  615. {
  616. int ret = 0;
  617. if(subtype == -1024) //any subtype
  618. {
  619. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  620. if(i->type == type && (!turn || i->turnsRemain > turn))
  621. ret += i->value;
  622. }
  623. else //given subtype
  624. {
  625. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  626. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  627. ret += i->value;
  628. }
  629. return ret;
  630. }
  631. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype, int turn) const
  632. {
  633. if(subtype == -1024) //any subtype
  634. {
  635. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  636. if(i->type == type && (!turn || i->turnsRemain > turn))
  637. return true;
  638. }
  639. else //given subtype
  640. {
  641. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  642. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  643. return true;
  644. }
  645. return false;
  646. }
  647. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  648. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  649. counterAttacks(1), shots(C->shots), features(C->abilities)
  650. {
  651. //additional retaliations
  652. for(int h=0; h<C->abilities.size(); ++h)
  653. {
  654. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  655. {
  656. counterAttacks += C->abilities[h].value;
  657. }
  658. }
  659. //alive state indication
  660. state.insert(ALIVE);
  661. }
  662. ui32 CStack::Speed( int turn /*= 0*/ ) const
  663. {
  664. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON, -1024, turn)) //war machnes cannot move
  665. return 0;
  666. int speed = creature->speed;
  667. speed += valOfFeatures(StackFeature::SPEED_BONUS, -1024, turn);
  668. int percentBonus = 0;
  669. for(int g=0; g<features.size(); ++g)
  670. {
  671. if(features[g].type == StackFeature::SPEED_BONUS)
  672. {
  673. percentBonus += features[g].additionalInfo;
  674. }
  675. }
  676. speed = ((100 + percentBonus) * speed)/100;
  677. //bind effect check
  678. if(getEffect(72))
  679. {
  680. return 0;
  681. }
  682. return speed;
  683. }
  684. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  685. {
  686. for (unsigned int i=0; i< effects.size(); i++)
  687. if(effects[i].id == id)
  688. if(!turn || effects[i].turnsRemain > turn)
  689. return &effects[i];
  690. return NULL;
  691. }
  692. ui8 CStack::howManyEffectsSet(ui16 id) const
  693. {
  694. ui8 ret = 0;
  695. for (unsigned int i=0; i< effects.size(); i++)
  696. if(effects[i].id == id) //effect found
  697. {
  698. ++ret;
  699. }
  700. return ret;
  701. }
  702. si8 CStack::Morale() const
  703. {
  704. si8 ret = morale;
  705. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  706. return 0;
  707. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  708. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  709. {
  710. ret = std::max<si8>(ret, +1);
  711. }
  712. if(ret > 3) ret = 3;
  713. if(ret < -3) ret = -3;
  714. return ret;
  715. }
  716. si8 CStack::Luck() const
  717. {
  718. si8 ret = luck;
  719. if(hasFeatureOfType(StackFeature::NO_LUCK))
  720. return 0;
  721. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  722. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  723. {
  724. ret = std::max<si8>(ret, +1);
  725. }
  726. if(ret > 3) ret = 3;
  727. if(ret < -3) ret = -3;
  728. return ret;
  729. }
  730. si32 CStack::Attack() const
  731. {
  732. si32 ret = creature->attack; //value to be returned
  733. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  734. {
  735. ret += si32(VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  736. }
  737. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  738. return ret;
  739. }
  740. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  741. {
  742. si32 ret = creature->defence;
  743. if(withFrenzy && getEffect(56)) //frenzy for defender
  744. {
  745. return 0;
  746. }
  747. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  748. return ret;
  749. }
  750. ui16 CStack::MaxHealth() const
  751. {
  752. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  753. }
  754. bool CStack::willMove(int turn /*= 0*/) const
  755. {
  756. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  757. && !moved(turn)
  758. && canMove(turn);
  759. }
  760. bool CStack::canMove( int turn /*= 0*/ ) const
  761. {
  762. return alive()
  763. && !hasFeatureOfType(StackFeature::NOT_ACTIVE, -1024, turn); //eg. Ammo Cart
  764. }
  765. bool CStack::moved( int turn /*= 0*/ ) const
  766. {
  767. if(!turn)
  768. return vstd::contains(state, MOVED);
  769. else
  770. return false;
  771. }
  772. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  773. {
  774. CGHeroInstance *ret = NULL;
  775. if(player<0 || player>=PLAYER_LIMIT)
  776. {
  777. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  778. return NULL;
  779. }
  780. std::vector<CGHeroInstance *> pool;
  781. if(native)
  782. {
  783. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  784. {
  785. if(pavailable.find(i->first)->second & 1<<player
  786. && i->second->type->heroType/2 == town->typeID)
  787. {
  788. pool.push_back(i->second); //get all avaliable heroes
  789. }
  790. }
  791. if(!pool.size())
  792. {
  793. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  794. return pickHeroFor(false, player, town, available);
  795. }
  796. else
  797. {
  798. ret = pool[rand()%pool.size()];
  799. }
  800. }
  801. else
  802. {
  803. int sum=0, r;
  804. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  805. {
  806. if(pavailable.find(i->first)->second & 1<<player)
  807. {
  808. pool.push_back(i->second);
  809. sum += i->second->type->heroClass->selectionProbability[town->typeID]; //total weight
  810. }
  811. }
  812. if(!pool.size())
  813. {
  814. tlog1 << "There are no heroes available for player " << player<<"!\n";
  815. return NULL;
  816. }
  817. r = rand()%sum;
  818. for (unsigned int i=0; i<pool.size(); i++)
  819. {
  820. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  821. if(r < 0)
  822. {
  823. ret = pool[i];
  824. break;
  825. }
  826. }
  827. if(!ret)
  828. ret = pool.back();
  829. }
  830. available.erase(ret->subID);
  831. return ret;
  832. }
  833. //void CGameState::apply(CPack * pack)
  834. //{
  835. // while(!mx->try_lock())
  836. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  837. // //applyNL(pack);
  838. // mx->unlock();
  839. //}
  840. int CGameState::pickHero(int owner)
  841. {
  842. int h=-1;
  843. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  844. return h;
  845. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  846. int i=0;
  847. do //try to find free hero of our faction
  848. {
  849. i++;
  850. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  851. } while( map->getHero(h) && i<175);
  852. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  853. {
  854. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  855. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  856. if(!map->getHero(j))
  857. h=j;
  858. }
  859. return h;
  860. }
  861. CGHeroInstance *CGameState::getHero(int objid)
  862. {
  863. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  864. return NULL;
  865. return static_cast<CGHeroInstance *>(map->objects[objid]);
  866. }
  867. const CGHeroInstance * CGameState::getHero( int objid ) const
  868. {
  869. return (const_cast<CGameState *>(this))->getHero(objid);
  870. }
  871. CGTownInstance *CGameState::getTown(int objid)
  872. {
  873. if(objid<0 || objid>=map->objects.size())
  874. return NULL;
  875. return static_cast<CGTownInstance *>(map->objects[objid]);
  876. }
  877. const CGTownInstance * CGameState::getTown( int objid ) const
  878. {
  879. return (const_cast<CGameState *>(this))->getTown(objid);
  880. }
  881. std::pair<int,int> CGameState::pickObject (CGObjectInstance *obj)
  882. {
  883. switch(obj->ID)
  884. {
  885. case 65: //random artifact
  886. return std::pair<int,int>(5,(ran()%136)+7); //the only reasonable range - there are siege weapons and blanks we must ommit
  887. case 66: //random treasure artifact
  888. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  889. case 67: //random minor artifact
  890. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  891. case 68: //random major artifact
  892. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  893. case 69: //random relic artifact
  894. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  895. /*case 65: //random artifact //TODO: apply new randndomization system
  896. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  897. case 66: //random treasure artifact
  898. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_TREASURE));
  899. case 67: //random minor artifact
  900. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MINOR));
  901. case 68: //random major artifact
  902. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_MAJOR));
  903. case 69: //random relic artifact
  904. return std::pair<int,int>(5, cb.getRandomArt (CArtifact::ART_RELIC));*/
  905. case 70: //random hero
  906. {
  907. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  908. }
  909. case 71: //random monster
  910. {
  911. int r;
  912. do
  913. {
  914. r = ran()%197;
  915. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  916. return std::pair<int,int>(54,r);
  917. }
  918. case 72: //random monster lvl1
  919. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  920. case 73: //random monster lvl2
  921. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  922. case 74: //random monster lvl3
  923. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  924. case 75: //random monster lvl4
  925. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  926. case 76: //random resource
  927. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  928. case 77: //random town
  929. {
  930. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  931. f;
  932. if(align>PLAYER_LIMIT-1)//same as owner / random
  933. {
  934. if(obj->tempOwner > PLAYER_LIMIT-1)
  935. f = -1; //random
  936. else
  937. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  938. }
  939. else
  940. {
  941. f = scenarioOps->getIthPlayersSettings(align).castle;
  942. }
  943. if(f<0) f = ran()%VLC->townh->towns.size();
  944. return std::pair<int,int>(TOWNI_TYPE,f);
  945. }
  946. case 162: //random monster lvl5
  947. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  948. case 163: //random monster lvl6
  949. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  950. case 164: //random monster lvl7
  951. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  952. case 216: //random dwelling
  953. {
  954. int faction = ran()%F_NUMBER;
  955. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  956. if (info->asCastle)
  957. {
  958. for(unsigned int i=0;i<map->objects.size();i++)
  959. {
  960. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  961. {
  962. randomizeObject(map->objects[i]); //we have to randomize the castle first
  963. faction = map->objects[i]->subID;
  964. break;
  965. }
  966. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  967. {
  968. faction = map->objects[i]->subID;
  969. break;
  970. }
  971. }
  972. }
  973. else
  974. {
  975. while((!(info->castles[0]&(1<<faction))))
  976. {
  977. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  978. break;
  979. faction = ran()%F_NUMBER;
  980. }
  981. }
  982. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  983. int cid = VLC->townh->towns[faction].basicCreatures[level];
  984. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  985. if(VLC->objh->cregens[i]==cid)
  986. return std::pair<int,int>(17,i);
  987. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  988. return std::pair<int,int>(17,0);
  989. }
  990. case 217:
  991. {
  992. int faction = ran()%F_NUMBER;
  993. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  994. if (info->asCastle)
  995. {
  996. for(unsigned int i=0;i<map->objects.size();i++)
  997. {
  998. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  999. {
  1000. randomizeObject(map->objects[i]); //we have to randomize the castle first
  1001. faction = map->objects[i]->subID;
  1002. break;
  1003. }
  1004. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  1005. {
  1006. faction = map->objects[i]->subID;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. else
  1012. {
  1013. while((!(info->castles[0]&(1<<faction))))
  1014. {
  1015. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  1016. break;
  1017. faction = ran()%F_NUMBER;
  1018. }
  1019. }
  1020. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  1021. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1022. if(VLC->objh->cregens[i]==cid)
  1023. return std::pair<int,int>(17,i);
  1024. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1025. return std::pair<int,int>(17,0);
  1026. }
  1027. case 218:
  1028. {
  1029. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  1030. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  1031. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1032. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1033. if(VLC->objh->cregens[i]==cid)
  1034. return std::pair<int,int>(17,i);
  1035. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1036. return std::pair<int,int>(17,0);
  1037. }
  1038. }
  1039. return std::pair<int,int>(-1,-1);
  1040. }
  1041. void convertHordes(CGTownInstance * town)//converting hordes from -36..-30 to 18 & 24
  1042. {
  1043. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1044. if (vstd::contains(town->builtBuildings,(-31-i))) //if we have horde for this level
  1045. {
  1046. town->builtBuildings.erase(-31-i);//remove old ID
  1047. if (town->town->hordeLvl[0] == i)//if town first horde is this one
  1048. {
  1049. town->builtBuildings.insert(18);//add it
  1050. if (vstd::contains(town->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1051. town->builtBuildings.insert(19);//add it as well
  1052. }
  1053. if (town->town->hordeLvl[1] == i)//if town second horde is this one
  1054. {
  1055. town->builtBuildings.insert(24);//add it
  1056. if (vstd::contains(town->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1057. town->builtBuildings.insert(25);//add it as well
  1058. }
  1059. }
  1060. }
  1061. void CGameState::randomizeObject(CGObjectInstance *cur)
  1062. {
  1063. std::pair<int,int> ran = pickObject(cur);
  1064. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1065. {
  1066. if(cur->ID==TOWNI_TYPE) //town - set def
  1067. {
  1068. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1069. t->town = &VLC->townh->towns[t->subID];
  1070. if(t->hasCapitol())
  1071. t->defInfo = capitols[t->subID];
  1072. else if(t->hasFort())
  1073. t->defInfo = forts[t->subID];
  1074. else
  1075. t->defInfo = villages[t->subID];
  1076. }
  1077. return;
  1078. }
  1079. else if(ran.first==HEROI_TYPE)//special code for hero
  1080. {
  1081. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1082. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1083. cur->ID = ran.first;
  1084. h->portrait = cur->subID = ran.second;
  1085. h->type = VLC->heroh->heroes[ran.second];
  1086. map->heroes.push_back(h);
  1087. return; //TODO: maybe we should do something with definfo?
  1088. }
  1089. else if(ran.first==TOWNI_TYPE)//special code for town
  1090. {
  1091. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1092. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1093. cur->ID = ran.first;
  1094. cur->subID = ran.second;
  1095. t->town = &VLC->townh->towns[ran.second];
  1096. if(t->hasCapitol())
  1097. t->defInfo = capitols[t->subID];
  1098. else if(t->hasFort())
  1099. t->defInfo = forts[t->subID];
  1100. else
  1101. t->defInfo = villages[t->subID];
  1102. map->towns.push_back(t);
  1103. return;
  1104. }
  1105. //we have to replace normal random object
  1106. cur->ID = ran.first;
  1107. cur->subID = ran.second;
  1108. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1109. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1110. if(!cur->defInfo)
  1111. {
  1112. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1113. return;
  1114. }
  1115. map->addBlockVisTiles(cur);
  1116. }
  1117. int CGameState::getDate(int mode) const
  1118. {
  1119. int temp;
  1120. switch (mode)
  1121. {
  1122. case 0:
  1123. return day;
  1124. break;
  1125. case 1:
  1126. temp = (day)%7;
  1127. if (temp)
  1128. return temp;
  1129. else return 7;
  1130. break;
  1131. case 2:
  1132. temp = ((day-1)/7)+1;
  1133. if (!(temp%4))
  1134. return 4;
  1135. else
  1136. return (temp%4);
  1137. break;
  1138. case 3:
  1139. return ((day-1)/28)+1;
  1140. break;
  1141. }
  1142. return 0;
  1143. }
  1144. CGameState::CGameState()
  1145. {
  1146. mx = new boost::shared_mutex();
  1147. map = NULL;
  1148. curB = NULL;
  1149. scenarioOps = NULL;
  1150. applierGs = new CGSApplier;
  1151. objCaller = new CObjectCallersHandler;
  1152. }
  1153. CGameState::~CGameState()
  1154. {
  1155. delete mx;
  1156. delete map;
  1157. delete curB;
  1158. delete scenarioOps;
  1159. delete applierGs;
  1160. delete objCaller;
  1161. }
  1162. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1163. {
  1164. day = 0;
  1165. seed = Seed;
  1166. ran.seed((boost::int32_t)seed);
  1167. scenarioOps = si;
  1168. this->map = map;
  1169. loadTownDInfos();
  1170. //pick grail location
  1171. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1172. {
  1173. if(!map->grailRadious) //radius not given -> anywhere on map
  1174. map->grailRadious = map->width * 2;
  1175. std::vector<int3> allowedPos;
  1176. // add all not blocked tiles in range
  1177. for (int i = 0; i < map->width ; i++)
  1178. {
  1179. for (int j = 0; j < map->height ; j++)
  1180. {
  1181. for (int k = 0; k <= map->twoLevel ; k++)
  1182. {
  1183. const TerrainTile &t = map->terrain[i][j][k];
  1184. if(!t.blocked
  1185. && !t.visitable
  1186. && t.tertype != TerrainTile::water
  1187. && t.tertype != TerrainTile::rock
  1188. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1189. allowedPos.push_back(int3(i,j,k));
  1190. }
  1191. }
  1192. }
  1193. //remove tiles with holes
  1194. for(unsigned int no=0; no<map->objects.size(); ++no)
  1195. if(map->objects[no]->ID == 124)
  1196. allowedPos -= map->objects[no]->pos;
  1197. if(allowedPos.size())
  1198. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1199. else
  1200. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1201. }
  1202. //picking random factions for players
  1203. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1204. {
  1205. if(scenarioOps->playerInfos[i].castle==-1)
  1206. {
  1207. int f;
  1208. do
  1209. {
  1210. f = ran()%F_NUMBER;
  1211. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1212. scenarioOps->playerInfos[i].castle = f;
  1213. }
  1214. }
  1215. //randomizing objects
  1216. for(unsigned int no=0; no<map->objects.size(); ++no)
  1217. {
  1218. randomizeObject(map->objects[no]);
  1219. if(map->objects[no]->ID==EVENTI_TYPE)
  1220. {
  1221. map->objects[no]->defInfo->handler=NULL;
  1222. }
  1223. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1224. }
  1225. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1226. /*********give starting hero****************************************/
  1227. for(int i=0;i<PLAYER_LIMIT;i++)
  1228. {
  1229. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1230. {
  1231. int3 hpos = map->players[i].posOfMainTown;
  1232. hpos.x+=1;// hpos.y+=1;
  1233. int j;
  1234. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1235. if(scenarioOps->playerInfos[j].color == i)
  1236. break;
  1237. if(j == scenarioOps->playerInfos.size())
  1238. continue;
  1239. int h=pickHero(i);
  1240. if(scenarioOps->playerInfos[j].hero == -1)
  1241. scenarioOps->playerInfos[j].hero = h;
  1242. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1243. nnn->id = map->objects.size();
  1244. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1245. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1246. {
  1247. if(map->towns[o]->pos == hpos)
  1248. {
  1249. map->towns[o]->visitingHero = nnn;
  1250. nnn->visitedTown = map->towns[o];
  1251. nnn->inTownGarrison = false;
  1252. break;
  1253. }
  1254. }
  1255. nnn->initHero();
  1256. map->heroes.push_back(nnn);
  1257. map->objects.push_back(nnn);
  1258. map->addBlockVisTiles(nnn);
  1259. }
  1260. }
  1261. /*********creating players entries in gs****************************************/
  1262. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1263. {
  1264. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1265. ins.second.color=ins.first;
  1266. ins.second.serial=i;
  1267. ins.second.human = scenarioOps->playerInfos[i].human;
  1268. players.insert(ins);
  1269. }
  1270. /******************RESOURCES****************************************************/
  1271. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1272. std::vector<int> startres;
  1273. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1274. int k;
  1275. for (int j=0;j<scenarioOps->difficulty;j++)
  1276. {
  1277. tis >> k;
  1278. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1279. tis>>k;
  1280. }
  1281. tis >> k;
  1282. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1283. {
  1284. tis >> k;
  1285. startres.push_back(k);
  1286. }
  1287. tis.close();
  1288. tis.clear();
  1289. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1290. {
  1291. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1292. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1293. (*i).second.resources[x] = startres[x];
  1294. }
  1295. tis.open(DATA_DIR "/config/resources.txt");
  1296. tis >> k;
  1297. int pom;
  1298. for(int i=0;i<k;i++)
  1299. {
  1300. tis >> pom;
  1301. resVals.push_back(pom);
  1302. }
  1303. /*************************HEROES************************************************/
  1304. std::set<int> hids;
  1305. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1306. if(map->allowedHeroes[i])
  1307. hids.insert(i);
  1308. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1309. {
  1310. if (map->heroes[i]->getOwner()<0)
  1311. {
  1312. tlog2 << "Warning - hero with uninitialized owner!\n";
  1313. continue;
  1314. }
  1315. CGHeroInstance * vhi = (map->heroes[i]);
  1316. vhi->initHero();
  1317. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1318. hids.erase(vhi->subID);
  1319. }
  1320. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1321. {
  1322. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1323. continue;
  1324. map->predefinedHeroes[i]->initHero();
  1325. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1326. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1327. hids.erase(map->predefinedHeroes[i]->subID);
  1328. }
  1329. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1330. {
  1331. CGHeroInstance * vhi = new CGHeroInstance();
  1332. vhi->initHero(hid);
  1333. hpool.heroesPool[hid] = vhi;
  1334. hpool.pavailable[hid] = 0xff;
  1335. }
  1336. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1337. {
  1338. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1339. }
  1340. /*************************FOG**OF**WAR******************************************/
  1341. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1342. {
  1343. k->second.fogOfWarMap.resize(map->width);
  1344. for(int g=0; g<map->width; ++g)
  1345. k->second.fogOfWarMap[g].resize(map->height);
  1346. for(int g=-0; g<map->width; ++g)
  1347. for(int h=0; h<map->height; ++h)
  1348. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1349. for(int g=0; g<map->width; ++g)
  1350. for(int h=0; h<map->height; ++h)
  1351. for(int v=0; v<map->twoLevel+1; ++v)
  1352. k->second.fogOfWarMap[g][h][v] = 0;
  1353. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1354. {
  1355. if(obj->tempOwner != k->first) continue; //not a flagged object
  1356. std::set<int3> tiles;
  1357. obj->getSightTiles(tiles);
  1358. BOOST_FOREACH(int3 tile, tiles)
  1359. {
  1360. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1361. }
  1362. }
  1363. //starting bonus
  1364. if(si->playerInfos[k->second.serial].bonus==brandom)
  1365. si->playerInfos[k->second.serial].bonus = ran()%3;
  1366. switch(si->playerInfos[k->second.serial].bonus)
  1367. {
  1368. case bgold:
  1369. k->second.resources[6] += 500 + (ran()%6)*100;
  1370. break;
  1371. case bresource:
  1372. {
  1373. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1374. if(res == 127)
  1375. {
  1376. k->second.resources[0] += 5 + ran()%6;
  1377. k->second.resources[2] += 5 + ran()%6;
  1378. }
  1379. else
  1380. {
  1381. k->second.resources[res] += 3 + ran()%4;
  1382. }
  1383. break;
  1384. }
  1385. case bartifact:
  1386. {
  1387. if(!k->second.heroes.size())
  1388. {
  1389. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1390. break;
  1391. }
  1392. CArtifact *toGive;
  1393. do
  1394. {
  1395. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1396. } while (!map->allowedArtifact[toGive->id]);
  1397. CGHeroInstance *hero = k->second.heroes[0];
  1398. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1399. if(slot!=toGive->possibleSlots.end())
  1400. {
  1401. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id);
  1402. hero->recreateArtBonuses();
  1403. }
  1404. else
  1405. hero->giveArtifact(toGive->id);
  1406. }
  1407. }
  1408. }
  1409. /****************************TOWNS************************************************/
  1410. for (unsigned int i=0;i<map->towns.size();i++)
  1411. {
  1412. CGTownInstance * vti =(map->towns[i]);
  1413. if(!vti->town)
  1414. vti->town = &VLC->townh->towns[vti->subID];
  1415. if (vti->name.length()==0) // if town hasn't name we draw it
  1416. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1417. //init buildings
  1418. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1419. {
  1420. vti->builtBuildings.erase(-50);
  1421. vti->builtBuildings.insert(10);
  1422. vti->builtBuildings.insert(5);
  1423. vti->builtBuildings.insert(30);
  1424. if(ran()%2)
  1425. vti->builtBuildings.insert(31);
  1426. }
  1427. convertHordes(vti);
  1428. //init spells
  1429. vti->spells.resize(SPELL_LEVELS);
  1430. CSpell *s;
  1431. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1432. {
  1433. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1434. vti->spells[s->level-1].push_back(s->id);
  1435. vti->possibleSpells -= s->id;
  1436. }
  1437. while(vti->possibleSpells.size())
  1438. {
  1439. ui32 total=0, sel=-1;
  1440. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1441. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1442. int r = (total)? ran()%total : -1;
  1443. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1444. {
  1445. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1446. if(r<0)
  1447. {
  1448. sel = ps;
  1449. break;
  1450. }
  1451. }
  1452. if(sel<0)
  1453. sel=0;
  1454. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1455. vti->spells[s->level-1].push_back(s->id);
  1456. vti->possibleSpells -= s->id;
  1457. }
  1458. //init garrisons
  1459. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1460. {
  1461. if(j->second.first > 196 && j->second.first < 211)
  1462. {
  1463. if(j->second.first%2)
  1464. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1465. else
  1466. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1467. }
  1468. }
  1469. if(vti->getOwner() != 255)
  1470. getPlayer(vti->getOwner())->towns.push_back(vti);
  1471. }
  1472. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1473. {
  1474. if(k->first==-1 || k->first==255)
  1475. continue;
  1476. //init visiting and garrisoned heroes
  1477. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1478. {
  1479. CGHeroInstance *h = k->second.heroes[l];
  1480. for(unsigned int m=0; m<k->second.towns.size();m++)
  1481. {
  1482. CGTownInstance *t = k->second.towns[m];
  1483. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1484. if(vistile == h->pos || h->pos==t->pos)
  1485. {
  1486. t->visitingHero = h;
  1487. h->visitedTown = t;
  1488. h->inTownGarrison = false;
  1489. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1490. {
  1491. map->removeBlockVisTiles(h);
  1492. h->pos.x -= 1;
  1493. map->addBlockVisTiles(h);
  1494. }
  1495. break;
  1496. }
  1497. }
  1498. }
  1499. }
  1500. for(unsigned int i=0; i<map->defy.size(); i++)
  1501. {
  1502. map->defy[i]->serial = i;
  1503. }
  1504. objCaller->preInit();
  1505. for(unsigned int i=0; i<map->objects.size(); i++)
  1506. {
  1507. map->objects[i]->initObj();
  1508. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1509. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1510. }
  1511. objCaller->postInit();
  1512. }
  1513. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1514. {
  1515. return true;
  1516. }
  1517. bool CGameState::battleCanFlee(int player)
  1518. {
  1519. if(!curB) //there is no battle
  1520. return false;
  1521. if(curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1522. || curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1523. return false;
  1524. return true;
  1525. }
  1526. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1527. {
  1528. if(!curB)
  1529. return -1;
  1530. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1531. {
  1532. if((curB->stacks[g]->position == pos
  1533. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1534. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1535. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1536. ))
  1537. && (!onlyAlive || curB->stacks[g]->alive())
  1538. )
  1539. return curB->stacks[g]->ID;
  1540. }
  1541. return -1;
  1542. }
  1543. int CGameState::battleGetBattlefieldType(int3 tile)
  1544. {
  1545. if(tile==int3() && curB)
  1546. tile = curB->tile;
  1547. else if(tile==int3() && !curB)
  1548. return -1;
  1549. const std::vector <CGObjectInstance*> & objs = map->objects;
  1550. for(int g=0; g<objs.size(); ++g)
  1551. {
  1552. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1553. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1554. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1555. ) //look only for objects covering given tile
  1556. continue;
  1557. switch(objs[g]->ID)
  1558. {
  1559. case 222: //clover field
  1560. return 19;
  1561. case 21: case 223: //cursed ground
  1562. return 22;
  1563. case 224: //evil fog
  1564. return 20;
  1565. case 225: //favourable winds
  1566. return 21;
  1567. case 226: //fiery fields
  1568. return 14;
  1569. case 227: //holy ground
  1570. return 18;
  1571. case 228: //lucid pools
  1572. return 17;
  1573. case 229: //magic clouds
  1574. return 16;
  1575. case 46: case 230: //magic plains
  1576. return 9;
  1577. case 231: //rocklands
  1578. return 15;
  1579. }
  1580. }
  1581. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1582. {
  1583. case TerrainTile::dirt:
  1584. return rand()%3+3;
  1585. case TerrainTile::sand:
  1586. return 2; //TODO: coast support
  1587. case TerrainTile::grass:
  1588. return rand()%2+6;
  1589. case TerrainTile::snow:
  1590. return rand()%2+10;
  1591. case TerrainTile::swamp:
  1592. return 13;
  1593. case TerrainTile::rough:
  1594. return 23;
  1595. case TerrainTile::subterranean:
  1596. return 12;
  1597. case TerrainTile::lava:
  1598. return 8;
  1599. case TerrainTile::water:
  1600. return 25;
  1601. case TerrainTile::rock:
  1602. return 15;
  1603. default:
  1604. return -1;
  1605. }
  1606. }
  1607. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1608. {
  1609. if(!curB)
  1610. return NULL;
  1611. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1612. }
  1613. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1614. {
  1615. UpgradeInfo ret;
  1616. const CCreature *base = &VLC->creh->creatures[obj->army.slots.find(stackPos)->second.first];
  1617. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1618. {
  1619. const CGTownInstance * t;
  1620. if(obj->ID == TOWNI_TYPE)
  1621. t = static_cast<const CGTownInstance *>(obj);
  1622. else
  1623. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1624. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1625. {
  1626. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1627. {
  1628. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1629. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1630. {
  1631. ret.newID.push_back(nid);
  1632. ret.cost.push_back(std::set<std::pair<int,int> >());
  1633. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1634. {
  1635. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1636. if(dif)
  1637. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1638. }
  1639. }
  1640. }
  1641. }//end for
  1642. }
  1643. //TODO: check if hero ability makes some upgrades possible
  1644. if(ret.newID.size())
  1645. ret.oldID = base->idNumber;
  1646. return ret;
  1647. }
  1648. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1649. {
  1650. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1651. if(mode) return -1; //todo - support other modes
  1652. int mcount = 0;
  1653. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1654. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1655. mcount++;
  1656. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1657. return ret;
  1658. }
  1659. void CGameState::loadTownDInfos()
  1660. {
  1661. for(int i=0;i<F_NUMBER;i++)
  1662. {
  1663. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1664. forts[i] = VLC->dobjinfo->castles[i];
  1665. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1666. }
  1667. }
  1668. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1669. {
  1670. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1671. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1672. vec.clear();
  1673. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1674. {
  1675. const int3 hlp = tile + dirs[i];
  1676. if(!map->isInTheMap(hlp))
  1677. continue;
  1678. const TerrainTile &hlpt = map->getTile(hlp);
  1679. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1680. && hlpt.tertype!=9)
  1681. {
  1682. vec.push_back(hlp);
  1683. }
  1684. }
  1685. }
  1686. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1687. {
  1688. if(src == dest) //same tile
  1689. return 0;
  1690. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1691. &d = map->terrain[dest.x][dest.y][dest.z];
  1692. //get basic cost
  1693. int ret = h->getTileCost(d,s);
  1694. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1695. {
  1696. int old = ret;
  1697. ret *= 1.414213;
  1698. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1699. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1700. {
  1701. return remainingMovePoints;
  1702. }
  1703. }
  1704. int left = remainingMovePoints-ret;
  1705. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1706. {
  1707. std::vector<int3> vec;
  1708. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1709. for(size_t i=0; i < vec.size(); i++)
  1710. {
  1711. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1712. if(fcost <= left)
  1713. {
  1714. return ret;
  1715. }
  1716. }
  1717. ret = remainingMovePoints;
  1718. }
  1719. return ret;
  1720. }
  1721. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1722. {
  1723. std::set<int> used;
  1724. used.insert(ID);
  1725. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1726. while(true)
  1727. {
  1728. size_t noloop=0;
  1729. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1730. {
  1731. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1732. {
  1733. used.insert(*i);
  1734. for(
  1735. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1736. j!=VLC->townh->requirements[t->subID][*i].end();
  1737. j++)
  1738. {
  1739. reqs.insert(*j);//creating full list of requirements
  1740. }
  1741. }
  1742. else
  1743. {
  1744. noloop++;
  1745. }
  1746. }
  1747. if(noloop==reqs.size())
  1748. break;
  1749. }
  1750. return reqs;
  1751. }
  1752. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1753. {
  1754. int ret = 7; //allowed by default
  1755. if(t->builded >= MAX_BUILDING_PER_TURN)
  1756. ret = 5; //building limit
  1757. //checking resources
  1758. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1759. if(!pom)return 8;
  1760. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1761. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1762. {
  1763. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1764. ret = 6; //lack of res
  1765. }
  1766. //checking for requirements
  1767. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1768. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1769. {
  1770. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1771. ret = 8; //lack of requirements - cannot build
  1772. }
  1773. //can we build it?
  1774. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1775. ret = 2; //forbidden
  1776. if(ID == 13) //capitol
  1777. {
  1778. for(unsigned int in = 0; in < map->towns.size(); in++)
  1779. {
  1780. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1781. {
  1782. ret = 0; //no more than one capitol
  1783. break;
  1784. }
  1785. }
  1786. }
  1787. else if(ID == 6) //shipyard
  1788. {
  1789. int3 t1(t->pos + int3(-1,3,0)),
  1790. t2(t->pos + int3(-3,3,0));
  1791. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1792. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1793. ret = 1; //lack of water
  1794. }
  1795. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1796. ret = 4;
  1797. return ret;
  1798. }
  1799. void CGameState::apply(CPack *pack)
  1800. {
  1801. ui16 typ = typeList.getTypeID(pack);
  1802. assert(typ >= 0);
  1803. applierGs->apps[typ]->applyOnGS(this,pack);
  1804. }
  1805. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1806. {
  1807. if(vstd::contains(players,color))
  1808. {
  1809. return &players[color];
  1810. }
  1811. else
  1812. {
  1813. if(verbose)
  1814. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1815. return NULL;
  1816. }
  1817. }
  1818. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1819. {
  1820. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1821. }
  1822. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1823. {
  1824. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1825. return false;
  1826. int3 hpos = hero->getPosition(false);
  1827. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1828. if (!hero->canWalkOnSea())
  1829. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1830. else
  1831. blockLandSea = boost::logic::indeterminate;
  1832. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1833. //graph initialization
  1834. std::vector< std::vector<CPathNode> > graph;
  1835. graph.resize(map->width);
  1836. for(size_t i=0; i<graph.size(); ++i)
  1837. {
  1838. graph[i].resize(map->height);
  1839. for(size_t j=0; j<graph[i].size(); ++j)
  1840. {
  1841. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1842. CPathNode &node = graph[i][j];
  1843. node.accessible = !tinfo->blocked;
  1844. node.dist = -1;
  1845. node.theNodeBefore = NULL;
  1846. node.visited = false;
  1847. node.coord.x = i;
  1848. node.coord.y = j;
  1849. node.coord.z = dest.z;
  1850. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1851. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1852. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1853. || !FoW[i][j][src.z] //tile is covered by the FoW
  1854. )
  1855. {
  1856. node.accessible = false;
  1857. }
  1858. }
  1859. }
  1860. //Special rules for the destination tile
  1861. {
  1862. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1863. CPathNode &d = graph[dest.x][dest.y];
  1864. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1865. if(t->visitable)
  1866. {
  1867. d.accessible = true; //for allowing visiting objects
  1868. }
  1869. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1870. {
  1871. size_t i = 0;
  1872. for(; i < t->visitableObjects.size(); i++)
  1873. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1874. break;
  1875. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1876. }
  1877. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1878. {
  1879. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1880. }
  1881. }
  1882. //graph initialized
  1883. //initial tile - set cost on 0 and add to the queue
  1884. graph[src.x][src.y].dist = 0;
  1885. std::queue<CPathNode> mq;
  1886. mq.push(graph[src.x][src.y]);
  1887. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1888. std::vector<int3> neighbours;
  1889. neighbours.reserve(8);
  1890. while(!mq.empty())
  1891. {
  1892. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1893. mq.pop();
  1894. if (cp.coord == dest) //it's destination tile
  1895. {
  1896. if (cp.dist < curDist) //that path is better than previous one
  1897. curDist = cp.dist;
  1898. continue;
  1899. }
  1900. else
  1901. {
  1902. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1903. continue;
  1904. }
  1905. //add accessible neighbouring nodes to the queue
  1906. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1907. for(unsigned int i=0; i < neighbours.size(); i++)
  1908. {
  1909. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1910. if(dp.accessible)
  1911. {
  1912. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1913. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1914. {
  1915. dp.dist = cp.dist + cost;
  1916. dp.theNodeBefore = &cp;
  1917. mq.push(dp);
  1918. }
  1919. }
  1920. }
  1921. }
  1922. CPathNode *curNode = &graph[dest.x][dest.y];
  1923. if(!curNode->theNodeBefore) //destination is not accessible
  1924. return false;
  1925. //fill ret with found path
  1926. ret.nodes.clear();
  1927. while(curNode->coord != graph[src.x][src.y].coord)
  1928. {
  1929. ret.nodes.push_back(*curNode);
  1930. curNode = curNode->theNodeBefore;
  1931. }
  1932. ret.nodes.push_back(graph[src.x][src.y]);
  1933. return true;
  1934. }
  1935. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1936. {
  1937. assert(hero);
  1938. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1939. if(src.x < 0)
  1940. src = hero->getPosition(false);
  1941. if(movement < 0)
  1942. movement = hero->movement;
  1943. out.hero = hero;
  1944. out.hpos = src;
  1945. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1946. {
  1947. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1948. return;
  1949. }
  1950. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1951. if (!hero->canWalkOnSea())
  1952. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1953. else
  1954. onLand = boost::logic::indeterminate;
  1955. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1956. //graph initialization
  1957. CGPathNode ***graph = out.nodes;
  1958. for(size_t i=0; i < out.sizes.x; ++i)
  1959. {
  1960. for(size_t j=0; j < out.sizes.y; ++j)
  1961. {
  1962. for(size_t k=0; k < out.sizes.z; ++k)
  1963. {
  1964. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1965. CGPathNode &node = graph[i][j][k];
  1966. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1967. node.turns = 0xff;
  1968. node.moveRemains = 0;
  1969. node.coord.x = i;
  1970. node.coord.y = j;
  1971. node.coord.z = k;
  1972. node.land = tinfo->tertype != TerrainTile::water;
  1973. node.theNodeBefore = NULL;
  1974. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1975. || onLand && !node.land //it's sea and we cannot walk on sea
  1976. || !onLand && node.land //it's land and we cannot walk on land
  1977. || !FoW[i][j][k] //tile is covered by the FoW
  1978. )
  1979. {
  1980. node.accessible = CGPathNode::BLOCKED;
  1981. }
  1982. else if(tinfo->visitable)
  1983. {
  1984. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1985. {
  1986. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  1987. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  1988. {
  1989. node.accessible = CGPathNode::ACCESSIBLE;
  1990. }
  1991. else if(obj->blockVisit)
  1992. {
  1993. node.accessible = CGPathNode::BLOCKVIS;
  1994. break;
  1995. }
  1996. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  1997. {
  1998. node.accessible = CGPathNode::VISITABLE;
  1999. }
  2000. }
  2001. }
  2002. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2003. {
  2004. size_t i = 0;
  2005. for(; i < tinfo->visitableObjects.size(); i++)
  2006. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2007. break;
  2008. if(i < tinfo->visitableObjects.size())
  2009. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2010. }
  2011. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  2012. {
  2013. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2014. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2015. }
  2016. }
  2017. }
  2018. }
  2019. //graph initialized
  2020. //initial tile - set cost on 0 and add to the queue
  2021. graph[src.x][src.y][src.z].turns = 0;
  2022. graph[src.x][src.y][src.z].moveRemains = movement;
  2023. std::queue<CGPathNode*> mq;
  2024. mq.push(&graph[src.x][src.y][src.z]);
  2025. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2026. std::vector<int3> neighbours;
  2027. neighbours.reserve(8);
  2028. while(!mq.empty())
  2029. {
  2030. CGPathNode *cp = mq.front();
  2031. mq.pop();
  2032. const TerrainTile &ct = map->getTile(cp->coord);
  2033. int movement = cp->moveRemains, turn = cp->turns;
  2034. if(!movement)
  2035. {
  2036. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2037. turn++;
  2038. }
  2039. //add accessible neighbouring nodes to the queue
  2040. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  2041. for(unsigned int i=0; i < neighbours.size(); i++)
  2042. {
  2043. int moveAtNextTile = movement;
  2044. int turnAtNextTile = turn;
  2045. const int3 &n = neighbours[i]; //current neighbor
  2046. CGPathNode & dp = graph[n.x][n.y][n.z];
  2047. if( !checkForVisitableDir(cp->coord, dp.coord)
  2048. || !checkForVisitableDir(dp.coord, cp->coord)
  2049. || dp.accessible == CGPathNode::BLOCKED )
  2050. {
  2051. continue;
  2052. }
  2053. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2054. int remains = movement - cost;
  2055. if(remains < 0)
  2056. {
  2057. //occurs rarely, when hero with low movepoints tries to go leave the road
  2058. turnAtNextTile++;
  2059. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2060. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2061. remains = moveAtNextTile - cost;
  2062. }
  2063. if(dp.turns==0xff //we haven't been here before
  2064. || dp.turns > turnAtNextTile
  2065. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2066. {
  2067. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2068. dp.moveRemains = remains;
  2069. dp.turns = turnAtNextTile;
  2070. dp.theNodeBefore = cp;
  2071. if(dp.accessible == CGPathNode::ACCESSIBLE)
  2072. {
  2073. mq.push(&dp);
  2074. }
  2075. }
  2076. } //neighbours loop
  2077. } //queue loop
  2078. }
  2079. bool CGameState::isVisible(int3 pos, int player)
  2080. {
  2081. if(player == 255) //neutral player
  2082. return false;
  2083. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2084. }
  2085. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2086. {
  2087. if(player == 255) //neutral player
  2088. return false;
  2089. //object is visible when at least one blocked tile is visible
  2090. for(int fx=0; fx<8; ++fx)
  2091. {
  2092. for(int fy=0; fy<6; ++fy)
  2093. {
  2094. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2095. if(map->isInTheMap(pos)
  2096. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2097. && isVisible(pos, player) )
  2098. return true;
  2099. }
  2100. }
  2101. return false;
  2102. }
  2103. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2104. {
  2105. const TerrainTile * pom = &map->getTile(dst);
  2106. return checkForVisitableDir(src, pom, dst);
  2107. }
  2108. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2109. {
  2110. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2111. {
  2112. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2113. continue;
  2114. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2115. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2116. {
  2117. return false;
  2118. }
  2119. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2120. {
  2121. return false;
  2122. }
  2123. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2124. {
  2125. return false;
  2126. }
  2127. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2128. {
  2129. return false;
  2130. }
  2131. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2132. {
  2133. return false;
  2134. }
  2135. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2136. {
  2137. return false;
  2138. }
  2139. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2140. {
  2141. return false;
  2142. }
  2143. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2144. {
  2145. return false;
  2146. }
  2147. }
  2148. return true;
  2149. }
  2150. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2151. {
  2152. float attackDefenseBonus,
  2153. minDmg = attacker->creature->damageMin * attacker->amount,
  2154. maxDmg = attacker->creature->damageMax * attacker->amount;
  2155. if(attacker->creature->idNumber == 149) //arrow turret
  2156. {
  2157. switch(attacker->position)
  2158. {
  2159. case -2: //keep
  2160. minDmg = 15;
  2161. maxDmg = 15;
  2162. break;
  2163. case -3: case -4: //turrets
  2164. minDmg = 7.5f;
  2165. maxDmg = 7.5f;
  2166. break;
  2167. }
  2168. }
  2169. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON) && attacker->creature->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2170. { //minDmg and maxDmg are multiplied by hero attack + 1
  2171. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2172. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2173. }
  2174. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  2175. {
  2176. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  2177. }
  2178. else
  2179. {
  2180. attackDefenseBonus = attacker->Attack() - defender->Defense();
  2181. }
  2182. //calculating total attack/defense skills modifier
  2183. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  2184. {
  2185. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  2186. }
  2187. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  2188. {
  2189. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  2190. }
  2191. if(attacker->getEffect(55)) //slayer handling
  2192. {
  2193. std::vector<int> affectedIds;
  2194. switch(attacker->getEffect(55)->level)
  2195. {
  2196. case 3: //expert
  2197. {
  2198. affectedIds.push_back(40); //giant
  2199. affectedIds.push_back(41); //titan
  2200. affectedIds.push_back(152); //lord of thunder
  2201. } //continue adding ...
  2202. case 2: //advanced
  2203. {
  2204. affectedIds.push_back(12); //angel
  2205. affectedIds.push_back(13); //archangel
  2206. affectedIds.push_back(54); //devil
  2207. affectedIds.push_back(55); //arch devil
  2208. affectedIds.push_back(150); //supreme archangel
  2209. affectedIds.push_back(153); //antichrist
  2210. } //continue adding ...
  2211. case 0: case 1: //none and basic
  2212. {
  2213. affectedIds.push_back(26); //green dragon
  2214. affectedIds.push_back(27); //gold dragon
  2215. affectedIds.push_back(82); //red dragon
  2216. affectedIds.push_back(83); //black dragon
  2217. affectedIds.push_back(96); //behemot
  2218. affectedIds.push_back(97); //ancient behemot
  2219. affectedIds.push_back(110); //hydra
  2220. affectedIds.push_back(111); //chaos hydra
  2221. affectedIds.push_back(132); //azure dragon
  2222. affectedIds.push_back(133); //crystal dragon
  2223. affectedIds.push_back(134); //faerie dragon
  2224. affectedIds.push_back(135); //rust dragon
  2225. affectedIds.push_back(151); //diamond dragon
  2226. affectedIds.push_back(154); //blood dragon
  2227. affectedIds.push_back(155); //darkness dragon
  2228. affectedIds.push_back(156); //ghost behemoth
  2229. affectedIds.push_back(157); //hell hydra
  2230. break;
  2231. }
  2232. }
  2233. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2234. {
  2235. if(defender->creature->idNumber == affectedIds[g])
  2236. {
  2237. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2238. break;
  2239. }
  2240. }
  2241. }
  2242. float dmgBonusMultiplier = 1.0f;
  2243. //applying jousting bonus
  2244. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2245. dmgBonusMultiplier += charge * 0.05f;
  2246. //bonus from attack/defense skills
  2247. if(attackDefenseBonus < 0) //decreasing dmg
  2248. {
  2249. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2250. {
  2251. dmgBonusMultiplier += -0.3f;
  2252. }
  2253. else
  2254. {
  2255. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2256. }
  2257. }
  2258. else //increasing dmg
  2259. {
  2260. if(0.05f * attackDefenseBonus > 4.0f)
  2261. {
  2262. dmgBonusMultiplier += 4.0f;
  2263. }
  2264. else
  2265. {
  2266. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2267. }
  2268. }
  2269. //handling secondary abilities and artifacts giving premies to them
  2270. if(attackerHero)
  2271. {
  2272. if(shooting)
  2273. {
  2274. switch(attackerHero->getSecSkillLevel(1)) //archery
  2275. {
  2276. case 1: //basic
  2277. dmgBonusMultiplier += 0.1f;
  2278. break;
  2279. case 2: //advanced
  2280. dmgBonusMultiplier += 0.25f;
  2281. break;
  2282. case 3: //expert
  2283. dmgBonusMultiplier += 0.5f;
  2284. break;
  2285. }
  2286. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2287. {
  2288. //apply artifact premy to archery
  2289. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2290. }
  2291. }
  2292. else
  2293. {
  2294. switch(attackerHero->getSecSkillLevel(22)) //offense
  2295. {
  2296. case 1: //basic
  2297. dmgBonusMultiplier += 0.1f;
  2298. break;
  2299. case 2: //advanced
  2300. dmgBonusMultiplier += 0.2f;
  2301. break;
  2302. case 3: //expert
  2303. dmgBonusMultiplier += 0.3f;
  2304. break;
  2305. }
  2306. }
  2307. }
  2308. if(defendingHero)
  2309. {
  2310. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2311. {
  2312. case 1: //basic
  2313. dmgBonusMultiplier *= 0.95f;
  2314. break;
  2315. case 2: //advanced
  2316. dmgBonusMultiplier *= 0.9f;
  2317. break;
  2318. case 3: //expert
  2319. dmgBonusMultiplier *= 0.85f;
  2320. break;
  2321. }
  2322. }
  2323. //handling hate effect
  2324. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2325. dmgBonusMultiplier += 0.5f;
  2326. //handling spell effects
  2327. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2328. {
  2329. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2330. }
  2331. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2332. {
  2333. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2334. }
  2335. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2336. {
  2337. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2338. }
  2339. minDmg *= dmgBonusMultiplier;
  2340. maxDmg *= dmgBonusMultiplier;
  2341. if(attacker->getEffect(42)) //curse handling (rest)
  2342. {
  2343. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2344. return std::make_pair(int(minDmg), int(minDmg));
  2345. }
  2346. else if(attacker->getEffect(41)) //bless handling
  2347. {
  2348. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2349. return std::make_pair(int(maxDmg), int(maxDmg));
  2350. }
  2351. else
  2352. {
  2353. return std::make_pair(int(minDmg), int(maxDmg));
  2354. }
  2355. tlog1 << "We are too far in calculateDmg...\n";
  2356. return std::make_pair(0, 0);
  2357. }
  2358. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2359. {
  2360. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2361. if(range.first != range.second)
  2362. return range.first + rand() % (range.second - range.first + 1);
  2363. else
  2364. return range.first;
  2365. }
  2366. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2367. {
  2368. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2369. {
  2370. const CStack * const st = stacks[i];
  2371. si32 killed = (st->alive() ? st->baseAmount - st->amount : st->baseAmount);
  2372. amax(killed, 0);
  2373. if(killed)
  2374. casualties[!st->attackerOwned][st->creature->idNumber] += killed;
  2375. }
  2376. }
  2377. si8 CGameState::battleMaxSpellLevel()
  2378. {
  2379. if(!curB) //there is not battle
  2380. {
  2381. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2382. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2383. }
  2384. si8 levelLimit = SPELL_LEVELS;
  2385. const CGHeroInstance *h1 = curB->heroes[0];
  2386. if(h1)
  2387. {
  2388. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2389. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2390. amin(levelLimit, i->val);
  2391. }
  2392. const CGHeroInstance *h2 = curB->heroes[1];
  2393. if(h2)
  2394. {
  2395. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2396. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2397. amin(levelLimit, i->val);
  2398. }
  2399. return levelLimit;
  2400. }
  2401. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2402. {
  2403. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2404. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2405. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2406. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2407. {
  2408. for(int it=0; it<stacks.size(); ++it)
  2409. {
  2410. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2411. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2412. || (s->id == 26) //Armageddon
  2413. )
  2414. {
  2415. if(stacks[it]->alive())
  2416. attackedCres.insert(stacks[it]);
  2417. }
  2418. }
  2419. }
  2420. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2421. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2422. {
  2423. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2424. {
  2425. CStack * st = getStackT(destinationTile, onlyAlive);
  2426. if(st)
  2427. attackedCres.insert(st);
  2428. }
  2429. else
  2430. {
  2431. for(int it=0; it<stacks.size(); ++it)
  2432. {
  2433. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2434. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2435. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2436. )
  2437. {
  2438. if(!onlyAlive || stacks[it]->alive())
  2439. attackedCres.insert(stacks[it]);
  2440. }
  2441. }
  2442. } //if(caster->getSpellSchoolLevel(s) < 3)
  2443. }
  2444. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2445. {
  2446. CStack * st = getStackT(destinationTile, onlyAlive);
  2447. if(st)
  2448. attackedCres.insert(st);
  2449. }
  2450. else //custom range from attackedHexes
  2451. {
  2452. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2453. {
  2454. CStack * st = getStackT(*it, onlyAlive);
  2455. if(st)
  2456. attackedCres.insert(st);
  2457. }
  2458. }
  2459. return attackedCres;
  2460. }
  2461. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2462. {
  2463. switch(spell->id)
  2464. {
  2465. case 56: //frenzy
  2466. return 1;
  2467. default: //other spells
  2468. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2469. }
  2470. }
  2471. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2472. {
  2473. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2474. if(owner)
  2475. {
  2476. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2477. //base luck/morale calculations
  2478. ret->morale = owner->getCurrentMorale(slot, false);
  2479. ret->luck = owner->getCurrentLuck(slot, false);
  2480. //other bonuses
  2481. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2482. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2483. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2484. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2485. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2486. StackFeature::BONUS_FROM_HERO));
  2487. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2488. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2489. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2490. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2491. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2492. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2493. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2494. ret->firstHPleft = ret->MaxHealth();
  2495. }
  2496. else
  2497. {
  2498. ret->morale = 0;
  2499. ret->luck = 0;
  2500. }
  2501. //native terrain bonuses
  2502. int faction = ret->creature->faction;
  2503. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2504. {
  2505. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2506. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2507. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2508. }
  2509. ret->position = position;
  2510. return ret;
  2511. }
  2512. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2513. {
  2514. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2515. //checking for friendly stacks reducing cost of the spell
  2516. si32 manaReduction = 0;
  2517. for(int g=0; g<stacks.size(); ++g)
  2518. {
  2519. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2520. {
  2521. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2522. }
  2523. }
  2524. return ret + manaReduction;
  2525. }
  2526. int BattleInfo::hexToWallPart(int hex) const
  2527. {
  2528. if(siege == 0) //there is no battle!
  2529. return -1;
  2530. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2531. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2532. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2533. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2534. {
  2535. if(attackable[g].first == hex)
  2536. return attackable[g].second;
  2537. }
  2538. return -1; //not found!
  2539. }
  2540. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2541. {
  2542. bool ac[BFIELD_SIZE];
  2543. std::set<int> occupyable;
  2544. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2545. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2546. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING), true);
  2547. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2548. for(int g=0; g<BFIELD_SIZE; ++g)
  2549. {
  2550. const CStack * atG = getStackT(g);
  2551. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2552. continue;
  2553. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2554. {
  2555. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2556. continue;
  2557. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2558. }
  2559. }
  2560. if(stackPairs.size() > 0)
  2561. {
  2562. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2563. minimalPairs.push_back(stackPairs[0]);
  2564. for(int b=1; b<stackPairs.size(); ++b)
  2565. {
  2566. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2567. {
  2568. minimalPairs.clear();
  2569. minimalPairs.push_back(stackPairs[b]);
  2570. }
  2571. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2572. {
  2573. minimalPairs.push_back(stackPairs[b]);
  2574. }
  2575. }
  2576. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2577. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2578. }
  2579. return std::make_pair<const CStack * , int>(NULL, -1);
  2580. }
  2581. ui32 BattleInfo::calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
  2582. {
  2583. ui32 ret = 0; //value to return
  2584. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2585. //24 - death ripple, 25 - destroy undead, 26 - armageddon
  2586. static std::map <int, int> dmgMultipliers = boost::assign::map_list_of(15, 10)(16, 20)(17, 25)(18, 75)(20, 10)(21, 10)(22, 10)(23, 10)(24, 5)(25, 10)(26, 50);
  2587. //check if spell really does damage - if not, return 0
  2588. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2589. return 0;
  2590. ret = caster->getPrimSkillLevel(2) * dmgMultipliers[sp->id] + sp->powers[caster->getSpellSchoolLevel(sp)];
  2591. //applying sorcerery secondary skill
  2592. switch(caster->getSecSkillLevel(25))
  2593. {
  2594. case 1: //basic
  2595. ret *= 1.05f;
  2596. break;
  2597. case 2: //advanced
  2598. ret *= 1.1f;
  2599. break;
  2600. case 3: //expert
  2601. ret *= 1.15f;
  2602. break;
  2603. }
  2604. //applying hero bonuses
  2605. if(sp->air && caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY) != 0)
  2606. {
  2607. ret *= (100.0f + caster->valOfBonuses(HeroBonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2608. }
  2609. else if(sp->fire && caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY) != 0)
  2610. {
  2611. ret *= (100.0f + caster->valOfBonuses(HeroBonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2612. }
  2613. else if(sp->water && caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY) != 0)
  2614. {
  2615. ret *= (100.0f + caster->valOfBonuses(HeroBonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2616. }
  2617. else if(sp->earth && caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY) != 0)
  2618. {
  2619. ret *= (100.0f + caster->valOfBonuses(HeroBonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2620. }
  2621. //affected creature-specific part
  2622. if(affectedCreature)
  2623. {
  2624. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2625. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2626. {
  2627. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 0);
  2628. ret /= 100;
  2629. }
  2630. else if(sp->fire && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2631. {
  2632. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 1);
  2633. ret /= 100;
  2634. }
  2635. else if(sp->water && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2636. {
  2637. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 2);
  2638. ret /= 100;
  2639. }
  2640. else if (sp->earth && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2641. {
  2642. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, 3);
  2643. ret /= 100;
  2644. }
  2645. //general spell dmg reduction
  2646. if(sp->air && affectedCreature->hasFeatureOfType(StackFeature::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2647. {
  2648. ret *= affectedCreature->valOfFeatures(StackFeature::SPELL_DAMAGE_REDUCTION, -1);
  2649. ret /= 100;
  2650. }
  2651. //dmg increasing
  2652. if( affectedCreature->hasFeatureOfType(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2653. {
  2654. ret *= 100 + affectedCreature->valOfFeatures(StackFeature::MORE_DAMAGE_FROM_SPELL, sp->id);
  2655. ret /= 100;
  2656. }
  2657. }
  2658. return ret;
  2659. }
  2660. bool CGameState::battleCanShoot(int ID, int dest)
  2661. {
  2662. if(!curB)
  2663. return false;
  2664. const CStack *our = curB->getStack(ID),
  2665. *dst = curB->getStackT(dest);
  2666. if(!our || !dst) return false;
  2667. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2668. if(our->hasFeatureOfType(StackFeature::FORGETFULL)) //forgetfulness
  2669. return false;
  2670. if(our->creature->idNumber == 145 && dst) //catapult cannot attack creatures
  2671. return false;
  2672. if(our->hasFeatureOfType(StackFeature::SHOOTER)//it's shooter
  2673. && our->owner != dst->owner
  2674. && dst->alive()
  2675. && (!curB->isStackBlocked(ID)
  2676. || ourHero->hasBonusOfType(HeroBonus::FREE_SHOOTING))
  2677. && our->shots
  2678. )
  2679. return true;
  2680. return false;
  2681. }
  2682. int CGameState::victoryCheck( ui8 player ) const
  2683. {
  2684. const PlayerState *p = getPlayer(player);
  2685. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2686. if(player == checkForStandardWin())
  2687. return -1;
  2688. if(p->human || map->victoryCondition.appliesToAI)
  2689. {
  2690. switch(map->victoryCondition.condition)
  2691. {
  2692. case artifact:
  2693. //check if any hero has winning artifact
  2694. for(size_t i = 0; i < p->heroes.size(); i++)
  2695. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2696. return 1;
  2697. break;
  2698. case gatherTroop:
  2699. {
  2700. //check if in players armies there is enough creatures
  2701. int total = 0; //creature counter
  2702. for(size_t i = 0; i < map->objects.size(); i++)
  2703. {
  2704. const CArmedInstance *ai = NULL;
  2705. if(map->objects[i]
  2706. && map->objects[i]->tempOwner == player //object controlled by player
  2707. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  2708. {
  2709. for(TSlots::const_iterator i=ai->army.slots.begin(); i!=ai->army.slots.end(); ++i) //iterate through army
  2710. if(i->second.first == map->victoryCondition.ID) //it's searched creature
  2711. total += i->second.second;
  2712. }
  2713. }
  2714. if(total >= map->victoryCondition.count)
  2715. return 1;
  2716. }
  2717. break;
  2718. case gatherResource:
  2719. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2720. return 1;
  2721. break;
  2722. case buildCity:
  2723. {
  2724. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2725. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2726. return 1;
  2727. }
  2728. break;
  2729. case buildGrail:
  2730. for(size_t i = 0; i < map->towns.size(); i++)
  2731. if(map->towns[i]->pos == map->victoryCondition.pos
  2732. && map->towns[i]->tempOwner == player
  2733. && vstd::contains(map->towns[i]->builtBuildings, 26))
  2734. return 1;
  2735. break;
  2736. case beatHero:
  2737. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2738. return 1;
  2739. break;
  2740. case captureCity:
  2741. {
  2742. if(map->victoryCondition.obj->tempOwner == player)
  2743. return 1;
  2744. }
  2745. break;
  2746. case beatMonster:
  2747. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2748. return 1;
  2749. break;
  2750. case takeDwellings:
  2751. for(size_t i = 0; i < map->objects.size(); i++)
  2752. {
  2753. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2754. {
  2755. switch(map->objects[i]->ID)
  2756. {
  2757. case 17: case 18: case 19: case 20: //dwellings
  2758. case 216: case 217: case 218:
  2759. return 0; //found not flagged dwelling - player not won
  2760. }
  2761. }
  2762. }
  2763. return 1;
  2764. break;
  2765. case takeMines:
  2766. for(size_t i = 0; i < map->objects.size(); i++)
  2767. {
  2768. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2769. {
  2770. switch(map->objects[i]->ID)
  2771. {
  2772. case 53: case 220:
  2773. return 0; //found not flagged mine - player not won
  2774. }
  2775. }
  2776. }
  2777. return 1;
  2778. break;
  2779. case transportItem:
  2780. {
  2781. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2782. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  2783. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  2784. {
  2785. return 1;
  2786. }
  2787. }
  2788. break;
  2789. }
  2790. }
  2791. return 0;
  2792. }
  2793. ui8 CGameState::checkForStandardWin() const
  2794. {
  2795. //std victory condition is:
  2796. //all enemies lost
  2797. ui8 supposedWinner = 255, winnerTeam = 255;
  2798. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2799. {
  2800. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2801. {
  2802. if(supposedWinner == 255)
  2803. {
  2804. //first player remaining ingame - candidate for victory
  2805. supposedWinner = i->second.color;
  2806. winnerTeam = map->players[supposedWinner].team;
  2807. }
  2808. else if(winnerTeam != map->players[i->second.color].team)
  2809. {
  2810. //current candidate has enemy remaining in game -> no vicotry
  2811. return 255;
  2812. }
  2813. }
  2814. }
  2815. return supposedWinner;
  2816. }
  2817. bool CGameState::checkForStandardLoss( ui8 player ) const
  2818. {
  2819. //std loss condition is: player lost all towns and heroes
  2820. const PlayerState &p = *getPlayer(player);
  2821. return !p.heroes.size() && !p.towns.size();
  2822. }
  2823. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2824. {
  2825. struct HLP
  2826. {
  2827. typedef std::pair< ui8, si64 > TStat;
  2828. //converts [<player's color, value>] to vec[place] -> platers
  2829. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2830. {
  2831. std::sort(stats.begin(), stats.end(), HLP());
  2832. //put first element
  2833. std::vector< std::list<ui8> > ret;
  2834. std::list<ui8> tmp;
  2835. tmp.push_back( stats[0].first );
  2836. ret.push_back( tmp );
  2837. //the rest of elements
  2838. for(int g=1; g<stats.size(); ++g)
  2839. {
  2840. if(stats[g].second == stats[g-1].second)
  2841. {
  2842. (ret.end()-1)->push_back( stats[g].first );
  2843. }
  2844. else
  2845. {
  2846. //create next occupied rank
  2847. std::list<ui8> tmp;
  2848. tmp.push_back(stats[g].first);
  2849. ret.push_back(tmp);
  2850. }
  2851. }
  2852. return ret;
  2853. }
  2854. bool operator()(const TStat & a, const TStat & b) const
  2855. {
  2856. return a.second > b.second;
  2857. }
  2858. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2859. {
  2860. //best hero will be that with highest exp
  2861. int best = 0;
  2862. for(int b=1; b<gs->players[color].heroes.size(); ++b)
  2863. {
  2864. if(gs->players[color].heroes[b]->exp > gs->players[color].heroes[best]->exp)
  2865. {
  2866. best = b;
  2867. }
  2868. }
  2869. return gs->players[color].heroes[best];
  2870. }
  2871. //calculates total number of artifacts that belong to given player
  2872. static int getNumberOfArts(const PlayerState * ps)
  2873. {
  2874. int ret = 0;
  2875. for(int g=0; g<ps->heroes.size(); ++g)
  2876. {
  2877. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2878. }
  2879. return ret;
  2880. }
  2881. };
  2882. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2883. { \
  2884. std::vector< std::pair< ui8, si64 > > stats; \
  2885. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2886. { \
  2887. if(g->second.color == 255) \
  2888. continue; \
  2889. std::pair< ui8, si64 > stat; \
  2890. stat.first = g->second.color; \
  2891. stat.second = VAL_GETTER; \
  2892. stats.push_back(stat); \
  2893. } \
  2894. tgi.FIELD = HLP::getRank(stats); \
  2895. }
  2896. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2897. {
  2898. if(g->second.color != 255)
  2899. tgi.playerColors.push_back(g->second.color);
  2900. }
  2901. if(level >= 1) //num of towns & num of heroes
  2902. {
  2903. //num of towns
  2904. FILL_FIELD(numOfTowns, g->second.towns.size())
  2905. //num of heroes
  2906. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2907. //best hero's portrait
  2908. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2909. {
  2910. if(g->second.color == 255)
  2911. continue;
  2912. const CGHeroInstance * best = HLP::findBestHero(this, g->second.color);
  2913. InfoAboutHero iah;
  2914. iah.initFromHero(best, level >= 8);
  2915. iah.army.slots.clear();
  2916. tgi.colorToBestHero[g->second.color] = iah;
  2917. }
  2918. }
  2919. if(level >= 2) //gold
  2920. {
  2921. FILL_FIELD(gold, g->second.resources[6])
  2922. }
  2923. if(level >= 2) //wood & ore
  2924. {
  2925. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  2926. }
  2927. if(level >= 3) //mercury, sulfur, crystal, gems
  2928. {
  2929. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  2930. }
  2931. if(level >= 4) //obelisks found
  2932. {
  2933. //TODO
  2934. }
  2935. if(level >= 5) //artifacts
  2936. {
  2937. FILL_FIELD(artifacts, HLP::getNumberOfArts(&g->second))
  2938. }
  2939. if(level >= 6) //army strength
  2940. {
  2941. //TODO
  2942. }
  2943. if(level >= 7) //income
  2944. {
  2945. //TODO
  2946. }
  2947. if(level >= 8) //best hero's stats
  2948. {
  2949. //already set in lvl 1 handling
  2950. }
  2951. if(level >= 9) //personality
  2952. {
  2953. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2954. {
  2955. if(g->second.color == 255) //do nothing for neutral player
  2956. continue;
  2957. if(g->second.human)
  2958. {
  2959. tgi.personality[g->second.color] = -1;
  2960. }
  2961. else //AI
  2962. {
  2963. tgi.personality[g->second.color] = map->players[g->second.serial].AITactic;
  2964. }
  2965. }
  2966. }
  2967. if(level >= 10) //best creature
  2968. {
  2969. //best creatures belonging to player (highest AI value)
  2970. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2971. {
  2972. if(g->second.color == 255) //do nothing for neutral player
  2973. continue;
  2974. int bestCre = -1; //best creature's ID
  2975. for(int b=0; b<g->second.heroes.size(); ++b)
  2976. {
  2977. for(TSlots::const_iterator it = g->second.heroes[b]->army.slots.begin(); it != g->second.heroes[b]->army.slots.end(); ++it)
  2978. {
  2979. int toCmp = it->second.first; //ID of creature we should compare with the best one
  2980. if(bestCre == -1 || VLC->creh->creatures[bestCre].AIValue < VLC->creh->creatures[toCmp].AIValue)
  2981. {
  2982. bestCre = toCmp;
  2983. }
  2984. }
  2985. }
  2986. tgi.bestCreature[g->second.color] = bestCre;
  2987. }
  2988. }
  2989. #undef FILL_FIELD
  2990. }
  2991. int CGameState::lossCheck( ui8 player ) const
  2992. {
  2993. const PlayerState *p = getPlayer(player);
  2994. //if(map->lossCondition.typeOfLossCon == lossStandard)
  2995. if(checkForStandardLoss(player))
  2996. return -1;
  2997. if(p->human) //special loss condition applies only to human player
  2998. {
  2999. switch(map->lossCondition.typeOfLossCon)
  3000. {
  3001. case lossCastle:
  3002. {
  3003. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3004. assert(t);
  3005. if(t->tempOwner != player)
  3006. return 1;
  3007. }
  3008. break;
  3009. case lossHero:
  3010. {
  3011. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3012. assert(h);
  3013. if(h->tempOwner != player)
  3014. return 1;
  3015. }
  3016. break;
  3017. case timeExpires:
  3018. if(map->lossCondition.timeLimit < day)
  3019. return 1;
  3020. break;
  3021. }
  3022. }
  3023. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3024. return 2;
  3025. return false;
  3026. }
  3027. const CStack * BattleInfo::getNextStack() const
  3028. {
  3029. std::vector<const CStack *> hlp;
  3030. getStackQueue(hlp, 1, -1);
  3031. if(hlp.size())
  3032. return hlp[0];
  3033. else
  3034. return NULL;
  3035. }
  3036. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3037. {
  3038. const CStack *ret = NULL;
  3039. unsigned i, //fastest stack
  3040. j; //fastest stack of the other side
  3041. for(i = 0; i < st.size(); i++)
  3042. if(st[i])
  3043. break;
  3044. //no stacks left
  3045. if(i == st.size())
  3046. return NULL;
  3047. const CStack *fastest = st[i], *other = NULL;
  3048. int bestSpeed = fastest->Speed(turn);
  3049. if(fastest->attackerOwned != curside)
  3050. {
  3051. ret = fastest;
  3052. }
  3053. else
  3054. {
  3055. for(j = i + 1; j < st.size(); j++)
  3056. {
  3057. if(!st[j]) continue;
  3058. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3059. break;
  3060. }
  3061. if(j >= st.size())
  3062. {
  3063. ret = fastest;
  3064. }
  3065. else
  3066. {
  3067. other = st[j];
  3068. if(other->Speed(turn) != bestSpeed)
  3069. ret = fastest;
  3070. else
  3071. ret = other;
  3072. }
  3073. }
  3074. assert(ret);
  3075. if(ret == fastest)
  3076. st[i] = NULL;
  3077. else
  3078. st[j] = NULL;
  3079. curside = ret->attackerOwned;
  3080. return ret;
  3081. }
  3082. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3083. {
  3084. //we'll split creatures with remaining movement to 4 parts
  3085. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  3086. int toMove = 0; //how many stacks still has move
  3087. const CStack *active = getStack(activeStack);
  3088. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3089. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3090. {
  3091. out.push_back(active);
  3092. if(out.size() == howMany)
  3093. return;
  3094. }
  3095. for(unsigned int i=0; i<stacks.size(); ++i)
  3096. {
  3097. const CStack * const s = stacks[i];
  3098. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3099. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3100. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3101. {
  3102. continue;
  3103. }
  3104. int p = -1; //in which phase this tack will move?
  3105. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3106. {
  3107. if(vstd::contains(s->state, HAD_MORALE))
  3108. p = 2;
  3109. else
  3110. p = 3;
  3111. }
  3112. else if(s->creature->idNumber == 145 || s->creature->idNumber == 149) //catapult and turrets are first
  3113. {
  3114. p = 0;
  3115. }
  3116. else
  3117. {
  3118. p = 1;
  3119. }
  3120. phase[p].push_back(s);
  3121. toMove++;
  3122. }
  3123. for(int i = 0; i < 4; i++)
  3124. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3125. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3126. out.push_back(phase[0][i]);
  3127. if(out.size() == howMany)
  3128. return;
  3129. if(lastMoved == -1)
  3130. {
  3131. if(active)
  3132. {
  3133. if(out.size() && out.front() == active)
  3134. lastMoved = active->attackerOwned;
  3135. else
  3136. lastMoved = active->attackerOwned;
  3137. }
  3138. else
  3139. {
  3140. lastMoved = 0;
  3141. }
  3142. }
  3143. int pi = 1;
  3144. while(out.size() < howMany)
  3145. {
  3146. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3147. if(!hlp)
  3148. {
  3149. pi++;
  3150. if(pi > 3)
  3151. {
  3152. //if(turn != 2)
  3153. getStackQueue(out, howMany, turn + 1, lastMoved);
  3154. return;
  3155. }
  3156. }
  3157. else
  3158. {
  3159. out.push_back(hlp);
  3160. }
  3161. }
  3162. }
  3163. int3 CPath::startPos() const
  3164. {
  3165. return nodes[nodes.size()-1].coord;
  3166. }
  3167. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3168. {
  3169. if (mode==0)
  3170. {
  3171. for (unsigned int i=0;i<nodes.size();i++)
  3172. {
  3173. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3174. }
  3175. }
  3176. }
  3177. int3 CPath::endPos() const
  3178. {
  3179. return nodes[0].coord;
  3180. }
  3181. CGPathNode::CGPathNode()
  3182. :coord(-1,-1,-1)
  3183. {
  3184. accessible = 0;
  3185. land = 0;
  3186. moveRemains = 0;
  3187. turns = 255;
  3188. theNodeBefore = NULL;
  3189. }
  3190. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3191. {
  3192. out.nodes.clear();
  3193. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3194. if(!curnode->theNodeBefore)
  3195. return false;
  3196. while(curnode)
  3197. {
  3198. out.nodes.push_back(*curnode);
  3199. curnode = curnode->theNodeBefore;
  3200. }
  3201. return true;
  3202. }
  3203. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3204. :sizes(Sizes)
  3205. {
  3206. hero = NULL;
  3207. nodes = new CGPathNode**[sizes.x];
  3208. for(int i = 0; i < sizes.x; i++)
  3209. {
  3210. nodes[i] = new CGPathNode*[sizes.y];
  3211. for (int j = 0; j < sizes.y; j++)
  3212. {
  3213. nodes[i][j] = new CGPathNode[sizes.z];
  3214. }
  3215. }
  3216. }
  3217. CPathsInfo::~CPathsInfo()
  3218. {
  3219. for(int i = 0; i < sizes.x; i++)
  3220. {
  3221. for (int j = 0; j < sizes.y; j++)
  3222. {
  3223. delete [] nodes[i][j];
  3224. }
  3225. delete [] nodes[i];
  3226. }
  3227. delete [] nodes;
  3228. }
  3229. int3 CGPath::startPos() const
  3230. {
  3231. return nodes[nodes.size()-1].coord;
  3232. }
  3233. int3 CGPath::endPos() const
  3234. {
  3235. return nodes[0].coord;
  3236. }
  3237. void CGPath::convert( ui8 mode )
  3238. {
  3239. if(mode==0)
  3240. {
  3241. for(unsigned int i=0;i<nodes.size();i++)
  3242. {
  3243. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3244. }
  3245. }
  3246. }
  3247. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3248. {
  3249. switch(phase)
  3250. {
  3251. case 0: //catapult moves after turrets
  3252. return a->creature->idNumber < b->creature->idNumber; //catapult is 145 and turrets are 149
  3253. //TODO? turrets order
  3254. case 1: //fastest first, upper slot first
  3255. {
  3256. int as = a->Speed(turn), bs = b->Speed(turn);
  3257. if(as != bs)
  3258. return as > bs;
  3259. else
  3260. return a->slot < b->slot;
  3261. }
  3262. case 2: //fastest last, upper slot first
  3263. //TODO: should be replaced with order of receiving morale!
  3264. case 3: //fastest last, upper slot first
  3265. {
  3266. int as = a->Speed(turn), bs = b->Speed(turn);
  3267. if(as != bs)
  3268. return as < bs;
  3269. else
  3270. return a->slot < b->slot;
  3271. }
  3272. default:
  3273. assert(0);
  3274. return false;
  3275. }
  3276. }
  3277. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3278. {
  3279. phase = Phase;
  3280. turn = Turn;
  3281. }
  3282. PlayerState::PlayerState()
  3283. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0)
  3284. {
  3285. }
  3286. InfoAboutHero::InfoAboutHero()
  3287. {
  3288. details = NULL;
  3289. hclass = NULL;
  3290. portrait = -1;
  3291. }
  3292. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3293. {
  3294. assign(iah);
  3295. }
  3296. InfoAboutHero::~InfoAboutHero()
  3297. {
  3298. delete details;
  3299. }
  3300. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3301. {
  3302. owner = h->tempOwner;
  3303. hclass = h->type->heroClass;
  3304. name = h->name;
  3305. portrait = h->portrait;
  3306. army = h->army;
  3307. if(detailed)
  3308. {
  3309. //include details about hero
  3310. details = new Details;
  3311. details->luck = h->getCurrentLuck();
  3312. details->morale = h->getCurrentMorale();
  3313. details->mana = h->mana;
  3314. details->primskills.resize(PRIMARY_SKILLS);
  3315. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3316. {
  3317. details->primskills[i] = h->getPrimSkillLevel(i);
  3318. }
  3319. }
  3320. else
  3321. {
  3322. //hide info about hero stacks counts using descriptives names ids
  3323. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army.slots.begin(); i != army.slots.end(); ++i)
  3324. {
  3325. i->second.second = CCreature::getQuantityID(i->second.second);
  3326. }
  3327. }
  3328. }
  3329. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3330. {
  3331. army = iah.army;
  3332. details = (iah.details ? new Details(*iah.details) : NULL);
  3333. hclass = iah.hclass;
  3334. name = iah.name;
  3335. owner = iah.owner;
  3336. portrait = iah.portrait;
  3337. }
  3338. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3339. {
  3340. assign(iah);
  3341. return *this;
  3342. }