CGameState.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268
  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; // 1 - Monday, 7 - Sunday
  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. //it's assumed that given hero should receive the bonus
  1102. static void giveCampaignBonusToHero(CGHeroInstance * hero, const StartInfo * si, const CScenarioTravel & st )
  1103. {
  1104. const CScenarioTravel::STravelBonus & curBonus = st.bonusesToChoose[si->choosenCampaignBonus];
  1105. if(curBonus.isBonusForHero())
  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. {
  1115. CCreatureSet newArmy = hero->getArmy();
  1116. for(int i=0; i<ARMY_SIZE; i++)
  1117. {
  1118. if(newArmy.slotEmpty(i))
  1119. {
  1120. newArmy.addToSlot(i, CStackInstance(curBonus.info2, curBonus.info3));
  1121. break;
  1122. }
  1123. }
  1124. hero->setArmy(newArmy);
  1125. }
  1126. break;
  1127. case 3: //artifact
  1128. hero->giveArtifact(curBonus.info2);
  1129. break;
  1130. case 4: //spell scroll
  1131. //TODO
  1132. break;
  1133. case 5: //prim skill
  1134. {
  1135. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus.info2);
  1136. for (int g=0; g<PRIMARY_SKILLS; ++g)
  1137. {
  1138. int val = ptr[g];
  1139. if (val == 0)
  1140. {
  1141. continue;
  1142. }
  1143. Bonus bb(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, si->whichMapInCampaign, g);
  1144. hero->bonuses.push_back(bb);
  1145. }
  1146. }
  1147. break;
  1148. case 6: //sec skills
  1149. hero->setSecSkillLevel(curBonus.info2, curBonus.info3, true);
  1150. break;
  1151. }
  1152. }
  1153. }
  1154. static std::vector<const PlayerSettings *> getHumanPlayerInfo(const StartInfo * si)
  1155. {
  1156. std::vector<const PlayerSettings *> ret;
  1157. for(std::map<int, PlayerSettings>::const_iterator it = si->playerInfos.begin();
  1158. it != si->playerInfos.end(); ++it)
  1159. {
  1160. if(it->second.human)
  1161. ret.push_back(&it->second);
  1162. }
  1163. return ret;
  1164. }
  1165. };
  1166. switch(si->mode)
  1167. {
  1168. case StartInfo::NEW_GAME:
  1169. map = new Mapa(si->mapname);
  1170. break;
  1171. case StartInfo::CAMPAIGN:
  1172. {
  1173. campaign = new CCampaignState();
  1174. campaign->initNewCampaign(*si);
  1175. assert(vstd::contains(campaign->camp->mapPieces, si->whichMapInCampaign));
  1176. std::string &mapContent = campaign->camp->mapPieces[si->whichMapInCampaign];
  1177. map = new Mapa();
  1178. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1179. }
  1180. break;
  1181. default:
  1182. tlog1 << "Wrong mode: " << (int)si->mode << std::endl;
  1183. return;
  1184. }
  1185. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  1186. tlog0 << "Map loaded!" << std::endl;
  1187. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1188. if(checksum)
  1189. {
  1190. tlog0 << "\tServer checksum for " << si->mapname <<": "<< checksum << std::endl;
  1191. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1192. if(map->checksum != checksum)
  1193. {
  1194. tlog1 << "Wrong map checksum!!!" << std::endl;
  1195. throw std::string("Wrong checksum");
  1196. }
  1197. }
  1198. day = 0;
  1199. seed = Seed;
  1200. ran.seed((boost::int32_t)seed);
  1201. scenarioOps = si;
  1202. loadTownDInfos();
  1203. //pick grail location
  1204. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1205. {
  1206. if(!map->grailRadious) //radius not given -> anywhere on map
  1207. map->grailRadious = map->width * 2;
  1208. std::vector<int3> allowedPos;
  1209. // add all not blocked tiles in range
  1210. for (int i = 0; i < map->width ; i++)
  1211. {
  1212. for (int j = 0; j < map->height ; j++)
  1213. {
  1214. for (int k = 0; k <= map->twoLevel ; k++)
  1215. {
  1216. const TerrainTile &t = map->terrain[i][j][k];
  1217. if(!t.blocked
  1218. && !t.visitable
  1219. && t.tertype != TerrainTile::water
  1220. && t.tertype != TerrainTile::rock
  1221. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1222. allowedPos.push_back(int3(i,j,k));
  1223. }
  1224. }
  1225. }
  1226. //remove tiles with holes
  1227. for(unsigned int no=0; no<map->objects.size(); ++no)
  1228. if(map->objects[no]->ID == 124)
  1229. allowedPos -= map->objects[no]->pos;
  1230. if(allowedPos.size())
  1231. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1232. else
  1233. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1234. }
  1235. //picking random factions for players
  1236. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  1237. it != scenarioOps->playerInfos.end(); ++it)
  1238. {
  1239. if(it->second.castle==-1)
  1240. {
  1241. int f;
  1242. do
  1243. {
  1244. f = ran()%F_NUMBER;
  1245. }while(!(map->players[it->first].allowedFactions & 1<<f));
  1246. it->second.castle = f;
  1247. }
  1248. }
  1249. //randomizing objects
  1250. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1251. {
  1252. randomizeObject(obj);
  1253. if(obj->ID==EVENTI_TYPE)
  1254. {
  1255. obj->defInfo->handler=NULL;
  1256. }
  1257. obj->hoverName = VLC->generaltexth->names[obj->ID];
  1258. //handle Favouring Winds - mark tiles under it
  1259. if(obj->ID == 225)
  1260. for (int i = 0; i < obj->getWidth() ; i++)
  1261. for (int j = 0; j < obj->getHeight() ; j++)
  1262. {
  1263. int3 pos = obj->pos - int3(i,j,0);
  1264. if(map->isInTheMap(pos))
  1265. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  1266. }
  1267. }
  1268. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1269. /*********creating players entries in gs****************************************/
  1270. for(std::map<int, PlayerSettings>::iterator it = scenarioOps->playerInfos.begin();
  1271. it != scenarioOps->playerInfos.end(); ++it)
  1272. {
  1273. std::pair<int,PlayerState> ins(it->first,PlayerState());
  1274. ins.second.color=ins.first;
  1275. ins.second.human = it->second.human;
  1276. ins.second.team = map->players[ins.first].team;
  1277. teams[ins.second.team].id = ins.second.team;//init team
  1278. teams[ins.second.team].players.insert(ins.first);//add player to team
  1279. players.insert(ins);
  1280. }
  1281. /*********give starting hero****************************************/
  1282. for(int i=0;i<PLAYER_LIMIT;i++)
  1283. {
  1284. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1285. {
  1286. int3 hpos = map->players[i].posOfMainTown;
  1287. hpos.x+=1;// hpos.y+=1;
  1288. if (scenarioOps->playerInfos.find(i) == scenarioOps->playerInfos.end())
  1289. {
  1290. continue;
  1291. }
  1292. int h=pickHero(i);
  1293. if(scenarioOps->playerInfos[i].hero == -1)
  1294. scenarioOps->playerInfos[i].hero = h;
  1295. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1296. nnn->id = map->objects.size();
  1297. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1298. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1299. {
  1300. if(map->towns[o]->pos == hpos)
  1301. {
  1302. map->towns[o]->visitingHero = nnn;
  1303. nnn->visitedTown = map->towns[o];
  1304. nnn->inTownGarrison = false;
  1305. break;
  1306. }
  1307. }
  1308. nnn->initHero();
  1309. map->heroes.push_back(nnn);
  1310. map->objects.push_back(nnn);
  1311. map->addBlockVisTiles(nnn);
  1312. //give campaign bonus
  1313. if (si->mode == StartInfo::CAMPAIGN && getPlayer(nnn->tempOwner)->human)
  1314. {
  1315. HLP::giveCampaignBonusToHero(nnn, si, campaign->camp->scenarios[si->whichMapInCampaign].travelOptions);
  1316. }
  1317. }
  1318. }
  1319. /******************RESOURCES****************************************************/
  1320. std::vector<int> startresAI, startresHuman;
  1321. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1322. int k;
  1323. for (int j=0; j<scenarioOps->difficulty * 2; j++)
  1324. {
  1325. tis >> k;
  1326. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1327. tis>>k;
  1328. }
  1329. tis >> k;
  1330. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1331. {
  1332. tis >> k;
  1333. startresHuman.push_back(k);
  1334. }
  1335. tis >> k;
  1336. for (int i=0; i<RESOURCE_QUANTITY; i++)
  1337. {
  1338. tis >> k;
  1339. startresAI.push_back(k);
  1340. }
  1341. tis.close();
  1342. tis.clear();
  1343. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1344. {
  1345. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1346. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1347. {
  1348. if (i->second.human)
  1349. {
  1350. (*i).second.resources[x] = startresHuman[x];
  1351. }
  1352. else
  1353. {
  1354. (*i).second.resources[x] = startresAI[x];
  1355. }
  1356. }
  1357. }
  1358. //give start resource bonus in case of campaign
  1359. if (si->mode == StartInfo::CAMPAIGN)
  1360. {
  1361. CScenarioTravel::STravelBonus chosenBonus =
  1362. campaign->camp->scenarios[si->whichMapInCampaign].travelOptions.bonusesToChoose[si->choosenCampaignBonus];
  1363. if(chosenBonus.type == 7) //resource
  1364. {
  1365. std::vector<const PlayerSettings *> people = HLP::getHumanPlayerInfo(si); //players we will give resource bonus
  1366. for (int b=0; b<people.size(); ++b)
  1367. {
  1368. std::vector<int> res; //resources we will give
  1369. switch (chosenBonus.info1)
  1370. {
  1371. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1372. res.push_back(chosenBonus.info1);
  1373. break;
  1374. case 0xFD: //wood+ore
  1375. res.push_back(0); res.push_back(2);
  1376. break;
  1377. case 0xFE: //rare
  1378. res.push_back(1); res.push_back(3); res.push_back(4); res.push_back(5);
  1379. break;
  1380. default:
  1381. assert(0);
  1382. break;
  1383. }
  1384. //increasing resource quantity
  1385. for (int n=0; n<res.size(); ++n)
  1386. {
  1387. players[people[b]->color].resources[res[n]] += chosenBonus.info2;
  1388. }
  1389. }
  1390. }
  1391. }
  1392. /*************************HEROES************************************************/
  1393. std::set<int> hids; //hero ids to create pool
  1394. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1395. if(map->allowedHeroes[i])
  1396. hids.insert(i);
  1397. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1398. {
  1399. if (map->heroes[i]->getOwner()<0)
  1400. {
  1401. tlog2 << "Warning - hero with uninitialized owner!\n";
  1402. continue;
  1403. }
  1404. CGHeroInstance * vhi = (map->heroes[i]);
  1405. vhi->initHero();
  1406. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1407. hids.erase(vhi->subID);
  1408. }
  1409. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1410. {
  1411. if (map->objects[i]->ID == 62)
  1412. hids.erase(map->objects[i]->subID);
  1413. }
  1414. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1415. {
  1416. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1417. continue;
  1418. map->predefinedHeroes[i]->initHero();
  1419. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1420. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1421. hids.erase(map->predefinedHeroes[i]->subID);
  1422. }
  1423. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1424. {
  1425. CGHeroInstance * vhi = new CGHeroInstance();
  1426. vhi->initHero(hid);
  1427. hpool.heroesPool[hid] = vhi;
  1428. hpool.pavailable[hid] = 0xff;
  1429. }
  1430. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1431. {
  1432. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1433. }
  1434. if (si->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1435. {
  1436. CScenarioTravel::STravelBonus chosenBonus =
  1437. campaign->camp->scenarios[si->whichMapInCampaign].travelOptions.bonusesToChoose[si->choosenCampaignBonus];
  1438. if (chosenBonus.isBonusForHero() && chosenBonus.info1 != 0xFFFE) //exclude generated heroes
  1439. {
  1440. //find human player
  1441. int humanPlayer;
  1442. for (std::map<ui8, PlayerState>::iterator it=players.begin(); it != players.end(); ++it)
  1443. {
  1444. if(it->second.human)
  1445. {
  1446. humanPlayer = it->first;
  1447. break;
  1448. }
  1449. }
  1450. std::vector<CGHeroInstance *> & heroes = players[humanPlayer].heroes;
  1451. if (chosenBonus.info1 == 0xFFFD) //most powerful
  1452. {
  1453. int maxB = -1;
  1454. for (int b=0; b<heroes.size(); ++b)
  1455. {
  1456. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1457. {
  1458. maxB = b;
  1459. }
  1460. }
  1461. HLP::giveCampaignBonusToHero(heroes[maxB], si, campaign->camp->scenarios[si->whichMapInCampaign].travelOptions);
  1462. }
  1463. else //specific hero
  1464. {
  1465. for (int b=0; b<heroes.size(); ++b)
  1466. {
  1467. if (heroes[b]->subID == chosenBonus.info1)
  1468. {
  1469. HLP::giveCampaignBonusToHero(heroes[b], si, campaign->camp->scenarios[si->whichMapInCampaign].travelOptions);
  1470. break;
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. /*************************FOG**OF**WAR******************************************/
  1477. for(std::map<ui8, TeamState>::iterator k=teams.begin(); k!=teams.end(); ++k)
  1478. {
  1479. k->second.fogOfWarMap.resize(map->width);
  1480. for(int g=0; g<map->width; ++g)
  1481. k->second.fogOfWarMap[g].resize(map->height);
  1482. for(int g=-0; g<map->width; ++g)
  1483. for(int h=0; h<map->height; ++h)
  1484. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1485. for(int g=0; g<map->width; ++g)
  1486. for(int h=0; h<map->height; ++h)
  1487. for(int v=0; v<map->twoLevel+1; ++v)
  1488. k->second.fogOfWarMap[g][h][v] = 0;
  1489. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1490. {
  1491. if( !vstd::contains(k->second.players, obj->tempOwner)) continue; //not a flagged object
  1492. std::set<int3> tiles;
  1493. obj->getSightTiles(tiles);
  1494. BOOST_FOREACH(int3 tile, tiles)
  1495. {
  1496. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1497. }
  1498. }
  1499. }
  1500. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1501. {
  1502. //starting bonus
  1503. if(si->playerInfos[k->first].bonus==PlayerSettings::brandom)
  1504. si->playerInfos[k->first].bonus = ran()%3;
  1505. switch(si->playerInfos[k->first].bonus)
  1506. {
  1507. case PlayerSettings::bgold:
  1508. k->second.resources[6] += 500 + (ran()%6)*100;
  1509. break;
  1510. case PlayerSettings::bresource:
  1511. {
  1512. int res = VLC->townh->towns[si->playerInfos[k->first].castle].primaryRes;
  1513. if(res == 127)
  1514. {
  1515. k->second.resources[0] += 5 + ran()%6;
  1516. k->second.resources[2] += 5 + ran()%6;
  1517. }
  1518. else
  1519. {
  1520. k->second.resources[res] += 3 + ran()%4;
  1521. }
  1522. break;
  1523. }
  1524. case PlayerSettings::bartifact:
  1525. {
  1526. if(!k->second.heroes.size())
  1527. {
  1528. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1529. break;
  1530. }
  1531. CArtifact *toGive;
  1532. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1533. CGHeroInstance *hero = k->second.heroes[0];
  1534. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  1535. if(slot != toGive->possibleSlots.end())
  1536. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id);
  1537. else
  1538. hero->giveArtifact(toGive->id);
  1539. }
  1540. }
  1541. }
  1542. /****************************TOWNS************************************************/
  1543. for ( int i=0; i<4; i++)
  1544. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1545. for (unsigned int i=0;i<map->towns.size();i++)
  1546. {
  1547. CGTownInstance * vti =(map->towns[i]);
  1548. if(!vti->town)
  1549. vti->town = &VLC->townh->towns[vti->subID];
  1550. if (vti->name.length()==0) // if town hasn't name we draw it
  1551. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1552. //init buildings
  1553. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1554. {
  1555. vti->builtBuildings.erase(-50);
  1556. vti->builtBuildings.insert(10);
  1557. vti->builtBuildings.insert(5);
  1558. vti->builtBuildings.insert(30);
  1559. if(ran()%2)
  1560. vti->builtBuildings.insert(31);
  1561. }
  1562. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==2)
  1563. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1564. //init hordes
  1565. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1566. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1567. {
  1568. vti->builtBuildings.erase(-31-i);//remove old ID
  1569. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1570. {
  1571. vti->builtBuildings.insert(18);//add it
  1572. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1573. vti->builtBuildings.insert(19);//add it as well
  1574. }
  1575. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1576. {
  1577. vti->builtBuildings.insert(24);
  1578. if (vstd::contains(vti->builtBuildings,(37+i)))
  1579. vti->builtBuildings.insert(25);
  1580. }
  1581. }
  1582. //init spells
  1583. vti->spells.resize(SPELL_LEVELS);
  1584. CSpell *s;
  1585. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1586. {
  1587. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1588. vti->spells[s->level-1].push_back(s->id);
  1589. vti->possibleSpells -= s->id;
  1590. }
  1591. while(vti->possibleSpells.size())
  1592. {
  1593. ui32 total=0, sel=-1;
  1594. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1595. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1596. int r = (total)? ran()%total : -1;
  1597. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1598. {
  1599. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1600. if(r<0)
  1601. {
  1602. sel = ps;
  1603. break;
  1604. }
  1605. }
  1606. if(sel<0)
  1607. sel=0;
  1608. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1609. vti->spells[s->level-1].push_back(s->id);
  1610. vti->possibleSpells -= s->id;
  1611. }
  1612. if(vti->getOwner() != 255)
  1613. getPlayer(vti->getOwner())->towns.push_back(vti);
  1614. }
  1615. //campaign bonuses for towns
  1616. if (si->mode == StartInfo::CAMPAIGN)
  1617. {
  1618. CScenarioTravel::STravelBonus chosenBonus =
  1619. campaign->camp->scenarios[si->whichMapInCampaign].travelOptions.bonusesToChoose[si->choosenCampaignBonus];
  1620. if (chosenBonus.type == 2)
  1621. {
  1622. for (int g=0; g<map->towns.size(); ++g)
  1623. {
  1624. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1625. PlayerInfo & pi = map->players[owner->color];
  1626. if (owner->human && //human-owned
  1627. map->towns[g]->pos == pi.posOfMainTown + int3(2, 0, 0))
  1628. {
  1629. map->towns[g]->builtBuildings.insert(
  1630. CBuildingHandler::campToERMU(chosenBonus.info1, map->towns[g]->town->typeID, map->towns[g]->builtBuildings));
  1631. break;
  1632. }
  1633. }
  1634. }
  1635. }
  1636. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1637. {
  1638. if(k->first==-1 || k->first==255)
  1639. continue;
  1640. //init visiting and garrisoned heroes
  1641. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1642. {
  1643. CGHeroInstance *h = k->second.heroes[l];
  1644. for(unsigned int m=0; m<k->second.towns.size();m++)
  1645. {
  1646. CGTownInstance *t = k->second.towns[m];
  1647. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1648. if(vistile == h->pos || h->pos==t->pos)
  1649. {
  1650. t->visitingHero = h;
  1651. h->visitedTown = t;
  1652. h->inTownGarrison = false;
  1653. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1654. {
  1655. map->removeBlockVisTiles(h);
  1656. h->pos.x -= 1;
  1657. map->addBlockVisTiles(h);
  1658. }
  1659. break;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. objCaller->preInit();
  1665. for(unsigned int i=0; i<map->objects.size(); i++)
  1666. {
  1667. map->objects[i]->initObj();
  1668. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1669. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1670. }
  1671. CGTeleport::postInit(); //pairing subterranean gates
  1672. }
  1673. bool CGameState::battleCanFlee(int player)
  1674. {
  1675. if(!curB) //there is no battle
  1676. return false;
  1677. if (player == curB->side1)
  1678. {
  1679. if (!curB->heroes[0])
  1680. return false;//current player have no hero
  1681. }
  1682. else
  1683. {
  1684. if (!curB->heroes[1])
  1685. return false;
  1686. }
  1687. if( ( curB->heroes[0] && curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) ) //eg. one of heroes is wearing shakles of war
  1688. || ( curB->heroes[1] && curB->heroes[1]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE)))
  1689. return false;
  1690. if (player == curB->side2 && curB->siege //defender in siege
  1691. && !(getTown(curB->tid)->subID == 6 && vstd::contains(getTown(curB->tid)->builtBuildings, 17)))//without escape tunnel
  1692. return false;
  1693. return true;
  1694. }
  1695. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1696. {
  1697. if(!curB)
  1698. return -1;
  1699. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1700. {
  1701. if((curB->stacks[g]->position == pos
  1702. || (curB->stacks[g]->doubleWide()
  1703. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1704. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1705. ))
  1706. && (!onlyAlive || curB->stacks[g]->alive())
  1707. )
  1708. return curB->stacks[g]->ID;
  1709. }
  1710. return -1;
  1711. }
  1712. int CGameState::battleGetBattlefieldType(int3 tile)
  1713. {
  1714. if(tile==int3() && curB)
  1715. tile = curB->tile;
  1716. else if(tile==int3() && !curB)
  1717. return -1;
  1718. const TerrainTile &t = map->getTile(tile);
  1719. //fight in mine -> subterranean
  1720. if(const CGMine *mine = dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1721. return 12;
  1722. const std::vector <CGObjectInstance*> & objs = map->objects;
  1723. for(int g=0; g<objs.size(); ++g)
  1724. {
  1725. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1726. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1727. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1728. ) //look only for objects covering given tile
  1729. continue;
  1730. switch(objs[g]->ID)
  1731. {
  1732. case 222: //clover field
  1733. return 19;
  1734. case 21: case 223: //cursed ground
  1735. return 22;
  1736. case 224: //evil fog
  1737. return 20;
  1738. case 225: //favourable winds
  1739. return 21;
  1740. case 226: //fiery fields
  1741. return 14;
  1742. case 227: //holy ground
  1743. return 18;
  1744. case 228: //lucid pools
  1745. return 17;
  1746. case 229: //magic clouds
  1747. return 16;
  1748. case 46: case 230: //magic plains
  1749. return 9;
  1750. case 231: //rocklands
  1751. return 15;
  1752. }
  1753. }
  1754. switch(t.tertype)
  1755. {
  1756. case TerrainTile::dirt:
  1757. return rand()%3+3;
  1758. case TerrainTile::sand:
  1759. return 2; //TODO: coast support
  1760. case TerrainTile::grass:
  1761. return rand()%2+6;
  1762. case TerrainTile::snow:
  1763. return rand()%2+10;
  1764. case TerrainTile::swamp:
  1765. return 13;
  1766. case TerrainTile::rough:
  1767. return 23;
  1768. case TerrainTile::subterranean:
  1769. return 12;
  1770. case TerrainTile::lava:
  1771. return 8;
  1772. case TerrainTile::water:
  1773. return 25;
  1774. case TerrainTile::rock:
  1775. return 15;
  1776. default:
  1777. return -1;
  1778. }
  1779. }
  1780. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1781. {
  1782. if(!curB)
  1783. return NULL;
  1784. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1785. }
  1786. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1787. {
  1788. std::set<std::pair<int, int> > ret;
  1789. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1790. {
  1791. assert(a[j] >= b[j]);
  1792. if(int dif = modifier * (a[j] - b[j]) / 100)
  1793. ret.insert(std::make_pair(j,dif));
  1794. }
  1795. return ret;
  1796. }
  1797. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1798. {
  1799. UpgradeInfo ret;
  1800. const CCreature *base = stack.type;
  1801. const CGHeroInstance *h = stack.armyObj->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1802. const CGTownInstance *t = NULL;
  1803. if(stack.armyObj->ID == TOWNI_TYPE)
  1804. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1805. else if(h)
  1806. { //hero speciality
  1807. BonusList lista = h->speciality.getBonuses(Selector::typeSybtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1808. for (BonusList::iterator it = lista.begin(); it != lista.end(); it++)
  1809. {
  1810. ui16 nid = it->additionalInfo;
  1811. if (nid != base->idNumber) //in very specific case the upgrade is avaliable by default (?)
  1812. {
  1813. ret.newID.push_back(nid);
  1814. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1815. }
  1816. }
  1817. t = h->visitedTown;
  1818. }
  1819. if(t)
  1820. {
  1821. BOOST_FOREACH(si32 bid, t->builtBuildings)
  1822. {
  1823. if( bid >= 37 && bid < 44 ) //upgraded creature dwelling
  1824. {
  1825. int nid = t->town->upgradedCreatures[bid-37]; //upgrade offered by that building
  1826. if(vstd::contains(base->upgrades, nid)) //possible upgrade
  1827. {
  1828. ret.newID.push_back(nid);
  1829. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1830. }
  1831. }
  1832. }
  1833. }
  1834. //hero is visiting Hill Fort
  1835. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1836. {
  1837. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1838. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1839. BOOST_FOREACH(si32 nid, base->upgrades)
  1840. {
  1841. ret.newID.push_back(nid);
  1842. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost, costModifier));
  1843. }
  1844. }
  1845. if(ret.newID.size())
  1846. ret.oldID = base->idNumber;
  1847. return ret;
  1848. }
  1849. int CGameState::getPlayerRelations( ui8 color1, ui8 color2 )
  1850. {
  1851. if ( color1 == color2 )
  1852. return 2;
  1853. const TeamState * ts = getPlayerTeam(color1);
  1854. if (ts && vstd::contains(ts->players, color2))
  1855. return 1;
  1856. return 0;
  1857. }
  1858. void CGameState::loadTownDInfos()
  1859. {
  1860. for(int i=0;i<F_NUMBER;i++)
  1861. {
  1862. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1863. forts[i] = VLC->dobjinfo->castles[i];
  1864. map->defy.push_back(forts[i]);
  1865. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1866. }
  1867. std::ifstream ifs(DATA_DIR "/config/townsDefs.txt");
  1868. int ccc;
  1869. ifs>>ccc;
  1870. for(int i=0; i < ccc*2; i++)
  1871. {
  1872. CGDefInfo *n;
  1873. if(i<ccc)
  1874. n = villages[i];
  1875. else
  1876. n = capitols[i%ccc];
  1877. ifs >> n->name;
  1878. map->defy.push_back(n);
  1879. }
  1880. }
  1881. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1882. {
  1883. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1884. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1885. vec.clear();
  1886. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1887. {
  1888. const int3 hlp = tile + dirs[i];
  1889. if(!map->isInTheMap(hlp))
  1890. continue;
  1891. const TerrainTile &hlpt = map->getTile(hlp);
  1892. //we cannot visit things from blocked tiles
  1893. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1894. {
  1895. continue;
  1896. }
  1897. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1898. {
  1899. int3 hlp1 = tile,
  1900. hlp2 = tile;
  1901. hlp1.x += dirs[i].x;
  1902. hlp2.y += dirs[i].y;
  1903. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1904. continue;
  1905. }
  1906. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1907. && hlpt.tertype != TerrainTile::rock)
  1908. {
  1909. vec.push_back(hlp);
  1910. }
  1911. }
  1912. }
  1913. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1914. {
  1915. if(src == dest) //same tile
  1916. return 0;
  1917. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1918. &d = map->terrain[dest.x][dest.y][dest.z];
  1919. //get basic cost
  1920. int ret = h->getTileCost(d,s);
  1921. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1922. {
  1923. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1924. if(!freeFlying)
  1925. {
  1926. ret *= 1.4f; //40% penalty for movement over blocked tile
  1927. }
  1928. }
  1929. else if (d.tertype == TerrainTile::water)
  1930. {
  1931. if(h->boat && s.siodmyTajemniczyBajt & 128 && d.siodmyTajemniczyBajt & 128) //Favourable Winds
  1932. ret *= 0.666f;
  1933. else if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1934. ret *= 1.4f; //40% penalty for water walking
  1935. }
  1936. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1937. {
  1938. int old = ret;
  1939. ret *= 1.414213;
  1940. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1941. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1942. {
  1943. return remainingMovePoints;
  1944. }
  1945. }
  1946. int left = remainingMovePoints-ret;
  1947. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1948. {
  1949. std::vector<int3> vec;
  1950. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1951. for(size_t i=0; i < vec.size(); i++)
  1952. {
  1953. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1954. if(fcost <= left)
  1955. {
  1956. return ret;
  1957. }
  1958. }
  1959. ret = remainingMovePoints;
  1960. }
  1961. return ret;
  1962. }
  1963. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1964. {
  1965. std::set<int> used;
  1966. used.insert(ID);
  1967. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1968. while(true)
  1969. {
  1970. size_t noloop=0;
  1971. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1972. {
  1973. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1974. {
  1975. used.insert(*i);
  1976. for(
  1977. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1978. j!=VLC->townh->requirements[t->subID][*i].end();
  1979. j++)
  1980. {
  1981. reqs.insert(*j);//creating full list of requirements
  1982. }
  1983. }
  1984. else
  1985. {
  1986. noloop++;
  1987. }
  1988. }
  1989. if(noloop==reqs.size())
  1990. break;
  1991. }
  1992. return reqs;
  1993. }
  1994. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1995. {
  1996. int ret = 7; //allowed by default
  1997. if(t->builded >= MAX_BUILDING_PER_TURN)
  1998. ret = 5; //building limit
  1999. //checking resources
  2000. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  2001. if(!pom)
  2002. return 8;
  2003. // if(pom->Name().size()==0||pom->resources.size()==0)
  2004. // return 2;//TODO: why does this happen?
  2005. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  2006. {
  2007. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  2008. ret = 6; //lack of res
  2009. }
  2010. //checking for requirements
  2011. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  2012. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  2013. {
  2014. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  2015. ret = 8; //lack of requirements - cannot build
  2016. }
  2017. //can we build it?
  2018. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  2019. ret = 2; //forbidden
  2020. if(ID == 13) //capitol
  2021. {
  2022. for(unsigned int in = 0; in < map->towns.size(); in++)
  2023. {
  2024. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  2025. {
  2026. ret = 0; //no more than one capitol
  2027. break;
  2028. }
  2029. }
  2030. }
  2031. else if(ID == 6) //shipyard
  2032. {
  2033. int3 t1(t->pos + int3(-1,3,0)),
  2034. t2(t->pos + int3(-3,3,0));
  2035. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  2036. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  2037. ret = 1; //lack of water
  2038. }
  2039. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  2040. ret = 4;
  2041. return ret;
  2042. }
  2043. void CGameState::apply(CPack *pack)
  2044. {
  2045. ui16 typ = typeList.getTypeID(pack);
  2046. applierGs->apps[typ]->applyOnGS(this,pack);
  2047. }
  2048. TeamState *CGameState::getTeam(ui8 teamID)
  2049. {
  2050. if(vstd::contains(teams,teamID))
  2051. {
  2052. return &teams[teamID];
  2053. }
  2054. else
  2055. {
  2056. tlog2 << "Warning: Cannot find info for team " << int(teamID) << std::endl;
  2057. return NULL;
  2058. }
  2059. }
  2060. TeamState *CGameState::getPlayerTeam(ui8 color)
  2061. {
  2062. PlayerState * ps = getPlayer(color);
  2063. if (ps)
  2064. return getTeam(ps->team);
  2065. return NULL;
  2066. }
  2067. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  2068. {
  2069. if(vstd::contains(players,color))
  2070. {
  2071. return &players[color];
  2072. }
  2073. else
  2074. {
  2075. if(verbose)
  2076. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  2077. return NULL;
  2078. }
  2079. }
  2080. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  2081. {
  2082. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  2083. }
  2084. const TeamState * CGameState::getTeam( ui8 teamID ) const
  2085. {
  2086. return (const_cast<CGameState *>(this))->getTeam(teamID);
  2087. }
  2088. const TeamState * CGameState::getPlayerTeam( ui8 teamID ) const
  2089. {
  2090. return (const_cast<CGameState *>(this))->getPlayerTeam(teamID);
  2091. }
  2092. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  2093. {
  2094. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  2095. return false;
  2096. int3 hpos = hero->getPosition(false);
  2097. bool flying = false; //hero is under flying effect TODO
  2098. bool waterWalking = false; //hero is on land and can walk on water TODO
  2099. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  2100. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  2101. //
  2102. // if (!hero->canWalkOnSea())
  2103. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  2104. // else
  2105. // blockLandSea = boost::logic::indeterminate;
  2106. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  2107. //graph initialization
  2108. std::vector< std::vector<CPathNode> > graph;
  2109. graph.resize(map->width);
  2110. for(size_t i=0; i<graph.size(); ++i)
  2111. {
  2112. graph[i].resize(map->height);
  2113. for(size_t j=0; j<graph[i].size(); ++j)
  2114. {
  2115. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  2116. CPathNode &node = graph[i][j];
  2117. node.accessible = !tinfo->blocked;
  2118. node.dist = -1;
  2119. node.theNodeBefore = NULL;
  2120. node.visited = false;
  2121. node.coord.x = i;
  2122. node.coord.y = j;
  2123. node.coord.z = dest.z;
  2124. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  2125. || !FoW[i][j][src.z] //tile is covered by the FoW
  2126. )
  2127. {
  2128. node.accessible = false;
  2129. }
  2130. }
  2131. }
  2132. //Special rules for the destination tile
  2133. {
  2134. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  2135. CPathNode &d = graph[dest.x][dest.y];
  2136. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  2137. if(t->visitable)
  2138. {
  2139. d.accessible = true; //for allowing visiting objects
  2140. }
  2141. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  2142. {
  2143. size_t i = 0;
  2144. for(; i < t->visitableObjects.size(); i++)
  2145. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2146. break;
  2147. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  2148. }
  2149. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  2150. {
  2151. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  2152. }
  2153. }
  2154. //graph initialized
  2155. //initial tile - set cost on 0 and add to the queue
  2156. graph[src.x][src.y].dist = 0;
  2157. std::queue<CPathNode> mq;
  2158. mq.push(graph[src.x][src.y]);
  2159. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2160. std::vector<int3> neighbours;
  2161. neighbours.reserve(8);
  2162. while(!mq.empty())
  2163. {
  2164. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  2165. mq.pop();
  2166. if (cp.coord == dest) //it's destination tile
  2167. {
  2168. if (cp.dist < curDist) //that path is better than previous one
  2169. curDist = cp.dist;
  2170. continue;
  2171. }
  2172. else
  2173. {
  2174. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  2175. continue;
  2176. }
  2177. //add accessible neighbouring nodes to the queue
  2178. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate, true);
  2179. for(unsigned int i=0; i < neighbours.size(); i++)
  2180. {
  2181. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  2182. if(dp.accessible)
  2183. {
  2184. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  2185. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  2186. {
  2187. dp.dist = cp.dist + cost;
  2188. dp.theNodeBefore = &cp;
  2189. mq.push(dp);
  2190. }
  2191. }
  2192. }
  2193. }
  2194. CPathNode *curNode = &graph[dest.x][dest.y];
  2195. if(!curNode->theNodeBefore) //destination is not accessible
  2196. return false;
  2197. //fill ret with found path
  2198. ret.nodes.clear();
  2199. while(curNode->coord != graph[src.x][src.y].coord)
  2200. {
  2201. ret.nodes.push_back(*curNode);
  2202. curNode = curNode->theNodeBefore;
  2203. }
  2204. ret.nodes.push_back(graph[src.x][src.y]);
  2205. return true;
  2206. }
  2207. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  2208. {
  2209. assert(hero);
  2210. boost::shared_lock<boost::shared_mutex> lock(*mx);
  2211. if(src.x < 0)
  2212. src = hero->getPosition(false);
  2213. if(movement < 0)
  2214. movement = hero->movement;
  2215. out.hero = hero;
  2216. out.hpos = src;
  2217. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  2218. {
  2219. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  2220. return;
  2221. }
  2222. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  2223. if (!hero->canWalkOnSea())
  2224. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  2225. else
  2226. onLand = boost::logic::indeterminate;
  2227. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayerTeam(hero->tempOwner)->fogOfWarMap;
  2228. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  2229. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  2230. //graph initialization
  2231. CGPathNode ***graph = out.nodes;
  2232. for(size_t i=0; i < out.sizes.x; ++i)
  2233. {
  2234. for(size_t j=0; j < out.sizes.y; ++j)
  2235. {
  2236. for(size_t k=0; k < out.sizes.z; ++k)
  2237. {
  2238. const TerrainTile *tinfo = &map->terrain[i][j][k];
  2239. CGPathNode &node = graph[i][j][k];
  2240. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  2241. if(!flying && node.accessible == CGPathNode::FLYABLE)
  2242. {
  2243. node.accessible = CGPathNode::BLOCKED;
  2244. }
  2245. node.turns = 0xff;
  2246. node.moveRemains = 0;
  2247. node.coord.x = i;
  2248. node.coord.y = j;
  2249. node.coord.z = k;
  2250. node.land = tinfo->tertype != TerrainTile::water;
  2251. node.theNodeBefore = NULL;
  2252. bool leaveAsBlocked = false;
  2253. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  2254. {
  2255. if (waterWalk || flying)
  2256. {
  2257. node.accessible = CGPathNode::FLYABLE;
  2258. }
  2259. else
  2260. {
  2261. node.accessible = CGPathNode::BLOCKED;
  2262. leaveAsBlocked = true;
  2263. }
  2264. }
  2265. if ( tinfo->tertype == TerrainTile::rock//it's rock
  2266. || !onLand && node.land //it's land and we cannot walk on land (complementary condition is handled above)
  2267. || !FoW[i][j][k] //tile is covered by the FoW
  2268. || leaveAsBlocked
  2269. )
  2270. {
  2271. node.accessible = CGPathNode::BLOCKED;
  2272. }
  2273. else if(tinfo->visitable)
  2274. {
  2275. //hero is protected in Sanctuary
  2276. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner)
  2277. node.accessible = CGPathNode::BLOCKED;
  2278. else
  2279. {
  2280. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  2281. {
  2282. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  2283. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2284. {
  2285. node.accessible = CGPathNode::ACCESSIBLE;
  2286. }
  2287. else if(obj->blockVisit)
  2288. {
  2289. node.accessible = CGPathNode::BLOCKVIS;
  2290. break;
  2291. }
  2292. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  2293. {
  2294. node.accessible = CGPathNode::VISITABLE;
  2295. }
  2296. }
  2297. }
  2298. }
  2299. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  2300. && tinfo->blockingObjects.size() == 0)
  2301. {
  2302. // Monster close by; blocked visit for battle.
  2303. node.accessible = CGPathNode::BLOCKVIS;
  2304. }
  2305. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2306. {
  2307. size_t i = 0;
  2308. for(; i < tinfo->visitableObjects.size(); i++)
  2309. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2310. break;
  2311. if(i < tinfo->visitableObjects.size())
  2312. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2313. }
  2314. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  2315. {
  2316. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2317. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2318. }
  2319. }
  2320. }
  2321. }
  2322. //graph initialized
  2323. //initial tile - set cost on 0 and add to the queue
  2324. graph[src.x][src.y][src.z].turns = 0;
  2325. graph[src.x][src.y][src.z].moveRemains = movement;
  2326. std::queue<CGPathNode*> mq;
  2327. mq.push(&graph[src.x][src.y][src.z]);
  2328. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2329. std::vector<int3> neighbours;
  2330. neighbours.reserve(8);
  2331. while(!mq.empty())
  2332. {
  2333. CGPathNode *cp = mq.front();
  2334. mq.pop();
  2335. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2336. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2337. const TerrainTile &ct = map->getTile(cp->coord);
  2338. int movement = cp->moveRemains, turn = cp->turns;
  2339. if(!movement)
  2340. {
  2341. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2342. turn++;
  2343. }
  2344. //add accessible neighbouring nodes to the queue
  2345. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate, !onLand);
  2346. for(unsigned int i=0; i < neighbours.size(); i++)
  2347. {
  2348. int moveAtNextTile = movement;
  2349. int turnAtNextTile = turn;
  2350. const int3 &n = neighbours[i]; //current neighbor
  2351. CGPathNode & dp = graph[n.x][n.y][n.z];
  2352. if( !checkForVisitableDir(cp->coord, dp.coord)
  2353. || !checkForVisitableDir(dp.coord, cp->coord)
  2354. || dp.accessible == CGPathNode::BLOCKED )
  2355. {
  2356. continue;
  2357. }
  2358. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2359. int remains = movement - cost;
  2360. if(remains < 0)
  2361. {
  2362. //occurs rarely, when hero with low movepoints tries to go leave the road
  2363. turnAtNextTile++;
  2364. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2365. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2366. remains = moveAtNextTile - cost;
  2367. }
  2368. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2369. if((dp.turns==0xff //we haven't been here before
  2370. || dp.turns > turnAtNextTile
  2371. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2372. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2373. {
  2374. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2375. dp.moveRemains = remains;
  2376. dp.turns = turnAtNextTile;
  2377. dp.theNodeBefore = cp;
  2378. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2379. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2380. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2381. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2382. {
  2383. mq.push(&dp);
  2384. }
  2385. }
  2386. } //neighbours loop
  2387. } //queue loop
  2388. }
  2389. /**
  2390. * Tells if the tile is guarded by a monster as well as the position
  2391. * of the monster that will attack on it.
  2392. *
  2393. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2394. * the monster guarding the tile.
  2395. */
  2396. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2397. {
  2398. const int3 originalPos = pos;
  2399. // Give monster at position priority.
  2400. if (!map->isInTheMap(pos))
  2401. return int3(-1, -1, -1);
  2402. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2403. if (posTile.visitable)
  2404. {
  2405. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2406. {
  2407. if(obj->blockVisit)
  2408. {
  2409. if (obj->ID == 54) // Monster
  2410. return pos;
  2411. else
  2412. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2413. }
  2414. }
  2415. }
  2416. // See if there are any monsters adjacent.
  2417. pos -= int3(1, 1, 0); // Start with top left.
  2418. for (int dx = 0; dx < 3; dx++)
  2419. {
  2420. for (int dy = 0; dy < 3; dy++)
  2421. {
  2422. if (map->isInTheMap(pos))
  2423. {
  2424. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2425. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  2426. {
  2427. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2428. {
  2429. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2430. {
  2431. return pos;
  2432. }
  2433. }
  2434. }
  2435. }
  2436. pos.y++;
  2437. }
  2438. pos.y -= 3;
  2439. pos.x++;
  2440. }
  2441. return int3(-1, -1, -1);
  2442. }
  2443. bool CGameState::isVisible(int3 pos, int player)
  2444. {
  2445. if(player == 255) //neutral player
  2446. return false;
  2447. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  2448. }
  2449. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2450. {
  2451. if(player == 255) //neutral player
  2452. return false;
  2453. //object is visible when at least one blocked tile is visible
  2454. for(int fx=0; fx<8; ++fx)
  2455. {
  2456. for(int fy=0; fy<6; ++fy)
  2457. {
  2458. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2459. if(map->isInTheMap(pos)
  2460. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2461. && isVisible(pos, player) )
  2462. return true;
  2463. }
  2464. }
  2465. return false;
  2466. }
  2467. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2468. {
  2469. const TerrainTile * pom = &map->getTile(dst);
  2470. return checkForVisitableDir(src, pom, dst);
  2471. }
  2472. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2473. {
  2474. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2475. {
  2476. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2477. continue;
  2478. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2479. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2480. {
  2481. return false;
  2482. }
  2483. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2484. {
  2485. return false;
  2486. }
  2487. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2488. {
  2489. return false;
  2490. }
  2491. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2492. {
  2493. return false;
  2494. }
  2495. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2496. {
  2497. return false;
  2498. }
  2499. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2500. {
  2501. return false;
  2502. }
  2503. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2504. {
  2505. return false;
  2506. }
  2507. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2508. {
  2509. return false;
  2510. }
  2511. }
  2512. return true;
  2513. }
  2514. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2515. {
  2516. float additiveBonus=1.0f, multBonus=1.0f,
  2517. minDmg = attacker->getMinDamage() * attacker->count,
  2518. maxDmg = attacker->getMaxDamage() * attacker->count;
  2519. if(attacker->type->idNumber == 149) //arrow turret
  2520. {
  2521. switch(attacker->position)
  2522. {
  2523. case -2: //keep
  2524. minDmg = 15;
  2525. maxDmg = 15;
  2526. break;
  2527. case -3: case -4: //turrets
  2528. minDmg = 7.5f;
  2529. maxDmg = 7.5f;
  2530. break;
  2531. }
  2532. }
  2533. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->type->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2534. { //minDmg and maxDmg are multiplied by hero attack + 1
  2535. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2536. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2537. }
  2538. int attackDefenceDifference = 0;
  2539. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  2540. {
  2541. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  2542. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  2543. }
  2544. else
  2545. {
  2546. attackDefenceDifference = attacker->Attack();
  2547. }
  2548. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  2549. {
  2550. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  2551. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  2552. }
  2553. else
  2554. {
  2555. attackDefenceDifference -= defender->Defense();
  2556. }
  2557. //calculating total attack/defense skills modifier
  2558. if(shooting) //precision handling (etc.)
  2559. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  2560. else //bloodlust handling (etc.)
  2561. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  2562. if(attacker->getEffect(55)) //slayer handling
  2563. {
  2564. std::vector<int> affectedIds;
  2565. int spLevel = attacker->getEffect(55)->level;
  2566. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  2567. {
  2568. BOOST_FOREACH(const Bonus &b, VLC->creh->creatures[g]->bonuses)
  2569. {
  2570. if ( (b.type == Bonus::KING3 && spLevel >= 3) || //expert
  2571. (b.type == Bonus::KING2 && spLevel >= 2) || //adv +
  2572. (b.type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  2573. {
  2574. affectedIds.push_back(g);
  2575. break;
  2576. }
  2577. }
  2578. }
  2579. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2580. {
  2581. if(defender->type->idNumber == affectedIds[g])
  2582. {
  2583. attackDefenceDifference += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2584. break;
  2585. }
  2586. }
  2587. }
  2588. //bonus from attack/defense skills
  2589. if(attackDefenceDifference < 0) //decreasing dmg
  2590. {
  2591. float dec = 0.025f * (-attackDefenceDifference);
  2592. if(dec > 0.7f)
  2593. {
  2594. multBonus *= 0.3f; //1.0 - 0.7
  2595. }
  2596. else
  2597. {
  2598. multBonus *= 1.0f - dec;
  2599. }
  2600. }
  2601. else //increasing dmg
  2602. {
  2603. float inc = 0.05f * attackDefenceDifference;
  2604. if(inc > 4.0f)
  2605. {
  2606. additiveBonus += 4.0f;
  2607. }
  2608. else
  2609. {
  2610. additiveBonus += inc;
  2611. }
  2612. }
  2613. //applying jousting bonus
  2614. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  2615. additiveBonus += charge * 0.05f;
  2616. //handling secondary abilities and artifacts giving premies to them
  2617. if(attackerHero)
  2618. {
  2619. if(shooting)
  2620. {
  2621. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2622. }
  2623. else
  2624. {
  2625. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 22) / 100.0f;
  2626. }
  2627. }
  2628. if(defendingHero)
  2629. {
  2630. multBonus *= (std::max(0, 100-defendingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 23))) / 100.0f;
  2631. }
  2632. //handling hate effect
  2633. if( attacker->hasBonusOfType(Bonus::HATE, defender->type->idNumber) )
  2634. additiveBonus += 0.5f;
  2635. //luck bonus
  2636. if (lucky)
  2637. {
  2638. additiveBonus += 1.0f;
  2639. }
  2640. //handling spell effects
  2641. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2642. {
  2643. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2644. }
  2645. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2646. {
  2647. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2648. }
  2649. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2650. {
  2651. multBonus *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2652. }
  2653. class HLP
  2654. {
  2655. public:
  2656. static bool hasAdvancedAirShield(const CStack * stack)
  2657. {
  2658. for(int g=0; g<stack->effects.size(); ++g)
  2659. {
  2660. if (stack->effects[g].id == 28 && stack->effects[g].level >= 2)
  2661. {
  2662. return true;
  2663. }
  2664. }
  2665. return false;
  2666. }
  2667. };
  2668. //wall / distance penalty + advanced air shield
  2669. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  2670. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  2671. HLP::hasAdvancedAirShield(defender) )
  2672. )
  2673. {
  2674. multBonus *= 0.5;
  2675. }
  2676. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  2677. {
  2678. multBonus *= 0.5;
  2679. }
  2680. minDmg *= additiveBonus * multBonus;
  2681. maxDmg *= additiveBonus * multBonus;
  2682. std::pair<ui32, ui32> returnedVal;
  2683. if(attacker->getEffect(42)) //curse handling (rest)
  2684. {
  2685. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2686. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  2687. }
  2688. else if(attacker->getEffect(41)) //bless handling
  2689. {
  2690. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2691. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  2692. }
  2693. else
  2694. {
  2695. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  2696. }
  2697. //damage cannot be less than 1
  2698. amax(returnedVal.first, 1);
  2699. amax(returnedVal.second, 1);
  2700. return returnedVal;
  2701. }
  2702. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2703. {
  2704. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  2705. if(range.first != range.second)
  2706. {
  2707. int valuesToAverage[10];
  2708. int howManyToAv = std::min<ui32>(10, attacker->count);
  2709. for (int g=0; g<howManyToAv; ++g)
  2710. {
  2711. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  2712. }
  2713. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  2714. }
  2715. else
  2716. return range.first;
  2717. }
  2718. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2719. {
  2720. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2721. {
  2722. const CStack * const st = stacks[i];
  2723. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  2724. amax(killed, 0);
  2725. if(killed)
  2726. casualties[!st->attackerOwned][st->type->idNumber] += killed;
  2727. }
  2728. }
  2729. si8 CGameState::battleMaxSpellLevel()
  2730. {
  2731. if(!curB) //there is not battle
  2732. {
  2733. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2734. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2735. }
  2736. si8 levelLimit = SPELL_LEVELS;
  2737. const CGHeroInstance *h1 = curB->heroes[0];
  2738. if(h1)
  2739. {
  2740. for(std::list<Bonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2741. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2742. amin(levelLimit, i->val);
  2743. }
  2744. const CGHeroInstance *h2 = curB->heroes[1];
  2745. if(h2)
  2746. {
  2747. for(std::list<Bonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2748. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2749. amin(levelLimit, i->val);
  2750. }
  2751. return levelLimit;
  2752. }
  2753. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  2754. {
  2755. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  2756. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2757. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2758. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2759. {
  2760. for(int it=0; it<stacks.size(); ++it)
  2761. {
  2762. if((s->id == 24 && !stacks[it]->type->isUndead()) //death ripple
  2763. || (s->id == 25 && stacks[it]->type->isUndead()) //destroy undead
  2764. || (s->id == 26) //Armageddon
  2765. )
  2766. {
  2767. if(stacks[it]->alive())
  2768. attackedCres.insert(stacks[it]);
  2769. }
  2770. }
  2771. }
  2772. else if (s->range[skillLevel].size() > 1) //custom many-hex range
  2773. {
  2774. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2775. {
  2776. CStack * st = getStackT(*it, onlyAlive);
  2777. if(st)
  2778. attackedCres.insert(st);
  2779. }
  2780. }
  2781. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2782. || 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
  2783. {
  2784. if(skillLevel < 3) /*not expert */
  2785. {
  2786. CStack * st = getStackT(destinationTile, onlyAlive);
  2787. if(st)
  2788. attackedCres.insert(st);
  2789. }
  2790. else
  2791. {
  2792. for(int it=0; it<stacks.size(); ++it)
  2793. {
  2794. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2795. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == attackerOwner)
  2796. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != attackerOwner )
  2797. )
  2798. {
  2799. if(!onlyAlive || stacks[it]->alive())
  2800. attackedCres.insert(stacks[it]);
  2801. }
  2802. }
  2803. } //if(caster->getSpellSchoolLevel(s) < 3)
  2804. }
  2805. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2806. {
  2807. CStack * st = getStackT(destinationTile, onlyAlive);
  2808. if(st)
  2809. attackedCres.insert(st);
  2810. }
  2811. else //custom range from attackedHexes
  2812. {
  2813. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2814. {
  2815. CStack * st = getStackT(*it, onlyAlive);
  2816. if(st)
  2817. attackedCres.insert(st);
  2818. }
  2819. }
  2820. return attackedCres;
  2821. }
  2822. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  2823. {
  2824. if(!caster) //TODO: something better
  2825. return std::max(5, usedSpellPower);
  2826. switch(spell->id)
  2827. {
  2828. case 56: //frenzy
  2829. return 1;
  2830. default: //other spells
  2831. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  2832. }
  2833. }
  2834. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2835. {
  2836. CStack * ret = new CStack(&base, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2837. //native terrain bonuses
  2838. int faction = ret->type->faction;
  2839. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2840. {
  2841. ret->bonuses.push_back(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE));
  2842. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE));
  2843. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE));
  2844. }
  2845. ret->position = position;
  2846. return ret;
  2847. }
  2848. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2849. {
  2850. ui32 ret = caster->getSpellCost(sp);
  2851. //checking for friendly stacks reducing cost of the spell and
  2852. //enemy stacks increasing it
  2853. si32 manaReduction = 0;
  2854. si32 manaIncrease = 0;
  2855. for(int g=0; g<stacks.size(); ++g)
  2856. {
  2857. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  2858. {
  2859. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  2860. }
  2861. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  2862. {
  2863. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  2864. }
  2865. }
  2866. return ret + manaReduction + manaIncrease;
  2867. }
  2868. int BattleInfo::hexToWallPart(int hex) const
  2869. {
  2870. if(siege == 0) //there is no battle!
  2871. return -1;
  2872. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2873. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2874. 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)};
  2875. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2876. {
  2877. if(attackable[g].first == hex)
  2878. return attackable[g].second;
  2879. }
  2880. return -1; //not found!
  2881. }
  2882. int BattleInfo::lineToWallHex( int line ) const
  2883. {
  2884. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  2885. return lineToHex[line];
  2886. }
  2887. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2888. {
  2889. bool ac[BFIELD_SIZE];
  2890. std::set<int> occupyable;
  2891. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  2892. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2893. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  2894. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2895. for(int g=0; g<BFIELD_SIZE; ++g)
  2896. {
  2897. const CStack * atG = getStackT(g);
  2898. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2899. continue;
  2900. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2901. {
  2902. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2903. continue;
  2904. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2905. }
  2906. }
  2907. if(stackPairs.size() > 0)
  2908. {
  2909. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2910. minimalPairs.push_back(stackPairs[0]);
  2911. for(int b=1; b<stackPairs.size(); ++b)
  2912. {
  2913. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2914. {
  2915. minimalPairs.clear();
  2916. minimalPairs.push_back(stackPairs[b]);
  2917. }
  2918. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2919. {
  2920. minimalPairs.push_back(stackPairs[b]);
  2921. }
  2922. }
  2923. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2924. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2925. }
  2926. return std::make_pair<const CStack * , int>(NULL, -1);
  2927. }
  2928. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  2929. {
  2930. ui32 ret = 0; //value to return
  2931. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2932. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  2933. 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);
  2934. //check if spell really does damage - if not, return 0
  2935. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2936. return 0;
  2937. ret = usedSpellPower * dmgMultipliers[sp->id];
  2938. ret += sp->powers[spellSchoolLevel];
  2939. //applying sorcery secondary skill
  2940. if(caster)
  2941. {
  2942. ret *= (100.f + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 25)) / 100.0f; //sorcery
  2943. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  2944. if(sp->air)
  2945. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2946. else if(sp->fire) //only one type of bonus for Magic Arrow
  2947. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2948. else if(sp->water)
  2949. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2950. else if(sp->earth)
  2951. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2952. }
  2953. //affected creature-specific part
  2954. if(affectedCreature)
  2955. {
  2956. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2957. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2958. {
  2959. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  2960. ret /= 100;
  2961. }
  2962. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2963. {
  2964. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  2965. ret /= 100;
  2966. }
  2967. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2968. {
  2969. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  2970. ret /= 100;
  2971. }
  2972. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2973. {
  2974. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  2975. ret /= 100;
  2976. }
  2977. //general spell dmg reduction
  2978. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2979. {
  2980. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  2981. ret /= 100;
  2982. }
  2983. //dmg increasing
  2984. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2985. {
  2986. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  2987. ret /= 100;
  2988. }
  2989. if (caster) //Hero specials like Solmyr, Deemer
  2990. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->type->level)) / 100.0f;
  2991. }
  2992. return ret;
  2993. }
  2994. bool CGameState::battleCanShoot(int ID, int dest)
  2995. {
  2996. if(!curB)
  2997. return false;
  2998. const CStack *our = curB->getStack(ID),
  2999. *dst = curB->getStackT(dest);
  3000. if(!our || !dst) return false;
  3001. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  3002. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  3003. return false;
  3004. if(our->type->idNumber == 145 && dst) //catapult cannot attack creatures
  3005. return false;
  3006. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  3007. && our->owner != dst->owner
  3008. && dst->alive()
  3009. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  3010. && our->shots
  3011. )
  3012. return true;
  3013. return false;
  3014. }
  3015. int CGameState::victoryCheck( ui8 player ) const
  3016. {
  3017. const PlayerState *p = getPlayer(player);
  3018. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  3019. if(player == checkForStandardWin())
  3020. return -1;
  3021. if (p->enteredWinningCheatCode)
  3022. { //cheater or tester, but has entered the code...
  3023. return 1;
  3024. }
  3025. if(p->human || map->victoryCondition.appliesToAI)
  3026. {
  3027. switch(map->victoryCondition.condition)
  3028. {
  3029. case artifact:
  3030. //check if any hero has winning artifact
  3031. for(size_t i = 0; i < p->heroes.size(); i++)
  3032. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  3033. return 1;
  3034. break;
  3035. case gatherTroop:
  3036. {
  3037. //check if in players armies there is enough creatures
  3038. int total = 0; //creature counter
  3039. for(size_t i = 0; i < map->objects.size(); i++)
  3040. {
  3041. const CArmedInstance *ai = NULL;
  3042. if(map->objects[i]
  3043. && map->objects[i]->tempOwner == player //object controlled by player
  3044. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  3045. {
  3046. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  3047. if(i->second.type->idNumber == map->victoryCondition.ID) //it's searched creature
  3048. total += i->second.count;
  3049. }
  3050. }
  3051. if(total >= map->victoryCondition.count)
  3052. return 1;
  3053. }
  3054. break;
  3055. case gatherResource:
  3056. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  3057. return 1;
  3058. break;
  3059. case buildCity:
  3060. {
  3061. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  3062. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  3063. return 1;
  3064. }
  3065. break;
  3066. case buildGrail:
  3067. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  3068. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  3069. && t->tempOwner == player
  3070. && vstd::contains(t->builtBuildings, 26))
  3071. return 1;
  3072. break;
  3073. case beatHero:
  3074. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  3075. return 1;
  3076. break;
  3077. case captureCity:
  3078. {
  3079. if(map->victoryCondition.obj->tempOwner == player)
  3080. return 1;
  3081. }
  3082. break;
  3083. case beatMonster:
  3084. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  3085. return 1;
  3086. break;
  3087. case takeDwellings:
  3088. for(size_t i = 0; i < map->objects.size(); i++)
  3089. {
  3090. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  3091. {
  3092. switch(map->objects[i]->ID)
  3093. {
  3094. case 17: case 18: case 19: case 20: //dwellings
  3095. case 216: case 217: case 218:
  3096. return 0; //found not flagged dwelling - player not won
  3097. }
  3098. }
  3099. }
  3100. return 1;
  3101. break;
  3102. case takeMines:
  3103. for(size_t i = 0; i < map->objects.size(); i++)
  3104. {
  3105. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  3106. {
  3107. switch(map->objects[i]->ID)
  3108. {
  3109. case 53: case 220:
  3110. return 0; //found not flagged mine - player not won
  3111. }
  3112. }
  3113. }
  3114. return 1;
  3115. break;
  3116. case transportItem:
  3117. {
  3118. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  3119. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  3120. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  3121. {
  3122. return 1;
  3123. }
  3124. }
  3125. break;
  3126. }
  3127. }
  3128. return 0;
  3129. }
  3130. ui8 CGameState::checkForStandardWin() const
  3131. {
  3132. //std victory condition is:
  3133. //all enemies lost
  3134. ui8 supposedWinner = 255, winnerTeam = 255;
  3135. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  3136. {
  3137. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  3138. {
  3139. if(supposedWinner == 255)
  3140. {
  3141. //first player remaining ingame - candidate for victory
  3142. supposedWinner = i->second.color;
  3143. winnerTeam = i->second.team;
  3144. }
  3145. else if(winnerTeam != i->second.team)
  3146. {
  3147. //current candidate has enemy remaining in game -> no vicotry
  3148. return 255;
  3149. }
  3150. }
  3151. }
  3152. return supposedWinner;
  3153. }
  3154. bool CGameState::checkForStandardLoss( ui8 player ) const
  3155. {
  3156. //std loss condition is: player lost all towns and heroes
  3157. const PlayerState &p = *getPlayer(player);
  3158. return !p.heroes.size() && !p.towns.size();
  3159. }
  3160. struct statsHLP
  3161. {
  3162. typedef std::pair< ui8, si64 > TStat;
  3163. //converts [<player's color, value>] to vec[place] -> platers
  3164. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  3165. {
  3166. std::sort(stats.begin(), stats.end(), statsHLP());
  3167. //put first element
  3168. std::vector< std::list<ui8> > ret;
  3169. std::list<ui8> tmp;
  3170. tmp.push_back( stats[0].first );
  3171. ret.push_back( tmp );
  3172. //the rest of elements
  3173. for(int g=1; g<stats.size(); ++g)
  3174. {
  3175. if(stats[g].second == stats[g-1].second)
  3176. {
  3177. (ret.end()-1)->push_back( stats[g].first );
  3178. }
  3179. else
  3180. {
  3181. //create next occupied rank
  3182. std::list<ui8> tmp;
  3183. tmp.push_back(stats[g].first);
  3184. ret.push_back(tmp);
  3185. }
  3186. }
  3187. return ret;
  3188. }
  3189. bool operator()(const TStat & a, const TStat & b) const
  3190. {
  3191. return a.second > b.second;
  3192. }
  3193. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  3194. {
  3195. std::vector<CGHeroInstance *> &h = gs->players[color].heroes;
  3196. if(!h.size())
  3197. return NULL;
  3198. //best hero will be that with highest exp
  3199. int best = 0;
  3200. for(int b=1; b<h.size(); ++b)
  3201. {
  3202. if(h[b]->exp > h[best]->exp)
  3203. {
  3204. best = b;
  3205. }
  3206. }
  3207. return h[best];
  3208. }
  3209. //calculates total number of artifacts that belong to given player
  3210. static int getNumberOfArts(const PlayerState * ps)
  3211. {
  3212. int ret = 0;
  3213. for(int g=0; g<ps->heroes.size(); ++g)
  3214. {
  3215. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  3216. }
  3217. return ret;
  3218. }
  3219. };
  3220. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  3221. {
  3222. #define FILL_FIELD(FIELD, VAL_GETTER) \
  3223. { \
  3224. std::vector< std::pair< ui8, si64 > > stats; \
  3225. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  3226. { \
  3227. if(g->second.color == 255) \
  3228. continue; \
  3229. std::pair< ui8, si64 > stat; \
  3230. stat.first = g->second.color; \
  3231. stat.second = VAL_GETTER; \
  3232. stats.push_back(stat); \
  3233. } \
  3234. tgi.FIELD = statsHLP::getRank(stats); \
  3235. }
  3236. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3237. {
  3238. if(g->second.color != 255)
  3239. tgi.playerColors.push_back(g->second.color);
  3240. }
  3241. if(level >= 1) //num of towns & num of heroes
  3242. {
  3243. //num of towns
  3244. FILL_FIELD(numOfTowns, g->second.towns.size())
  3245. //num of heroes
  3246. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  3247. //best hero's portrait
  3248. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3249. {
  3250. if(g->second.color == 255)
  3251. continue;
  3252. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  3253. InfoAboutHero iah;
  3254. iah.initFromHero(best, level >= 8);
  3255. iah.army.clear();
  3256. tgi.colorToBestHero[g->second.color] = iah;
  3257. }
  3258. }
  3259. if(level >= 2) //gold
  3260. {
  3261. FILL_FIELD(gold, g->second.resources[6])
  3262. }
  3263. if(level >= 2) //wood & ore
  3264. {
  3265. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  3266. }
  3267. if(level >= 3) //mercury, sulfur, crystal, gems
  3268. {
  3269. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  3270. }
  3271. if(level >= 4) //obelisks found
  3272. {
  3273. //TODO
  3274. }
  3275. if(level >= 5) //artifacts
  3276. {
  3277. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  3278. }
  3279. if(level >= 6) //army strength
  3280. {
  3281. //TODO
  3282. }
  3283. if(level >= 7) //income
  3284. {
  3285. //TODO
  3286. }
  3287. if(level >= 8) //best hero's stats
  3288. {
  3289. //already set in lvl 1 handling
  3290. }
  3291. if(level >= 9) //personality
  3292. {
  3293. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3294. {
  3295. if(g->second.color == 255) //do nothing for neutral player
  3296. continue;
  3297. if(g->second.human)
  3298. {
  3299. tgi.personality[g->second.color] = -1;
  3300. }
  3301. else //AI
  3302. {
  3303. tgi.personality[g->second.color] = map->players[g->second.color].AITactic;
  3304. }
  3305. }
  3306. }
  3307. if(level >= 10) //best creature
  3308. {
  3309. //best creatures belonging to player (highest AI value)
  3310. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3311. {
  3312. if(g->second.color == 255) //do nothing for neutral player
  3313. continue;
  3314. int bestCre = -1; //best creature's ID
  3315. for(int b=0; b<g->second.heroes.size(); ++b)
  3316. {
  3317. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  3318. {
  3319. int toCmp = it->second.type->idNumber; //ID of creature we should compare with the best one
  3320. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  3321. {
  3322. bestCre = toCmp;
  3323. }
  3324. }
  3325. }
  3326. tgi.bestCreature[g->second.color] = bestCre;
  3327. }
  3328. }
  3329. #undef FILL_FIELD
  3330. }
  3331. int CGameState::lossCheck( ui8 player ) const
  3332. {
  3333. const PlayerState *p = getPlayer(player);
  3334. //if(map->lossCondition.typeOfLossCon == lossStandard)
  3335. if(checkForStandardLoss(player))
  3336. return -1;
  3337. if (p->enteredLosingCheatCode)
  3338. {
  3339. return 1;
  3340. }
  3341. if(p->human) //special loss condition applies only to human player
  3342. {
  3343. switch(map->lossCondition.typeOfLossCon)
  3344. {
  3345. case lossCastle:
  3346. {
  3347. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3348. assert(t);
  3349. if(t->tempOwner != player)
  3350. return 1;
  3351. }
  3352. break;
  3353. case lossHero:
  3354. {
  3355. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3356. assert(h);
  3357. if(h->tempOwner != player)
  3358. return 1;
  3359. }
  3360. break;
  3361. case timeExpires:
  3362. if(map->lossCondition.timeLimit < day)
  3363. return 1;
  3364. break;
  3365. }
  3366. }
  3367. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3368. return 2;
  3369. return false;
  3370. }
  3371. std::map<ui32,CGHeroInstance *> CGameState::unusedHeroesFromPool()
  3372. {
  3373. std::map<ui32,CGHeroInstance *> pool = hpool.heroesPool;
  3374. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  3375. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  3376. if(*j)
  3377. pool.erase((**j).subID);
  3378. return pool;
  3379. }
  3380. const CStack * BattleInfo::getNextStack() const
  3381. {
  3382. std::vector<const CStack *> hlp;
  3383. getStackQueue(hlp, 1, -1);
  3384. if(hlp.size())
  3385. return hlp[0];
  3386. else
  3387. return NULL;
  3388. }
  3389. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3390. {
  3391. const CStack *ret = NULL;
  3392. unsigned i, //fastest stack
  3393. j; //fastest stack of the other side
  3394. for(i = 0; i < st.size(); i++)
  3395. if(st[i])
  3396. break;
  3397. //no stacks left
  3398. if(i == st.size())
  3399. return NULL;
  3400. const CStack *fastest = st[i], *other = NULL;
  3401. int bestSpeed = fastest->Speed(turn);
  3402. if(fastest->attackerOwned != curside)
  3403. {
  3404. ret = fastest;
  3405. }
  3406. else
  3407. {
  3408. for(j = i + 1; j < st.size(); j++)
  3409. {
  3410. if(!st[j]) continue;
  3411. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3412. break;
  3413. }
  3414. if(j >= st.size())
  3415. {
  3416. ret = fastest;
  3417. }
  3418. else
  3419. {
  3420. other = st[j];
  3421. if(other->Speed(turn) != bestSpeed)
  3422. ret = fastest;
  3423. else
  3424. ret = other;
  3425. }
  3426. }
  3427. assert(ret);
  3428. if(ret == fastest)
  3429. st[i] = NULL;
  3430. else
  3431. st[j] = NULL;
  3432. curside = ret->attackerOwned;
  3433. return ret;
  3434. }
  3435. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3436. {
  3437. //we'll split creatures with remaining movement to 4 parts
  3438. 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
  3439. int toMove = 0; //how many stacks still has move
  3440. const CStack *active = getStack(activeStack);
  3441. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3442. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3443. {
  3444. out.push_back(active);
  3445. if(out.size() == howMany)
  3446. return;
  3447. }
  3448. for(unsigned int i=0; i<stacks.size(); ++i)
  3449. {
  3450. const CStack * const s = stacks[i];
  3451. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3452. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3453. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3454. {
  3455. continue;
  3456. }
  3457. int p = -1; //in which phase this tack will move?
  3458. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3459. {
  3460. if(vstd::contains(s->state, HAD_MORALE))
  3461. p = 2;
  3462. else
  3463. p = 3;
  3464. }
  3465. else if(s->type->idNumber == 145 || s->type->idNumber == 149) //catapult and turrets are first
  3466. {
  3467. p = 0;
  3468. }
  3469. else
  3470. {
  3471. p = 1;
  3472. }
  3473. phase[p].push_back(s);
  3474. toMove++;
  3475. }
  3476. for(int i = 0; i < 4; i++)
  3477. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3478. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3479. out.push_back(phase[0][i]);
  3480. if(out.size() == howMany)
  3481. return;
  3482. if(lastMoved == -1)
  3483. {
  3484. if(active)
  3485. {
  3486. if(out.size() && out.front() == active)
  3487. lastMoved = active->attackerOwned;
  3488. else
  3489. lastMoved = active->attackerOwned;
  3490. }
  3491. else
  3492. {
  3493. lastMoved = 0;
  3494. }
  3495. }
  3496. int pi = 1;
  3497. while(out.size() < howMany)
  3498. {
  3499. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3500. if(!hlp)
  3501. {
  3502. pi++;
  3503. if(pi > 3)
  3504. {
  3505. //if(turn != 2)
  3506. getStackQueue(out, howMany, turn + 1, lastMoved);
  3507. return;
  3508. }
  3509. }
  3510. else
  3511. {
  3512. out.push_back(hlp);
  3513. }
  3514. }
  3515. }
  3516. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  3517. {
  3518. const CStack * stack = getStack(stackID);
  3519. struct HLP
  3520. {
  3521. static bool lowerAnalyze(const CStack * stack, int hex)
  3522. {
  3523. int distance = BattleInfo::getDistance(hex, stack->position);
  3524. //I hope it's approximately correct
  3525. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  3526. }
  3527. };
  3528. const CStack * dstStack = getStackT(destHex, false);
  3529. if (dstStack->doubleWide())
  3530. return HLP::lowerAnalyze(stack, destHex) && HLP::lowerAnalyze(stack, dstStack->occupiedHex());
  3531. else
  3532. return HLP::lowerAnalyze(stack, destHex);
  3533. }
  3534. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  3535. {
  3536. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  3537. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  3538. bool stackLeft = pos1 < wallInStackLine;
  3539. bool destLeft = pos2 < wallInDestLine;
  3540. return stackLeft != destLeft;
  3541. }
  3542. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  3543. {
  3544. if (siege == 0)
  3545. {
  3546. return false;
  3547. }
  3548. const CStack * stack = getStack(stackID);
  3549. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY));
  3550. {
  3551. return false;
  3552. }
  3553. return !sameSideOfWall(stack->position, destHex);
  3554. }
  3555. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  3556. {
  3557. bool ac[BFIELD_SIZE];
  3558. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  3559. std::set<int> occupyable;
  3560. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  3561. if (siege && telportLevel < 2) //check for wall
  3562. {
  3563. return ac[destHex] && sameSideOfWall(s->position, destHex);
  3564. }
  3565. else
  3566. {
  3567. return ac[destHex];
  3568. }
  3569. }
  3570. void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3571. {
  3572. CBonusSystemNode::getBonuses(out, selector, root);
  3573. const CStack *dest = dynamic_cast<const CStack*>(root);
  3574. if (!dest)
  3575. return;
  3576. //TODO: make it in clean way
  3577. if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  3578. {
  3579. BOOST_FOREACH(const CStack *s, stacks)
  3580. {
  3581. if(s->owner == dest->owner)
  3582. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  3583. else
  3584. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  3585. }
  3586. }
  3587. }
  3588. si8 BattleInfo::getDistance( int hex1, int hex2 )
  3589. {
  3590. int xDst = std::abs(hex1 % BFIELD_WIDTH - hex2 % BFIELD_WIDTH),
  3591. yDst = std::abs(hex1 / BFIELD_WIDTH - hex2 / BFIELD_WIDTH);
  3592. return std::max(xDst, yDst) + std::min(xDst, yDst) - (yDst + 1)/2;
  3593. }
  3594. int3 CPath::startPos() const
  3595. {
  3596. return nodes[nodes.size()-1].coord;
  3597. }
  3598. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3599. {
  3600. if (mode==0)
  3601. {
  3602. for (unsigned int i=0;i<nodes.size();i++)
  3603. {
  3604. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3605. }
  3606. }
  3607. }
  3608. int3 CPath::endPos() const
  3609. {
  3610. return nodes[0].coord;
  3611. }
  3612. CGPathNode::CGPathNode()
  3613. :coord(-1,-1,-1)
  3614. {
  3615. accessible = 0;
  3616. land = 0;
  3617. moveRemains = 0;
  3618. turns = 255;
  3619. theNodeBefore = NULL;
  3620. }
  3621. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3622. {
  3623. out.nodes.clear();
  3624. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3625. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  3626. return false;
  3627. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  3628. bool transition01 = false;
  3629. while(curnode)
  3630. {
  3631. CGPathNode cpn = *curnode;
  3632. if(transition01)
  3633. {
  3634. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  3635. {
  3636. transition01 = false;
  3637. }
  3638. else if (curnode->accessible == CGPathNode::FLYABLE)
  3639. {
  3640. cpn.turns = 1;
  3641. }
  3642. }
  3643. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  3644. {
  3645. transition01 = true;
  3646. }
  3647. curnode = curnode->theNodeBefore;
  3648. out.nodes.push_back(cpn);
  3649. }
  3650. return true;
  3651. }
  3652. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3653. :sizes(Sizes)
  3654. {
  3655. hero = NULL;
  3656. nodes = new CGPathNode**[sizes.x];
  3657. for(int i = 0; i < sizes.x; i++)
  3658. {
  3659. nodes[i] = new CGPathNode*[sizes.y];
  3660. for (int j = 0; j < sizes.y; j++)
  3661. {
  3662. nodes[i][j] = new CGPathNode[sizes.z];
  3663. }
  3664. }
  3665. }
  3666. CPathsInfo::~CPathsInfo()
  3667. {
  3668. for(int i = 0; i < sizes.x; i++)
  3669. {
  3670. for (int j = 0; j < sizes.y; j++)
  3671. {
  3672. delete [] nodes[i][j];
  3673. }
  3674. delete [] nodes[i];
  3675. }
  3676. delete [] nodes;
  3677. }
  3678. int3 CGPath::startPos() const
  3679. {
  3680. return nodes[nodes.size()-1].coord;
  3681. }
  3682. int3 CGPath::endPos() const
  3683. {
  3684. return nodes[0].coord;
  3685. }
  3686. void CGPath::convert( ui8 mode )
  3687. {
  3688. if(mode==0)
  3689. {
  3690. for(unsigned int i=0;i<nodes.size();i++)
  3691. {
  3692. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3693. }
  3694. }
  3695. }
  3696. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3697. {
  3698. switch(phase)
  3699. {
  3700. case 0: //catapult moves after turrets
  3701. return a->type->idNumber < b->type->idNumber; //catapult is 145 and turrets are 149
  3702. //TODO? turrets order
  3703. case 1: //fastest first, upper slot first
  3704. {
  3705. int as = a->Speed(turn), bs = b->Speed(turn);
  3706. if(as != bs)
  3707. return as > bs;
  3708. else
  3709. return a->slot < b->slot;
  3710. }
  3711. case 2: //fastest last, upper slot first
  3712. //TODO: should be replaced with order of receiving morale!
  3713. case 3: //fastest last, upper slot first
  3714. {
  3715. int as = a->Speed(turn), bs = b->Speed(turn);
  3716. if(as != bs)
  3717. return as < bs;
  3718. else
  3719. return a->slot < b->slot;
  3720. }
  3721. default:
  3722. assert(0);
  3723. return false;
  3724. }
  3725. }
  3726. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3727. {
  3728. phase = Phase;
  3729. turn = Turn;
  3730. }
  3731. PlayerState::PlayerState()
  3732. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0),
  3733. enteredLosingCheatCode(0), enteredWinningCheatCode(0)
  3734. {
  3735. }
  3736. void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  3737. {
  3738. /*
  3739. for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); ++it)
  3740. {
  3741. if (*it != root)
  3742. (*it)->getParents(out, root);
  3743. }
  3744. for (std::vector<CGTownInstance *>::const_iterator it = towns.begin(); it != towns.end(); ++it)
  3745. {
  3746. if (*it != root)
  3747. (*it)->getParents(out, root);
  3748. }
  3749. */
  3750. //TODO - dwellings
  3751. }
  3752. void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3753. {//temporary
  3754. //CBonusSystemNode::getBonuses(out, selector, root);
  3755. }
  3756. InfoAboutHero::InfoAboutHero()
  3757. {
  3758. details = NULL;
  3759. hclass = NULL;
  3760. portrait = -1;
  3761. }
  3762. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3763. {
  3764. assign(iah);
  3765. }
  3766. InfoAboutHero::~InfoAboutHero()
  3767. {
  3768. delete details;
  3769. }
  3770. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3771. {
  3772. if(!h) return;
  3773. owner = h->tempOwner;
  3774. hclass = h->type->heroClass;
  3775. name = h->name;
  3776. portrait = h->portrait;
  3777. army = h->getArmy();
  3778. if(detailed)
  3779. {
  3780. //include details about hero
  3781. details = new Details;
  3782. details->luck = h->LuckVal();
  3783. details->morale = h->MoraleVal();
  3784. details->mana = h->mana;
  3785. details->primskills.resize(PRIMARY_SKILLS);
  3786. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3787. {
  3788. details->primskills[i] = h->getPrimSkillLevel(i);
  3789. }
  3790. }
  3791. else
  3792. {
  3793. //hide info about hero stacks counts using descriptives names ids
  3794. for(TSlots::const_iterator i = army.Slots().begin(); i != army.Slots().end(); ++i)
  3795. {
  3796. army.setStackCount(i->first, i->second.getQuantityID()+1);
  3797. }
  3798. }
  3799. }
  3800. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3801. {
  3802. army = iah.army;
  3803. details = (iah.details ? new Details(*iah.details) : NULL);
  3804. hclass = iah.hclass;
  3805. name = iah.name;
  3806. owner = iah.owner;
  3807. portrait = iah.portrait;
  3808. }
  3809. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3810. {
  3811. assign(iah);
  3812. return *this;
  3813. }