CGameState.cpp 128 KB

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