CGameState.cpp 131 KB

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