CGameState.cpp 128 KB

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