CGameState.cpp 118 KB

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