2
0

CGameState.cpp 106 KB

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