CGameState.cpp 128 KB

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