CGameState.cpp 116 KB

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